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,
)
}
}