Files
baji-vc/scripts/probe-reply-emotion.py
T

164 lines
11 KiB
Python

#!/usr/bin/env python3
"""One bounded public-sample round against live gateway. Run only in the workspace ordinary shell."""
import json
import subprocess
from pathlib import Path
PROBE = r'''
import asyncio, contextlib, io, json, math, re, ssl, struct, sys, time, urllib.request, wave
from pathlib import Path
ROOT = Path('/home/gorios-spark-2/lan-voice')
sys.path.insert(0, str(ROOT))
summary = {'test': 'one_public_sample_round', 'real_phone_playback': 'not_tested'}
async def probe():
import websockets
from protocol import pack, unpack
ctx=ssl.create_default_context(cafile=str(ROOT/'.runtime/gateway-cert.pem'))
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
with opener.open('https://192.168.31.61:5011/health',timeout=5) as response: health=json.load(response)
if health.get('busy'): raise RuntimeError('gateway_busy_probe_not_started')
sample=ROOT/'tmp/public_tts_16k.wav'
with wave.open(str(sample),'rb') as audio:
assert (audio.getframerate(),audio.getnchannels(),audio.getsampwidth())==(16000,1,2)
assert audio.getnframes() <= 16000*15, 'public sample exceeds 15s bound'
pcm=audio.readframes(audio.getnframes())
summary['input_samples']=len(pcm)//2
started=time.perf_counter()
summary.update(emotion_count=0,emotion_before_pcm=False,json_free_body=True,events={},llm_chars=0,llm_deltas=0,downlink_frames=0,downlink_bytes=0,pcm_peak=0,pcm_square=0,drained_ack=False)
def stamp(name): summary.setdefault(name,round((time.perf_counter()-started)*1000,2))
kwargs=dict(ssl=ctx,origin='https://192.168.31.61:5011',open_timeout=5,close_timeout=2)
# The deployed websockets version accepts proxy=None; avoid any system proxy.
if 'proxy' in __import__('inspect').signature(websockets.connect).parameters: kwargs['proxy']=None
async with websockets.connect('wss://192.168.31.61:5011/ws/dialogue',**kwargs) as ws:
auth=json.loads(await asyncio.wait_for(ws.recv(),5)); assert auth['type']=='auth' and auth.get('state')=='ok'
await ws.send(json.dumps({'type':'hello','codec':'pcm16','sample_rate':16000,'frame_duration':20,'persona':'default','voice_mode':'continuous_voice','tts_debug':False}))
while True:
event=json.loads(await asyncio.wait_for(ws.recv(),5))
if event['type']=='hello': break
summary['face_context_supported']=event.get('context_face_cue_version')
summary['reply_emotion_supported']=event.get('reply_emotion_version')
summary['llm_structured_output']=event.get('llm_structured_output')
assert summary['llm_structured_output']=='json_schema', 'live schema mode missing'
assert summary['reply_emotion_supported']==1
if after: assert summary['face_context_supported']==1, 'face protocol not advertised'
await ws.send(json.dumps({'type':'listen','mode':'manual','state':'start','barge_in':False}))
while True:
event=json.loads(await asyncio.wait_for(ws.recv(),5))
if event['type']=='listen' and event.get('state')=='start': turn=event['turn_id']; break
for offset in range(0,len(pcm),640):
chunk=pcm[offset:offset+640]
if len(chunk)<640: chunk += bytes(640-len(chunk))
await ws.send(pack(1,turn,offset//640+1,chunk))
await asyncio.sleep(.02)
if after:
cue={'type':'context.face_cue','version':1,'turn_id':turn,'valid':True,'cue':'smiling','intensity':.8,'duration_ms':900,'age_ms':0}
# Explicit synthetic observation: never represents the user's face.
await ws.send(json.dumps(cue))
summary['synthetic_face_context_sent']=True
await ws.send(json.dumps({'type':'listen','mode':'manual','state':'stop'}))
stamp('input_end_ms')
last_seq=0; stopped=False;reply_body='';emotion=None
async with asyncio.timeout(60):
while True:
raw=await ws.recv()
if isinstance(raw,bytes):
actual,seq,audio=unpack(raw,2)
assert emotion is not None and emotion['turn_id']==actual, 'PCM before parsed emotion'
summary['emotion_before_pcm']=True
assert actual==turn and seq==last_seq+1 and 0<len(audio)<=1920
last_seq=seq; summary['downlink_frames']+=1;summary['downlink_bytes']+=len(audio)
samples=struct.unpack('<'+'h'*(len(audio)//2),audio)
summary['pcm_peak']=max(summary['pcm_peak'],max(map(abs,samples),default=0))
summary['pcm_square']+=sum(x*x for x in samples)
stamp('first_pcm_ms')
continue
event=json.loads(raw);kind=event.get('type','unknown')
summary['events'][kind]=summary['events'].get(kind,0)+1
if kind=='abort': turn=event['turn_id'];last_seq=0
if kind=='capture.end': stamp('capture_end_ms');summary['turn']=turn
if kind=='stt': summary['stt_chars']=len(event.get('text',''));stamp('stt_ms')
if kind=='llm':
text=event.get('text','');assert text.strip() and not text.lstrip().startswith(('{','[','```'))
assert not re.search(r'"(?:reply|emotion|intensity)"\s*:',text), 'JSON leaked as dialogue body'
reply_body+=text
summary['llm_chars']+=len(event.get('text',''));summary['llm_deltas']+=1;stamp('first_llm_ms')
if kind=='reply.emotion':
assert event['turn_id']==turn and isinstance(event.get('seq'),int) and event['seq']>0
assert (event.get('emotion'),event.get('intensity')) in [('neutral',0)]+[(e,i) for e in ('happy','angry','sad') for i in (1,2)]
assert event.get('source') in ('model','fallback')
assert event.get('reason') in ('none','missing_fields','unexpected_fields','invalid_emotion','invalid_intensity','invalid_reply','non_json','invalid_json','truncated','input_limit')
if event['source']=='fallback':assert (event['emotion'],event['intensity'])==('neutral',0) and event['reason']!='none'
if event['reason']=='truncated':assert event.get('finish_reason')=='length'
summary['structured_model_output']=event['source']=='model'
assert summary['downlink_frames']==0 and emotion is None and reply_body, 'emotion event order/duplicate'
emotion=event;summary['emotion_count']+=1
summary['reply_emotion']={key:event[key] for key in ('turn_id','seq','emotion','intensity','source','reason','parse_branch','finish_reason','usage')}
if kind=='tts' and event.get('state')=='sentence_start':
assert event.get('text')==reply_body, 'TTS text differs from parsed body'
summary['tts_input_matches_body']=True
if kind=='llm.finished': stamp('llm_finished_ms')
if kind=='voice.metrics': summary['tts_requests']=event.get('tts_request_count')
if kind=='metrics':
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['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=='tts' and event.get('state')=='stop':
stopped=True; stamp('tts_stop_ms')
assert summary.get('stt_chars',0)>0 and summary['llm_chars']>0 and summary['downlink_frames']>0
# Model native drain is tested separately; this probe only confirms protocol ack.
await ws.send(json.dumps({'type':'playback.drained','turn_id':turn}))
if stopped and kind=='listen' and event.get('state')=='resumed':
summary['drained_ack']=True;stamp('drained_ack_ms');break
if after:
assert summary['backend_metrics'].get('face_cue_used') is True, 'ASR-time face snapshot missing'
await ws.send(json.dumps({'type':'context.face_cue','version':1,'turn_id':turn,'valid':False,'cue':'unknown','intensity':0,'duration_ms':0,'age_ms':0}))
await ws.send(json.dumps({'type':'context.face_cue','version':1,'turn_id':turn,'valid':True,'cue':'gaze_left','intensity':.8,'duration_ms':900,'age_ms':0}))
# A whitelisted control with invalid fields clears context; it must not close 1008.
await ws.send(json.dumps({'type':'ping'}))
while json.loads(await asyncio.wait_for(ws.recv(),5)).get('type')!='pong': pass
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['structured_model_output'], 'live structured reply fell back'
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['status']='passed'
try:
asyncio.run(probe())
except Exception as error:
summary['status']='failed'; summary['error_type']=type(error).__name__
summary['close_code']=getattr(error,'code',None)
summary.pop('pcm_square',None)
print(json.dumps(summary,ensure_ascii=False,indent=2))
raise SystemExit(0 if summary['status']=='passed' else 1)
'''
def main():
root = Path(__file__).resolve().parents[1]
payload = 'after=True\n'+PROBE
# Use the existing gateway venv if present; never install packages or load a new model.
remote = ('cd /home/gorios-spark-2/lan-voice && '
'if [ -x .venv/bin/python ]; then exec .venv/bin/python -; '
'elif [ -x venv/bin/python ]; then exec venv/bin/python -; else exec python3 -; fi')
result = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5',
'gorios-spark-2@192.168.31.61', remote],
input=payload.encode(), capture_output=True, timeout=100)
output = root / 'logs/voice-investigation'
output.mkdir(parents=True, exist_ok=True)
if result.stdout:
data = json.loads(result.stdout)
target = output / 'probe-emotion.json'
if target.exists():
(output/'probe-emotion-previous.json').write_bytes(target.read_bytes())
target.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n')
print(f'Saved redacted numeric probe results: {target.relative_to(root)}; status={data.get("status")}')
if result.stderr:
# Remote script emits no payloads. Avoid printing unexpected tracebacks/raw server errors.
print('Remote stderr present; inspect script/environment (no content printed).')
raise SystemExit(result.returncode)
if __name__ == '__main__':
main()