Files

177 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'}
sanitize = helper['log_metadata']
summary['tts_metadata'] = []
for path in sorted((ROOT/'.runtime/tts-debug').glob('*/metadata.json'), key=lambda p:p.stat().st_mtime, reverse=True)[:20]:
try:
if path.stat().st_size > 1_000_000: continue
data = json.loads(path.read_text())
row = {key:data.get(key) for key in ('turn_id','created','status','samples','seconds','peak','rms','truncated','writer_error')}
row['tts_requests'] = len(data.get('tts_requests',[]))
row['tts_input_chars'] = [len(r.get('input','')) for r in data.get('tts_requests',[])]
metrics = data.get('metrics',{})
row['metrics'] = {key:metrics.get(key) for key in ('stt_ms','llm_first_body_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_first_pcm_ms','total_ms','tts_request_count','face_cue_used')}
row['segments'] = [{k:s.get(k) for k in ('audio_seconds','total_ms','rtf','pcm_chunks','first_pcm_ms','first_voiced_ms','max_chunk_interarrival_ms')} for s in metrics.get('tts_segments',[])]
summary['tts_metadata'].append(row)
except Exception as error:
summary['tts_metadata'].append({'error_type':type(error).__name__})
summary['runtime_logs'] = {}
logpaths = list((ROOT/'.runtime').glob('*.log')) + list((ROOT/'logs').glob('*.log'))
unit = Path.home()/'.config/systemd/user/lan-voice-gateway.service'
if unit.exists():
for line in unit.read_text().splitlines():
if line.startswith(('StandardOutput=append:','StandardError=append:','StandardOutput=file:','StandardError=file:')):
logpaths.append(Path(line.split(':',1)[1]))
for path in dict.fromkeys(logpaths):
if not path.is_file(): continue
with path.open('rb') as stream:
stream.seek(max(0,path.stat().st_size-131072))
lines=stream.read().decode(errors='replace').splitlines()[-500:]
rows=[]
for line in lines:
row=sanitize(line)
trace=re.search(r'File "([^"\n]+)", line (\d+), in ([A-Za-z_0-9<>]+)',line)
if trace: row['trace']={'file':trace[1], 'line':int(trace[2]), 'function':trace[3]}
http=re.search(r'\b(POST|GET) (/v1/(?:chat/completions|audio/speech|audio/transcriptions))[^\n]*?\b([1-5]\d\d)\b',line)
if http: row['backend_http']={'method':http[1],'path':http[2],'status':int(http[3])}
if row.get('trace') or row.get('exception_types') or row.get('backend_http') or row['event']!='redacted': rows.append(row)
summary['runtime_logs'][str(path)] = rows
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(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')
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
async with asyncio.timeout(60):
while True:
raw=await ws.recv()
if isinstance(raw,bytes):
actual,seq,audio=unpack(raw,2)
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':
summary['llm_chars']+=len(event.get('text',''));summary['llm_deltas']+=1;stamp('first_llm_ms')
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_finished_ms','tts_first_pcm_ms','total_ms','tts_request_count','face_cue_used')}
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['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]
collector = (root / 'scripts/collect-voice-evidence.py').read_text()
payload = "after=" + repr('--after' in __import__('sys').argv) + "\nhelper={'__name__':'collector_library'}\nexec(" + repr(collector) + ",helper)\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-after.json' if '--after' in __import__('sys').argv else 'probe-before.json')
if target.exists() and '--after' in __import__('sys').argv:
(output/'probe-after-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()