"""Versioned enum-only camera observations, scoped to a live socket/utterance. No images or text.""" import math import time TEMPLATE = ( '本轮可选摄像头观察(可能误判,不是情绪识别):{cue},规则强度{intensity},持续约{duration}毫秒。' '只作为弱辅助信息,用户台词和聊天内容优先;冲突时忽略观察。' '微笑可能是礼貌或苦笑,皱眉可能是困惑,不能断言内心情绪、健康状况或危险等级。' '不做身份识别,不从闭眼推断疲劳或疾病,不必每句评论表情。' ) class FaceContext: def __init__(self): self.value = None def clear(self): self.value = None def update(self, data, turn, now=None): self.clear() # Invalid observations must never leave an older cue latched. allowed = {'type', 'version', 'turn_id', 'valid', 'cue', 'intensity', 'duration_ms', 'age_ms'} if not isinstance(data, dict) or set(data) != allowed: return False if data['type'] != 'context.face_cue' or type(data['version']) is not int or data['version'] != 1: return False if type(data['turn_id']) is not int or not 0 <= data['turn_id'] <= 0xffffffff or data['turn_id'] != turn: return False if type(data['valid']) is not bool: return False 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: return False if type(intensity) not in (int, float) or not math.isfinite(intensity) or not 0 <= intensity <= 1: return False if not data['valid']: return data['cue'] == 'unknown' and intensity == 0 and duration == 0 if data['cue'] not in ('smiling', 'brow_furrowed') or duration < 800 or intensity < .5: return False self.value = (turn, data['cue'], intensity, duration, age, time.monotonic() if now is None else now) return True def advance_capture(self, old_turn, new_turn): # new_turn names the response to the just-finished capture, not another utterance. if self.value and self.value[0] == old_turn: self.value = (new_turn, *self.value[1:]) else: self.clear() def take(self, turn, now=None): value, self.value = self.value, None if value is None or value[0] != turn: return None _, cue, intensity, duration, age, received = value elapsed = ((time.monotonic() if now is None else now) - received) * 1000 if elapsed < 0 or age + round(elapsed, 6) > 3000: return None label = {'smiling': '明显、持续的嘴角上扬', 'brow_furrowed': '明显、持续的双侧眉头收紧'}[cue] return {'role': 'system', 'content': TEMPLATE.format(cue=label, intensity=round(intensity, 2), duration=duration)}