feat: refine role expression and diagnose camera context in 0.5.2

This commit is contained in:
zenord
2026-10-12 14:02:14 +08:00
parent 18ec4c2104
commit 4d305ad0df
26 changed files with 461 additions and 123 deletions
+2 -2
View File
@@ -45,8 +45,8 @@ android {
applicationId 'com.gorios.lanvoice' applicationId 'com.gorios.lanvoice'
minSdk 26 minSdk 26
targetSdk 34 targetSdk 34
versionCode 9 versionCode 10
versionName '0.5.1' versionName '0.5.2'
ndk { abiFilters 'arm64-v8a' } ndk { abiFilters 'arm64-v8a' }
} }
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 } compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
@@ -124,6 +124,8 @@ class MainActivity : ComponentActivity() {
cameraStatus = expressionState.status, cameraStatus = expressionState.status,
cameraPermissionPending = cameraGate.permissionPending, cameraPermissionPending = cameraGate.permissionPending,
faceSharing = shareFace, faceSharing = shareFace,
cameraAnalysis = expressions.diagnosticsSnapshot(),
faceTransmission = session.faceDiagnosticsSnapshot(),
rolePlaying = state.phase == VoicePhase.ANSWERING, rolePlaying = state.phase == VoicePhase.ANSWERING,
role = state.replyEmotion.takeIf { it.turnId != null }, role = state.replyEmotion.takeIf { it.turnId != null },
previousRole = state.previousReplyEmotion, previousRole = state.previousReplyEmotion,
@@ -14,6 +14,9 @@ import com.gorios.lanvoice.net.EventKind
import com.gorios.lanvoice.net.ServerEvent import com.gorios.lanvoice.net.ServerEvent
import com.gorios.lanvoice.expression.FaceCue import com.gorios.lanvoice.expression.FaceCue
import com.gorios.lanvoice.expression.FaceCueObservation import com.gorios.lanvoice.expression.FaceCueObservation
import com.gorios.lanvoice.expression.FaceCueReason
import com.gorios.lanvoice.expression.FaceSendReason
import com.gorios.lanvoice.expression.FaceTransmissionDiagnostics
enum class VoicePhase { IDLE, LISTENING, RECOGNIZING, THINKING, ANSWERING } enum class VoicePhase { IDLE, LISTENING, RECOGNIZING, THINKING, ANSWERING }
@@ -59,15 +62,11 @@ class VoiceSession(
private var faceSupported = false private var faceSupported = false
private var faceCue = FaceCueObservation() private var faceCue = FaceCueObservation()
private var faceSent = false private var faceSent = false
private val faceDiagnostics = FaceTransmissionDiagnostics()
private val faceTick = object : Runnable { private val faceTick = object : Runnable {
override fun run() { override fun run() {
if (!faceSharing || released) return if (!faceSharing || released) return
if (isActive() && faceSupported && hasTurn) { sendFaceContext()
val age = SystemClock.elapsedRealtime() - faceCue.observedAtMs
if (dialogue.sendFaceCue(currentTurn, faceCue, age)) {
faceSent = faceCue.cue != FaceCue.UNKNOWN && age in 0..3_000
}
}
main.postDelayed(this, 1_000L) main.postDelayed(this, 1_000L)
} }
} }
@@ -215,6 +214,8 @@ class VoiceSession(
main.removeCallbacks(faceTick) main.removeCallbacks(faceTick)
if (!enabled) clearFaceContext() if (!enabled) clearFaceContext()
faceSharing = enabled faceSharing = enabled
diagnostic("face sharing enabled=$enabled")
if (!enabled) faceDiagnostics.record(FaceSendReason.SHARING_OFF)
if (enabled && !released) main.post(faceTick) if (enabled && !released) main.post(faceTick)
} }
@@ -224,12 +225,42 @@ class VoiceSession(
faceCue = observation faceCue = observation
} }
private fun clearFaceContext() { private fun clearFaceContext(clearObservation: Boolean = true) {
if (faceSent && faceSupported && state.connection == ConnectionStatus.CONNECTED && hasTurn) { if (faceSent && faceSupported && state.connection == ConnectionStatus.CONNECTED && hasTurn) {
dialogue.sendFaceCue(currentTurn, FaceCueObservation(), 0) val sent = dialogue.sendFaceCue(currentTurn, FaceCueObservation(), 0)
faceDiagnostics.record(if (sent) FaceSendReason.CLEARED else FaceSendReason.CLEAR_FAILED)
} }
faceSent = false faceSent = false
faceCue = FaceCueObservation() if (clearObservation) faceCue = FaceCueObservation()
}
fun faceDiagnosticsSnapshot() = faceDiagnostics.snapshot()
private fun sendFaceContext() {
val now = SystemClock.elapsedRealtime()
val age = now - faceCue.observedAtMs
val reason = when {
!faceSharing -> FaceSendReason.SHARING_OFF
!foreground -> FaceSendReason.BACKGROUND
state.connection != ConnectionStatus.CONNECTED -> FaceSendReason.NOT_CONNECTED
!state.voiceActive -> FaceSendReason.VOICE_INACTIVE
!faceSupported -> FaceSendReason.UNSUPPORTED
!hasTurn -> FaceSendReason.NO_TURN
faceCue.cue == FaceCue.UNKNOWN -> if (faceCue.reason == FaceCueReason.NO_FACE) FaceSendReason.NO_FACE else FaceSendReason.NO_STABLE_CUE
age !in 0..3_000 -> FaceSendReason.STALE
!faceCue.intensity.isFinite() || faceCue.intensity !in .5f..1f || faceCue.durationMs !in 800..10_000 -> FaceSendReason.INVALID_CUE
else -> null
}
if (reason != null) {
// Send a one-shot clear for a previously published observation; no repeated unknown controls.
if (reason in setOf(FaceSendReason.STALE, FaceSendReason.INVALID_CUE, FaceSendReason.NO_FACE, FaceSendReason.NO_STABLE_CUE)) clearFaceContext(clearObservation = false)
faceDiagnostics.record(reason)
} else {
val sent = dialogue.sendFaceCue(currentTurn, faceCue, age)
if (sent) faceSent = true
faceDiagnostics.record(if (sent) FaceSendReason.SENT else FaceSendReason.SEND_FAILED, faceCue.cue)
}
faceDiagnostics.summary(now)?.let { diagnostic(it) }
} }
private fun onConnection(connection: ConnectionStatus, reason: String) { private fun onConnection(connection: ConnectionStatus, reason: String) {
@@ -2,6 +2,8 @@ package com.gorios.lanvoice.diag
import com.gorios.lanvoice.dialogue.ReplyEmotion import com.gorios.lanvoice.dialogue.ReplyEmotion
import com.gorios.lanvoice.expression.ExpressionStatus import com.gorios.lanvoice.expression.ExpressionStatus
import com.gorios.lanvoice.expression.CameraAnalysisSnapshot
import com.gorios.lanvoice.expression.FaceTransmissionSnapshot
import okhttp3.Call import okhttp3.Call
import okhttp3.Callback import okhttp3.Callback
import okhttp3.ConnectionPool import okhttp3.ConnectionPool
@@ -35,6 +37,8 @@ data class DiagnosticReportInfo(
val rolePlaying: Boolean = false, val rolePlaying: Boolean = false,
val role: ReplyEmotion? = null, val role: ReplyEmotion? = null,
val previousRole: ReplyEmotion? = null, val previousRole: ReplyEmotion? = null,
val cameraAnalysis: CameraAnalysisSnapshot = CameraAnalysisSnapshot(),
val faceTransmission: FaceTransmissionSnapshot = FaceTransmissionSnapshot(),
) )
/** Explicit user submission, isolated from both voice traffic and per-entry debug uploads. */ /** Explicit user submission, isolated from both voice traffic and per-entry debug uploads. */
@@ -94,6 +98,15 @@ object DiagnosticReportUpload {
.put("role_playing", info.rolePlaying) .put("role_playing", info.rolePlaying)
.put("role_active", roleMetadata(info.role)) .put("role_active", roleMetadata(info.role))
.put("role_previous", roleMetadata(info.previousRole)) .put("role_previous", roleMetadata(info.previousRole))
.put("camera_analysis", JSONObject().put("received", info.cameraAnalysis.received)
.put("processed", info.cameraAnalysis.processed).put("failures", info.cameraAnalysis.failures)
.put("faces", info.cameraAnalysis.faceCount).put("cue", info.cameraAnalysis.cue.wire)
.put("reason", info.cameraAnalysis.reason.name.lowercase()).put("failure", info.cameraAnalysis.failure.name.lowercase())
.put("last_process_ms", info.cameraAnalysis.lastProcessMs))
.put("face_transmission", JSONObject().put("attempts", info.faceTransmission.attempts)
.put("sent", info.faceTransmission.sent).put("clears", info.faceTransmission.clears)
.put("failures", info.faceTransmission.failures).put("reason", info.faceTransmission.reason.name.lowercase())
.put("cue", info.faceTransmission.cue.wire))
.put("logs", logs) .put("logs", logs)
.toString().toRequestBody(json) .toString().toRequestBody(json)
client.newCall(Request.Builder().url(ENDPOINT).post(body).build()).enqueue(object : Callback { client.newCall(Request.Builder().url(ENDPOINT).post(body).build()).enqueue(object : Callback {
@@ -37,6 +37,7 @@ class ExpressionController(
} }
val rules = ExpressionRules() val rules = ExpressionRules()
val faceRules = FaceCueRules() val faceRules = FaceCueRules()
val diagnostics = CameraAnalysisDiagnostics()
var landmarker: FaceLandmarker? = null // Accessed only on this run's executor. var landmarker: FaceLandmarker? = null // Accessed only on this run's executor.
var analysis: ImageAnalysis? = null // Accessed only on main. var analysis: ImageAnalysis? = null // Accessed only on main.
var provider: ProcessCameraProvider? = null // Accessed only on main. var provider: ProcessCameraProvider? = null // Accessed only on main.
@@ -49,6 +50,16 @@ class ExpressionController(
private val main = Handler(Looper.getMainLooper()) private val main = Handler(Looper.getMainLooper())
private var current: Run? = null private var current: Run? = null
private var released = false private var released = false
private var lastDiagnostics = CameraAnalysisDiagnostics()
private val diagnosticTick = object : Runnable {
override fun run() {
val run = current ?: return
run.diagnostics.summary(SystemClock.elapsedRealtime())?.let { DebugLogUpload.log("audio", it) }
main.postDelayed(this, 10_000)
}
}
fun diagnosticsSnapshot(): CameraAnalysisSnapshot = lastDiagnostics.snapshot()
/** Called only after an explicit user toggle and CAMERA permission approval. */ /** Called only after an explicit user toggle and CAMERA permission approval. */
fun start() { fun start() {
@@ -60,6 +71,8 @@ class ExpressionController(
} }
val run = Run() val run = Run()
current = run current = run
lastDiagnostics = run.diagnostics
main.post(diagnosticTick)
onState(ExpressionUiState(ExpressionStatus.STARTING)) onState(ExpressionUiState(ExpressionStatus.STARTING))
// Model loading and all synchronous VIDEO inference stay off the UI/audio threads. // Model loading and all synchronous VIDEO inference stay off the UI/audio threads.
run.executor.execute { run.executor.execute {
@@ -148,6 +161,7 @@ class ExpressionController(
var bitmap: Bitmap? = null var bitmap: Bitmap? = null
try { try {
if (!run.active) return if (!run.active) return
run.diagnostics.received()
val now = SystemClock.elapsedRealtime() val now = SystemClock.elapsedRealtime()
if (run.lastSampleMs != Long.MIN_VALUE && now - run.lastSampleMs < SAMPLE_INTERVAL_MS) return if (run.lastSampleMs != Long.MIN_VALUE && now - run.lastSampleMs < SAMPLE_INTERVAL_MS) return
run.lastSampleMs = now run.lastSampleMs = now
@@ -158,7 +172,10 @@ class ExpressionController(
run.landmarker?.detectForVideo(mpImage, now) run.landmarker?.detectForVideo(mpImage, now)
} finally { } finally {
mpImage.close() mpImage.close()
} ?: return } ?: kotlin.run {
run.diagnostics.failed(CameraFailure.NO_RESULT)
return
}
if (!run.active) return if (!run.active) return
val observation = if (result.faceLandmarks().isEmpty()) null else { val observation = if (result.faceLandmarks().isEmpty()) null else {
val categories = result.faceBlendshapes().orElse(emptyList()).firstOrNull().orEmpty() val categories = result.faceBlendshapes().orElse(emptyList()).firstOrNull().orEmpty()
@@ -176,6 +193,7 @@ class ExpressionController(
(landmarks.maxOf { it.x() } - landmarks.minOf { it.x() }) * (landmarks.maxOf { it.x() } - landmarks.minOf { it.x() }) *
(landmarks.maxOf { it.y() } - landmarks.minOf { it.y() }) >= .06f (landmarks.maxOf { it.y() } - landmarks.minOf { it.y() }) >= .06f
val faceCue = run.faceRules.evaluate(observation, result.faceLandmarks().size, quality, now) val faceCue = run.faceRules.evaluate(observation, result.faceLandmarks().size, quality, now)
run.diagnostics.processed(result.faceLandmarks().size, faceCue, SystemClock.elapsedRealtime() - now)
main.post { if (isCurrent(run)) onFaceCue(faceCue) } main.post { if (isCurrent(run)) onFaceCue(faceCue) }
// UI receives only <=2 enum labels; 52 coefficients, pose and images stay transient. // UI receives only <=2 enum labels; 52 coefficients, pose and images stay transient.
if (run.lastPublished != visible || run.lastStableCue != faceCue.cue) { if (run.lastPublished != visible || run.lastStableCue != faceCue.cue) {
@@ -197,6 +215,7 @@ class ExpressionController(
} }
private fun fail(run: Run, guidance: String, reason: String) { private fun fail(run: Run, guidance: String, reason: String) {
run.diagnostics.failed(CameraFailure.entries.firstOrNull { it.name.lowercase() == reason } ?: CameraFailure.ANALYSIS)
// Prevent another scheduled frame from running before main unbinds the camera. // Prevent another scheduled frame from running before main unbinds the camera.
run.active = false run.active = false
main.post { main.post {
@@ -212,6 +231,7 @@ class ExpressionController(
private fun stopCurrent() { private fun stopCurrent() {
val run = current ?: return val run = current ?: return
current = null // Invalidate every pending model/provider/result callback before unbinding. current = null // Invalidate every pending model/provider/result callback before unbinding.
main.removeCallbacks(diagnosticTick)
run.active = false run.active = false
try { try {
run.analysis?.clearAnalyzer() run.analysis?.clearAnalyzer()
@@ -232,6 +252,7 @@ class ExpressionController(
run.rules.reset() run.rules.reset()
run.faceRules.reset() run.faceRules.reset()
run.lastPublished = null run.lastPublished = null
run.diagnostics.summary(SystemClock.elapsedRealtime(), force = true)?.let { DebugLogUpload.log("audio", it) }
} }
} }
run.executor.shutdown() run.executor.shutdown()
@@ -1,6 +1,10 @@
package com.gorios.lanvoice.expression package com.gorios.lanvoice.expression
enum class FaceCue(val wire: String) { UNKNOWN("unknown"), SMILING("smiling"), BROW_FURROWED("brow_furrowed") } enum class FaceCue(val wire: String) { UNKNOWN("unknown"), SMILING("smiling"), BROW_FURROWED("brow_furrowed") }
enum class FaceCueReason {
NO_FRAME, NO_FACE, MULTIPLE_FACES, POOR_QUALITY, MISSING_COEFFICIENTS,
INVALID_COEFFICIENTS, CONFLICT, NO_CLEAR_CUE, STABILIZING, STABLE,
}
/** Rule intensity is an uncalibrated coefficient, never a probability or emotional state. */ /** Rule intensity is an uncalibrated coefficient, never a probability or emotional state. */
data class FaceCueObservation( data class FaceCueObservation(
@@ -8,6 +12,7 @@ data class FaceCueObservation(
val intensity: Float = 0f, val intensity: Float = 0f,
val durationMs: Long = 0, val durationMs: Long = 0,
val observedAtMs: Long = 0, val observedAtMs: Long = 0,
val reason: FaceCueReason = FaceCueReason.NO_FRAME,
) )
class FaceCueRules { class FaceCueRules {
@@ -22,24 +27,26 @@ class FaceCueRules {
val last = previous val last = previous
if (last != null && (nowMs <= last || nowMs - last > 500)) reset() if (last != null && (nowMs <= last || nowMs - last > 500)) reset()
previous = nowMs previous = nowMs
fun unknown(): FaceCueObservation { fun unknown(reason: FaceCueReason): FaceCueObservation {
candidate = FaceCue.UNKNOWN; active = false; since = nowMs candidate = FaceCue.UNKNOWN; active = false; since = nowMs
return FaceCueObservation(observedAtMs = nowMs) return FaceCueObservation(observedAtMs = nowMs, reason = reason)
} }
if (faceCount != 1 || !quality || observation == null) return unknown() if (faceCount == 0 || observation == null) return unknown(FaceCueReason.NO_FACE)
if (faceCount != 1) return unknown(FaceCueReason.MULTIPLE_FACES)
if (!quality) return unknown(FaceCueReason.POOR_QUALITY)
val names = listOf("mouthSmileLeft", "mouthSmileRight", "browDownLeft", "browDownRight") val names = listOf("mouthSmileLeft", "mouthSmileRight", "browDownLeft", "browDownRight")
val scores = names.map { observation.blendshapes[it] ?: return unknown() } val scores = names.map { observation.blendshapes[it] ?: return unknown(FaceCueReason.MISSING_COEFFICIENTS) }
if (scores.any { !it.isFinite() || it !in 0f..1f }) return unknown() if (scores.any { !it.isFinite() || it !in 0f..1f }) return unknown(FaceCueReason.INVALID_COEFFICIENTS)
val smile = minOf(scores[0], scores[1]) val smile = minOf(scores[0], scores[1])
val brow = minOf(scores[2], scores[3]) val brow = minOf(scores[2], scores[3])
val smiling = smile >= if (active && candidate == FaceCue.SMILING) .60f else .75f val smiling = smile >= if (active && candidate == FaceCue.SMILING) .60f else .75f
val furrowed = brow >= if (active && candidate == FaceCue.BROW_FURROWED) .50f else .65f val furrowed = brow >= if (active && candidate == FaceCue.BROW_FURROWED) .50f else .65f
if (smiling == furrowed) return unknown() // Conflict or no clear cue. if (smiling == furrowed) return unknown(if (smiling) FaceCueReason.CONFLICT else FaceCueReason.NO_CLEAR_CUE)
val next = if (smiling) FaceCue.SMILING else FaceCue.BROW_FURROWED val next = if (smiling) FaceCue.SMILING else FaceCue.BROW_FURROWED
if (candidate != next) { candidate = next; since = nowMs; active = false } if (candidate != next) { candidate = next; since = nowMs; active = false }
val duration = (nowMs - since).coerceIn(0, 10_000) val duration = (nowMs - since).coerceIn(0, 10_000)
if (duration < 800) return FaceCueObservation(observedAtMs = nowMs) if (duration < 800) return FaceCueObservation(observedAtMs = nowMs, reason = FaceCueReason.STABILIZING)
active = true active = true
return FaceCueObservation(next, if (smiling) smile else brow, duration, nowMs) return FaceCueObservation(next, if (smiling) smile else brow, duration, nowMs, FaceCueReason.STABLE)
} }
} }
@@ -0,0 +1,55 @@
package com.gorios.lanvoice.expression
/** Fixed fields only. No image, coefficient, pose, free text, or user speech. */
enum class CameraFailure { NONE, MODEL_LOAD, DEVICE_SUPPORT, NO_FRONT_CAMERA, CAMERA_BIND, ANALYSIS, NO_RESULT }
data class CameraAnalysisSnapshot(
val received: Int = 0, val processed: Int = 0, val failures: Int = 0,
val faceCount: Int = 0, val cue: FaceCue = FaceCue.UNKNOWN,
val reason: FaceCueReason = FaceCueReason.NO_FRAME, val failure: CameraFailure = CameraFailure.NONE,
val lastProcessMs: Long = 0,
)
class CameraAnalysisDiagnostics {
private var state = CameraAnalysisSnapshot()
private var lastLogMs: Long? = null
@Synchronized fun received() { state = state.copy(received = (state.received + 1).coerceAtMost(1_000_000)) }
@Synchronized fun processed(count: Int, cue: FaceCueObservation, elapsedMs: Long) {
state = state.copy(processed = (state.processed + 1).coerceAtMost(1_000_000),
faceCount = count.coerceIn(0, 2), cue = cue.cue, reason = cue.reason,
lastProcessMs = elapsedMs.coerceIn(0, 60_000))
}
@Synchronized fun failed(failure: CameraFailure) {
state = state.copy(failures = (state.failures + 1).coerceAtMost(1_000_000), failure = failure)
}
@Synchronized fun snapshot() = state
@Synchronized fun summary(nowMs: Long, force: Boolean = false): String? {
val last = lastLogMs
if (!force && last != null && nowMs - last < 10_000) return null
lastLogMs = nowMs
return "camera analysis received=${state.received} processed=${state.processed} failures=${state.failures} faces=${state.faceCount} cue=${state.cue.wire} reason=${state.reason.name.lowercase()} failure=${state.failure.name.lowercase()} process_ms=${state.lastProcessMs}"
}
}
enum class FaceSendReason { SHARING_OFF, BACKGROUND, NOT_CONNECTED, VOICE_INACTIVE, UNSUPPORTED, NO_TURN,
NO_FACE, NO_STABLE_CUE, STALE, INVALID_CUE, SENT, SEND_FAILED, CLEARED, CLEAR_FAILED }
data class FaceTransmissionSnapshot(val attempts: Int = 0, val sent: Int = 0, val clears: Int = 0,
val failures: Int = 0, val reason: FaceSendReason = FaceSendReason.SHARING_OFF, val cue: FaceCue = FaceCue.UNKNOWN)
class FaceTransmissionDiagnostics {
private var state = FaceTransmissionSnapshot()
private var lastLogMs: Long? = null
fun record(reason: FaceSendReason, cue: FaceCue = FaceCue.UNKNOWN) {
val attempt = reason in setOf(FaceSendReason.SENT, FaceSendReason.SEND_FAILED, FaceSendReason.CLEARED, FaceSendReason.CLEAR_FAILED)
state = state.copy(reason = reason, cue = cue,
attempts = (state.attempts + if (attempt) 1 else 0).coerceAtMost(1_000_000),
sent = (state.sent + if (reason == FaceSendReason.SENT) 1 else 0).coerceAtMost(1_000_000),
clears = (state.clears + if (reason == FaceSendReason.CLEARED) 1 else 0).coerceAtMost(1_000_000),
failures = (state.failures + if (reason in setOf(FaceSendReason.SEND_FAILED, FaceSendReason.CLEAR_FAILED)) 1 else 0).coerceAtMost(1_000_000))
}
fun snapshot() = state
fun summary(nowMs: Long): String? {
val last = lastLogMs
if (last != null && nowMs - last < 10_000) return null
lastLogMs = nowMs
return "face transmission attempts=${state.attempts} sent=${state.sent} clears=${state.clears} failures=${state.failures} reason=${state.reason.name.lowercase()} cue=${state.cue.wire}"
}
}
+33
View File
@@ -0,0 +1,33 @@
# Android 0.5.2 / gateway 0.7.3
The report received on 2026-10-12 at 13:41:02 +08:00 came from an alps/API31 device running 0.5.1/code9. Five retained rounds were model-selected neutral0/strict_json/stop, with no fallback or discarded nonneutral event. The camera reached ACTIVE and later stopped on background; none of those rounds used face context. That establishes the symptom in those retained rounds, not that neutral was semantically incorrect or that the camera hardware failed. User speech, model envelopes and raw face data were not read for this investigation.
## Role expression
The single system now explains seven reply intents and strengths: objective facts neutral0, warm congratulations/relaxed joy happy1, strong joy happy2, restrained disapproval angry1, strong anger angry2, gentle regret/empathy sad1, deep sadness sad2. Classification follows the character's actual reply intent, not a user's emotional word, negation, quotation, another person's emotion or face. It no longer says ordinary questions default to neutral regardless of a warm reply. Objective answers remain neutral; no emotion quota or probability is introduced. Persona style/content/safety rules remain intact.
The exact verified Qwen endpoint still uses json_schema, thinking=false, max_tokens160, one system and one request. The simple schema and parser cross-field checks are unchanged; neutral0 fallback with finite reasons, reply-only history/TTS and one streaming generator remain. Doubao provider switching and private Authorization/template settings are retained; unverified providers remain prompt-only unless explicitly configured after verification. ASR/TTS voice/parameters/models are unchanged.
## Camera diagnostics
Frame arrival and successful processing counts, failures, bounded face count (0/1/2), latest stable cue, last processing duration and fixed reasons are recorded for each local camera run. `camera_analysis` in an explicit diagnostic report is the current or last run snapshot; the existing camera status distinguishes a running camera from a stopped run. Reasons distinguish no frame, no face, multiple faces, poor quality, missing/invalid coefficients, conflicting cues, no clear cue, stabilizing and stable. Failures use fixed stage enums (model_load/device_support/no_front_camera/camera_bind/analysis/no_result), never raw exception strings.
Camera summaries and transmission summaries each emit at most once per10s, with one final camera summary during stop; there are no per-frame logs or cue-transition bursts. Frame analysis stays on its existing executor and the10Hz limit is unchanged. Counts are capped at1,000,000, durations at60,000ms. Camera permissions retain the foreground-only gate and explicit pending permission handling. Camera/share remain off by default; thresholds, pose/framing and800ms stability requirements are unchanged. No camera failure was established, so no threshold or model change is claimed.
`face_transmission` records activity-lifetime attempts, valid sends, clear sends, failures, last cue and fixed gating reason: sharing_off/background/not_connected/voice_inactive/unsupported/no_turn/no_face/no_stable_cue/stale/invalid_cue/sent/send_failed/cleared/clear_failed. Sharing toggle is explicit. Controls retain the existing1s send interval. Unknown observations no longer produce redundant periodic clear messages; a previously sent cue still receives a one-shot clear on loss/staleness/disable, with existing server TTL protection if a clear cannot send. This is bounded control cleanup, not a proven repair of the user's camera detection. Protocol fields are unchanged; the local diagnostic reason is not inserted in face control payloads.
Gateway metrics snapshot finite `face_context` counters since that socket began, with receive/use reasons and used cue for the current reply turn. Receive rejection distinguishes malformed fields/version/turn/age/duration/intensity/cue/clear. Snapshot use distinguishes no cue/clear/new turn/consumed/wrong turn/stale/used. No extra model request or wait for a camera is introduced. Old clients/reports remain accepted. All images, video, coefficients, landmarks, pose, speech and raw model output remain excluded from these new logs/reports; only enums/counts/times are added.
## Validation and release
Candidate prompt: six fixed public cases were run once each under the active Yangmi persona, with no resampling or conversation history. Results: fact neutral0; congratulations happy1; sympathy sad1; restrained disapproval angry1; objective emotion-word definition neutral0; negated emotional phrase followed by arithmetic neutral0. All HTTP200/SSE[DONE]/model/strict_json/stop at160-token budget, reply lengths4/33/38/33/21/8. These are finite-case intent checks, not an accuracy estimate or proof about the user's prior five dialogues. Strong intensity2 is covered by model-free7-state/cross-field tests, not claimed as real-model acceptance in this six-case run. First content257.77–439.19ms; full structure1258.83–3287.67ms; waiting after first content819.64–2975.24ms. Usage absent does not mean zero tokens.
The full isolated gateway suite and eight JVM suite entry points cover parser states/types/finish reasons/provider isolation, single system/LLM/TTS, cancellation/turn/seq/current-vs-previous labels, face stability/TTL/clear, camera permission lifecycle, no-face/stable/failure/send gating and10s summary rate/privacy. Android builds through scripts/build.sh with the existing JDK17 environment. APK is0.5.2/code10, arm64-v8a/minSdk26, verified against retained0.5.1 signature and HTTP bytes. Only0.5.1 and0.5.2 artifacts are retained for this release; no old APK is regenerated or deleted. No automatic USB install or device permission control occurs.
Deployment remains canonical gateway/, hash/busy/unit/environment fenced with source/mode/private-loading backup on the server, restarting only gateway. Rollback: python3 scripts/rollback-gateway-source.py for the exact deployment record; checks remain mandatory. APK rollback file is artifacts/lan-voice-v051-arm64-debug.apk. Android generally rejects a lower versionCode over an installed higher version; retaining the file does not promise a data-preserving downgrade. User data/device changes are not performed here.
Actual numeric release/full-chain artifacts are ignored under logs/emotion-052/ and logs/voice-investigation/. Real camera capture/frames/face recognition, alps and MI MAX phone behavior, phone audio audibility, long-session latency/semantic quality and the original user's conversations remain untested. New camera diagnostics become available only after installing0.5.2 and explicitly sending a report.
Completed release:74 gateway tests passed in0.975s during deployment; all eight JVM entry points passed. One public audio round after deployment was happy1/model/strict_json/stop, one LLM and one TTS request, emotion before PCM,476160 PCM bytes and drained acknowledged. Synthetic smiling context was received1/accepted1/rejected0 and use_reason=used; it does not validate a real camera. LLM first content338.90ms, full structure2903.96ms, structure wait2565.06ms, TTS first PCM199.08ms, capture end to first PCM3153.46ms. Nonzero structure waiting remains significant.
APK: http://192.168.31.124:8080/lan-voice-v052-arm64-debug.apk (31510181bytes), SHA256 `b0618f7e6befdd4403287ccaddae353f8180fd3e461e0b09bc357d89501eb6a4`. Signature verified and certificate matches retained0.5.1. APK and .apk.sha256 HTTP200/download bytes verified. Backup for gateway rollback: `/home/gorios-spark-2/lan-voice/.runtime/backups/voice-gateway-20261012-135835`. Qwen3.8-27b/thinkingfalse/json_schema and private unit/environment were reverified unchanged. No USB installation was attempted.
+2
View File
@@ -34,3 +34,5 @@ Gateway 0.7.2 repairs the observed 0.5.1 `non_json/plain_text/stop` fallback by
Persona format rules now explicitly bind only spoken `reply`, preserving style/content/safety while removing the competing outer JSON prohibition. One system and the 160-token budget remain. JSON/labels still never enter speech or history, and each parsed reply uses one streaming TTS generator. Health/hello and numeric metrics expose the format mode; optional diagnostics remain compatible with the 0.5.1 APK. No Android update is needed. See ../docs/STRUCTURED_REPLY_072.md for compatibility evidence, rollout and limitations. Persona format rules now explicitly bind only spoken `reply`, preserving style/content/safety while removing the competing outer JSON prohibition. One system and the 160-token budget remain. JSON/labels still never enter speech or history, and each parsed reply uses one streaming TTS generator. Health/hello and numeric metrics expose the format mode; optional diagnostics remain compatible with the 0.5.1 APK. No Android update is needed. See ../docs/STRUCTURED_REPLY_072.md for compatibility evidence, rollout and limitations.
Deployment uses `deployment_baseline` in SOURCE_MANIFEST as the reviewed live hash fence, including the two whitelisted public persona lore JSON files. Ignored records no longer override the expected baseline. Backups retain all Python sources/tests, public persona lore, permissions and private unit/environment relationships on the server. The rollback script restores exactly the deployment whitelist and refuses busy/source/environment conflicts. Deployment uses `deployment_baseline` in SOURCE_MANIFEST as the reviewed live hash fence, including the two whitelisted public persona lore JSON files. Ignored records no longer override the expected baseline. Backups retain all Python sources/tests, public persona lore, permissions and private unit/environment relationships on the server. The rollback script restores exactly the deployment whitelist and refuses busy/source/environment conflicts.
Gateway0.7.3 / Android0.5.2 refines reply-intent rules with seven semantic examples and adds bounded camera/frame/transmission diagnostics. FaceContext emits finite receive/use reason/counters in per-turn metrics; counters are cumulative for the current socket, cue/use reason describes the current snapshot. Camera criteria and models remain unchanged. New diagnostic reports add camera_analysis (current/last run) and face_transmission (activity lifetime) snapshots; old reports are accepted. Each camera and transmission summary is limited to one per10s plus final camera stop summary. See ../docs/EMOTION_CAMERA_052.md for actual public-case results and test limits. Retained0.5.1 APK needs an update to0.5.2/code10 to supply the new camera fields.
+73 -71
View File
@@ -1,7 +1,7 @@
{ {
"baseline_android_commit": "9b428fb76ffa1468aa46124b33d9c598cf3740d8", "baseline_android_commit": "9b428fb76ffa1468aa46124b33d9c598cf3740d8",
"source": "SPARK-2 deployed lan-voice gateway", "source": "SPARK-2 deployed lan-voice gateway",
"code_version": "0.7.2 (streaming json_schema for verified local provider; reply.emotion version 1)", "code_version": "0.7.3 (role reply intent rules; bounded face pipeline diagnostics; schema)",
"python": "3.12.3", "python": "3.12.3",
"machine": "aarch64", "machine": "aarch64",
"scope": "whitelisted source only; no runtime/models/credentials", "scope": "whitelisted source only; no runtime/models/credentials",
@@ -27,14 +27,15 @@
"bytes": 554 "bytes": 554
}, },
"face_context.py": { "face_context.py": {
"source": "face_context.py", "source": "workspace:gateway/face_context.py",
"sha256": "01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a", "sha256": "d032ff8033a49219595d6edff2950856937e024782143621d37d02b56b024315",
"bytes": 2997 "bytes": 4561,
"upstream_sha256": "01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a"
}, },
"gateway.py": { "gateway.py": {
"source": "workspace:gateway/gateway.py", "source": "workspace:gateway/gateway.py",
"sha256": "06797c4d327977eef755f72db70ef91ff6925ca20cc5ae8a6cefb5ffa1890534", "sha256": "ea268a5abf36f79483427a78991d9ab2bab814ea3042ffcc08025de8c4af6b6d",
"bytes": 38786, "bytes": 38914,
"upstream_sha256": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce" "upstream_sha256": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce"
}, },
"guest_sessions.py": { "guest_sessions.py": {
@@ -228,14 +229,16 @@
"bytes": 2216 "bytes": 2216
}, },
"tests/test_face_context.py": { "tests/test_face_context.py": {
"source": "workspace:backend/test_face_context.py", "source": "workspace:gateway/tests/test_face_context.py",
"sha256": "50ca57adee1d07a194ebaa95b15e09d3e836b97b19490e99e3e045c72a89682c", "sha256": "c297866117fa7406b5fda95250b67ca7ebd7476486ddd5455935c140d31c9f6f",
"bytes": 1851 "bytes": 3230,
"upstream_sha256": "50ca57adee1d07a194ebaa95b15e09d3e836b97b19490e99e3e045c72a89682c"
}, },
"tests/test_gateway_reply_face.py": { "tests/test_gateway_reply_face.py": {
"source": "workspace:backend/test_gateway_reply_face.py", "source": "workspace:gateway/tests/test_gateway_reply_face.py",
"sha256": "4a4a8fd997941c0d92356c2ebab2c336abbcf84954735a6955d8fa7e3700ec3f", "sha256": "393c95b7e97981b46445cd699890bb7b732d1c479310daf09bdf2c8349e47f4c",
"bytes": 5320 "bytes": 5802,
"upstream_sha256": "4a4a8fd997941c0d92356c2ebab2c336abbcf84954735a6955d8fa7e3700ec3f"
}, },
"requirements.lock": { "requirements.lock": {
"source": "deployed interpreter distribution metadata", "source": "deployed interpreter distribution metadata",
@@ -249,8 +252,8 @@
}, },
"README.md": { "README.md": {
"source": "workspace:gateway/README.md", "source": "workspace:gateway/README.md",
"sha256": "8e13b5532e5af921b411d5fa8185e9e8efbef42859f47ec3615099bb87304c10", "sha256": "a558871dd83dd5c764c9cc3ba9b769c180bf8865adfc52ffed7fbbc93a5ca29a",
"bytes": 9220, "bytes": 9974,
"upstream_sha256": "799bc84308eb17d58987c5bee8ce3cf7617b4c52169d9307d344ac7d9996b6c5" "upstream_sha256": "799bc84308eb17d58987c5bee8ce3cf7617b4c52169d9307d344ac7d9996b6c5"
}, },
"config/active_profile.json.example": { "config/active_profile.json.example": {
@@ -275,8 +278,8 @@
}, },
"env.example": { "env.example": {
"source": "workspace:gateway/env.example", "source": "workspace:gateway/env.example",
"sha256": "ccc97d0e357d8120303cedf7947e1ba302070980a14cc8801f2424344fcab820", "sha256": "b0c591d5e253ea4ea3ca1b177f4670a8939cfdba5c662cdaedbff7a95418ee85",
"bytes": 1115, "bytes": 1266,
"upstream_sha256": "d92e60812f49b02f3b0582d8b3dee03eb51cfca6dba77d9468a3ffddfce32499" "upstream_sha256": "d92e60812f49b02f3b0582d8b3dee03eb51cfca6dba77d9468a3ffddfce32499"
}, },
"pytest.ini": { "pytest.ini": {
@@ -286,8 +289,8 @@
}, },
"reply_emotion.py": { "reply_emotion.py": {
"source": "workspace:gateway/reply_emotion.py", "source": "workspace:gateway/reply_emotion.py",
"sha256": "a32b9dedc135cac1ed6f25f33123946152a6bd3dc8d0d816a897c00b9e444ead", "sha256": "080f04e368c5a7d26254f2b870803238941aa481d457227ba15a870fd4a4e3c0",
"bytes": 4343, "bytes": 5455,
"upstream_sha256": "488fbd24ff1ce7d3d4ab92257c8ccabafe24fc857e11c8486f54fa689276a565" "upstream_sha256": "488fbd24ff1ce7d3d4ab92257c8ccabafe24fc857e11c8486f54fa689276a565"
}, },
"scripts/check-archive.py": { "scripts/check-archive.py": {
@@ -298,8 +301,8 @@
}, },
"tests/test_gateway_emotion.py": { "tests/test_gateway_emotion.py": {
"source": "workspace:gateway/tests/test_gateway_emotion.py", "source": "workspace:gateway/tests/test_gateway_emotion.py",
"sha256": "51a8f751d14345fe2ccf3afd9250b0962f0ab260a97023afcee4a7b9b0f535d0", "sha256": "234310a9f44e3ece56482f4e2080e4f0882d1ea8b7dcd85795c816a8c1ebed78",
"bytes": 8535, "bytes": 8596,
"upstream_sha256": "86f22211e753e4b5ebfa11266e2e33eb2ea6b85707fbe8a988be6b8ff05f3f75" "upstream_sha256": "86f22211e753e4b5ebfa11266e2e33eb2ea6b85707fbe8a988be6b8ff05f3f75"
}, },
"tests/test_reply_emotion.py": { "tests/test_reply_emotion.py": {
@@ -322,7 +325,7 @@
} }
}, },
"archive_baseline_commit": "19a7adccd9322986eb0646b165b9ce1cf2650cf2", "archive_baseline_commit": "19a7adccd9322986eb0646b165b9ce1cf2650cf2",
"workspace_release": "0.5.1", "workspace_release": "0.5.2",
"provider_baseline": { "provider_baseline": {
"source": "SPARK2 whitelist observed 2026-10-12", "source": "SPARK2 whitelist observed 2026-10-12",
"files": { "files": {
@@ -352,6 +355,55 @@
}, },
"release_baseline_commit": "d43c7d4e809a5a6b18ca9f28c8163a2f9ad34c7f", "release_baseline_commit": "d43c7d4e809a5a6b18ca9f28c8163a2f9ad34c7f",
"deployment_baseline": { "deployment_baseline": {
"release": "gateway-0.7.3 / Android-0.5.2",
"files": {
"app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f",
"face_context.py": "d032ff8033a49219595d6edff2950856937e024782143621d37d02b56b024315",
"gateway.py": "ea268a5abf36f79483427a78991d9ab2bab814ea3042ffcc08025de8c4af6b6d",
"guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82",
"history.py": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f",
"llm_provider.py": "21aa2885c24f3240e891fd5325b09446ae1d8a95497d07a53082410d9fac2b10",
"persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de",
"personas/lvbu.lorebook.json": "1f144b431bdd5d9cda0ce593438fa88e717c0671d496105883a3d4db7bd635ea",
"personas/yangmi.lorebook.json": "73badae3fd8582555caa338e50fb6193e64e6a43025dd469672aa903c1c4b71b",
"protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5",
"reply_emotion.py": "080f04e368c5a7d26254f2b870803238941aa481d457227ba15a870fd4a4e3c0",
"segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d",
"tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae",
"tests/test_debug.py": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e",
"tests/test_face_context.py": "c297866117fa7406b5fda95250b67ca7ebd7476486ddd5455935c140d31c9f6f",
"tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104",
"tests/test_gateway_emotion.py": "234310a9f44e3ece56482f4e2080e4f0882d1ea8b7dcd85795c816a8c1ebed78",
"tests/test_gateway_reply_face.py": "393c95b7e97981b46445cd699890bb7b732d1c479310daf09bdf2c8349e47f4c",
"tests/test_guests.py": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35",
"tests/test_history.py": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78",
"tests/test_llm_provider.py": "43669d1fd7e61452b96f314a7f161fbcec843e463c74208d0f892fb58b839785",
"tests/test_personas.py": "013b18e7b7f0e582d8d7e04f5b1fb78009e993f96357be67a5367e70444b43e1",
"tests/test_reply_emotion.py": "4ff2774187df8220ddbc8ef5b79910ae5047af3bacdb9476b0d2a8f55929d3be",
"tests/test_segmentation.py": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463",
"tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082",
"tests/test_vad.py": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228",
"tests_fake.py": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8",
"tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2",
"vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23"
}
},
"server_capabilities": {
"structured_output_env": "LAN_LLM_STRUCTURED_OUTPUT",
"modes": [
"prompt",
"json_schema"
],
"verified_default": {
"base_url": "http://127.0.0.1:8888/v1",
"model": "qwen3.8-27b",
"chat_template_kwargs": {
"enable_thinking": false
}
},
"doubao_schema_verified": false
},
"previous_deployment_baseline": {
"release": "gateway-0.7.2 / Android-0.5.1", "release": "gateway-0.7.2 / Android-0.5.1",
"files": { "files": {
"app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f", "app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f",
@@ -384,55 +436,5 @@
"tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2", "tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2",
"vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23" "vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23"
} }
},
"server_capabilities": {
"structured_output_env": "LAN_LLM_STRUCTURED_OUTPUT",
"modes": [
"prompt",
"json_schema"
],
"verified_default": {
"base_url": "http://127.0.0.1:8888/v1",
"model": "qwen3.8-27b",
"chat_template_kwargs": {
"enable_thinking": false
}
},
"doubao_schema_verified": false
},
"previous_deployment_baseline": {
"release": "0.5.1",
"commit": "b521d368a5a5bab77599c860f651dce04b0de67e",
"files": {
"app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f",
"face_context.py": "01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a",
"gateway.py": "b8e64e9387fca05808fac61bd097ae179e996a2c7ccd33f23bb729a61693dd0d",
"guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82",
"history.py": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f",
"llm_provider.py": "56ce6c1a4a647dea6ef86a83615f03db3a4397ebb3fa800b7fa655147d4f9978",
"persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de",
"protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5",
"reply_emotion.py": "a2b6a1a51639d77368c200f2a6db8bb66fff1eebb4f60219d49da69ae402a8a2",
"segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d",
"tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae",
"tests/test_debug.py": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e",
"tests/test_face_context.py": "50ca57adee1d07a194ebaa95b15e09d3e836b97b19490e99e3e045c72a89682c",
"tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104",
"tests/test_gateway_emotion.py": "e4da9a092e6ee19ef421a43a04cd2b6d12cb65f1b210946092dcad016c8816bb",
"tests/test_gateway_reply_face.py": "4a4a8fd997941c0d92356c2ebab2c336abbcf84954735a6955d8fa7e3700ec3f",
"tests/test_guests.py": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35",
"tests/test_history.py": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78",
"tests/test_llm_provider.py": "45404653daa71a006a90852b2f07f00cac608bd7311dd5ea850da0c1a3e52940",
"tests/test_personas.py": "2576f2be903c69270cb1dec1e12448154554798bd7fca866d78e66e31594cbcb",
"tests/test_reply_emotion.py": "2bd1ee33f11e2d23ccf9a30603f0db3b9f20c6d5fce8001f37f9ca76167974dd",
"tests/test_segmentation.py": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463",
"tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082",
"tests/test_vad.py": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228",
"tests_fake.py": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8",
"tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2",
"vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23",
"personas/lvbu.lorebook.json": "266078a2aed07dcbcf3283ae102a8215cef6c181bb240ac5e53ee240414721e4",
"personas/yangmi.lorebook.json": "d3b0201dff992b1bd0258d4aa06f8e7688322c9904c0b885aa6cf7be7046717d"
}
} }
} }
+2
View File
@@ -17,3 +17,5 @@ LAN_LLM_CHAT_TEMPLATE_KWARGS={"enable_thinking":false}
# model alias doubao-seed-2-1-pro, kwargs {}, LAN_LLM_STRUCTURED_OUTPUT=prompt. # model alias doubao-seed-2-1-pro, kwargs {}, LAN_LLM_STRUCTURED_OUTPUT=prompt.
# Reset this mode when switching providers; Doubao schema support is unverified. # Reset this mode when switching providers; Doubao schema support is unverified.
# Alias does not identify actual weights. # Alias does not identify actual weights.
# Gateway0.7.3 keeps this provider/schema contract and the160-token dialogue budget;
# camera/frame diagnostics do not add a model or inference retry.
+41 -11
View File
@@ -13,30 +13,51 @@ TEMPLATE = (
class FaceContext: class FaceContext:
def __init__(self): def __init__(self):
self.value = None self.value = None
self.received = self.accepted = self.rejected = self.clears = 0
self.receive_reason = 'not_received'
self.use_reason = 'not_taken'
self.state_reason = 'no_cue'
self.used_cue = 'unknown'
def clear(self): def clear(self, reason='cleared'):
self.value = None self.value = None
self.state_reason = reason
def diagnostics(self):
return {'received': self.received, 'accepted': self.accepted, 'rejected': self.rejected,
'clears': self.clears, 'receive_reason': self.receive_reason,
'use_reason': self.use_reason, 'cue': self.used_cue}
def update(self, data, turn, now=None): def update(self, data, turn, now=None):
self.clear() # Invalid observations must never leave an older cue latched. self.clear() # Invalid observations must never leave an older cue latched.
self.received = min(self.received + 1, 1_000_000)
def reject(reason):
self.rejected = min(self.rejected + 1, 1_000_000)
self.receive_reason = self.state_reason = reason
return False
allowed = {'type', 'version', 'turn_id', 'valid', 'cue', 'intensity', 'duration_ms', 'age_ms'} allowed = {'type', 'version', 'turn_id', 'valid', 'cue', 'intensity', 'duration_ms', 'age_ms'}
if not isinstance(data, dict) or set(data) != allowed: if not isinstance(data, dict) or set(data) != allowed:
return False return reject('invalid_fields')
if data['type'] != 'context.face_cue' or type(data['version']) is not int or data['version'] != 1: if data['type'] != 'context.face_cue' or type(data['version']) is not int or data['version'] != 1:
return False return reject('invalid_version')
if type(data['turn_id']) is not int or not 0 <= data['turn_id'] <= 0xffffffff or data['turn_id'] != turn: if type(data['turn_id']) is not int or not 0 <= data['turn_id'] <= 0xffffffff or data['turn_id'] != turn:
return False return reject('wrong_turn')
if type(data['valid']) is not bool: if type(data['valid']) is not bool:
return False return reject('invalid_valid')
age, duration, intensity = data['age_ms'], data['duration_ms'], data['intensity'] age, duration, intensity = data['age_ms'], data['duration_ms'], data['intensity']
if type(age) is not int or not 0 <= age <= 3000 or type(duration) is not int or not 0 <= duration <= 10000: if type(age) is not int or not 0 <= age <= 3000 or type(duration) is not int or not 0 <= duration <= 10000:
return False return reject('invalid_age_duration')
if type(intensity) not in (int, float) or not math.isfinite(intensity) or not 0 <= intensity <= 1: if type(intensity) not in (int, float) or not math.isfinite(intensity) or not 0 <= intensity <= 1:
return False return reject('invalid_intensity')
if not data['valid']: if not data['valid']:
return data['cue'] == 'unknown' and intensity == 0 and duration == 0 if data['cue'] != 'unknown' or intensity != 0 or duration != 0: return reject('invalid_clear')
self.clears = min(self.clears + 1, 1_000_000)
self.receive_reason = self.state_reason = 'explicit_clear'
return True
if data['cue'] not in ('smiling', 'brow_furrowed') or duration < 800 or intensity < .5: if data['cue'] not in ('smiling', 'brow_furrowed') or duration < 800 or intensity < .5:
return False return reject('invalid_cue')
self.accepted = min(self.accepted + 1, 1_000_000)
self.receive_reason = self.state_reason = 'accepted'
self.value = (turn, data['cue'], intensity, duration, age, time.monotonic() if now is None else now) self.value = (turn, data['cue'], intensity, duration, age, time.monotonic() if now is None else now)
return True return True
@@ -45,15 +66,24 @@ class FaceContext:
if self.value and self.value[0] == old_turn: if self.value and self.value[0] == old_turn:
self.value = (new_turn, *self.value[1:]) self.value = (new_turn, *self.value[1:])
else: else:
self.clear() self.clear('new_turn')
def take(self, turn, now=None): def take(self, turn, now=None):
value, self.value = self.value, None value, self.value = self.value, None
if value is None or value[0] != turn: self.used_cue = 'unknown'
if value is None:
self.use_reason = self.state_reason
return None
if value[0] != turn:
self.use_reason = self.state_reason = 'wrong_turn'
return None return None
_, cue, intensity, duration, age, received = value _, cue, intensity, duration, age, received = value
elapsed = ((time.monotonic() if now is None else now) - received) * 1000 elapsed = ((time.monotonic() if now is None else now) - received) * 1000
if elapsed < 0 or age + round(elapsed, 6) > 3000: if elapsed < 0 or age + round(elapsed, 6) > 3000:
self.use_reason = self.state_reason = 'stale'
return None return None
self.use_reason = 'used'
self.state_reason = 'consumed'
self.used_cue = cue
label = {'smiling': '明显、持续的嘴角上扬', 'brow_furrowed': '明显、持续的双侧眉头收紧'}[cue] label = {'smiling': '明显、持续的嘴角上扬', 'brow_furrowed': '明显、持续的双侧眉头收紧'}[cue]
return {'role': 'system', 'content': TEMPLATE.format(cue=label, intensity=round(intensity, 2), duration=duration)} return {'role': 'system', 'content': TEMPLATE.format(cue=label, intensity=round(intensity, 2), duration=duration)}
+4 -2
View File
@@ -30,7 +30,7 @@ from protocol import WavStream, pack, unpack
from vad import Config, Silero, VadSession from vad import Config, Silero, VadSession
ROOT = Path(__file__).resolve().parent ROOT = Path(__file__).resolve().parent
VERSION = '0.7.2' VERSION = '0.7.3'
DEFAULT_VOICE_ID = '9a97272c-3919-5606-9c8f-9552ab602528' DEFAULT_VOICE_ID = '9a97272c-3919-5606-9c8f-9552ab602528'
ORIGINS = {'https://192.168.31.61:5011', 'https://localhost:5011', 'https://127.0.0.1:5011'} ORIGINS = {'https://192.168.31.61:5011', 'https://localhost:5011', 'https://127.0.0.1:5011'}
@@ -425,6 +425,7 @@ class Dialogue:
face_message = self.face_context.take(turn) face_message = self.face_context.take(turn)
if face_message is not None: self.face_messages[turn] = [face_message] if face_message is not None: self.face_messages[turn] = [face_message]
metrics['face_cue_used'] = face_message is not None metrics['face_cue_used'] = face_message is not None
metrics['face_context'] = self.face_context.diagnostics()
text = text[:2000] text = text[:2000]
if self.history: if self.history:
recorded = True recorded = True
@@ -472,6 +473,7 @@ class Dialogue:
'\n\n' + item['content'] for item in self.face_messages.get(turn, [])) + '\n\n' + SYSTEM_FRAGMENT '\n\n' + item['content'] for item in self.face_messages.get(turn, [])) + '\n\n' + SYSTEM_FRAGMENT
messages = [{'role': 'system', 'content': system}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}] messages = [{'role': 'system', 'content': system}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}]
url, headers, body = self.llm_provider.request(messages, max_tokens=160) url, headers, body = self.llm_provider.request(messages, max_tokens=160)
metrics['llm_request_count'] = 1
raw_body = '' raw_body = ''
finish_reason = 'not_provided' finish_reason = 'not_provided'
usage = {} usage = {}
@@ -671,7 +673,7 @@ async def dialogue(ws: WebSocket):
if not isinstance(data, dict): raise ValueError('control object') if not isinstance(data, dict): raise ValueError('control object')
if data.get('type') == 'context.face_cue': if data.get('type') == 'context.face_cue':
if len(raw.encode('utf-8')) > 512: if len(raw.encode('utf-8')) > 512:
session.face_context.clear() session.face_context.clear('input_limit')
else: else:
session.face_context.update(data, session.turn) session.face_context.update(data, session.turn)
elif data.get('type') == 'debug': elif data.get('type') == 'debug':
+5 -1
View File
@@ -14,7 +14,11 @@ REPLY_SCHEMA = {
'additionalProperties': False, 'additionalProperties': False,
} }
SYSTEM_FRAGMENT = '''本轮只输出一个JSON对象,格式为{"reply":"简短中文回答","emotion":"neutral","intensity":0},不加代码围栏或额外文字。reply直接回答用户,最多两小句,不含情绪标签、动作旁白或思考过程。emotion是角色本轮表达意图,不是用户心理判断;只允许neutral(intensity=0)、happy/angry/sad(intensity=1轻度或2明显)。普通问答默认neutral;帮助性和用户台词优先,不为表演牺牲回答,不根据摄像头皱眉强行生气或攻击。每轮仅一个主情绪,无混合或长期状态。''' SYSTEM_FRAGMENT = '''本轮只输出一个JSON对象,字段reply为简短中文回答,emotion为neutral/happy/angry/sad,intensity为整数。无围栏或额外文字。reply直接回答用户,最多两小句,不含情绪标签、动作旁白或思考过程,保持角色风格与实际帮助。
emotion描述角色这句reply自身传达的态度和感受,不识别用户心理,不直接复制用户、人脸或第三方情绪。先按回复语义和表达意图选择,再给强度:neutral只配0,happy/angry/sad只配1轻度或2明显。温暖祝贺、欣慰和轻松欣喜可用happy1;惋惜、遗憾和共情可用sad1,不必因回复也是回答问题就中立。仅事实、操作说明或没有明显情感态度时neutral0。强度由reply实际措辞与意图决定,不能由用户使用“非常”等词决定。
七种意图示例(说明分类,不是固定台词):客观说明“水通常在一百度沸腾”→neutral0;温暖祝贺“做得好,替你开心”→happy1;明确强烈欢喜“太棒了,我真是开心极了”→happy2;克制不满“这处理确实不妥,我不赞同”→angry1;明确强烈愤怒“这太过分了,我非常气愤”→angry2;温和惋惜共情“真遗憾,这一定很不好受”→sad1;明确深切悲伤“听到这消息我非常难过”→sad2。
引用、否定、情绪词解释、讲述别人情绪不自动变成角色情绪;如客观解释愤怒仍可neutral。摄像头只供弱辅助,微笑不必高兴、皱眉不必生气。每轮只选一个主情绪,不混合,不强迫非中立,不输出概率。不为表演牺牲准确性或安全,不因愤怒辱骂攻击,不虚构亲历。'''
SAFE_REPLY = '抱歉,这次回答格式有误,请再说一次。' SAFE_REPLY = '抱歉,这次回答格式有误,请再说一次。'
@dataclass(frozen=True) @dataclass(frozen=True)
+25
View File
@@ -8,6 +8,31 @@ def cue(**changes):
class FaceContextTests(unittest.TestCase): class FaceContextTests(unittest.TestCase):
def test_diagnostics_use_clear_stale_and_rejected_without_raw_fields(self):
state=FaceContext()
self.assertIsNone(state.take(1))
self.assertEqual(state.diagnostics()['use_reason'],'no_cue')
state.update(cue(),1,now=100)
state.take(1,now=100)
self.assertEqual(state.diagnostics(),{'received':1,'accepted':1,'rejected':0,'clears':0,
'receive_reason':'accepted','use_reason':'used','cue':'smiling'})
state.update(cue(),1,now=100)
self.assertIsNone(state.take(1,now=103))
self.assertEqual(state.diagnostics()['use_reason'],'stale')
state.update(cue(turn_id=2),1,now=100)
state.take(1,now=100)
self.assertEqual(state.diagnostics()['use_reason'],'wrong_turn')
state.update(cue(valid=False,cue='unknown',intensity=0,duration_ms=0),1)
state.take(1)
self.assertEqual(state.diagnostics()['use_reason'],'explicit_clear')
state.update(cue(text='never-store-this',landmarks=[1]),1)
self.assertNotIn('never-store-this',str(state.diagnostics()))
self.assertEqual(state.diagnostics()['receive_reason'],'invalid_fields')
state.received=state.accepted=1_000_000
state.update(cue(),1)
self.assertEqual(state.diagnostics()['received'],1_000_000)
self.assertEqual(state.diagnostics()['accepted'],1_000_000)
def test_ttl_and_one_shot(self): def test_ttl_and_one_shot(self):
state = FaceContext() state = FaceContext()
self.assertTrue(state.update(cue(), 1, now=100)) self.assertTrue(state.update(cue(), 1, now=100))
+1
View File
@@ -77,6 +77,7 @@ class EmotionPipelineTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual((event['emotion'],event['intensity'],event['source']),('neutral',0,'fallback')) self.assertEqual((event['emotion'],event['intensity'],event['source']),('neutral',0,'fallback'))
self.assertNotIn('reply',event);self.assertNotIn('公开正文',json.dumps(metrics,ensure_ascii=False)) self.assertNotIn('reply',event);self.assertNotIn('公开正文',json.dumps(metrics,ensure_ascii=False))
self.assertEqual(metrics['llm_max_tokens'],160) self.assertEqual(metrics['llm_max_tokens'],160)
self.assertEqual(metrics['llm_request_count'],1)
async def test_debug_metadata_contains_counts_not_reply_text(self): async def test_debug_metadata_contains_counts_not_reply_text(self):
import tempfile import tempfile
+7
View File
@@ -48,9 +48,16 @@ class ReplyFaceTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(d.face_messages, {}) self.assertEqual(d.face_messages, {})
self.assertIsNone(d.face_context.value) self.assertIsNone(d.face_context.value)
self.assertTrue(socket.frames) self.assertTrue(socket.frames)
metrics=next(e['values'] for e in socket.events if e['type']=='metrics')
self.assertEqual(metrics['face_context']['use_reason'],'used')
self.assertEqual(metrics['face_context']['cue'],'smiling')
self.assertEqual(metrics['face_context']['accepted'],1)
d, socket, messages = await self.round(observation=False) d, socket, messages = await self.round(observation=False)
self.assertEqual([m['role'] for m in messages[0]], ['system','user']) self.assertEqual([m['role'] for m in messages[0]], ['system','user'])
self.assertNotIn('摄像头观察', messages[0][0]['content']) self.assertNotIn('摄像头观察', messages[0][0]['content'])
metrics=next(e['values'] for e in socket.events if e['type']=='metrics')
self.assertFalse(metrics['face_cue_used'])
self.assertEqual(metrics['face_context']['cue'],'unknown')
async def test_expired_and_barge_clear(self): async def test_expired_and_barge_clear(self):
d = Dialogue(Socket(), FakeModel(), None) d = Dialogue(Socket(), FakeModel(), None)
+4 -1
View File
@@ -29,10 +29,13 @@ with tempfile.TemporaryDirectory(prefix='lan-voice-expression-check-') as output
'app/src/main/java/com/gorios/lanvoice/expression/ExpressionRules.kt', 'app/src/main/java/com/gorios/lanvoice/expression/ExpressionRules.kt',
'app/src/main/java/com/gorios/lanvoice/expression/FaceCueRules.kt', 'app/src/main/java/com/gorios/lanvoice/expression/FaceCueRules.kt',
'app/src/main/java/com/gorios/lanvoice/expression/CameraPermissionGate.kt', 'app/src/main/java/com/gorios/lanvoice/expression/CameraPermissionGate.kt',
'app/src/main/java/com/gorios/lanvoice/expression/FaceDiagnostics.kt',
'tests/expression/ExpressionRulesCheck.kt', 'tests/expression/ExpressionRulesCheck.kt',
'tests/expression/FaceCueRulesCheck.kt', 'tests/expression/FaceCueRulesCheck.kt',
'tests/expression/CameraPermissionCheck.kt'], check=True) 'tests/expression/CameraPermissionCheck.kt',
'tests/expression/FaceDiagnosticsCheck.kt'], check=True)
subprocess.run([java, '-cp', output + ':' + stdlib, 'ExpressionRulesCheckKt'], check=True) subprocess.run([java, '-cp', output + ':' + stdlib, 'ExpressionRulesCheckKt'], check=True)
subprocess.run([java, '-cp', output + ':' + stdlib, 'FaceCueRulesCheckKt'], check=True) subprocess.run([java, '-cp', output + ':' + stdlib, 'FaceCueRulesCheckKt'], check=True)
subprocess.run([java, '-cp', output + ':' + stdlib, 'CameraPermissionCheckKt'], check=True) subprocess.run([java, '-cp', output + ':' + stdlib, 'CameraPermissionCheckKt'], check=True)
subprocess.run([java, '-cp', output + ':' + stdlib, 'FaceDiagnosticsCheckKt'], check=True)
PY PY
+1 -1
View File
@@ -23,7 +23,7 @@ compiler = ':'.join([jar('org.jetbrains.kotlin','kotlin-compiler-embeddable','2.
cp = ':'.join([stdlib, jar('com.squareup.okhttp3','okhttp','4.12.0'), jar('com.squareup.okio','okio-jvm','3.6.0')]) cp = ':'.join([stdlib, jar('com.squareup.okhttp3','okhttp','4.12.0'), jar('com.squareup.okio','okio-jvm','3.6.0')])
source = ROOT/'app/src/main/java/com/gorios/lanvoice' source = ROOT/'app/src/main/java/com/gorios/lanvoice'
suites = [ suites = [
('session','ConnectionCheckKt', [source/'audio/VoiceSession.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']), ('session','ConnectionCheckKt', [source/'audio/VoiceSession.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt', source/'expression/FaceDiagnostics.kt']),
('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt']), ('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt']),
('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']), ('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']),
('protocol','ProtocolCheckKt', [source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']), ('protocol','ProtocolCheckKt', [source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']),
+11 -9
View File
@@ -7,13 +7,16 @@ from pathlib import Path
import hashlib,json import hashlib,json
root=Path.cwd();directory=root/'logs/voice-investigation' root=Path.cwd();directory=root/'logs/voice-investigation'
load=lambda name:json.loads((directory/name).read_text()) load=lambda name:json.loads((directory/name).read_text())
deploy=load('gateway-emotion-deploy.json');probe=load('probe-emotion.json');client=load('client-emotion-tests.json');compat=load('reply-structure.json') deploy=load('gateway-emotion-deploy.json');probe=load('probe-emotion.json');client=load('client-emotion-tests.json')
compat=json.loads((root/'logs/emotion-052/semantic-candidate.json').read_text())
assert deploy['applied'] and deploy['health']=='ok' and deploy['environment_unchanged'] assert deploy['applied'] and deploy['health']=='ok' and deploy['environment_unchanged']
assert probe['status']=='passed' and probe['downlink_bytes']>0 and probe['emotion_before_pcm'] and probe['drained_ack'] and probe['tts_requests']==1 assert probe['status']=='passed' and probe['downlink_bytes']>0 and probe['emotion_before_pcm'] and probe['drained_ack'] and probe['tts_requests']==1
assert compat['status']=='passed' and client['status']=='passed' assert compat['status']=='passed' and compat['semantic_status']=='matched_fixed_cases' and client['status']=='passed'
for name,digest in deploy['hashes'].items():assert hashlib.sha256((root/'gateway'/name).read_bytes()).hexdigest()==digest,name for name,digest in deploy['hashes'].items():assert hashlib.sha256((root/'gateway'/name).read_bytes()).hexdigest()==digest,name
for name,digest in client['hashes'].items():assert hashlib.sha256((root/name).read_bytes()).hexdigest()==digest,name for name,digest in client['hashes'].items():assert hashlib.sha256((root/name).read_bytes()).hexdigest()==digest,name
assert not (root/'artifacts/lan-voice-v051-arm64-debug.apk').exists(), 'release artifact exists: refusing overwrite' assert not (root/'artifacts/lan-voice-v052-arm64-debug.apk').exists(), 'release artifact exists: refusing overwrite'
assert (root/'artifacts/lan-voice-v051-arm64-debug.apk').is_file(), 'previous release required for signature comparison/rollback'
assert hashlib.sha256((root/'gateway/reply_emotion.py').read_bytes()).hexdigest()==compat['candidate_source_sha256'], 'semantic probe does not match candidate prompt source'
print('Verified tested client/provider source and successful deployed pipeline before APK build') print('Verified tested client/provider source and successful deployed pipeline before APK build')
PY PY
./scripts/build.sh ./scripts/build.sh
@@ -29,20 +32,19 @@ from pathlib import Path
root=Path.cwd() root=Path.cwd()
badging=(root/'logs/voice-investigation/release-emotion-badging.txt').read_text() badging=(root/'logs/voice-investigation/release-emotion-badging.txt').read_text()
assert "name='com.gorios.lanvoice'" in badging assert "name='com.gorios.lanvoice'" in badging
assert "versionCode='9'" in badging and "versionName='0.5.1'" in badging assert "versionCode='10'" in badging and "versionName='0.5.2'" in badging
native=re.search(r'^native-code: (.+)$',badging,re.M) native=re.search(r'^native-code: (.+)$',badging,re.M)
assert native and native[1].strip()=="'arm64-v8a'", 'unexpected ABI' assert native and native[1].strip()=="'arm64-v8a'", 'unexpected ABI'
source=root/'app/build/outputs/apk/debug/app-debug.apk' source=root/'app/build/outputs/apk/debug/app-debug.apk'
previous=root/'artifacts/lan-voice-v040-arm64-debug.apk' previous=root/'artifacts/lan-voice-v051-arm64-debug.apk'
if previous.exists(): if previous.exists():
old=subprocess.check_output(['/home/ubuntu/android-build/sdk/build-tools/34.0.0/apksigner','verify','--print-certs',str(previous)],text=True) old=subprocess.check_output(['/home/ubuntu/android-build/sdk/build-tools/34.0.0/apksigner','verify','--print-certs',str(previous)],text=True)
new=(root/'logs/voice-investigation/release-emotion-signature.txt').read_text() new=(root/'logs/voice-investigation/release-emotion-signature.txt').read_text()
pattern=r'Signer #1 certificate SHA-256 digest: (\w+)' pattern=r'Signer #1 certificate SHA-256 digest: (\w+)'
assert re.search(pattern,old)[1]==re.search(pattern,new)[1], 'signing certificate changed: update install would fail' assert re.search(pattern,old)[1]==re.search(pattern,new)[1], 'signing certificate changed: update install would fail'
artifact=root/'artifacts/lan-voice-v051-arm64-debug.apk' artifact=root/'artifacts/lan-voice-v052-arm64-debug.apk'
assert not artifact.exists(), 'release artifact exists: refusing overwrite' assert not artifact.exists(), 'release artifact exists: refusing overwrite'
assert hashlib.sha256((root/'artifacts/lan-voice-v040-arm64-debug.apk').read_bytes()).hexdigest()=='5a6f88cb2f825dbcd5c7b8c1f212b369534bc53c49533e196fb5e9287902e934' assert hashlib.sha256(previous.read_bytes()).hexdigest()=='7d089517cde3241d79c971d6260ed8f71af86851e2623fdc66e51fb1583ae77f'
assert hashlib.sha256((root/'artifacts/lan-voice-v050-arm64-debug.apk').read_bytes()).hexdigest()=='da47f7a08f63a68fbb6dbe7fb3d803ee58b402de393112a32f92a63ad50c1f33'
shutil.copy2(source,artifact) shutil.copy2(source,artifact)
digest=hashlib.sha256(artifact.read_bytes()).hexdigest() digest=hashlib.sha256(artifact.read_bytes()).hexdigest()
artifact.with_suffix('.apk.sha256').write_text(f'{digest} {artifact.name}\n') artifact.with_suffix('.apk.sha256').write_text(f'{digest} {artifact.name}\n')
@@ -60,7 +62,7 @@ for path in ('artifacts/'+artifact.name, artifact.name):
if downloaded==digest: url=base+path;break if downloaded==digest: url=base+path;break
except Exception: pass except Exception: pass
assert url is not None, 'APK built, but existing HTTP server did not serve matching bytes' assert url is not None, 'APK built, but existing HTTP server did not serve matching bytes'
result=dict(version_name='0.5.1',version_code=9,apk=str(artifact.relative_to(root)),bytes=artifact.stat().st_size,sha256=digest,url=url,download_http_status=200,download_bytes=len(content),signature='apksigner_verified',real_phone_playback='not_tested') result=dict(version_name='0.5.2',version_code=10,apk=str(artifact.relative_to(root)),bytes=artifact.stat().st_size,sha256=digest,url=url,download_http_status=200,download_bytes=len(content),signature='apksigner_verified',same_signing_certificate_as='0.5.1',real_phone_playback='not_tested')
(root/'logs/voice-investigation/release-emotion.json').write_text(json.dumps(result,indent=2)+'\n') (root/'logs/voice-investigation/release-emotion.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(result,indent=2)) print(json.dumps(result,indent=2))
PY PY
+22 -6
View File
@@ -3,12 +3,13 @@
import argparse import argparse
import json import json
import subprocess import subprocess
import hashlib
from pathlib import Path from pathlib import Path
import sys import sys
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'gateway')) sys.path.insert(0, str(ROOT / 'gateway'))
from reply_emotion import REPLY_SCHEMA from reply_emotion import REPLY_SCHEMA, SYSTEM_FRAGMENT
REMOTE = r''' REMOTE = r'''
import asyncio, json, pathlib, ssl, subprocess, time, urllib.request import asyncio, json, pathlib, ssl, subprocess, time, urllib.request
@@ -17,6 +18,7 @@ from llm_provider import LLMProvider
from reply_emotion import SYSTEM_FRAGMENT, parse_reply from reply_emotion import SYSTEM_FRAGMENT, parse_reply
from persona_resolver import resolve_persona from persona_resolver import resolve_persona
root=pathlib.Path('/home/gorios-spark-2/lan-voice') root=pathlib.Path('/home/gorios-spark-2/lan-voice')
if candidate_prompt is not None: SYSTEM_FRAGMENT=candidate_prompt
result={'status':'failed','public_samples':samples,'rows':[],'real_phone_playback':'not_tested'} result={'status':'failed','public_samples':samples,'rows':[],'real_phone_playback':'not_tested'}
async def probe(): async def probe():
ctx=ssl.create_default_context(cafile=str(root/'.runtime/gateway-cert.pem')) ctx=ssl.create_default_context(cafile=str(root/'.runtime/gateway-cert.pem'))
@@ -33,9 +35,8 @@ async def probe():
rules=resolve_persona(root,persona,voice_ids)['rules'] rules=resolve_persona(root,persona,voice_ids)['rules']
if preflight:system='以下角色设定只约束reply字段的口述内容;其中旧有不输出JSON等格式约定不约束本轮外层结构。\n'+rules+'\n\n'+SYSTEM_FRAGMENT if preflight:system='以下角色设定只约束reply字段的口述内容;其中旧有不输出JSON等格式约定不约束本轮外层结构。\n'+rules+'\n\n'+SYSTEM_FRAGMENT
else:system='以下角色设定只约束reply字段的可朗读正文。\n'+rules+'\n\n'+SYSTEM_FRAGMENT else:system='以下角色设定只约束reply字段的可朗读正文。\n'+rules+'\n\n'+SYSTEM_FRAGMENT
public=['请简短说一声你好。','公开合成测试:朋友考试通过了,表达轻度高兴,简短祝贺。']
async with httpx.AsyncClient(trust_env=False,timeout=30) as client: async with httpx.AsyncClient(trust_env=False,timeout=30) as client:
for index,text in enumerate(public[:samples]): for index,(name,text,expected) in enumerate(cases):
url,headers,body=p.request([{'role':'system','content':system},{'role':'user','content':text}],max_tokens=160) url,headers,body=p.request([{'role':'system','content':system},{'role':'user','content':text}],max_tokens=160)
if preflight:body['response_format']={'type':'json_schema','json_schema':{'name':'role_reply','strict':True,'schema':schema}} if preflight:body['response_format']={'type':'json_schema','json_schema':{'name':'role_reply','strict':True,'schema':schema}}
else:assert body.get('response_format')=={'type':'json_schema','json_schema':{'name':'role_reply','strict':True,'schema':schema}}, 'schema_not_enabled' else:assert body.get('response_format')=={'type':'json_schema','json_schema':{'name':'role_reply','strict':True,'schema':schema}}, 'schema_not_enabled'
@@ -59,9 +60,13 @@ async def probe():
elapsed=round((time.perf_counter()-start)*1000,2) elapsed=round((time.perf_counter()-start)*1000,2)
parsed=parse_reply(raw,finish_reason=finish) parsed=parse_reply(raw,finish_reason=finish)
row={'sample':index+1,'http_status':response.status_code,'sse_done':done,'chunks':chunks,'envelope_chars':len(raw),'reply_chars':len(parsed.reply),'emotion':parsed.emotion,'intensity':parsed.intensity,'source':parsed.source,'reason':parsed.reason,'parse_branch':parsed.parse_branch,'finish_reason':finish,'usage':usage,'max_tokens':160,'first_content_ms':first,'complete_ms':elapsed,'structured_wait_ms':round(elapsed-(first or elapsed),2)} row={'sample':index+1,'http_status':response.status_code,'sse_done':done,'chunks':chunks,'envelope_chars':len(raw),'reply_chars':len(parsed.reply),'emotion':parsed.emotion,'intensity':parsed.intensity,'source':parsed.source,'reason':parsed.reason,'parse_branch':parsed.parse_branch,'finish_reason':finish,'usage':usage,'max_tokens':160,'first_content_ms':first,'complete_ms':elapsed,'structured_wait_ms':round(elapsed-(first or elapsed),2)}
row['case']=name
if expected is not None:row.update(expected_emotion=expected,expected_emotion_match=parsed.emotion==expected)
result['rows'].append(row) result['rows'].append(row)
assert done and finish=='stop' and parsed.source=='model' and parsed.parse_branch=='strict_json' and 0<len(parsed.reply)<=160, 'schema_validation_failed' assert done and finish=='stop' and parsed.source=='model' and parsed.parse_branch=='strict_json' and 0<len(parsed.reply)<=160, 'schema_validation_failed'
result.update(status='passed',provider='qwen3.8-27b',thinking=False,format_mode='json_schema',persona=persona) result.update(status='passed',provider='qwen3.8-27b',thinking=False,format_mode='json_schema',persona=persona)
if any(row.get('expected_emotion_match') is False for row in result['rows']):result['semantic_status']='mismatch'
elif any('expected_emotion_match' in row for row in result['rows']):result['semantic_status']='matched_fixed_cases'
try:asyncio.run(probe()) try:asyncio.run(probe())
except Exception as error: except Exception as error:
result['error_type']=type(error).__name__ result['error_type']=type(error).__name__
@@ -75,12 +80,23 @@ def main():
parser=argparse.ArgumentParser(description=__doc__) parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--preflight',action='store_true',help='Validate explicit schema before provider implementation is deployed') parser.add_argument('--preflight',action='store_true',help='Validate explicit schema before provider implementation is deployed')
parser.add_argument('--samples',type=int,choices=(1,2),default=1) parser.add_argument('--samples',type=int,choices=(1,2),default=1)
parser.add_argument('--emotion-cases',action='store_true',help='Six fixed public semantic cases; records every match/mismatch without resampling')
parser.add_argument('--candidate',action='store_true',help='Use workspace candidate prompt in memory before deploying it')
args=parser.parse_args() args=parser.parse_args()
payload='schema='+repr(REPLY_SCHEMA)+'\npreflight='+repr(args.preflight)+'\nsamples='+repr(args.samples)+'\n'+REMOTE cases=[('greeting','请简短说一声你好。',None),('explicit_happy','公开合成测试:朋友考试通过了,表达轻度高兴,简短祝贺。',None)][:args.samples]
result=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61','cd /home/gorios-spark-2/lan-voice && exec .venv/bin/python -'],input=payload.encode(),capture_output=True,timeout=85) if args.emotion_cases:
cases=[('fact','七乘八等于多少?只给出结果。','neutral'),
('congratulations','朋友通过资格考试了,请简短祝贺。','happy'),
('sympathy','朋友努力准备的比赛落选了,请简短表示惋惜并安慰。','sad'),
('disapproval','有人故意插队还嘲讽排队的人,请用克制口吻表达你对此的不满。','angry'),
('definition','客观解释“愤怒”一词的含义,不表达你自己的情绪。','neutral'),
('negated_fact','这不是一个悲伤的故事。请只回答一加一等于几。','neutral')]
payload='schema='+repr(REPLY_SCHEMA)+'\npreflight='+repr(args.preflight)+'\nsamples='+repr(len(cases))+'\ncases='+repr(cases)+'\ncandidate_prompt='+repr(SYSTEM_FRAGMENT if args.candidate else None)+'\n'+REMOTE
result=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61','cd /home/gorios-spark-2/lan-voice && exec .venv/bin/python -'],input=payload.encode(),capture_output=True,timeout=220 if args.emotion_cases else 85)
if result.stdout: if result.stdout:
data=json.loads(result.stdout) data=json.loads(result.stdout)
target=ROOT/'logs/structure-output-fix'/('schema-preflight.json' if args.preflight else 'schema-deployed.json') if args.candidate:data['candidate_source_sha256']=hashlib.sha256((ROOT/'gateway/reply_emotion.py').read_bytes()).hexdigest()
target=ROOT/'logs/emotion-052'/('semantic-candidate.json' if args.candidate else 'semantic-deployed.json') if args.emotion_cases else ROOT/'logs/structure-output-fix'/('schema-preflight.json' if args.preflight else 'schema-deployed.json')
target.parent.mkdir(parents=True,exist_ok=True) target.parent.mkdir(parents=True,exist_ok=True)
target.write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n') target.write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n')
print(json.dumps(data,ensure_ascii=False,indent=2)) print(json.dumps(data,ensure_ascii=False,indent=2))
+2 -1
View File
@@ -100,7 +100,7 @@ async def probe():
if kind=='voice.metrics': summary['tts_requests']=event.get('tts_request_count') if kind=='voice.metrics': summary['tts_requests']=event.get('tts_request_count')
if kind=='metrics': if kind=='metrics':
values=event.get('values',{}) values=event.get('values',{})
summary['backend_metrics']={key:values.get(key) for key in ('stt_ms','llm_first_token_ms','llm_first_body_ms','structured_wait_ms','reply_parse_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_first_pcm_ms','total_ms','tts_request_count','face_cue_used','reply_emotion_reason','reply_parse_branch','reply_emotion','reply_intensity','llm_finish_reason','llm_usage','llm_max_tokens','llm_structured_output')} summary['backend_metrics']={key:values.get(key) for key in ('stt_ms','llm_first_token_ms','llm_first_body_ms','structured_wait_ms','reply_parse_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_first_pcm_ms','total_ms','tts_request_count','llm_request_count','face_cue_used','reply_emotion_reason','reply_parse_branch','reply_emotion','reply_intensity','llm_finish_reason','llm_usage','llm_max_tokens','llm_structured_output','face_context')}
summary['segments']=[{key:s.get(key) for key in ('audio_seconds','total_ms','rtf','max_chunk_interarrival_ms')} for s in values.get('tts_segments',[])] summary['segments']=[{key:s.get(key) for key in ('audio_seconds','total_ms','rtf','max_chunk_interarrival_ms')} for s in values.get('tts_segments',[])]
if kind=='error': raise RuntimeError('gateway_backend_error') if kind=='error': raise RuntimeError('gateway_backend_error')
if kind=='tts' and event.get('state')=='stop': if kind=='tts' and event.get('state')=='stop':
@@ -120,6 +120,7 @@ async def probe():
summary['invalid_face_control_survived']=True summary['invalid_face_control_survived']=True
assert summary['emotion_count']==1 and summary.get('tts_input_matches_body') and summary.get('tts_requests')==1 assert summary['emotion_count']==1 and summary.get('tts_input_matches_body') and summary.get('tts_requests')==1
assert summary['structured_model_output'], 'live structured reply fell back' assert summary['structured_model_output'], 'live structured reply fell back'
assert summary['backend_metrics'].get('llm_request_count')==1, 'LLM request count differs'
assert summary['pcm_peak']>327, 'no voiced PCM amplitude' assert summary['pcm_peak']>327, 'no voiced PCM amplitude'
summary['pcm_rms']=round(math.sqrt(summary.pop('pcm_square')/(summary['downlink_bytes']//2)),2) summary['pcm_rms']=round(math.sqrt(summary.pop('pcm_square')/(summary['downlink_bytes']//2)),2)
summary['status']='passed' summary['status']='passed'
+8
View File
@@ -25,5 +25,13 @@ fun main() {
check(result.cue == if(t==800L) FaceCue.BROW_FURROWED else FaceCue.UNKNOWN) check(result.cue == if(t==800L) FaceCue.BROW_FURROWED else FaceCue.UNKNOWN)
} }
checkUnknown(obs=face(.1f,.4f),t=900) checkUnknown(obs=face(.1f,.4f),t=900)
check(rules.evaluate(null,0,false,1000).reason == FaceCueReason.NO_FACE)
check(rules.evaluate(face(),2,true,1100).reason == FaceCueReason.MULTIPLE_FACES)
check(rules.evaluate(face(),1,false,1200).reason == FaceCueReason.POOR_QUALITY)
check(rules.evaluate(face(.1f,.1f),1,true,1300).reason == FaceCueReason.NO_CLEAR_CUE)
check(rules.evaluate(face(.9f,.9f),1,true,1400).reason == FaceCueReason.CONFLICT)
check(rules.evaluate(face(),1,true,1500).reason == FaceCueReason.STABILIZING)
check(rules.evaluate(face(Float.NaN),1,true,1600).reason == FaceCueReason.INVALID_COEFFICIENTS)
check(rules.evaluate(FaceObservation(emptyMap(),null),1,true,1700).reason == FaceCueReason.MISSING_COEFFICIENTS)
println("PASS: sustained bilateral cues, hysteresis, conflict/multiple/no face/poor quality/invalid score/stale reset; no gaze/eye emotion inference") println("PASS: sustained bilateral cues, hysteresis, conflict/multiple/no face/poor quality/invalid score/stale reset; no gaze/eye emotion inference")
} }
+33
View File
@@ -0,0 +1,33 @@
import com.gorios.lanvoice.expression.*
fun main() {
val camera = CameraAnalysisDiagnostics()
check(camera.snapshot().reason == FaceCueReason.NO_FRAME)
var summaries = 0
for (time in 0L..600_000L step 100) {
camera.received()
camera.processed(0, FaceCueObservation(reason = FaceCueReason.NO_FACE), 8)
if (camera.summary(time) != null) summaries++
}
check(summaries == 61) // 10Hz samples, <=1 summary/10s including first.
check(camera.snapshot().received == 6001 && camera.snapshot().processed == 6001)
check(camera.snapshot().faceCount == 0 && camera.snapshot().reason == FaceCueReason.NO_FACE)
camera.processed(1, FaceCueObservation(FaceCue.SMILING, .9f, 900, 0, FaceCueReason.STABLE), 12)
camera.failed(CameraFailure.ANALYSIS)
check(camera.snapshot().cue == FaceCue.SMILING && camera.snapshot().failures == 1)
check(camera.summary(600_001) == null)
val final = checkNotNull(camera.summary(600_001, force = true))
check("failure=analysis" in final && "cue=smiling" in final)
check(listOf("landmark", "blendshape", "image", "prompt", "reply").none { it in final })
val send = FaceTransmissionDiagnostics()
check(send.snapshot().reason == FaceSendReason.SHARING_OFF)
send.record(FaceSendReason.NO_STABLE_CUE)
check(send.snapshot().attempts == 0)
send.record(FaceSendReason.SENT, FaceCue.SMILING)
send.record(FaceSendReason.CLEARED)
send.record(FaceSendReason.SEND_FAILED)
send.record(FaceSendReason.STALE)
check(send.snapshot().attempts == 3 && send.snapshot().sent == 1 && send.snapshot().clears == 1 && send.snapshot().failures == 1)
check(send.summary(0) != null && send.summary(9999) == null && send.summary(10000) != null)
println("PASS: enum-only camera/frame/send snapshots, failure counters, 10s rate bound, no-face/stable/stale/clear accounting")
}
+1
View File
@@ -481,6 +481,7 @@ fun runChecks() {
} }
fun main() { fun main() {
checkFaceTransmission()
run { run {
val normal = com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(2L, 1L, "neutral", 0, "model")!! val normal = com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(2L, 1L, "neutral", 0, "model")!!
val fallback = com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(2L, 1L, "neutral", 0, "fallback", "invalid_intensity")!! val fallback = com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(2L, 1L, "neutral", 0, "fallback", "invalid_intensity")!!
+37
View File
@@ -0,0 +1,37 @@
import android.os.SystemClock
import com.gorios.lanvoice.audio.*
import com.gorios.lanvoice.expression.*
import com.gorios.lanvoice.net.*
fun checkFaceTransmission() {
val session=VoiceSession("localhost",5011,{})
fun set(name: String, value: Any) { session.javaClass.getDeclaredField(name).apply { isAccessible=true }.set(session,value) }
val dialogue=session.javaClass.getDeclaredField("dialogue").apply { isAccessible=true }.get(session) as DialogueClient
val socket=FakeSocket()
dialogue.setField("socket",socket);dialogue.setField("ready",true)
fun tick() { session.javaClass.getDeclaredMethod("sendFaceContext").apply { isAccessible=true }.invoke(session) }
set("foreground",true);set("faceSupported",true);set("hasTurn",true);set("currentTurn",7L)
set("state",VoiceUiState(connection=ConnectionStatus.CONNECTED,voiceActive=true,phase=VoicePhase.LISTENING))
session.setFaceSharing(true)
tick()
check(session.faceDiagnosticsSnapshot().reason == FaceSendReason.NO_STABLE_CUE && socket.sent.isEmpty())
session.observeFace(FaceCueObservation(reason=FaceCueReason.NO_FACE));tick()
check(session.faceDiagnosticsSnapshot().reason == FaceSendReason.NO_FACE)
val stable=FaceCueObservation(FaceCue.SMILING,.9f,900,SystemClock.elapsedRealtime(),FaceCueReason.STABLE)
session.observeFace(stable);tick()
check(session.faceDiagnosticsSnapshot().sent==1)
session.observeFace(stable.copy(observedAtMs=SystemClock.elapsedRealtime()-4000));tick()
check(session.faceDiagnosticsSnapshot().reason==FaceSendReason.STALE && session.faceDiagnosticsSnapshot().clears==1)
val count=socket.sent.size;tick();check(socket.sent.size==count) // clear only once, retain stale reason.
session.observeFace(stable.copy(observedAtMs=SystemClock.elapsedRealtime()));socket.acceptSend=false;tick()
check(session.faceDiagnosticsSnapshot().reason==FaceSendReason.SEND_FAILED)
socket.acceptSend=true;tick();session.setFaceSharing(false)
check(session.faceDiagnosticsSnapshot().reason==FaceSendReason.SHARING_OFF)
check(session.faceDiagnosticsSnapshot().clears==2)
session.setFaceSharing(true)
set("foreground",false);tick();check(session.faceDiagnosticsSnapshot().reason==FaceSendReason.BACKGROUND)
set("foreground",true);set("state",VoiceUiState(connection=ConnectionStatus.DISCONNECTED));tick()
check(session.faceDiagnosticsSnapshot().reason==FaceSendReason.NOT_CONNECTED)
session.setFaceSharing(false);dialogue.release()
println("PASS: real coordinator face sharing/no-face/stable-send/failure/TTL one-shot clear/background/disconnect; transport doubles")
}