chore: archive recoverable gateway source baseline
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import time
|
||||
import unittest
|
||||
import wave
|
||||
|
||||
import httpx
|
||||
|
||||
from gateway import Dialogue, DEFAULT_VOICE_ID
|
||||
from tests_fake import FakeModel
|
||||
from test_gateway import Socket
|
||||
|
||||
|
||||
class ContinuityTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_multidelta_one_tts_and_realtime_text(self):
|
||||
socket=Socket();tts=[]
|
||||
wav=io.BytesIO()
|
||||
with wave.open(wav,'wb') as w:
|
||||
w.setnchannels(1);w.setsampwidth(2);w.setframerate(48000);w.writeframes(bytes(1920))
|
||||
parts=['你好,今天一起','去散步。','记得喝水!']
|
||||
def backend(request):
|
||||
if 'transcriptions' in request.url.path:return httpx.Response(200,json={'text':'公开问题'})
|
||||
if 'chat' in request.url.path:
|
||||
stream=''.join('data: '+json.dumps({'choices':[{'delta':{'content':x}}]},ensure_ascii=False)+'\n\n' for x in parts)+'data: [DONE]\n\n'
|
||||
return httpx.Response(200,text=stream)
|
||||
tts.append(json.loads(request.content))
|
||||
self.assertEqual(len([e for e in socket.events if e['type']=='llm']),3)
|
||||
return httpx.Response(200,content=wav.getvalue())
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
d=Dialogue(socket,FakeModel(),client)
|
||||
await d.run(0,bytes(640))
|
||||
self.assertEqual(len(tts),1)
|
||||
self.assertEqual(tts[0]['input'],''.join(parts))
|
||||
self.assertEqual(tts[0]['voice'],DEFAULT_VOICE_ID)
|
||||
metrics=next(e['values'] for e in socket.events if e['type']=='metrics')
|
||||
self.assertEqual(metrics['tts_request_count'],1)
|
||||
self.assertEqual(metrics['voice_mode'],'continuous_voice')
|
||||
self.assertIn('llm_finished_ms',metrics)
|
||||
|
||||
async def test_cancel_before_finish_never_starts_tts(self):
|
||||
started=asyncio.Event();tts=[]
|
||||
class Slow(httpx.AsyncByteStream):
|
||||
async def __aiter__(self):
|
||||
yield b'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n'
|
||||
started.set()
|
||||
await asyncio.sleep(10)
|
||||
yield b'data: [DONE]\n\n'
|
||||
def backend(request):
|
||||
if 'chat' in request.url.path:return httpx.Response(200,stream=Slow())
|
||||
tts.append(request);return httpx.Response(200)
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
d=Dialogue(Socket(),FakeModel(),client);q=asyncio.Queue(2);d.answers[0]=''
|
||||
task=asyncio.create_task(d.generate(0,'question',q,{},time.perf_counter()))
|
||||
await started.wait();d.task=task
|
||||
await d.invalidate('client_abort')
|
||||
await d.close()
|
||||
self.assertTrue(q.empty())
|
||||
self.assertEqual(tts,[])
|
||||
@@ -0,0 +1,47 @@
|
||||
import asyncio
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
import uuid
|
||||
import wave
|
||||
from pathlib import Path
|
||||
from fastapi.testclient import TestClient
|
||||
from gateway import app
|
||||
from tts_debug import DebugStore
|
||||
|
||||
|
||||
class DebugTests(unittest.TestCase):
|
||||
def test_complete_partial_permissions_and_retention(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
store=DebugStore(root,max_runs=2)
|
||||
cid=str(uuid.uuid4())
|
||||
for status in ['completed','interrupted','failed']:
|
||||
c=store.create({'conversation_id':cid,'run_id':str(uuid.uuid4()),'tts_requests':[{'input':'公开测试'}]})
|
||||
c.append(bytes(960),10,1);c.finalize(status)
|
||||
with wave.open(str(c.path/'audio.wav')) as w:self.assertEqual(w.getnframes(),480)
|
||||
self.assertEqual((c.path/'metadata.json').stat().st_mode&511,0o600)
|
||||
rows=store.list(cid);self.assertEqual(len(rows),2)
|
||||
store.mark(rows[0]['debug_id'],cid)
|
||||
self.assertTrue(store.list(cid)[0]['marked_abnormal'])
|
||||
with self.assertRaises(ValueError):store.authorized('../escape',cid,'wav')
|
||||
with self.assertRaises(ValueError):store.authorized(rows[0]['debug_id'],str(uuid.uuid4()),'wav')
|
||||
text=store.authorized(rows[0]['debug_id'],cid,'metadata').read_text()
|
||||
for secret in ['LAN_GATEWAY_TOKEN','Authorization','reference_wav_path']:self.assertNotIn(secret,text)
|
||||
capped=store.create({'conversation_id':cid});capped.append(bytes(48000*31*2),0,1);capped.finalize('interrupted')
|
||||
with wave.open(str(capped.path/'audio.wav')) as w:self.assertLessEqual(w.getnframes(),48000*30)
|
||||
|
||||
def test_download_requires_auth_origin_and_scoped_id(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
app.state.token='x'*40;app.state.debug=DebugStore(root);cid=str(uuid.uuid4());c=app.state.debug.create({'conversation_id':cid});c.append(bytes(960),0,1);c.finalize('completed')
|
||||
client=TestClient(app)
|
||||
payload={'conversation_id':cid,'debug_id':c.id,'kind':'wav'}
|
||||
self.assertEqual(client.post('/debug/download',json=payload).status_code,403)
|
||||
headers={'Authorization':'Bearer '+'x'*40,'Origin':'https://192.168.31.61:5011'}
|
||||
self.assertEqual(client.post('/debug/download',json=payload,headers=headers).status_code,200)
|
||||
payload['debug_id']='../bad'
|
||||
self.assertEqual(client.post('/debug/download',json=payload,headers=headers).status_code,404)
|
||||
|
||||
def test_lore_constraints_bounded(self):
|
||||
d=json.loads(Path('personas/lvbu.lorebook.json').read_text());text=d['rules']+'\n'+'\n'.join(e['text'] for e in d['entries'])
|
||||
self.assertLess(len(text),1400)
|
||||
for word in ['AI','安全','Markdown','日常','现代']:self.assertIn(word,text)
|
||||
@@ -0,0 +1,46 @@
|
||||
import unittest
|
||||
from face_context import FaceContext
|
||||
|
||||
|
||||
def cue(**changes):
|
||||
return dict({'type': 'context.face_cue', 'version': 1, 'turn_id': 1, 'valid': True,
|
||||
'cue': 'smiling', 'intensity': .8, 'duration_ms': 900, 'age_ms': 100}, **changes)
|
||||
|
||||
|
||||
class FaceContextTests(unittest.TestCase):
|
||||
def test_ttl_and_one_shot(self):
|
||||
state = FaceContext()
|
||||
self.assertTrue(state.update(cue(), 1, now=100))
|
||||
state.advance_capture(1, 2)
|
||||
self.assertEqual(state.take(2, now=102.9)['role'], 'system')
|
||||
self.assertIsNone(state.take(2, now=102.9))
|
||||
state.update(cue(), 1, now=100)
|
||||
self.assertIsNone(state.take(1, now=102.901))
|
||||
|
||||
def test_no_cue_is_no_message(self):
|
||||
state = FaceContext()
|
||||
self.assertIsNone(state.take(1))
|
||||
state.update(cue(), 1, now=10)
|
||||
state.clear()
|
||||
self.assertIsNone(state.take(1, now=10))
|
||||
|
||||
def test_whitelist_invalid_clears(self):
|
||||
for change in ({'cue':'angry'}, {'text':'untrusted prompt'}, {'intensity':float('nan')},
|
||||
{'intensity':True}, {'duration_ms':799}, {'age_ms':3001}, {'version':True},
|
||||
{'turn_id':2}, {'valid':'true'}, {'cue':'eyes_closed'}, {'landmarks':[]}):
|
||||
state = FaceContext()
|
||||
state.update(cue(), 1, now=1)
|
||||
self.assertFalse(state.update(cue(**change), 1, now=1))
|
||||
self.assertIsNone(state.take(1, now=1))
|
||||
|
||||
def test_unknown_clear_and_turn_scope(self):
|
||||
state = FaceContext()
|
||||
state.update(cue(), 1, now=1)
|
||||
self.assertTrue(state.update(cue(valid=False, cue='unknown', intensity=0, duration_ms=0), 1, now=1))
|
||||
self.assertIsNone(state.take(1, now=1))
|
||||
state.update(cue(), 1, now=1)
|
||||
self.assertIsNone(state.take(2, now=1))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,115 @@
|
||||
import asyncio
|
||||
import contextlib
|
||||
import io
|
||||
import struct
|
||||
import unittest
|
||||
import wave
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from gateway import Dialogue, app
|
||||
from protocol import WavStream, pack, unpack
|
||||
from tests_fake import FakeModel
|
||||
|
||||
|
||||
class Socket:
|
||||
def __init__(self): self.events = []; self.frames = []
|
||||
async def send_json(self, data): self.events.append(data)
|
||||
async def send_bytes(self, data): self.frames.append(data)
|
||||
|
||||
|
||||
class ProtocolTests(unittest.TestCase):
|
||||
def test_frame(self):
|
||||
self.assertEqual(unpack(pack(1, 7, 3, bytes(640)), 1), (7, 3, bytes(640)))
|
||||
for data in (b'', pack(2, 7, 3, bytes(640)), b'wrong header!'):
|
||||
with self.assertRaises(ValueError): unpack(data, 1)
|
||||
|
||||
def test_incremental_wav(self):
|
||||
wav = io.BytesIO()
|
||||
with wave.open(wav, 'wb') as w:
|
||||
w.setnchannels(1); w.setsampwidth(2); w.setframerate(48000); w.writeframes(bytes(3840))
|
||||
for size in (1, 3, 137, 4096):
|
||||
parser = WavStream(); out = b''; data = wav.getvalue()
|
||||
for i in range(0, len(data), size): out += parser.feed(data[i:i + size])
|
||||
parser.finish(); self.assertEqual(out, bytes(3840))
|
||||
|
||||
def test_auth_origin_and_no_pre_auth_audio(self):
|
||||
app.state.busy = False; app.state.token = 'x' * 40
|
||||
client = TestClient(app)
|
||||
with contextlib.nullcontext(client) as client:
|
||||
with self.assertRaises(Exception):
|
||||
with client.websocket_connect('/ws/dialogue', headers={'Origin': 'https://evil.invalid'}): pass
|
||||
with client.websocket_connect('/ws/dialogue', headers={'Origin': 'https://192.168.31.61:5011'}) as ws:
|
||||
ws.send_json({'type': 'auth', 'token': 'wrong'})
|
||||
with self.assertRaises(Exception): ws.receive_json()
|
||||
self.assertFalse(app.state.busy)
|
||||
with client.websocket_connect('/ws/dialogue', headers={'Origin': 'https://192.168.31.61:5011'}) as ws:
|
||||
ws.send_bytes(pack(1, 0, 1, bytes(640)))
|
||||
with self.assertRaises(Exception): ws.receive_json()
|
||||
|
||||
|
||||
class DialogueTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_cancel_and_sequence(self):
|
||||
socket = Socket(); dialogue = Dialogue(socket, FakeModel(), None)
|
||||
await dialogue.listen('manual')
|
||||
old = dialogue.turn
|
||||
await dialogue.input(pack(1, old, 1, bytes(640)))
|
||||
with self.assertRaises(ValueError): await dialogue.input(pack(1, old, 3, bytes(640)))
|
||||
dialogue.task = asyncio.create_task(asyncio.sleep(10))
|
||||
await dialogue.invalidate('test_abort')
|
||||
await dialogue.audio(old, bytes(1920))
|
||||
await dialogue.event('llm', old, text='stale')
|
||||
await dialogue.input(pack(1, old, 2, bytes(640)))
|
||||
self.assertEqual(socket.frames, [])
|
||||
self.assertFalse(any(e.get('text') == 'stale' for e in socket.events))
|
||||
self.assertEqual(len(dialogue.capture), 0)
|
||||
await dialogue.close()
|
||||
|
||||
async def test_barge_preserves_coordinates_and_submits(self):
|
||||
class SpeechModel(FakeModel):
|
||||
def infer(self, pcm, state): return (0.9 if pcm[0] else 0.0), state
|
||||
socket = Socket(); dialogue = Dialogue(socket, SpeechModel(), None)
|
||||
await dialogue.listen('auto', barge=True)
|
||||
old = dialogue.turn
|
||||
dialogue.task = asyncio.create_task(asyncio.sleep(10))
|
||||
await dialogue.input(pack(1, old, 1, struct.pack('<h', 1000) * 1536))
|
||||
self.assertGreater(dialogue.turn, old)
|
||||
self.assertTrue(dialogue.vad.active)
|
||||
submitted = []
|
||||
async def submit(pcm, end): submitted.append((len(pcm), end))
|
||||
dialogue.submit = submit
|
||||
await dialogue.input(pack(1, dialogue.turn, 1, bytes(10240)))
|
||||
self.assertEqual(submitted, [(3072, 1536)])
|
||||
await dialogue.close()
|
||||
|
||||
async def test_debug_half_duplex_drain_blocks_echo_input(self):
|
||||
dialogue = Dialogue(Socket(), FakeModel(), None)
|
||||
await dialogue.listen('auto', barge=False)
|
||||
dialogue.playback_waiting = True
|
||||
await dialogue.input(pack(1, dialogue.turn, 1, bytes(640)))
|
||||
self.assertEqual(dialogue.capture, b'')
|
||||
self.assertEqual(dialogue.vad.samples, 0)
|
||||
await dialogue.close()
|
||||
|
||||
async def test_stage_metrics_mock_pipeline(self):
|
||||
socket = Socket()
|
||||
wav = io.BytesIO()
|
||||
with wave.open(wav, 'wb') as w:
|
||||
w.setnchannels(1); w.setsampwidth(2); w.setframerate(48000); w.writeframes(struct.pack('<h', 1000) * 1920)
|
||||
def backend(request):
|
||||
if 'transcriptions' in request.url.path: return httpx.Response(200, json={'text': '喝水有什么用?'})
|
||||
if 'chat' in request.url.path:
|
||||
return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"补充水分。"}}]}\n\ndata: [DONE]\n\n', headers={'Content-Type': 'text/event-stream'})
|
||||
return httpx.Response(200, content=wav.getvalue())
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
dialogue = Dialogue(socket, FakeModel(), client)
|
||||
await dialogue.run(0, bytes(640))
|
||||
metrics = [e for e in socket.events if e['type'] == 'metrics'][0]['values']
|
||||
for key in ['stt_ms','llm_first_body_ms','first_fragment_ms','tts_first_pcm_ms','tts_first_voiced_block_ms']: self.assertIn(key, metrics)
|
||||
segment=metrics['tts_segments'][0]
|
||||
for key in ['first_pcm_ms','first_voiced_ms','total_ms','audio_seconds','rtf','schedule_gap_ms','pcm_arrival_gap_ms','ready_ahead']: self.assertIn(key,segment)
|
||||
self.assertNotIn('text',segment)
|
||||
self.assertEqual(segment['audio_seconds'],.04)
|
||||
self.assertEqual(len(socket.frames), 2)
|
||||
self.assertEqual(unpack(socket.frames[0], 2)[:2], (0, 1))
|
||||
@@ -0,0 +1,105 @@
|
||||
"""No live models/sockets: actual Dialogue + HTTP doubles, including drain/finalization race."""
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import time
|
||||
import unittest
|
||||
import wave
|
||||
import httpx
|
||||
from gateway import Dialogue
|
||||
from tests_fake import FakeModel
|
||||
from test_gateway import Socket
|
||||
from test_face_context import cue
|
||||
|
||||
|
||||
def wav(pcm):
|
||||
out = io.BytesIO()
|
||||
with wave.open(out, 'wb') as file:
|
||||
file.setnchannels(1); file.setsampwidth(2); file.setframerate(48000); file.writeframes(pcm)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
class ReplyFaceTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def round(self, observation=False, empty_llm=False, empty_tts=False, empty_stt=False):
|
||||
messages = []
|
||||
def backend(request):
|
||||
if 'transcriptions' in request.url.path:
|
||||
return httpx.Response(200, json={'text': '' if empty_stt else '公开合成测试'})
|
||||
if 'chat' in request.url.path:
|
||||
messages.append(json.loads(request.content)['messages'])
|
||||
# The actual deployed Qwen template accepts only one initial system.
|
||||
self.assertEqual(sum(m['role']=='system' for m in messages[-1]), 1)
|
||||
body = '' if empty_llm else '测试回答'
|
||||
return httpx.Response(200, text='data: '+json.dumps({'choices':[{'delta':{'content':body}}]})+'\n\ndata: [DONE]\n\n')
|
||||
return httpx.Response(200, content=wav(b'' if empty_tts else b'\x10\x01'*960))
|
||||
socket = Socket()
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
d = Dialogue(socket, FakeModel(), client)
|
||||
if observation:
|
||||
self.assertTrue(d.face_context.update(cue(turn_id=0), 0))
|
||||
await d.invalidate('new_turn')
|
||||
await d.run(d.turn, bytes(640))
|
||||
return d, socket, messages
|
||||
|
||||
async def test_optional_ephemeral_message(self):
|
||||
d, socket, messages = await self.round(observation=True)
|
||||
self.assertEqual([m['role'] for m in messages[0]], ['system','user'])
|
||||
self.assertIn('摄像头观察', messages[0][0]['content'])
|
||||
self.assertEqual(d.face_messages, {})
|
||||
self.assertIsNone(d.face_context.value)
|
||||
self.assertTrue(socket.frames)
|
||||
d, socket, messages = await self.round(observation=False)
|
||||
self.assertEqual([m['role'] for m in messages[0]], ['system','user'])
|
||||
self.assertNotIn('摄像头观察', messages[0][0]['content'])
|
||||
|
||||
async def test_expired_and_barge_clear(self):
|
||||
d = Dialogue(Socket(), FakeModel(), None)
|
||||
d.face_context.update(cue(turn_id=0),0,now=time.monotonic()-4)
|
||||
await d.invalidate('new_turn')
|
||||
self.assertIsNone(d.face_context.take(d.turn))
|
||||
for reason in ('listen_start','voice_barge_in','client_abort','history_new'):
|
||||
d.face_context.update(cue(turn_id=d.turn),d.turn)
|
||||
await d.invalidate(reason)
|
||||
self.assertIsNone(d.face_context.value)
|
||||
|
||||
async def test_empty_body_or_pcm_explicit_error(self):
|
||||
for options in ({'empty_llm':True}, {'empty_tts':True}):
|
||||
d, socket, _ = await self.round(**options)
|
||||
self.assertTrue(any(e['type']=='error' and e['code']=='backend_failed' for e in socket.events))
|
||||
self.assertFalse(socket.frames)
|
||||
|
||||
async def test_empty_stt_recovers_listening(self):
|
||||
d, socket, messages = await self.round(empty_stt=True)
|
||||
self.assertFalse(messages)
|
||||
self.assertTrue(any(e['type']=='listen' and e['state']=='resumed' for e in socket.events))
|
||||
|
||||
async def test_native_drain_during_history_finalize_not_lost(self):
|
||||
entered, finish = asyncio.Event(), asyncio.Event()
|
||||
class History:
|
||||
async def begin(self,*args): pass
|
||||
async def context(self,*args): return []
|
||||
async def rows(self,*args): return []
|
||||
async def finish(self,*args): entered.set(); await finish.wait()
|
||||
async def drained(self,*args): pass
|
||||
def backend(request):
|
||||
if 'transcriptions' in request.url.path: return httpx.Response(200,json={'text':'公开测试'})
|
||||
if 'chat' in request.url.path: return httpx.Response(200,text='data: {"choices":[{"delta":{"content":"回答"}}]}\n\ndata: [DONE]\n\n')
|
||||
return httpx.Response(200,content=wav(b'\x10\x01'*960))
|
||||
socket = Socket()
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
d=Dialogue(socket,FakeModel(),client,History(),'synthetic-conversation')
|
||||
d.run_id='synthetic-run'
|
||||
d.task=asyncio.create_task(d.run(0,bytes(640)))
|
||||
await asyncio.wait_for(entered.wait(),2)
|
||||
self.assertTrue(any(e['type']=='tts' and e.get('state')=='stop' for e in socket.events))
|
||||
await d.request_drained(0)
|
||||
self.assertEqual(d.pending_drained,0)
|
||||
finish.set()
|
||||
await asyncio.wait_for(d.task,2)
|
||||
self.assertFalse(d.playback_waiting)
|
||||
self.assertEqual(sum(e['type']=='listen' and e['state']=='resumed' for e in socket.events),1)
|
||||
await d.request_drained(0) # duplicate must not send another ack
|
||||
self.assertEqual(sum(e['type']=='listen' and e['state']=='resumed' for e in socket.events),1)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,28 @@
|
||||
import time
|
||||
import unittest
|
||||
from fastapi.testclient import TestClient
|
||||
from guest_sessions import GuestSessions, COOKIE
|
||||
from gateway import app
|
||||
|
||||
|
||||
class GuestTests(unittest.TestCase):
|
||||
def test_network_owner_expiry_capacity(self):
|
||||
for ip in ['192.168.31.2','127.0.0.1','::1']:self.assertTrue(GuestSessions.lan(ip))
|
||||
for ip in ['10.0.0.1','192.168.1.2','172.16.1.1','bad']:self.assertFalse(GuestSessions.lan(ip))
|
||||
g=GuestSessions(capacity=2);a=g.create();b=g.create();g.bind(a,'cid')
|
||||
with self.assertRaises(ValueError):g.own(b,'cid')
|
||||
with self.assertRaises(ValueError):g.create()
|
||||
g.sessions[a]['expires']=time.time()-1;self.assertIsNone(g.get(a));g.revoke(b);self.assertIsNone(g.get(b))
|
||||
|
||||
def test_bootstrap_origin_cookie_nonlan_and_logout(self):
|
||||
app.state.guests=GuestSessions();app.state.guest_enabled=True
|
||||
client=TestClient(app,base_url='https://192.168.31.61:5011',client=('192.168.31.2',4000))
|
||||
self.assertEqual(client.post('/session/bootstrap',json={}).status_code,403)
|
||||
self.assertEqual(client.post('/session/bootstrap',json={},headers={'Origin':'https://evil.test'}).status_code,403)
|
||||
r=client.post('/session/bootstrap',json={},headers={'Origin':'https://192.168.31.61:5011'})
|
||||
self.assertEqual(r.status_code,200)
|
||||
for flag in ['HttpOnly','Secure','SameSite=strict']:self.assertIn(flag,r.headers['set-cookie'])
|
||||
key=client.cookies.get(COOKIE);self.assertTrue(app.state.guests.get(key))
|
||||
bad=TestClient(app,client=('10.0.0.1',4000))
|
||||
self.assertEqual(bad.post('/session/bootstrap',json={},headers={'Origin':'https://192.168.31.61:5011','X-Forwarded-For':'192.168.31.2'}).status_code,403)
|
||||
client.post('/session/logout',headers={'Origin':'https://192.168.31.61:5011'});self.assertIsNone(app.state.guests.get(key))
|
||||
@@ -0,0 +1,168 @@
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import struct
|
||||
import tempfile
|
||||
import unittest
|
||||
import uuid
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
from unittest.mock import patch
|
||||
|
||||
from gateway import Dialogue, app
|
||||
from history import History
|
||||
from protocol import pack
|
||||
from tests_fake import FakeModel
|
||||
from test_gateway import Socket
|
||||
|
||||
|
||||
class SpeechModel(FakeModel):
|
||||
def infer(self, pcm, state): return (0.9 if pcm[0] else 0.0), state
|
||||
|
||||
|
||||
class HistoryTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.h = History(Path(self.temp.name) / 'history.sqlite3')
|
||||
await self.h.initialize()
|
||||
self.cid = await self.h.conversation()
|
||||
|
||||
async def asyncTearDown(self): self.temp.cleanup()
|
||||
|
||||
async def test_restore_window_clear_and_partial(self):
|
||||
for i in range(12):
|
||||
rid = str(uuid.uuid4())
|
||||
await self.h.begin(self.cid, rid, f'user{i}')
|
||||
await self.h.finish(rid, f'answer{i}', 'completed')
|
||||
await self.h.drained(rid)
|
||||
partial = str(uuid.uuid4())
|
||||
await self.h.begin(self.cid, partial, 'partial user')
|
||||
await self.h.finish(partial, 'unfinished', 'interrupted')
|
||||
restarted = History(self.h.path); await restarted.initialize()
|
||||
context = await restarted.context(self.cid, 'current')
|
||||
self.assertEqual(len(context), 20)
|
||||
self.assertEqual(context[0]['content'], 'user2')
|
||||
self.assertFalse(any(x['content'] == 'unfinished' for x in context))
|
||||
self.assertEqual(len(await restarted.rows(self.cid)), 26)
|
||||
other = await restarted.conversation()
|
||||
await restarted.begin(other, str(uuid.uuid4()), 'keep')
|
||||
await restarted.clear(self.cid)
|
||||
self.assertEqual(await restarted.rows(self.cid), [])
|
||||
self.assertEqual(len(await restarted.rows(other)), 2)
|
||||
self.assertEqual(self.h.path.stat().st_mode & 0o777, 0o600)
|
||||
with self.assertRaises(ValueError): await restarted.conversation('../bad')
|
||||
|
||||
async def test_stale_finalize_and_playback_separate(self):
|
||||
rid = str(uuid.uuid4())
|
||||
await self.h.begin(self.cid, rid, 'user')
|
||||
await self.h.interrupt(rid)
|
||||
await self.h.finish(rid, 'partial', 'interrupted')
|
||||
await self.h.finish(rid, 'old complete', 'completed')
|
||||
rows = await self.h.rows(self.cid)
|
||||
self.assertEqual(rows[-1]['text'], 'partial')
|
||||
self.assertEqual(rows[-1]['status'], 'interrupted')
|
||||
self.assertEqual(await self.h.context(self.cid, 'other'), [])
|
||||
rid2 = str(uuid.uuid4())
|
||||
await self.h.begin(self.cid, rid2, 'user2')
|
||||
await self.h.finish(rid2, 'answer2', 'completed')
|
||||
self.assertEqual((await self.h.rows(self.cid))[-1]['playback'], 'awaiting_drain')
|
||||
self.assertEqual(await self.h.context(self.cid, 'next'), [])
|
||||
rid3 = str(uuid.uuid4())
|
||||
await self.h.begin(self.cid, rid3, 'unheard user')
|
||||
await self.h.finish(rid3, 'unheard completed answer', 'completed')
|
||||
await self.h.interrupt(rid3)
|
||||
self.assertEqual(await self.h.context(self.cid, 'next'), [])
|
||||
self.assertEqual((await self.h.rows(self.cid))[-1]['status'], 'completed')
|
||||
await self.h.drained(rid2)
|
||||
rows = await self.h.rows(self.cid)
|
||||
self.assertEqual(next(r for r in rows if r['run_id'] == rid2 and r['role'] == 'assistant')['playback'], 'confirmed')
|
||||
self.assertEqual(len(await self.h.context(self.cid, 'next')), 2)
|
||||
|
||||
async def test_duplex_running_and_awaiting_drain_no_loop(self):
|
||||
for running in (True, False):
|
||||
socket = Socket(); d = Dialogue(socket, SpeechModel(), None)
|
||||
await d.listen('auto')
|
||||
old = d.turn
|
||||
if running: d.task = asyncio.create_task(asyncio.sleep(10))
|
||||
else: d.playback_waiting = True
|
||||
await d.input(pack(1, old, 1, struct.pack('<h', 1000) * 1536))
|
||||
self.assertEqual(d.turn, old + 1)
|
||||
after_start = d.turn
|
||||
await d.input(pack(1, d.turn, 1, struct.pack('<h', 1000) * 1536))
|
||||
self.assertEqual(d.turn, after_start)
|
||||
submitted = []
|
||||
async def submit(pcm, end): submitted.append((len(pcm), end))
|
||||
d.submit = submit
|
||||
await d.input(pack(1, d.turn, 2, bytes(10240)))
|
||||
self.assertEqual(submitted, [(6144, 3072)])
|
||||
self.assertEqual(len([e for e in socket.events if e.get('reason') == 'voice_barge_in']), 1)
|
||||
await d.close()
|
||||
|
||||
async def test_two_turn_mock_context_and_drain(self):
|
||||
calls = []
|
||||
wav = io.BytesIO()
|
||||
with wave.open(wav, 'wb') as w:
|
||||
w.setnchannels(1); w.setsampwidth(2); w.setframerate(48000); w.writeframes(struct.pack('<h', 1000) * 960)
|
||||
def backend(request):
|
||||
if 'transcriptions' in request.url.path: return httpx.Response(200, json={'text': '当前问题'})
|
||||
if 'chat' in request.url.path:
|
||||
calls.append(json.loads(request.content)['messages'])
|
||||
return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"直接回答。"}}]}\n\ndata: [DONE]\n\n')
|
||||
return httpx.Response(200, content=wav.getvalue())
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
d = Dialogue(Socket(), SpeechModel(), client, self.h, self.cid)
|
||||
for _ in range(2):
|
||||
await d.submit(bytes(640), 320)
|
||||
await d.task
|
||||
await d.drained()
|
||||
self.assertEqual(len(calls[0]), 2)
|
||||
self.assertEqual(len(calls[1]), 4)
|
||||
self.assertEqual(calls[1][-1], {'role':'user','content':'当前问题'})
|
||||
self.assertEqual(len(await self.h.rows(self.cid)), 4)
|
||||
await d.close()
|
||||
|
||||
async def test_interrupted_pipeline_keeps_partial_no_new_turn_pollution(self):
|
||||
socket = Socket(); d = Dialogue(socket, SpeechModel(), None, self.h, self.cid)
|
||||
rid = str(uuid.uuid4()); d.run_id = rid
|
||||
await self.h.begin(self.cid, rid, 'old question')
|
||||
async def old_pipeline():
|
||||
try: await asyncio.sleep(10)
|
||||
finally: await self.h.finish(rid, 'old partial', 'interrupted')
|
||||
d.task = asyncio.create_task(old_pipeline()); await asyncio.sleep(0)
|
||||
await d.invalidate('voice_barge_in')
|
||||
await asyncio.gather(*list(d.cancelled_tasks), return_exceptions=True)
|
||||
new_rid = str(uuid.uuid4())
|
||||
await self.h.begin(self.cid, new_rid, 'new question')
|
||||
await self.h.finish(new_rid, 'new answer', 'completed')
|
||||
await self.h.drained(new_rid)
|
||||
rows = await self.h.rows(self.cid)
|
||||
self.assertEqual([r['status'] for r in rows], ['completed','interrupted','completed','completed'])
|
||||
self.assertEqual(len(await self.h.context(self.cid, 'future')), 2)
|
||||
await d.close()
|
||||
|
||||
|
||||
class AuthHistoryTests(unittest.TestCase):
|
||||
def test_history_only_after_auth_and_scoped(self):
|
||||
with tempfile.TemporaryDirectory() as directory, patch.dict('os.environ', {'LAN_GATEWAY_TOKEN':'x'*40}), patch('gateway.ROOT', Path(directory)):
|
||||
app.state.busy = False; app.state.token = 'x'*40
|
||||
h = History(Path(directory)/'history.sqlite3')
|
||||
asyncio.run(h.initialize()); app.state.history = h
|
||||
app.state.model = FakeModel(); app.state.client = None
|
||||
from tts_debug import DebugStore
|
||||
app.state.debug = DebugStore(Path(directory)/'debug')
|
||||
from gateway import DEFAULT_VOICE_ID
|
||||
app.state.voices = [{'id':DEFAULT_VOICE_ID,'source':'design','default':True}]
|
||||
client = TestClient(app)
|
||||
with client.websocket_connect('/ws/dialogue', headers={'Origin':'https://192.168.31.61:5011'}) as ws:
|
||||
ws.send_json({'type':'history','action':'get'})
|
||||
with self.assertRaises(Exception): ws.receive_json()
|
||||
with client.websocket_connect('/ws/dialogue', headers={'Origin':'https://192.168.31.61:5011'}) as ws:
|
||||
ws.send_json({'type':'auth','token':'x'*40}); ws.receive_json()
|
||||
ws.send_json({'type':'hello','codec':'pcm16','sample_rate':16000,'frame_duration':20})
|
||||
cid = ws.receive_json()['conversation_id']; history = ws.receive_json()
|
||||
self.assertEqual(history['messages'], [])
|
||||
ws.send_json({'type':'history','action':'clear','conversation_id':str(uuid.uuid4())})
|
||||
with self.assertRaises(Exception): ws.receive_json()
|
||||
@@ -0,0 +1,23 @@
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from persona_resolver import resolve_persona, DEFAULT_VOICE_ID
|
||||
|
||||
|
||||
class PersonaTests(unittest.TestCase):
|
||||
def test_yangmi_authorized_voice_new_context_and_rules(self):
|
||||
import json
|
||||
vid=json.loads(Path('.runtime/personas/yangmi_fiction.json').read_text())['voice_id']
|
||||
p=resolve_persona(Path('.'),'yangmi_fiction',[vid])
|
||||
self.assertEqual(p['voice_id'],vid)
|
||||
self.assertTrue(p['fresh_conversation']);self.assertTrue(p['locked'])
|
||||
self.assertIn('北京',p['rules']);self.assertNotIn('奉先',p['rules'])
|
||||
self.assertNotIn('https://',p['rules']);self.assertLessEqual(len(p['rules']),1400)
|
||||
for value in ['北京','演员','旁白']:self.assertIn(value,p['rules'])
|
||||
|
||||
def test_lvbu_unchanged_and_unknown_rejected(self):
|
||||
import json
|
||||
vid=json.loads(Path('.runtime/personas/lvbu.json').read_text())['voice_id']
|
||||
p=resolve_persona('.','lvbu',[vid]);self.assertEqual(p['voice_id'],vid);self.assertIn('奉先',p['rules']);self.assertNotIn('杨密',p['rules'])
|
||||
for value in ['unknown','../lvbu',None]:
|
||||
with self.assertRaises(ValueError):resolve_persona('.',value,[vid])
|
||||
with self.assertRaises(ValueError):resolve_persona('.','yangmi_fiction',[])
|
||||
@@ -0,0 +1,50 @@
|
||||
import unittest
|
||||
from segmentation import Segmenter
|
||||
|
||||
|
||||
class SegmentTests(unittest.TestCase):
|
||||
def test_user_three_plus_four_short_final(self):
|
||||
for mode in ('balanced', 'low_latency'):
|
||||
for text in ('好的,我们去。', '好呀!一起走。', '是的,我们去散步。'):
|
||||
s = Segmenter(mode)
|
||||
first=s.add(text, 0)
|
||||
if first is not None:
|
||||
self.assertEqual(first,text)
|
||||
else:
|
||||
self.assertIsNone(s.take(2))
|
||||
self.assertEqual(s.take(2, final=True), text)
|
||||
self.assertEqual(s.buffer, '')
|
||||
|
||||
def test_natural_first_min_and_no_undersized_fallback(self):
|
||||
for mode, minimum in [('balanced', 12), ('low_latency', 8)]:
|
||||
s=Segmenter(mode)
|
||||
self.assertIsNone(s.add('好的,'+'甲'*(minimum-4),0))
|
||||
self.assertIsNone(s.take(3))
|
||||
self.assertEqual(s.add('乙'*30,3),('好的,'+'甲'*(minimum-4)+'乙'*30)[:24])
|
||||
self.assertEqual(s.last_cut,'hard_limit')
|
||||
self.assertEqual(s.hardcuts,1)
|
||||
s=Segmenter(mode)
|
||||
value=s.add('甲'*minimum+',后续。',0)
|
||||
self.assertEqual(value,'甲'*minimum+',')
|
||||
self.assertEqual(s.take(1,final=True),'后续。')
|
||||
|
||||
def test_limits_multi_delta_final_no_loss(self):
|
||||
for mode in ('balanced','low_latency'):
|
||||
s=Segmenter(mode);text=('甲'*12+',')*20;output=[]
|
||||
fragment=s.add(text,0)
|
||||
if fragment:output.append(fragment)
|
||||
while True:
|
||||
value=s.take(.1)
|
||||
if not value:break
|
||||
output.append(value)
|
||||
if s.buffer:output.append(s.take(1,final=True))
|
||||
self.assertEqual(''.join(output),text)
|
||||
self.assertTrue(all(len(x)>=s.first_min for x in output[:-1]))
|
||||
with self.assertRaises(ValueError):Segmenter('bad')
|
||||
|
||||
def test_final_remaining_whole_multiple_punctuation(self):
|
||||
s=Segmenter();s.add('甲'*12+',',0)
|
||||
tail='好的,走吧。慢慢来!'
|
||||
self.assertIsNone(s.add(tail,.1))
|
||||
self.assertEqual(s.take(1,final=True),tail)
|
||||
self.assertIsNone(s.take(1,final=True))
|
||||
@@ -0,0 +1,81 @@
|
||||
"""v0.8: LAN 直连授权 + active_profile 单元测试(不需要网络/模型)。"""
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import gateway
|
||||
from guest_sessions import GuestSessions
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, host):
|
||||
self.host = host
|
||||
|
||||
|
||||
class FakeConn:
|
||||
def __init__(self, host):
|
||||
self.client = FakeClient(host)
|
||||
|
||||
|
||||
class TestLanOpenMode(unittest.TestCase):
|
||||
def setUp(self):
|
||||
gateway.app.state.guests = GuestSessions()
|
||||
gateway.app.state.lan_open = True
|
||||
|
||||
def test_open_key_from_lan_ip(self):
|
||||
key = gateway.open_key(FakeConn('192.168.31.200'))
|
||||
self.assertEqual(key, 'lan:192.168.31.200')
|
||||
self.assertIsNotNone(gateway.app.state.guests.get(key))
|
||||
|
||||
def test_open_key_reusable_and_own_bind(self):
|
||||
key = gateway.open_key(FakeConn('192.168.31.200'))
|
||||
gateway.app.state.guests.bind(key, 'cid-1')
|
||||
gateway.app.state.guests.own(key, 'cid-1')
|
||||
with self.assertRaises(ValueError):
|
||||
gateway.app.state.guests.own(key, 'cid-other')
|
||||
|
||||
def test_open_key_none_when_disabled(self):
|
||||
gateway.app.state.lan_open = False
|
||||
self.assertIsNone(gateway.open_key(FakeConn('192.168.31.200')))
|
||||
|
||||
def test_open_key_none_for_foreign_ip(self):
|
||||
self.assertIsNone(gateway.open_key(FakeConn('10.9.9.9')))
|
||||
|
||||
|
||||
class TestActiveProfile(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.orig_root = gateway.ROOT
|
||||
root = Path(self.tmp.name)
|
||||
(root / '.runtime').mkdir()
|
||||
gateway.ROOT = root
|
||||
self.addCleanup(setattr, gateway, 'ROOT', self.orig_root)
|
||||
|
||||
def write(self, data):
|
||||
(gateway.ROOT / '.runtime' / 'active_profile.json').write_text(json.dumps(data), encoding='utf-8')
|
||||
|
||||
def test_missing_file_returns_none(self):
|
||||
self.assertIsNone(gateway.load_active_profile())
|
||||
|
||||
def test_valid_profile(self):
|
||||
self.write({'persona': 'yangmi_fiction', 'voice_id': 'v-1'})
|
||||
p = gateway.load_active_profile()
|
||||
self.assertEqual(p['persona'], 'yangmi_fiction')
|
||||
self.assertEqual(p['voice_id'], 'v-1')
|
||||
|
||||
def test_invalid_json_returns_none(self):
|
||||
(gateway.ROOT / '.runtime' / 'active_profile.json').write_text('{bad', encoding='utf-8')
|
||||
self.assertIsNone(gateway.load_active_profile())
|
||||
|
||||
def test_non_dict_returns_none(self):
|
||||
self.write([1, 2])
|
||||
self.assertIsNone(gateway.load_active_profile())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,123 @@
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vad import Config, Silero, VadSession, WINDOW
|
||||
|
||||
|
||||
class Fake:
|
||||
def new_state(self):
|
||||
return np.zeros(1)
|
||||
|
||||
def infer(self, pcm, state):
|
||||
state = state.copy() + 1
|
||||
return (0.9 if pcm[0] else 0.0), state
|
||||
|
||||
|
||||
class VadTests(unittest.TestCase):
|
||||
def test_chunks_and_frames_equal(self):
|
||||
data = np.concatenate([np.zeros(2048, dtype='<i2'), np.ones(4096, dtype='<i2'), np.zeros(8192, dtype='<i2')]).tobytes()
|
||||
outputs = []
|
||||
for size in (640, 1, 137, 65536):
|
||||
session = VadSession(Fake())
|
||||
events = []
|
||||
for i in range(0, len(data), size):
|
||||
events += session.feed(data[i:i + size])
|
||||
events += session.finish()
|
||||
outputs.append(events)
|
||||
self.assertLess(len(session.pending), 1024)
|
||||
self.assertTrue(all(x == outputs[0] for x in outputs))
|
||||
self.assertEqual([e['type'] for e in outputs[0]], ['speech.start', 'speech.end', 'session.ended'])
|
||||
|
||||
def test_isolation(self):
|
||||
model = Fake()
|
||||
a, b = VadSession(model), VadSession(model)
|
||||
a.feed(np.ones(1536, dtype='<i2').tobytes())
|
||||
self.assertTrue(a.active)
|
||||
self.assertFalse(b.active)
|
||||
self.assertEqual(b.state[0], 0)
|
||||
b.feed(bytes(4096))
|
||||
self.assertTrue(a.active)
|
||||
self.assertFalse(b.active)
|
||||
|
||||
def test_silero_silence_and_state(self):
|
||||
model = Silero(Path('models/silero_vad.onnx'))
|
||||
a, b = VadSession(model), VadSession(model)
|
||||
self.assertEqual(a.feed(bytes(32000)), [])
|
||||
self.assertTrue(np.all(b.state[0] == 0))
|
||||
b.feed(bytes(32000))
|
||||
np.testing.assert_array_equal(a.state[0], b.state[0])
|
||||
a.reset()
|
||||
self.assertTrue(np.all(a.state[0] == 0))
|
||||
|
||||
def test_reset_end(self):
|
||||
a = VadSession(Fake())
|
||||
a.feed(np.ones(1536, dtype='<i2').tobytes())
|
||||
events = a.reset()
|
||||
self.assertEqual(events[0]['reason'], 'reset')
|
||||
self.assertEqual(a.samples, 0)
|
||||
self.assertEqual(a.epoch, 1)
|
||||
a.feed(np.ones(1536, dtype='<i2').tobytes())
|
||||
self.assertEqual(a.finish()[0]['reason'], 'input_end')
|
||||
with self.assertRaises(ValueError):
|
||||
a.feed(bytes(2))
|
||||
a.reset()
|
||||
self.assertEqual(a.feed(bytes(2)), [])
|
||||
|
||||
def test_limits(self):
|
||||
a = VadSession(Fake(), Config(max_speech_seconds=1, max_session_seconds=2))
|
||||
events = a.feed(np.ones(20000, dtype='<i2').tobytes())
|
||||
self.assertIn('max_duration', [e.get('reason') for e in events])
|
||||
with self.assertRaises(ValueError):
|
||||
a.feed(bytes(30000))
|
||||
with self.assertRaises(ValueError):
|
||||
VadSession(Fake()).feed(bytes(65537))
|
||||
a = VadSession(Fake())
|
||||
a.feed(b'\x01')
|
||||
with self.assertRaises(ValueError):
|
||||
a.finish()
|
||||
for value in (199, 601):
|
||||
with self.assertRaises(ValueError):
|
||||
Config(silence_ms=value)
|
||||
|
||||
def test_debounce_silence_timestamps(self):
|
||||
a = VadSession(Fake())
|
||||
self.assertEqual(a.feed(np.ones(1024, dtype='<i2').tobytes()), [])
|
||||
start = a.feed(np.ones(512, dtype='<i2').tobytes())[0]
|
||||
self.assertEqual(start['sample'], 0)
|
||||
self.assertEqual(start['detected_at_sample'], 1536)
|
||||
ends = a.feed(bytes(1024 * 10))
|
||||
self.assertEqual(ends[0]['sample'], 1536)
|
||||
self.assertEqual(ends[0]['detected_at_sample'], 6656)
|
||||
|
||||
def test_low_threshold_ends_silence(self):
|
||||
a = VadSession(Fake(), Config(threshold=0.1))
|
||||
a.feed(np.ones(1536, dtype='<i2').tobytes())
|
||||
events = a.feed(bytes(1024 * 10))
|
||||
self.assertEqual(events[0]['reason'], 'silence')
|
||||
self.assertFalse(a.active)
|
||||
|
||||
def test_tail_timestamps_and_audio(self):
|
||||
for size in (513, 1025, 15999):
|
||||
a = VadSession(Fake(), Config(max_speech_seconds=1, start_windows=2, include_preroll_audio=True))
|
||||
a.feed(np.ones(size, dtype='<i2').tobytes())
|
||||
events = a.finish()
|
||||
for event in events:
|
||||
self.assertLessEqual(event['sample'], size)
|
||||
self.assertLessEqual(event['time_ms'], size / 16)
|
||||
self.assertLessEqual(event['detected_at_sample'], size)
|
||||
if 'audio_until_sample' in event:
|
||||
self.assertLessEqual(event['audio_until_sample'], size)
|
||||
import base64
|
||||
self.assertEqual(len(base64.b64decode(event['preroll_pcm16_base64'])), (event['audio_until_sample'] - event['preroll_start_sample']) * 2)
|
||||
self.assertEqual(events[-1]['sample'], size)
|
||||
|
||||
def test_preroll_audio_opt_in(self):
|
||||
a = VadSession(Fake())
|
||||
event = a.feed(np.ones(1536, dtype='<i2').tobytes())[0]
|
||||
self.assertNotIn('preroll_pcm16_base64', event)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user