M5: camera expression cues via MediaPipe Face Landmarker

- CameraX ImageAnalysis + Face Landmarker (CPU, 10Hz, KEEP_ONLY_LATEST)
- Rule-based blendshape mapping: smiling/brow_furrowed/gaze/blink/face_presence
- Camera off by default, explicit user toggle, no image storage/upload
- Expression cues displayed as passive labels, never affect dialogue flow
- CameraX pinned 1.4.2 (compileSdk 34 compat), MediaPipe tasks-vision 1.1.0
- Face model bundled: face_landmarker.task (sha256 TOFU recorded)
- docs/EXPRESSION.md with rules table and privacy notes
- Version 0.2.0-m5
This commit is contained in:
zenord
2026-10-11 08:40:51 +08:00
parent 07d5f77808
commit f1da7abf93
18 changed files with 1612 additions and 21 deletions
+20 -1
View File
@@ -4,6 +4,19 @@ plugins {
id 'org.jetbrains.kotlin.plugin.compose'
}
// Populated once by scripts/prepare-expression.sh from stable Maven versions, then pinned.
def expressionVersions = new Properties()
def expressionVersionFile = rootProject.file('gradle/expression-versions.properties')
if (!expressionVersionFile.isFile()) {
throw new GradleException('Run ./scripts/prepare-expression.sh in the external shell before building M5')
}
expressionVersionFile.withInputStream { expressionVersions.load(it) }
def cameraVersion = expressionVersions.getProperty('camerax.version')
def mediaPipeVersion = expressionVersions.getProperty('mediapipe.version')
if (!cameraVersion || !mediaPipeVersion) {
throw new GradleException('Incomplete gradle/expression-versions.properties; run scripts/prepare-expression.sh')
}
// Android's <domain> text cannot reference @string. Generate it from the one address config
// so changing voice_server_host and rebuilding also updates the certificate trust scope.
def networkSecurityResources = layout.buildDirectory.dir('generated/networkSecurity/res')
@@ -33,12 +46,13 @@ android {
minSdk 26
targetSdk 34
versionCode 1
versionName '0.1.0-m2'
versionName '0.2.0-m5'
ndk { abiFilters 'arm64-v8a' }
}
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
kotlinOptions { jvmTarget = '17' }
buildFeatures { compose true }
androidResources { noCompress += ['task'] }
sourceSets.main.res.srcDir(networkSecurityResources)
}
tasks.named('preBuild').configure { dependsOn(generateNetworkSecurityConfig) }
@@ -48,4 +62,9 @@ dependencies {
implementation 'androidx.compose.material3:material3'
implementation 'androidx.activity:activity-compose:1.9.3'
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation "com.google.mediapipe:tasks-vision:$mediaPipeVersion"
implementation "androidx.camera:camera-core:$cameraVersion"
implementation "androidx.camera:camera-camera2:$cameraVersion"
implementation "androidx.camera:camera-lifecycle:$cameraVersion"
implementation "androidx.camera:camera-view:$cameraVersion"
}
+4
View File
@@ -2,6 +2,10 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
<application
android:label="@string/app_name"
android:theme="@android:style/Theme.Material.NoActionBar"
Binary file not shown.
@@ -33,11 +33,25 @@ import com.gorios.lanvoice.audio.VoicePhase
import com.gorios.lanvoice.audio.VoiceSession
import com.gorios.lanvoice.audio.VoiceUiState
import com.gorios.lanvoice.net.ConnectionStatus
import com.gorios.lanvoice.expression.ExpressionController
import com.gorios.lanvoice.expression.ExpressionControls
import com.gorios.lanvoice.expression.ExpressionStatus
import com.gorios.lanvoice.expression.ExpressionUiState
class MainActivity : ComponentActivity() {
private var state by mutableStateOf(VoiceUiState())
private lateinit var session: VoiceSession
private var pendingStart = false
private var expressionState by mutableStateOf(ExpressionUiState())
private lateinit var expressions: ExpressionController
private var pendingCamera = false
private var inForeground = false
private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
val shouldStart = pendingCamera && inForeground
pendingCamera = false
if (granted && shouldStart) expressions.start()
else if (!granted) expressions.permissionDenied()
}
private val microphonePermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
val shouldStart = pendingStart
pendingStart = false
@@ -51,7 +65,21 @@ class MainActivity : ComponentActivity() {
getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port),
onState = { state = it },
)
setContent { Home(state, ::toggleVoice, session::interrupt) }
expressions = ExpressionController(this, this) { expressionState = it }
setContent { Home(state, ::toggleVoice, session::interrupt, expressionState, ::toggleExpressions) }
}
private fun toggleExpressions() {
if (!inForeground) return
if (expressionState.status == ExpressionStatus.STARTING || expressionState.status == ExpressionStatus.ACTIVE) {
pendingCamera = false
expressions.stop()
} else if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
expressions.start()
} else if (!pendingCamera) {
pendingCamera = true
cameraPermission.launch(Manifest.permission.CAMERA)
}
}
private fun toggleVoice() {
@@ -68,45 +96,58 @@ class MainActivity : ComponentActivity() {
override fun onStart() {
super.onStart()
inForeground = true
session.foreground()
}
override fun onStop() {
inForeground = false
pendingCamera = false
expressions.stop()
pendingStart = false
session.background()
super.onStop()
}
override fun onDestroy() {
expressions.release()
session.release()
super.onDestroy()
}
}
@Composable
fun Home(state: VoiceUiState, onToggleVoice: () -> Unit, onInterrupt: () -> Unit) {
fun Home(
state: VoiceUiState, onToggleVoice: () -> Unit, onInterrupt: () -> Unit,
expressionState: ExpressionUiState, onToggleExpressions: () -> Unit,
) {
val gold = Color(0xFFE8C884)
val muted = Color(0xFF9CA3AF)
val connected = state.connection == ConnectionStatus.CONNECTED
Box(Modifier.fillMaxSize().background(Color(0xFF121220)).padding(24.dp)) {
Text(
text = when (state.connection) {
ConnectionStatus.DISCONNECTED -> "已断开"
ConnectionStatus.BUSY -> "被占用 · 另一设备正在使用"
ConnectionStatus.CONNECTED -> when (state.phase) {
VoicePhase.IDLE -> "已连接"
VoicePhase.LISTENING -> "听取中"
VoicePhase.RECOGNIZING -> "识别中"
VoicePhase.THINKING -> "思考中"
VoicePhase.ANSWERING -> "回答中"
}
},
color = if (connected) gold else muted,
fontSize = 14.sp,
modifier = Modifier.align(Alignment.TopCenter).padding(top = 24.dp)
.background(Color(0xFF242433), RoundedCornerShape(50))
.padding(horizontal = 20.dp, vertical = 10.dp)
)
Column(
modifier = Modifier.align(Alignment.TopCenter).padding(top = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = when (state.connection) {
ConnectionStatus.DISCONNECTED -> "已断开"
ConnectionStatus.BUSY -> "被占用 · 另一设备正在使用"
ConnectionStatus.CONNECTED -> when (state.phase) {
VoicePhase.IDLE -> "已连接"
VoicePhase.LISTENING -> "听取中"
VoicePhase.RECOGNIZING -> "识别中"
VoicePhase.THINKING -> "思考中"
VoicePhase.ANSWERING -> "回答中"
}
},
color = if (connected) gold else muted,
fontSize = 14.sp,
modifier = Modifier.background(Color(0xFF242433), RoundedCornerShape(50))
.padding(horizontal = 20.dp, vertical = 10.dp)
)
ExpressionControls(expressionState, onToggleExpressions)
}
Column(
modifier = Modifier.align(Alignment.Center).padding(bottom = 180.dp),
horizontalAlignment = Alignment.CenterHorizontally,
@@ -0,0 +1,254 @@
package com.gorios.lanvoice.expression
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Matrix
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Size
import android.view.WindowManager
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.lifecycle.LifecycleOwner
import com.google.mediapipe.framework.image.BitmapImageBuilder
import com.google.mediapipe.tasks.core.BaseOptions
import com.google.mediapipe.tasks.vision.core.RunningMode
import com.google.mediapipe.tasks.vision.facelandmarker.FaceLandmarker
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
/** Independent local feature. It never references net/audio, writes user data or opens a network. */
class ExpressionController(
context: Context,
private val lifecycleOwner: LifecycleOwner,
private val onState: (ExpressionUiState) -> Unit,
) {
private class Run {
@Volatile var active = true
val executor: ExecutorService = Executors.newSingleThreadExecutor { task ->
Thread(task, "lan-voice-expression").apply { isDaemon = true }
}
val rules = ExpressionRules()
var landmarker: FaceLandmarker? = null // Accessed only on this run's executor.
var analysis: ImageAnalysis? = null // Accessed only on main.
var provider: ProcessCameraProvider? = null // Accessed only on main.
var lastSampleMs = Long.MIN_VALUE
var lastPublished: List<ExpressionCue>? = null
}
private val appContext = context.applicationContext
private val main = Handler(Looper.getMainLooper())
private var current: Run? = null
private var released = false
/** Called only after an explicit user toggle and CAMERA permission approval. */
fun start() {
checkMainThread()
if (released || current != null) return
if (appContext.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
permissionDenied()
return
}
val run = Run()
current = run
onState(ExpressionUiState(ExpressionStatus.STARTING))
// Model loading and all synchronous VIDEO inference stay off the UI/audio threads.
run.executor.execute {
try {
if (!run.active) return@execute
val base = BaseOptions.builder().setModelAssetPath("face_landmarker.task").build()
val options = FaceLandmarker.FaceLandmarkerOptions.builder()
.setBaseOptions(base) // Default delegate is CPU; no GPU/context requirements.
.setRunningMode(RunningMode.VIDEO)
.setNumFaces(1)
.setMinFaceDetectionConfidence(.5f)
.setMinFacePresenceConfidence(.5f)
.setMinTrackingConfidence(.5f)
.setOutputFaceBlendshapes(true)
.setOutputFacialTransformationMatrixes(true)
.build()
run.landmarker = FaceLandmarker.createFromOptions(appContext, options)
main.post { if (isCurrent(run)) bind(run) }
} catch (_: Exception) {
fail(run, "表情分析暂不可用,请检查模型和设备支持;语音功能不受影响。")
} catch (_: LinkageError) {
fail(run, "设备暂不支持表情分析,语音功能仍可使用。")
}
}
}
fun stop() {
checkMainThread()
stopCurrent()
if (!released) onState(ExpressionUiState())
}
fun permissionDenied() {
checkMainThread()
stopCurrent()
if (!released) onState(ExpressionUiState(guidance =
"摄像头权限未授予。可在系统应用权限中开启,语音功能仍可使用。"))
}
fun release() {
checkMainThread()
if (released) return
released = true
stopCurrent()
}
@Suppress("DEPRECATION") // targetResolution keeps compatibility with stable CameraX APIs.
private fun bind(run: Run) {
try {
val future = ProcessCameraProvider.getInstance(appContext)
future.addListener({
if (!isCurrent(run)) return@addListener
try {
val provider = future.get()
if (!provider.hasCamera(CameraSelector.DEFAULT_FRONT_CAMERA)) {
fail(run, "未找到前置摄像头,语音功能仍可使用。")
return@addListener
}
val analysis = ImageAnalysis.Builder()
.setTargetResolution(Size(640, 480))
.setTargetRotation((appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager)
.defaultDisplay.rotation)
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888)
.build()
run.provider = provider
run.analysis = analysis
analysis.setAnalyzer(run.executor) { image -> analyze(run, image) }
// ImageAnalysis only: no Preview, capture, video recording or image persistence.
provider.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_FRONT_CAMERA, analysis)
onState(ExpressionUiState(ExpressionStatus.ACTIVE))
} catch (_: Exception) {
fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。")
}
}, { action -> main.post(action) })
} catch (_: Exception) {
fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。")
}
}
private fun analyze(run: Run, image: ImageProxy) {
var bitmap: Bitmap? = null
try {
if (!run.active) return
val now = SystemClock.elapsedRealtime()
if (run.lastSampleMs != Long.MIN_VALUE && now - run.lastSampleMs < SAMPLE_INTERVAL_MS) return
run.lastSampleMs = now
bitmap = rgbaBitmap(image)
if (!run.active) return
val mpImage = BitmapImageBuilder(bitmap).build()
val result = try {
run.landmarker?.detectForVideo(mpImage, now)
} finally {
mpImage.close()
} ?: return
if (!run.active) return
val observation = if (result.faceLandmarks().isEmpty()) null else {
val categories = result.faceBlendshapes().orElse(emptyList()).firstOrNull().orEmpty()
val blendshapes = categories.associate { it.categoryName() to it.score() }
val transform = result.facialTransformationMatrixes().orElse(emptyList()).firstOrNull()
FaceObservation(blendshapes, transform?.let(HeadPose::fromMatrix))
}
val visible = ExpressionRules.visible(run.rules.evaluate(observation, now))
// UI receives only <=2 enum labels; 52 coefficients, pose and images stay transient.
if (run.lastPublished != visible) {
run.lastPublished = visible
main.post {
if (isCurrent(run)) onState(ExpressionUiState(ExpressionStatus.ACTIVE, visible))
}
}
} catch (_: Exception) {
// Never log exceptions from inference, frames, coefficients or head pose.
fail(run, "表情分析已停止,请重新开启;语音功能不受影响。")
} catch (_: LinkageError) {
fail(run, "设备暂不支持表情分析,语音功能仍可使用。")
} finally {
bitmap?.recycle()
image.close() // Includes throttle/stop/error paths, so CameraX never retains the proxy.
}
}
private fun fail(run: Run, guidance: String) {
// Prevent another scheduled frame from running before main unbinds the camera.
run.active = false
main.post {
if (!released && current === run) {
stopCurrent()
onState(ExpressionUiState(ExpressionStatus.UNAVAILABLE, guidance = guidance))
}
}
}
private fun stopCurrent() {
val run = current ?: return
current = null // Invalidate every pending model/provider/result callback before unbinding.
run.active = false
try {
run.analysis?.clearAnalyzer()
} catch (_: Exception) { }
try {
run.analysis?.let { run.provider?.unbind(it) } // Unbind only this feature's use case.
} catch (_: Exception) { }
run.analysis = null
run.provider = null
// An in-flight CPU inference may finish; its result is discarded. Close on its executor
// after that call, rather than blocking main or closing a native task while it is running.
run.executor.execute {
try { run.landmarker?.close() } catch (_: Exception) {
// Feature cleanup must not interrupt voice, and never logs model/frame data.
} catch (_: LinkageError) {
} finally {
run.landmarker = null
run.rules.reset()
run.lastPublished = null
}
}
run.executor.shutdown()
}
private fun isCurrent(run: Run) = !released && current === run && run.active
private fun checkMainThread() {
check(Looper.myLooper() === main.looper) { "ExpressionController must be used on main" }
}
companion object { private const val SAMPLE_INTERVAL_MS = 100L }
}
/** Convert CameraX RGBA using pixel/row strides, crop and sensor rotation; no selfie mirror. */
private fun rgbaBitmap(image: ImageProxy): Bitmap {
val plane = image.planes.first()
val bytes = plane.buffer.duplicate()
val base = bytes.position()
val crop = image.cropRect
val width = crop.width()
val height = crop.height()
val pixels = IntArray(width * height)
for (y in 0 until height) {
for (x in 0 until width) {
val offset = base + (y + crop.top) * plane.rowStride + (x + crop.left) * plane.pixelStride
val red = bytes.get(offset).toInt() and 0xff
val green = bytes.get(offset + 1).toInt() and 0xff
val blue = bytes.get(offset + 2).toInt() and 0xff
val alpha = bytes.get(offset + 3).toInt() and 0xff
pixels[y * width + x] = (alpha shl 24) or (red shl 16) or (green shl 8) or blue
}
}
val raw = Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888)
val rotation = image.imageInfo.rotationDegrees
if (rotation == 0) return raw
return try {
Bitmap.createBitmap(raw, 0, 0, width, height, Matrix().apply { postRotate(rotation.toFloat()) }, true)
} finally {
raw.recycle()
}
}
@@ -0,0 +1,178 @@
package com.gorios.lanvoice.expression
import kotlin.math.asin
import kotlin.math.atan2
import kotlin.math.sqrt
import java.util.ArrayDeque
enum class ExpressionCue(val label: String) {
FACE_PRESENT("检测到人脸"), FACE_LOST("未检测到人脸"),
GAZE_CENTER("视线居中"), GAZE_LEFT("视线偏左"), GAZE_RIGHT("视线偏右"),
SMILING("微笑中"), BROW_FURROWED("眉头收紧"), EYES_CLOSED_LONG("闭眼/眨眼偏多"),
}
/** Approximate Euler pose in degrees from MediaPipe's column-major face transform. */
data class HeadPose(val yaw: Float, val pitch: Float, val roll: Float) {
companion object {
fun fromMatrix(matrix: FloatArray): HeadPose? {
if (matrix.size != 16 || matrix.any { !it.isFinite() }) return null
val firstColumnScale = sqrt(matrix[0] * matrix[0] + matrix[1] * matrix[1] + matrix[2] * matrix[2])
val secondColumnScale = sqrt(matrix[4] * matrix[4] + matrix[5] * matrix[5] + matrix[6] * matrix[6])
val thirdColumnScale = sqrt(matrix[8] * matrix[8] + matrix[9] * matrix[9] + matrix[10] * matrix[10])
if (minOf(firstColumnScale, secondColumnScale, thirdColumnScale) < 1e-6f) return null
val degrees = (180.0 / Math.PI).toFloat()
val yaw = asin((-matrix[2] / firstColumnScale).coerceIn(-1f, 1f)) * degrees
val pitch = atan2(matrix[6] / secondColumnScale, matrix[10] / thirdColumnScale) * degrees
val roll = atan2(matrix[1] / firstColumnScale, matrix[0] / firstColumnScale) * degrees
return HeadPose(yaw, pitch, roll)
}
}
}
/** All 52 coefficients and pose are used transiently by the analyzer, never stored or logged. */
data class FaceObservation(val blendshapes: Map<String, Float>, val pose: HeadPose?)
/** Deterministic 10 Hz heuristics; labels describe cues, never emotions or diagnoses. */
class ExpressionRules {
private class Gate {
private var candidateSince: Long? = null
private var active = false
fun update(score: Float, enter: Float, leave: Float, holdMs: Long, now: Long): Boolean {
if (!score.isFinite()) { reset(); return false }
if (active) {
if (score < leave) reset()
} else if (score >= enter) {
val since = candidateSince ?: now.also { candidateSince = it }
if (now - since >= holdMs) active = true
} else candidateSince = null
return active
}
fun reset() { candidateSince = null; active = false }
}
private val smile = Gate()
private val brow = Gate()
private val eyes = Gate()
private var present = false
private var presentSince: Long? = null
private var lostSince: Long? = null
private var lastTimestamp: Long? = null
private var gaze = ExpressionCue.GAZE_CENTER
private var gazeCandidate = ExpressionCue.GAZE_CENTER
private var gazeSince = 0L
private var eyeClosedSince: Long? = null
private var eyeWindowSince: Long? = null
private val blinkEnds = ArrayDeque<Long>()
fun reset() {
resetFeatures()
present = false
presentSince = null
lostSince = null
lastTimestamp = null
}
fun evaluate(observation: FaceObservation?, nowMs: Long): Set<ExpressionCue> {
val previous = lastTimestamp
// A stalled camera cannot turn two unrelated samples into a long eye closure.
if (previous != null && (nowMs <= previous || nowMs - previous > 500)) reset()
lastTimestamp = nowMs
if (observation == null) {
presentSince = null
resetFeatures() // Never retain smiling/gaze/closed-eye cues across missing faces.
val since = lostSince ?: nowMs.also { lostSince = it }
if (nowMs - since >= 500) present = false
return if (present) setOf(ExpressionCue.FACE_PRESENT)
else if (nowMs - since >= 500) setOf(ExpressionCue.FACE_LOST) else emptySet()
}
lostSince = null
val since = presentSince ?: nowMs.also { presentSince = it }
if (!present && nowMs - since >= 200) {
present = true
gazeSince = nowMs
}
if (!present) return emptySet()
val values = observation.blendshapes
fun value(name: String) = values[name]?.takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: 0f
val cues = linkedSetOf(ExpressionCue.FACE_PRESENT)
val blink = minOf(value("eyeBlinkLeft"), value("eyeBlinkRight"))
val closed = eyes.update(blink, .65f, .40f, 1_000, nowMs)
val frequentBlinking = updateBlinkWindow(blink, nowMs)
if (closed || frequentBlinking) cues.add(ExpressionCue.EYES_CLOSED_LONG)
if (smile.update((value("mouthSmileLeft") + value("mouthSmileRight")) / 2, .55f, .40f, 300, nowMs)) {
cues.add(ExpressionCue.SMILING)
}
if (brow.update(minOf(value("browDownLeft"), value("browDownRight")), .45f, .30f, 300, nowMs)) {
cues.add(ExpressionCue.BROW_FURROWED)
}
// Canonical subject coordinates, without mirroring; horizontal ocular cue plus head yaw.
// A look toward the subject's left increases eyeLookOutLeft + eyeLookInRight.
// Positive right-handed Y rotation points the canonical face toward its own left.
val left = (value("eyeLookOutLeft") + value("eyeLookInRight")) / 2
val right = (value("eyeLookInLeft") + value("eyeLookOutRight")) / 2
val horizontal = right - left
val yaw = observation.pose?.yaw ?: 0f
val desired = when {
blink >= .40f -> null // Eye direction is unreliable while eyelids are closing.
gaze == ExpressionCue.GAZE_LEFT && (horizontal <= -.15f || yaw >= 12f) -> ExpressionCue.GAZE_LEFT
gaze == ExpressionCue.GAZE_RIGHT && (horizontal >= .15f || yaw <= -12f) -> ExpressionCue.GAZE_RIGHT
horizontal <= -.25f || yaw >= 20f -> ExpressionCue.GAZE_LEFT
horizontal >= .25f || yaw <= -20f -> ExpressionCue.GAZE_RIGHT
observation.pose != null || values.keys.any { it.startsWith("eyeLook") } -> ExpressionCue.GAZE_CENTER
else -> null
}
if (desired == null) {
gazeCandidate = ExpressionCue.GAZE_CENTER
gazeSince = nowMs
} else {
if (gazeCandidate != desired) {
gazeCandidate = desired
gazeSince = nowMs
}
if (nowMs - gazeSince >= 300) {
gaze = desired
cues.add(gaze)
}
}
return cues
}
private fun resetFeatures() {
smile.reset(); brow.reset(); eyes.reset()
gaze = ExpressionCue.GAZE_CENTER
gazeCandidate = ExpressionCue.GAZE_CENTER
gazeSince = lastTimestamp ?: 0
eyeClosedSince = null
eyeWindowSince = null
blinkEnds.clear()
}
private fun updateBlinkWindow(score: Float, nowMs: Long): Boolean {
val windowStart = eyeWindowSince ?: nowMs.also { eyeWindowSince = it }
if (score >= .65f && eyeClosedSince == null) eyeClosedSince = nowMs
if (score < .40f) {
eyeClosedSince?.let { start ->
// At 10 Hz only sampled bilateral closures can be counted, not every real blink.
if (nowMs - start in 100..500) blinkEnds.addLast(nowMs)
}
eyeClosedSince = null
}
while (blinkEnds.isNotEmpty() && nowMs - blinkEnds.first > 10_000) blinkEnds.removeFirst()
return nowMs - windowStart >= 10_000 && blinkEnds.size >= 8
}
companion object {
/** Explicit presentation priority; no more than two labels are ever shown. */
fun visible(cues: Set<ExpressionCue>): List<ExpressionCue> {
val salient = listOf(ExpressionCue.FACE_LOST, ExpressionCue.EYES_CLOSED_LONG,
ExpressionCue.SMILING, ExpressionCue.BROW_FURROWED,
ExpressionCue.GAZE_LEFT, ExpressionCue.GAZE_RIGHT).filter { it in cues }
return if (salient.isNotEmpty()) salient.take(2)
else listOf(ExpressionCue.FACE_PRESENT, ExpressionCue.GAZE_CENTER).filter { it in cues }.take(2)
}
}
}
@@ -0,0 +1,9 @@
package com.gorios.lanvoice.expression
enum class ExpressionStatus { OFF, STARTING, ACTIVE, UNAVAILABLE }
data class ExpressionUiState(
val status: ExpressionStatus = ExpressionStatus.OFF,
val cues: List<ExpressionCue> = emptyList(),
val guidance: String? = null,
)
@@ -0,0 +1,50 @@
package com.gorios.lanvoice.expression
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun ExpressionControls(state: ExpressionUiState, onToggle: () -> Unit) {
val enabled = state.status == ExpressionStatus.STARTING || state.status == ExpressionStatus.ACTIVE
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
state.cues.take(2).forEach { cue ->
Text(
cue.label, fontSize = 12.sp, color = Color(0xFFE8C884),
modifier = Modifier.background(Color(0xFF242433), RoundedCornerShape(50))
.padding(horizontal = 10.dp, vertical = 5.dp),
)
}
TextButton(onClick = onToggle) {
Text(when {
state.status == ExpressionStatus.STARTING -> "取消开启"
enabled -> "关闭摄像头"
else -> "开启表情线索"
}, fontSize = 12.sp, color = Color(0xFFE8C884))
}
}
if (state.status == ExpressionStatus.STARTING) {
Text("正在开启摄像头…", color = Color(0xFF9CA3AF), fontSize = 12.sp)
}
state.guidance?.let {
Text(it, fontSize = 12.sp, color = Color(0xFF9CA3AF), textAlign = TextAlign.Center)
}
Text(
"表情线索仅供参考,不代表真实情绪",
fontSize = 11.sp, color = Color(0xFF9CA3AF), textAlign = TextAlign.Center,
)
}
}
+53
View File
@@ -0,0 +1,53 @@
# M5 表情线索
版本:`0.2.0-m5`。这是独立的 `expression/` feature;不调用 net/ 或 audio/,不向服务端发送线索。摄像头默认关闭,只有用户点击并授予 CAMERA 权限后才加载模型、绑定前置摄像头。关闭、退后台或销毁时立即清除 analyzer 并解绑本 feature 的 ImageAnalysis;已在执行的 CPU 推理返回后丢弃结果,再安全关闭模型,避免阻塞语音/UI 线程。返回前台不自动开启。
CameraX 使用 `KEEP_ONLY_LATEST`、约 640×480 分辨率和最多 10Hz 分析。只绑定 ImageAnalysis,无预览、拍照或录制。MediaPipe Face Landmarker 使用 VIDEO 模式、单人脸、默认 CPU delegate,输出 52 个 blendshape 类别和脸部变换矩阵;矩阵在内存中转换为 yaw/pitch/roll。输入 RGBA 处理行/像素步长、裁剪与传感器旋转,不做自拍镜像。
帧、Bitmap、系数和 head pose 不保存、不上传、不写日志;每帧 ImageProxy 与 MPImage 在 finally 中关闭,Bitmap 回收。UI 只接收最多两个枚举线索。采样发生在独立工作线程,模型失败、无摄像头或权限拒绝只更新表情 feature 状态,不调用语音控制。
## 规则映射
系数范围为 0~1;缺失/无效系数不触发正向线索。所有时间均使用单调时钟。新的人脸持续出现 200ms 后才判断表情;采样间隔超过 500ms 或时间不递增时,重置时间门限,不能把相隔很久的两帧认作连续闭眼。
定义:`L = (eyeLookOutLeft + eyeLookInRight)/2`,`R = (eyeLookInLeft + eyeLookOutRight)/2`,`D = R-L`。左右按被摄者自身左右、未镜像的模型坐标定义;正 yaw 是右手 Y 轴旋转,canonical face 转向自身左侧。视线是眼部系数与头部朝向的粗略规则线索,不是经过校准的视线追踪。
| 输出状态 | UI 标签 | 进入条件 | 退出/迟滞 |
|---|---|---|---|
| `face_present` | 检测到人脸 | Face Landmarker 检测到单脸,持续 ≥200ms | 连续未检测到 ≥500ms;一旦丢失样本,立刻清除表情、视线及闭眼计时 |
| `face_lost` | 未检测到人脸 | 连续无脸 ≥500ms,含首次开启未找到脸 | 新脸持续 ≥200ms 后转 present;重获脸的确认阶段不显示旧 lost 标签 |
| `gaze_left` | 视线偏左 | `D ≤ -0.25` 或 `yaw ≥ +20°`,持续 ≥300ms | 已激活时保持至 `D > -0.15` 且 `yaw < +12°`,再确认新方向 ≥300ms |
| `gaze_right` | 视线偏右 | `D ≥ +0.25` 或 `yaw ≤ -20°`,持续 ≥300ms | 已激活时保持至 `D < +0.15` 且 `yaw > -12°`,再确认新方向 ≥300ms |
| `gaze_center` | 视线居中 | 有眼部方向系数或 head pose,且不满足侧向规则,持续 ≥300ms | 转为侧向方向;闭眼系数 min ≥0.40 时不显示 gaze 标签 |
| `smiling` | 微笑中 | `(mouthSmileLeft + mouthSmileRight)/2 ≥0.55`,持续 ≥300ms | 平均值 <0.40 |
| `brow_furrowed` | 眉头收紧 | `min(browDownLeft,browDownRight) ≥0.45`,持续 ≥300ms | 最小值 <0.30 |
| `eyes_closed_long` | 闭眼/眨眼偏多 | 双眼 `min(eyeBlinkLeft,eyeBlinkRight) ≥0.65` 持续 ≥1秒;或完整观察 10秒后,滚动 10秒内 ≥8 次采样可见双眼闭合—睁开周期 | 长闭眼在 min <0.40 时退出;眨眼计数不足 8 次时退出。计数周期闭合 100~500ms、睁开 min <0.40;人脸丢失/采样中断清空窗口 |
眨眼窗口是保守的采样计数:10Hz 会漏掉短眨眼,不声称测得完整眨眼率或诊断“异常”。同一个有限标签涵盖持续闭眼或眨眼偏多,不额外增加情绪/医学标签。
标签优先级:face_lost → eyes_closed_long → smiling → brow_furrowed → gaze_left/right,取前两个;无这些显著线索时显示 face_present / gaze_center。UI 固定展示“表情线索仅供参考,不代表真实情绪”。门限是初始工程规则,需在真机上检查左/右方向、佩戴眼镜、光照、闭眼和微笑,不根据规则推断真实情绪。
## 依赖和外部构建
新增 `com.google.mediapipe:tasks-vision` 及 CameraX 的 `camera-core`、`camera-camera2`、`camera-lifecycle`、`camera-view`。当前 agent 沙箱不能联网,不能把已过期的已知版本冒充“最新稳定”。`scripts/prepare-expression.sh` 首次从官方 Google Maven 元数据选择最新数字稳定版(排除 alpha/beta/rc),CameraX 四模块使用共同的最新稳定版本,写入 `gradle/expression-versions.properties`。后续构建使用这个具体版本文件,不使用动态 `+` 或 `latest.release`,也不静默升级。
准备脚本同时从官方版本化 URL 下载 `face_landmarker/float16/1/face_landmarker.task` 到 `app/src/main/assets/face_landmarker.task`,检查 task ZIP 中含 blendshape 模型,记录 `gradle/face-landmarker-model.sha256`。float16 指模型资源精度,运行仍为默认 CPU delegate。后续已有版本和模型时不联网,并核对模型 SHA256;初次 HTTPS 下载采用 TOFU。模型仅是构建资源,运行时不下载。
外部 shell 执行:
```bash
# build.sh 自动调用准备脚本;首次联网选择具体版本并下载模型、依赖,同时固化 SHA256。
./scripts/build.sh --write-verification-metadata sha256 assembleDebug
# 用已固定版本和 verification-metadata 再验证常规构建。
./scripts/build.sh
```
应保留/提交生成的版本文件、模型、模型 SHA256 和更新后的 `gradle/verification-metadata.xml`。直接调用 gradlew 时,先运行 `./scripts/prepare-expression.sh` 并 source 构建环境。当前 AGP/SDK 基线仍是 AGP8.5.2 / compileSdk34;最新稳定依赖的实际 AAR/SDK 要求需要由外部首次构建检查,不能通过静默降级依赖或修改 android-build 基线规避。
## 已做验证与待验收
- `./scripts/check-expression-rules.sh` 通过纯 Kotlin 合成时间线检查:人脸出现/丢失门限、短微笑不触发、迟滞、双侧皱眉、长闭眼、采样中断、眨眼窗口、头部 yaw 与视线方向、重置和两标签上限;不使用真实人脸数据。
- 表情规则、状态与 Compose 控件通过 SDK34/Kotlin2.0.20/Compose 插件及缓存真实依赖的独立编译检查;新 CameraX/MediaPipe 依赖尚未下载,因此不宣称整个 M5 通过编译。
- 准备脚本通过合成 Maven/task 输入检查:稳定版筛选、版本数字排序、CameraX 共同版本、重复运行无需网络、模型 SHA256 不匹配拒绝;shell 语法及 Manifest XML 检查通过。
- audio/ 三个文件 SHA256 与任务开始时一致;net/、config.xml host/port 和语音协议未修改。没有新增图像/视频持久化或上传路径。
- 待外部:准备真实模型/依赖、完整构建、固化校验元数据;待真机:默认关闭、首次权限/拒绝、开关与权限撤销、退后台解绑、快速开关无旧结果、旋转/颜色/左右规则、最多两个标签,以及语音同时运行时的 CPU/延迟表现。
+10
View File
@@ -179,3 +179,13 @@ APK 侧实现、编译及依赖校验元数据固化已完成。用户在外部
- 待真机联调:一轮及连续两轮对话、采集/播放格式、drained 时机、短回答启动、打断即时停播、换轮及旧回调隔离、HTTP 403 占用、断网/前后台恢复、权限拒绝及撤销、设备 AEC 实际效果与系统音频路由。
本次停在 M2 源码交付,等待外部构建结果和下一步指令。
## 11. M5 独立表情线索 feature(2026-10-11,待外部构建)
- 按本次用户确定的 M5 方案新增 `expression/`:CameraX ImageAnalysis + MediaPipe Face Landmarker,单人脸、52 blendshapes + head pose、CPU 推理、最多 10Hz、KEEP_ONLY_LATEST。历史“不做摄像头/表情”是此前阶段范围,本次用户授权的独立 feature 以本节为准。
- 摄像头默认关闭;用户开启时单独申请 CAMERA,拒绝或模型失败仅影响表情模块。关闭/退后台立刻清 analyzer 并解绑摄像头,所有迟到结果按本 feature 的运行身份丢弃;不改动 audio/ 或 net/,原 config.xml 地址不变。
- UI 在顶部胶囊附近显示最多两个规则线索,增加独立摄像头按钮及“表情线索仅供参考,不代表真实情绪”。帧/图像/系数/pose 仅内存瞬时处理,不保存、上传或写日志,无摄像头预览/录像功能。
- 版本号 `0.2.0-m5`;新增 tasks-vision 与 CameraX core/camera2/lifecycle/view。最新稳定版本在外部首次构建时由准备脚本读取官方 Maven 元数据并固定,不猜测沙箱内无法核对的版本。
- 改动文件:`expression/ExpressionController.kt`、`ExpressionRules.kt`、`ExpressionState.kt`、`ExpressionUi.kt`;MainActivity、Manifest、app/build.gradle;scripts/build.sh、prepare-expression.sh/.py、check-expression-rules.sh;tests/expression/ExpressionRulesCheck.kt;docs/EXPRESSION.md 及本实施记录。
- 规则映射、采样限制、关闭行为、模型资源下载和外部构建步骤详见 `docs/EXPRESSION.md`。外部准备会生成 assets/face_landmarker.task、模型 SHA256 和具体依赖版本文件,再用 `--write-verification-metadata sha256` 固化依赖。
- 有限验证:合成规则时间线、规则/state/Compose 控件独立编译、准备脚本合成输入和 shell/XML 检查通过;audio/ 文件 SHA256 确认不变。沙箱无法下载新依赖/模型,完整编译及真机运行仍需外部验收,不将源码检查当作 M5 APK 构建通过。
+3
View File
@@ -0,0 +1,3 @@
# Selected from official Google Maven stable versions; keep this file for reproducibility.
mediapipe.version=1.1.0
camerax.version=1.4.2
+1
View File
@@ -0,0 +1 @@
64184e229b263107bc2b804c6625db1341ff2bb731874b0bcc2fe6544e0bc9ff app/src/main/assets/face_landmarker.task
File diff suppressed because it is too large Load Diff
+1
View File
@@ -4,6 +4,7 @@ set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
source /home/ubuntu/android-build/env.sh
cd "$ROOT"
./scripts/prepare-expression.sh
if [ $# -eq 0 ]; then set -- assembleDebug; fi
TS=$(date +%Y%m%d-%H%M%S)
./gradlew --console=plain "$@" 2>&1 | tee "logs/build-$TS.log"
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
# Pure Kotlin synthetic-rule checks, no Gradle daemon, CAMERA, network or new dependencies.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
source /home/ubuntu/android-build/env.sh
cd "$ROOT"
python3 - <<'PY'
from pathlib import Path
import os
import subprocess
import tempfile
cache = Path(os.environ['GRADLE_USER_HOME']) / 'caches/modules-2/files-2.1'
def jar(group, name, version):
return str(next((cache / group / name / version).glob('*/*.jar')))
stdlib = jar('org.jetbrains.kotlin', 'kotlin-stdlib', '2.0.20')
compiler = ':'.join([
jar('org.jetbrains.kotlin', 'kotlin-compiler-embeddable', '2.0.20'), stdlib,
jar('org.jetbrains.kotlin', 'kotlin-reflect', '1.6.10'),
jar('org.jetbrains.kotlin', 'kotlin-script-runtime', '2.0.20'),
jar('org.jetbrains.intellij.deps', 'trove4j', '1.0.20200330'),
jar('org.jetbrains', 'annotations', '23.0.0'),
str(next((cache / 'org.jetbrains.kotlinx/kotlinx-coroutines-core-jvm').glob('*/*/*.jar'))),
])
java = str(Path(os.environ['JAVA_HOME']) / 'bin/java')
with tempfile.TemporaryDirectory(prefix='lan-voice-expression-check-') as output:
subprocess.run([java, '-cp', compiler, 'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler',
'-no-stdlib', '-no-reflect', '-jvm-target', '17', '-classpath', stdlib, '-d', output,
'app/src/main/java/com/gorios/lanvoice/expression/ExpressionRules.kt',
'tests/expression/ExpressionRulesCheck.kt'], check=True)
subprocess.run([java, '-cp', output + ':' + stdlib, 'ExpressionRulesCheckKt'], check=True)
PY
+98
View File
@@ -0,0 +1,98 @@
"""Build inputs only. Never handles camera frames, blendshapes or user data."""
import hashlib
import re
import tempfile
import urllib.request
import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
VERSIONS = ROOT / "gradle/expression-versions.properties"
MODEL = ROOT / "app/src/main/assets/face_landmarker.task"
MODEL_HASH = ROOT / "gradle/face-landmarker-model.sha256"
MODEL_URL = (
"https://storage.googleapis.com/mediapipe-models/face_landmarker/"
"face_landmarker/float16/1/face_landmarker.task"
)
GOOGLE_MAVEN = "https://dl.google.com/dl/android/maven2"
def fetch(url):
request = urllib.request.Request(url, headers={"User-Agent": "lan-voice-build/0.2"})
with urllib.request.urlopen(request, timeout=60) as response:
return response.read()
def stable_versions(path):
root = ET.fromstring(fetch(f"{GOOGLE_MAVEN}/{path}/maven-metadata.xml"))
return {node.text for node in root.findall("versioning/versions/version")
if node.text and re.fullmatch(r"\d+(?:\.\d+){2,}", node.text)}
def newest(versions):
if not versions:
raise RuntimeError("No common stable version found in official Maven metadata")
return max(versions, key=lambda value: tuple(map(int, value.split("."))))
def atomic_write(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as temporary:
temporary.write(data)
staging = Path(temporary.name)
try:
staging.replace(path)
finally:
staging.unlink(missing_ok=True)
def main():
if not VERSIONS.exists():
mediapipe = newest(stable_versions("com/google/mediapipe/tasks-vision"))
# All four CameraX modules use one common stable version; never use '+' at build time.
modules = ("camera-core", "camera-camera2", "camera-lifecycle", "camera-view")
camera_versions = [stable_versions(f"androidx/camera/{module}") for module in modules]
camera = newest(set.intersection(*camera_versions))
atomic_write(VERSIONS, (
"# Selected from official Google Maven stable versions; keep this file for reproducibility.\n"
f"mediapipe.version={mediapipe}\ncamerax.version={camera}\n"
).encode())
print(f"Pinned tasks-vision {mediapipe}, CameraX {camera}")
else:
values = dict(re.findall(r"^(mediapipe\.version|camerax\.version)=(.+)$",
VERSIONS.read_text(), re.MULTILINE))
if set(values) != {"mediapipe.version", "camerax.version"} or any(
not re.fullmatch(r"\d+(?:\.\d+){2,}", value) for value in values.values()
):
raise RuntimeError("Invalid pinned expression dependency versions")
if not MODEL.exists():
if MODEL_HASH.exists():
# Re-downloading must match the model already accepted for this repository.
expected = MODEL_HASH.read_text().split()[0]
else:
expected = None
data = fetch(MODEL_URL)
digest = hashlib.sha256(data).hexdigest()
if expected and digest != expected:
raise RuntimeError("Downloaded model does not match recorded SHA256")
atomic_write(MODEL, data)
if not zipfile.is_zipfile(MODEL):
raise RuntimeError("face_landmarker.task must be the official task bundle, not an HTML download")
with zipfile.ZipFile(MODEL) as bundle:
if not any("blendshape" in name and name.endswith(".tflite") for name in bundle.namelist()):
raise RuntimeError("Face model bundle is missing its blendshape model")
digest = hashlib.sha256(MODEL.read_bytes()).hexdigest()
if MODEL_HASH.exists():
if MODEL_HASH.read_text().split()[0] != digest:
raise RuntimeError("Packaged face model does not match recorded SHA256")
else:
# First download uses HTTPS TOFU, as with the Gradle dependency metadata.
atomic_write(MODEL_HASH, f"{digest} app/src/main/assets/face_landmarker.task\n".encode())
print(f"Face model ready: {digest}")
if __name__ == "__main__":
main()
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
# External-shell bootstrap: pin stable dependencies once and package the official CPU model.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
python3 "$ROOT/scripts/prepare-expression.py"
+99
View File
@@ -0,0 +1,99 @@
import com.gorios.lanvoice.expression.ExpressionCue
import com.gorios.lanvoice.expression.ExpressionRules
import com.gorios.lanvoice.expression.FaceObservation
import com.gorios.lanvoice.expression.HeadPose
import kotlin.math.cos
import kotlin.math.sin
// Synthetic timelines only. No camera inputs, persisted coefficients or Android test dependency.
private val center = FaceObservation(emptyMap(), HeadPose(0f, 0f, 0f))
private fun observation(vararg values: Pair<String, Float>) = FaceObservation(values.toMap(), center.pose)
private fun prime(rules: ExpressionRules) {
for (time in 0L..600L step 100) rules.evaluate(center, time)
}
fun main() {
val rules = ExpressionRules()
check(rules.evaluate(null, 0).isEmpty())
for (time in 100L..500L step 100) rules.evaluate(null, time)
check(rules.evaluate(null, 600) == setOf(ExpressionCue.FACE_LOST))
check(rules.evaluate(center, 700).isEmpty())
check(ExpressionCue.FACE_PRESENT !in rules.evaluate(center, 800))
check(ExpressionCue.FACE_PRESENT in rules.evaluate(center, 900))
rules.reset()
prime(rules)
val smile = observation("mouthSmileLeft" to .8f, "mouthSmileRight" to .8f)
check(ExpressionCue.SMILING !in rules.evaluate(smile, 700))
check(ExpressionCue.SMILING !in rules.evaluate(center, 800)) // Single spike must not latch.
for (time in 900L..1_200L step 100) rules.evaluate(smile, time)
check(ExpressionCue.SMILING in rules.evaluate(smile, 1_300))
check(ExpressionCue.SMILING in rules.evaluate(observation("mouthSmileLeft" to .45f,
"mouthSmileRight" to .45f), 1_400)) // Hysteresis suppresses threshold chatter.
check(ExpressionCue.SMILING !in rules.evaluate(center, 1_500))
rules.reset()
prime(rules)
val unilateralBrow = observation("browDownLeft" to .9f, "browDownRight" to .1f)
for (time in 700L..1_200L step 100) {
check(ExpressionCue.BROW_FURROWED !in rules.evaluate(unilateralBrow, time))
}
val bilateralBrow = observation("browDownLeft" to .6f, "browDownRight" to .6f)
for (time in 1_300L..1_600L step 100) rules.evaluate(bilateralBrow, time)
check(ExpressionCue.BROW_FURROWED in rules.evaluate(bilateralBrow, 1_700))
rules.reset()
prime(rules)
val closed = observation("eyeBlinkLeft" to .9f, "eyeBlinkRight" to .9f)
for (time in 700L..1_600L step 100) {
check(ExpressionCue.EYES_CLOSED_LONG !in rules.evaluate(closed, time))
}
check(ExpressionCue.EYES_CLOSED_LONG in rules.evaluate(closed, 1_700))
check(ExpressionCue.GAZE_CENTER !in rules.evaluate(closed, 1_800))
check(ExpressionCue.EYES_CLOSED_LONG !in rules.evaluate(center, 1_900))
for (time in 2_000L..2_900L step 100) rules.evaluate(closed, time)
check(ExpressionCue.EYES_CLOSED_LONG !in rules.evaluate(closed, 4_000)) // 1.1s gap resets timers.
rules.reset()
prime(rules)
var frequent = emptySet<ExpressionCue>()
for (time in 700L..12_000L step 100) {
frequent = rules.evaluate(if (time % 1_000 in 0L..100L) closed else center, time)
if (time < 10_200) check(ExpressionCue.EYES_CLOSED_LONG !in frequent)
}
check(ExpressionCue.EYES_CLOSED_LONG in frequent)
for (time in 12_100L..23_000L step 100) frequent = rules.evaluate(center, time)
check(ExpressionCue.EYES_CLOSED_LONG !in frequent)
rules.reset()
prime(rules)
val left = observation("eyeLookOutLeft" to .7f, "eyeLookInRight" to .7f)
for (time in 700L..1_000L step 100) rules.evaluate(left, time)
check(ExpressionCue.GAZE_LEFT in rules.evaluate(left, 1_100))
check(ExpressionCue.GAZE_RIGHT !in rules.evaluate(left, 1_200))
check(rules.evaluate(null, 1_300) == setOf(ExpressionCue.FACE_PRESENT)) // No stale feature labels.
for (time in 1_400L..1_800L step 100) rules.evaluate(null, time)
check(rules.evaluate(null, 1_900) == setOf(ExpressionCue.FACE_LOST))
rules.reset()
prime(rules)
val rightHead = FaceObservation(emptyMap(), HeadPose(-25f, 0f, 0f))
for (time in 700L..1_000L step 100) rules.evaluate(rightHead, time)
check(ExpressionCue.GAZE_RIGHT in rules.evaluate(rightHead, 1_100))
check(ExpressionCue.GAZE_RIGHT in rules.evaluate(FaceObservation(emptyMap(), HeadPose(-15f, 0f, 0f)), 1_200))
val angle = Math.toRadians(25.0)
val c = cos(angle).toFloat()
val s = sin(angle).toFloat()
val matrix = floatArrayOf(c, 0f, -s, 0f, 0f, 1f, 0f, 0f, s, 0f, c, 0f, 0f, 0f, 0f, 1f)
check(kotlin.math.abs(checkNotNull(HeadPose.fromMatrix(matrix)).yaw - 25f) < .01f)
check(HeadPose.fromMatrix(FloatArray(16)) == null)
check(HeadPose.fromMatrix(FloatArray(16) { Float.NaN }) == null)
val visible = ExpressionRules.visible(ExpressionCue.entries.toSet())
check(visible == listOf(ExpressionCue.FACE_LOST, ExpressionCue.EYES_CLOSED_LONG))
check(ExpressionRules.visible(setOf(ExpressionCue.FACE_PRESENT, ExpressionCue.GAZE_CENTER)).size == 2)
rules.reset()
check(rules.evaluate(center, 0).isEmpty())
println("PASS: face debounce, smile hysteresis, bilateral brow, eye duration/gaps/blink window, gaze/head pose, loss/reset and 2-label limit")
}