feat: merge reply emotions while preserving configurable Qwen/Doubao provider

This commit is contained in:
zenord
2026-10-12 10:57:14 +08:00
parent 19a7adccd9
commit d43c7d4e80
36 changed files with 1264 additions and 98 deletions
@@ -255,6 +255,7 @@ fun Home(
)
}
ExpressionControls(expressionState, onToggleExpressions, shareFace, onShareFace)
Text("角色:${state.replyEmotion.label}(角色表达)", color = gold, fontSize = 13.sp)
}
Column(
modifier = Modifier.padding(top = 24.dp, bottom = 12.dp),
@@ -4,6 +4,8 @@ import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import com.gorios.lanvoice.dialogue.ReplyEmotion
import com.gorios.lanvoice.dialogue.ReplyEmotionObserver
import com.gorios.lanvoice.net.ConnectionStatus
import com.gorios.lanvoice.net.DialogueClient
import com.gorios.lanvoice.net.DebugLogUpload
@@ -21,6 +23,7 @@ data class VoiceUiState(
val voiceActive: Boolean = false,
val aec: AecAvailability = AecAvailability.UNKNOWN,
val guidance: String? = null,
val replyEmotion: ReplyEmotion = ReplyEmotion(),
)
/** Main-thread coordinator; both audio workers add their own epochs to the socket's fence. */
@@ -29,6 +32,7 @@ class VoiceSession(
private val onConnectionLog: (String) -> Unit = {},
private val onPreparePlayback: () -> String? = { null },
private val onVoiceStopped: () -> Unit = {},
private val emotionObserver: ReplyEmotionObserver = ReplyEmotionObserver {},
) {
private val main = Handler(Looper.getMainLooper())
private var state = VoiceUiState()
@@ -43,6 +47,7 @@ class VoiceSession(
private var blockedTurn: Long? = null
private var sequence = 1L
private var preparedPlaybackTurn: Long? = null
private var emotionEndedTurn: Long? = null
private var faceSharing = false
private var faceSupported = false
private var faceCue = FaceCueObservation()
@@ -66,7 +71,8 @@ class VoiceSession(
if (isActive() && playbackIsCurrent(turn, epoch) && blockedTurn != turn) {
diagnostic("playback drained turn=$turn")
if (dialogue.playbackDrained(turn)) {
update(state.copy(phase = VoicePhase.LISTENING))
emotionEndedTurn = turn
update(state.copy(phase = VoicePhase.LISTENING, replyEmotion = ReplyEmotion()))
startCapture()
}
}
@@ -163,7 +169,7 @@ class VoiceSession(
clearFaceContext()
onVoiceStopped()
blockedTurn = currentTurn
update(state.copy(voiceActive = false, phase = VoicePhase.IDLE))
update(state.copy(voiceActive = false, phase = VoicePhase.IDLE, replyEmotion = ReplyEmotion()))
if (sendControls && wasActive && state.connection == ConnectionStatus.CONNECTED) {
dialogue.listen(false)
dialogue.abort(currentTurn)
@@ -176,7 +182,7 @@ class VoiceSession(
blockedTurn = currentTurn
playback.interrupt() // Silence locally before waiting for the server's abort event.
if (dialogue.abort(currentTurn)) {
update(state.copy(phase = VoicePhase.LISTENING))
update(state.copy(phase = VoicePhase.LISTENING, replyEmotion = ReplyEmotion()))
startCapture()
}
}
@@ -223,6 +229,7 @@ class VoiceSession(
faceSent = false
faceCue = FaceCueObservation()
preparedPlaybackTurn = null
emotionEndedTurn = null
onVoiceStopped()
stopCapture()
playback.interrupt()
@@ -231,7 +238,7 @@ class VoiceSession(
retiredTurns.clear()
blockedTurn = null
sequence = 1
update(state.copy(connection = connection, voiceActive = false, phase = VoicePhase.IDLE))
update(state.copy(connection = connection, voiceActive = false, phase = VoicePhase.IDLE, replyEmotion = ReplyEmotion()))
} else update(state.copy(
connection = connection,
// onStop runs while the screen is hidden. Keep the reason visible on
@@ -294,6 +301,8 @@ class VoiceSession(
}
// An ABORT can announce the replacement turn. Remember the interrupted
// turn before acceptTurn updates currentTurn and retires the old one.
// An expression cannot announce/switch a turn. Other protocol events establish it first.
if (event.kind == EventKind.REPLY_EMOTION && (!hasTurn || turn != currentTurn)) return
val oldTurn = if (hasTurn) currentTurn else null
if (turn != null && !acceptTurn(turn)) return
val action = event.payload.optString("state", "").ifBlank { event.type.substringAfter('.', "") }
@@ -329,6 +338,11 @@ class VoiceSession(
EventKind.LLM -> if (isActive() && state.phase != VoicePhase.ANSWERING) {
update(state.copy(phase = VoicePhase.THINKING))
}
EventKind.REPLY_EMOTION -> if (isActive() && blockedTurn != currentTurn && emotionEndedTurn != currentTurn) {
val emotion = ReplyEmotion.fromWire(event.payload.opt("turn_id"), event.payload.opt("seq"),
event.payload.opt("emotion"), event.payload.opt("intensity"), event.payload.opt("source")) ?: return
if (emotion.sequence > state.replyEmotion.sequence) update(state.copy(replyEmotion = emotion))
}
EventKind.TTS -> if (isActive() && blockedTurn != currentTurn) {
// The gateway sends start BEFORE LLM generation and also tts.metrics.
// Only received PCM means there is an answer to play.
@@ -350,7 +364,7 @@ class VoiceSession(
diagnostic("ABORT blockedTurn=$blockedTurn active=${isActive()} listenReset=$listenReset oldTurn=$oldTurn currentTurn=$currentTurn")
playback.interrupt()
if (isActive()) {
update(state.copy(phase = VoicePhase.LISTENING))
update(state.copy(phase = VoicePhase.LISTENING, replyEmotion = ReplyEmotion()))
startCapture()
}
}
@@ -391,6 +405,8 @@ class VoiceSession(
playback.interrupt()
preparedPlaybackTurn = null
currentTurn = id
emotionEndedTurn = null
update(state.copy(replyEmotion = ReplyEmotion()))
hasTurn = true
sequence = 1
if (blockedTurn != id) blockedTurn = null
@@ -414,7 +430,12 @@ class VoiceSession(
}
private fun playbackIsCurrent(epoch: Long): Boolean = playback.isCurrent(epoch)
private fun isActive() = !released && foreground && state.voiceActive && state.connection == ConnectionStatus.CONNECTED
private fun update(next: VoiceUiState) { state = next; onState(next) }
private fun update(next: VoiceUiState) {
val changed = state.replyEmotion != next.replyEmotion
state = next
onState(next)
if (changed) emotionObserver.onReplyEmotion(next.replyEmotion)
}
private fun checkMainThread() {
check(Looper.myLooper() === main.looper) { "VoiceSession must be used on main" }
}
@@ -0,0 +1,35 @@
package com.gorios.lanvoice.dialogue
/** Role expression for one reply, never a classification of the user's feelings. */
enum class RoleEmotion(val wire: String, val label: String) {
NEUTRAL("neutral", "中立"), HAPPY("happy", "高兴"), ANGRY("angry", "生气"), SAD("sad", "难过")
}
enum class EmotionSource { MODEL, FALLBACK }
data class ReplyEmotion(
val emotion: RoleEmotion = RoleEmotion.NEUTRAL,
val intensity: Int = 0,
val source: EmotionSource = EmotionSource.FALLBACK,
val turnId: Long? = null,
val sequence: Long = -1,
) {
val label: String get() = emotion.label + when (intensity) { 1 -> "·轻度"; 2 -> "·明显"; else -> "" }
companion object {
fun fromWire(turn: Any?, seq: Any?, emotion: Any?, intensity: Any?, source: Any?): ReplyEmotion? {
fun integer(value: Any?): Long? = when (value) { is Int -> value.toLong(); is Long -> value; else -> null }
val id = integer(turn)?.takeIf { it in 0..0xffff_ffffL } ?: return null
val sequence = integer(seq)?.takeIf { it >= 0 } ?: return null
val kind = RoleEmotion.entries.firstOrNull { it.wire == emotion }
val strength = integer(intensity)
val origin = when (source) { "model" -> EmotionSource.MODEL; "fallback" -> EmotionSource.FALLBACK; else -> null }
if (kind == null || origin == null || !(kind == RoleEmotion.NEUTRAL && strength == 0L ||
kind != RoleEmotion.NEUTRAL && strength in 1L..2L) ||
origin == EmotionSource.FALLBACK && kind != RoleEmotion.NEUTRAL) {
return ReplyEmotion(turnId = id, sequence = sequence)
}
return ReplyEmotion(kind, strength!!.toInt(), origin, id, sequence)
}
}
}
/** Main-thread observation point reserved for future visuals; no renderer/service dependency. */
fun interface ReplyEmotionObserver { fun onReplyEmotion(emotion: ReplyEmotion) }
@@ -41,6 +41,7 @@ class ExpressionController(
var provider: ProcessCameraProvider? = null // Accessed only on main.
var lastSampleMs = Long.MIN_VALUE
var lastPublished: List<ExpressionCue>? = null
var lastStableCue = FaceCue.UNKNOWN
}
private val appContext = context.applicationContext
@@ -175,10 +176,11 @@ class ExpressionController(
val faceCue = run.faceRules.evaluate(observation, result.faceLandmarks().size, quality, now)
main.post { if (isCurrent(run)) onFaceCue(faceCue) }
// UI receives only <=2 enum labels; 52 coefficients, pose and images stay transient.
if (run.lastPublished != visible) {
if (run.lastPublished != visible || run.lastStableCue != faceCue.cue) {
run.lastStableCue = faceCue.cue
run.lastPublished = visible
main.post {
if (isCurrent(run)) onState(ExpressionUiState(ExpressionStatus.ACTIVE, visible))
if (isCurrent(run)) onState(ExpressionUiState(ExpressionStatus.ACTIVE, visible, stableCue = faceCue.cue))
}
}
} catch (_: Exception) {
@@ -6,4 +6,5 @@ data class ExpressionUiState(
val status: ExpressionStatus = ExpressionStatus.OFF,
val cues: List<ExpressionCue> = emptyList(),
val guidance: String? = null,
val stableCue: FaceCue = FaceCue.UNKNOWN,
)
@@ -25,13 +25,16 @@ fun ExpressionControls(
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),
)
}
Text(
"你:" + when {
!enabled -> "摄像头已关闭"
state.status == ExpressionStatus.STARTING -> "检测中"
ExpressionCue.FACE_LOST in state.cues -> "无脸"
state.stableCue == FaceCue.SMILING -> "明显微笑"
state.stableCue == FaceCue.BROW_FURROWED -> "明显皱眉"
else -> "未见明显线索"
}, fontSize = 12.sp, color = Color(0xFFE8C884),
)
TextButton(onClick = onToggle) {
Text(when {
state.status == ExpressionStatus.STARTING -> "取消开启"
@@ -47,7 +50,7 @@ fun ExpressionControls(
Text(it, fontSize = 12.sp, color = Color(0xFF9CA3AF), textAlign = TextAlign.Center)
}
Text(
"表情线索仅供参考,不代表真实情绪",
"表情不等于情绪;线索仅供参考,不代表真实情绪",
fontSize = 11.sp, color = Color(0xFF9CA3AF), textAlign = TextAlign.Center,
)
Row(verticalAlignment = Alignment.CenterVertically) {
@@ -10,7 +10,7 @@ import com.gorios.lanvoice.expression.FaceCueObservation
data class ServerEvent(val type: String, val kind: EventKind, val payload: JSONObject)
enum class EventKind {
AUTH, HELLO, HISTORY, LISTEN, VAD, STT, LLM, TTS, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN
AUTH, HELLO, HISTORY, LISTEN, VAD, STT, LLM, TTS, REPLY_EMOTION, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN
}
/** Header integers are unsigned, network byte order; PCM samples are signed little endian. */
@@ -77,7 +77,7 @@ object DialogueProtocol {
val payload = JSONObject(text)
val type = payload.opt("type") as? String
require(!type.isNullOrBlank()) { "Event is missing a string type" }
val kind = when (type.substringBefore('.')) {
val kind = if (type == "reply.emotion") EventKind.REPLY_EMOTION else when (type.substringBefore('.')) {
"auth" -> EventKind.AUTH
"hello" -> EventKind.HELLO
"history" -> EventKind.HISTORY