diff --git a/gateway/.gitignore b/gateway/.gitignore new file mode 100644 index 0000000..d5a2bd9 --- /dev/null +++ b/gateway/.gitignore @@ -0,0 +1,15 @@ +.runtime/ +.env +.env.* +!.env.example +venv/ +.venv/ +models/ +__pycache__/ +*.py[cod] +logs/ +tmp/ +*.wav +*.pcm +*.key +*.pem diff --git a/gateway/README.md b/gateway/README.md new file mode 100644 index 0000000..e967667 --- /dev/null +++ b/gateway/README.md @@ -0,0 +1,18 @@ +# LAN Voice gateway — recoverable source archive + +This directory contains the actual deployed SPARK-2 source, not just an Android-side patch. `SOURCE_MANIFEST.json` identifies the source files by SHA256, the observed code version, interpreter and dependency versions. No `.runtime`, chat/history/diagnostic data, token/Cookie, voice reference audio, model, private key, cache or venv is included. Existing Android `app/` is unchanged by archiving. + +`gateway.py` is the dialogue gateway; `app.py` is the separate VAD API. `guest_sessions.py`, `vad.py`, `history.py`, `persona_resolver.py`, `segmentation.py`, `protocol.py`, `tts_debug.py` and `face_context.py` are restored alongside them. Public lore is in `personas/`, browser source in `web/`, tests in `tests/`. Upstream documentation, if present, is preserved separately under `docs/UPSTREAM_README.md`. Legacy scripts may contain deployment-specific addresses/paths: they are source records, not portable install commands. + +## Restore on a suitable server + +1. Read `SOURCE_MANIFEST.json`. Create a venv using a compatible Python/platform, then install `requirements.lock` (exact installed distribution versions from the deployed gateway interpreter). This is a version lock, not a hash-locked wheel bundle; wheels and system libraries must be available for the target platform. Nothing here downloads a model automatically. `requirements.txt`, if upstream supplied one, records the original direct requirements. +2. Run `python scripts/check-archive.py` **from this directory**, or invoke it by absolute/relative path from the repository root; it fixes the import/cwd paths itself. Tests run in a temporary directory with synthetic persona IDs, no live service, credentials or history. The model-dependent Silero check is explicitly skipped. To run the full VAD test separately, provision the authorized external model first. No model service is restarted by tests. +3. Provision the existing approved Silero CPU model externally at `models/silero_vad.onnx`; verify its SHA256 against `app.EXPECTED_HASH` before service startup. Restore existing ASR/TTS/Qwen endpoints/registered voice resources separately. Large models and voice reference recordings are intentionally outside this source backup. +4. Copy `env.example` into a **private untracked** environment file and replace the secret placeholders. Keep it out of Git and shell logs. Generate/provision the HTTPS certificate and private key outside Git; the private key is never part of this archive. Do not change Android trust/token merely to make a test pass. +5. Create `.runtime/personas/` from `config/personas/*.json.example`, replacing voice IDs with existing registered voice IDs. For active-profile default selection, create `.runtime/active_profile.json` from `config/active_profile.json.example`. These examples deliberately contain no deployed profile/runtime information. Public persona lore in `personas/` is required. `.runtime/history.sqlite3` is initialized by the service; production history is not backed up here. +6. Review the LAN origin/source allowlist, fixed backend endpoint addresses and registered default voice in the source for the target network. They reflect the actual deployed implementation; paths such as `/home/gorios-spark-2/...` in legacy scripts are **not** assumed valid on another server. Use the placeholder-based `deploy/gateway.service.example` for new deployments, replacing paths explicitly. +7. From this directory, start the gateway with the existing private environment loaded, e.g. `.venv/bin/python -m uvicorn gateway:app --host 0.0.0.0 --port 5011 --ssl-certfile --ssl-keyfile `. LAN open mode is only for the trusted LAN/WG source allowlist, never public Internet exposure. Install a reviewed user service from the example if needed. Do not start duplicate gateway instances alongside the existing busy lock owner. +8. Verify HTTPS health and authorized Origin/auth/hello/history, then run one bounded public-sample protocol check. Real Android speaker playback still needs a real phone; nonempty backend PCM does not prove audible output. + +The v0.4.0 repair/context protocol and evidence boundaries are documented in `../docs/VOICE_REPAIR_040.md`. Archive and future deployments use this workspace's scripts with hash, backup, tests and busy checks. Archiving itself does not deploy or restart anything. diff --git a/gateway/SOURCE_MANIFEST.json b/gateway/SOURCE_MANIFEST.json new file mode 100644 index 0000000..cfc1b08 --- /dev/null +++ b/gateway/SOURCE_MANIFEST.json @@ -0,0 +1,240 @@ +{ + "baseline_android_commit": "9b428fb76ffa1468aa46124b33d9c598cf3740d8", + "source": "SPARK-2 deployed lan-voice gateway", + "code_version": "0.7.1", + "python": "3.12.3", + "machine": "aarch64", + "scope": "whitelisted source only; no runtime/models/credentials", + "files": { + "docs/UPSTREAM_README.md": { + "source": "README.md", + "sha256": "b9e86445aaac1d0cc98acb252e5c9a00a3f5ed53be67323984ba178d13e8344e", + "bytes": 12421 + }, + "app.py": { + "source": "app.py", + "sha256": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f", + "bytes": 5105 + }, + "deploy/lan-voice-gateway.service": { + "source": "deploy/lan-voice-gateway.service", + "sha256": "c175dfd1386f5cfb3be81b19b99600a6367dd8907a17f37d749f4139b35d50cb", + "bytes": 753 + }, + "deploy/lan-voice-vad.service": { + "source": "deploy/lan-voice-vad.service", + "sha256": "afc5d032e707999b263d4966525b638220bbdf5b2febbba715a1d83acb239c8f", + "bytes": 554 + }, + "face_context.py": { + "source": "face_context.py", + "sha256": "01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a", + "bytes": 2997 + }, + "gateway.py": { + "source": "gateway.py", + "sha256": "725577a378b688c24519ab2a0a9dfdb48723f365309e7ccccc9fc1de26c2894f", + "bytes": 38598 + }, + "guest_sessions.py": { + "source": "guest_sessions.py", + "sha256": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82", + "bytes": 1429 + }, + "history.py": { + "source": "history.py", + "sha256": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f", + "bytes": 4842 + }, + "persona_resolver.py": { + "source": "persona_resolver.py", + "sha256": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de", + "bytes": 1180 + }, + "personas/LVBU.md": { + "source": "personas/LVBU.md", + "sha256": "652c0b883afe70d5c5170664ff3dab827fd4174afa571346c39478469fb09308", + "bytes": 963 + }, + "personas/YANGMI.md": { + "source": "personas/YANGMI.md", + "sha256": "b6a047d7392ce6b766ba0b9c0c0bc603aa24d6a05c4d05a81490c90eb0ae3a98", + "bytes": 330 + }, + "personas/lvbu.lorebook.json": { + "source": "personas/lvbu.lorebook.json", + "sha256": "266078a2aed07dcbcf3283ae102a8215cef6c181bb240ac5e53ee240414721e4", + "bytes": 1322 + }, + "personas/yangmi.lorebook.json": { + "source": "personas/yangmi.lorebook.json", + "sha256": "d3b0201dff992b1bd0258d4aa06f8e7688322c9904c0b885aa6cf7be7046717d", + "bytes": 3212 + }, + "protocol.py": { + "source": "protocol.py", + "sha256": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5", + "bytes": 2419 + }, + "requirements.upstream.lock": { + "source": "requirements.lock", + "sha256": "d1999af42b7c445ad113fd176fe58f2ec464bbd8384bf17f443de5594415afa7", + "bytes": 456 + }, + "scripts/check_auto.py": { + "source": "scripts/check_auto.py", + "sha256": "ffe754c5e21f5406cac545615dd25123650fa642b083051c535d91b0e53551ff", + "bytes": 2537 + }, + "scripts/check_browser.py": { + "source": "scripts/check_browser.py", + "sha256": "99830ccadeec9849aa6ea5f3585a54a44468e81ae964537e0e44c340dccbfa04", + "bytes": 5255 + }, + "scripts/check_gateway.py": { + "source": "scripts/check_gateway.py", + "sha256": "26f9068703552c354a2867c029a146613477304955f919f886f1c18b37ba80e9", + "bytes": 3296 + }, + "scripts/check_ws.py": { + "source": "scripts/check_ws.py", + "sha256": "4f1f2793f1f8f3d5e98d28df710faa8b8ceaf716b979551eef2ff1dada3c16bd", + "bytes": 3118 + }, + "scripts/measure.py": { + "source": "scripts/measure.py", + "sha256": "068aa8c97dfb17c8a1db07e8026c734e844cb63ff7a72d1aaa1707993d17bf15", + "bytes": 6585 + }, + "scripts/test_role_selection.py": { + "source": "scripts/test_role_selection.py", + "sha256": "02a86f3b00f4bbb727750707773e9b497dbe98cd4a61e66dd45a2945a09b6440", + "bytes": 6223 + }, + "segmentation.py": { + "source": "segmentation.py", + "sha256": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d", + "bytes": 2206 + }, + "tests/test_continuity.py": { + "source": "tests/test_continuity.py", + "sha256": "6dd818484a064dc3fc9efe5ca71cc11ffcd3a0dcc45ea4185065732dab0289cc", + "bytes": 2769 + }, + "tests/test_debug.py": { + "source": "tests/test_debug.py", + "sha256": "26f9e374354b714ab1a03b56af90bcbf32135711dc4f26e2c53eaa90c7f02ddd", + "bytes": 2837 + }, + "tests/test_gateway.py": { + "source": "tests/test_gateway.py", + "sha256": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104", + "bytes": 5814 + }, + "tests/test_guests.py": { + "source": "tests/test_guests.py", + "sha256": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35", + "bytes": 1848 + }, + "tests/test_history.py": { + "source": "tests/test_history.py", + "sha256": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78", + "bytes": 8570 + }, + "tests/test_personas.py": { + "source": "tests/test_personas.py", + "sha256": "2576f2be903c69270cb1dec1e12448154554798bd7fca866d78e66e31594cbcb", + "bytes": 1288 + }, + "tests/test_segmentation.py": { + "source": "tests/test_segmentation.py", + "sha256": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463", + "bytes": 2240 + }, + "tests/test_v08.py": { + "source": "tests/test_v08.py", + "sha256": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082", + "bytes": 2635 + }, + "tests/test_vad.py": { + "source": "tests/test_vad.py", + "sha256": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228", + "bytes": 4899 + }, + "tests_fake.py": { + "source": "tests_fake.py", + "sha256": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8", + "bytes": 133 + }, + "tts_debug.py": { + "source": "tts_debug.py", + "sha256": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2", + "bytes": 5103 + }, + "vad.py": { + "source": "vad.py", + "sha256": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23", + "bytes": 6997 + }, + "web/audio-core.js": { + "source": "web/audio-core.js", + "sha256": "3d582761c013bc8b10330cceb3ea13898db073b1e0a10cdd3d426fa982ccab25", + "bytes": 1326 + }, + "web/capture-worklet.js": { + "source": "web/capture-worklet.js", + "sha256": "112ff29b2224366a8782a76784fa5cb4d92292561e146a51c1cb6c47fce9e5bc", + "bytes": 994 + }, + "web/client.js": { + "source": "web/client.js", + "sha256": "e59db1540d2f2645e9b0fdb15e1757be39c3b7d6569a636b3fcd8f3a44bee1b7", + "bytes": 15611 + }, + "web/debug.html": { + "source": "web/debug.html", + "sha256": "b2c8ff9b192675185849a9e927716360da69cc8223ac41f083b4cfbfd5ec8478", + "bytes": 4183 + }, + "web/home.css": { + "source": "web/home.css", + "sha256": "7a9a5307141186b7dcde613cd025c37cdf316d2f663eb087cdb25ce5c8d9ef16", + "bytes": 2750 + }, + "web/index.html": { + "source": "web/index.html", + "sha256": "9815222e496aa0f5855332bf837d06880a70c111a8b614a1b215384b66567c07", + "bytes": 4351 + }, + "web/play-worklet.js": { + "source": "web/play-worklet.js", + "sha256": "20b314fd0f61e73b6f60bdd3458a2fcfdec4f3470975a9856515fb28ba6bb5dc", + "bytes": 1526 + }, + "web/playback-core.js": { + "source": "web/playback-core.js", + "sha256": "c17ba11701705fd4a8588f1f5bbb65bf01c434a6ad956bf8e258428c5af8807c", + "bytes": 3078 + }, + "web/playback-test.js": { + "source": "web/playback-test.js", + "sha256": "e3eae2abfbade96769f47149f58f3c305a2eea956ccffcae5af61241c485f964", + "bytes": 2216 + }, + "tests/test_face_context.py": { + "source": "workspace:backend/test_face_context.py", + "sha256": "50ca57adee1d07a194ebaa95b15e09d3e836b97b19490e99e3e045c72a89682c", + "bytes": 1851 + }, + "tests/test_gateway_reply_face.py": { + "source": "workspace:backend/test_gateway_reply_face.py", + "sha256": "4a4a8fd997941c0d92356c2ebab2c336abbcf84954735a6955d8fa7e3700ec3f", + "bytes": 5320 + }, + "requirements.lock": { + "source": "deployed interpreter distribution metadata", + "sha256": "26fec2a2814c6b52cc50015e3b838a4c42c257b495db66482f65e33c7207f90c", + "bytes": 5539 + } + } +} diff --git a/gateway/app.py b/gateway/app.py new file mode 100644 index 0000000..1e2c777 --- /dev/null +++ b/gateway/app.py @@ -0,0 +1,110 @@ +import asyncio +import hashlib +import json +import os +import secrets +import time +from contextlib import asynccontextmanager +from pathlib import Path + +from fastapi import FastAPI, WebSocket, WebSocketDisconnect + +from vad import Config, Silero, VadSession + +VERSION = '0.1.0' +ROOT = Path(__file__).resolve().parent +EXPECTED_HASH = '1a153a22f4509e292a94e67d6f9b85e8deb25b4988682b7e174c65279d8788e3' +MAX_SESSIONS = 4 + + +@asynccontextmanager +async def lifespan(app): + token = os.environ.get('LAN_VAD_TOKEN', '') + if len(token) < 32: + raise RuntimeError('LAN_VAD_TOKEN must contain at least 32 characters') + path = ROOT / 'models/silero_vad.onnx' + if hashlib.sha256(path.read_bytes()).hexdigest() != EXPECTED_HASH: + raise RuntimeError('Silero model checksum mismatch') + app.state.model = await asyncio.to_thread(Silero, path) + app.state.token = token + app.state.sessions = 0 + yield + + +app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None) + + +@app.get('/health') +async def health(): + return {'status': 'ok', 'version': VERSION, 'model': 'silero-vad-6.2.0', 'model_sha256': EXPECTED_HASH, 'provider': 'CPUExecutionProvider', 'sample_rate': 16000, 'window_samples': 512, 'active_sessions': app.state.sessions} + + +@app.websocket('/ws/vad') +async def websocket(ws: WebSocket): + auth = ws.headers.get('authorization', '') + if not secrets.compare_digest(auth, 'Bearer ' + app.state.token): + await ws.close(code=1008) + return + if app.state.sessions >= MAX_SESSIONS: + await ws.close(code=1013) + return + app.state.sessions += 1 + session = None + try: + await ws.accept() + message = await asyncio.wait_for(ws.receive(), 10) + if message.get('type') == 'websocket.disconnect': + return + raw = message.get('text') + if raw is None or len(raw) > 2048: + raise ValueError('first message must be session.start JSON') + settings = json.loads(raw) + if not isinstance(settings, dict) or settings.get('type') != 'session.start': + raise ValueError('first message must be session.start') + if settings.get('format', 'pcm16le') != 'pcm16le' or settings.get('sample_rate', 16000) != 16000 or settings.get('channels', 1) != 1: + raise ValueError('only pcm16le mono 16000 Hz supported') + include_audio = settings.get('include_preroll_audio', False) + if not isinstance(include_audio, bool): + raise ValueError('include_preroll_audio must be boolean') + config = Config(silence_ms=int(settings.get('silence_ms', 300)), start_windows=int(settings.get('start_windows', 3)), threshold=float(settings.get('threshold', 0.5)), max_speech_seconds=float(settings.get('max_speech_seconds', 30)), max_session_seconds=float(settings.get('max_session_seconds', 600)), include_preroll_audio=include_audio) + session = VadSession(app.state.model, config) + started = time.monotonic() + await ws.send_json({'type': 'session.ready', 'version': VERSION, 'epoch': 0, 'sample_rate': 16000, 'window_samples': 512, 'silence_ms': config.silence_ms, 'debounce_ms': config.start_windows * 32, 'preroll_ms': 200, 'max_message_bytes': 65536}) + while True: + remaining = 600 - (time.monotonic() - started) + if remaining <= 0: + raise ValueError('wall-clock session limit reached') + message = await asyncio.wait_for(ws.receive(), min(60, remaining)) + if message['type'] == 'websocket.disconnect': + break + if message.get('bytes') is not None: + events = await asyncio.to_thread(session.feed, message['bytes']) + else: + raw = message.get('text') or '' + if len(raw) > 2048: + raise ValueError('control message too large') + command = json.loads(raw) + if not isinstance(command, dict): + raise ValueError('control must be object') + if command.get('type') == 'reset': + events = session.reset() + elif command.get('type') == 'audio.end': + events = await asyncio.to_thread(session.finish) + elif command.get('type') == 'ping': + events = [{'type': 'pong', 'epoch': session.epoch, 'sample': session.samples}] + else: + raise ValueError('unknown control type') + for event in events: + await asyncio.wait_for(ws.send_json(event), 5) + except WebSocketDisconnect: + pass + except (ValueError, TypeError, OverflowError, asyncio.TimeoutError): + try: + await ws.send_json({'type': 'error', 'code': 'invalid_input_or_limit', 'message': 'Invalid format, control, configuration or session limit; reconnect/reset with valid input.'}) + await ws.close(code=1008) + except (WebSocketDisconnect, RuntimeError): + pass + finally: + if session is not None: + session.reset() + app.state.sessions -= 1 diff --git a/gateway/config/active_profile.json.example b/gateway/config/active_profile.json.example new file mode 100644 index 0000000..3e5ce19 --- /dev/null +++ b/gateway/config/active_profile.json.example @@ -0,0 +1 @@ +{"persona":"yangmi_fiction","voice_id":"REPLACE_WITH_REGISTERED_YANGMI_VOICE_ID"} diff --git a/gateway/config/personas/lvbu.json.example b/gateway/config/personas/lvbu.json.example new file mode 100644 index 0000000..c253c80 --- /dev/null +++ b/gateway/config/personas/lvbu.json.example @@ -0,0 +1 @@ +{"voice_id":"REPLACE_WITH_REGISTERED_LVBU_VOICE_ID"} diff --git a/gateway/config/personas/yangmi_fiction.json.example b/gateway/config/personas/yangmi_fiction.json.example new file mode 100644 index 0000000..f7a38b7 --- /dev/null +++ b/gateway/config/personas/yangmi_fiction.json.example @@ -0,0 +1 @@ +{"voice_id":"REPLACE_WITH_REGISTERED_YANGMI_VOICE_ID"} diff --git a/gateway/deploy/gateway.service.example b/gateway/deploy/gateway.service.example new file mode 100644 index 0000000..805c8e2 --- /dev/null +++ b/gateway/deploy/gateway.service.example @@ -0,0 +1,14 @@ +# User service example. Replace all /ABSOLUTE/PATH placeholders before installing. +[Unit] +Description=LAN Voice HTTPS dialogue gateway +After=network-online.target + +[Service] +Type=simple +WorkingDirectory=/ABSOLUTE/PATH/TO/baji-vc/gateway +EnvironmentFile=/ABSOLUTE/PATH/TO/PRIVATE/gateway.env +ExecStart=/ABSOLUTE/PATH/TO/baji-vc/gateway/.venv/bin/python -m uvicorn gateway:app --host 0.0.0.0 --port 5011 --ssl-certfile /ABSOLUTE/PATH/TO/PRIVATE/gateway-cert.pem --ssl-keyfile /ABSOLUTE/PATH/TO/PRIVATE/gateway-key.pem +Restart=on-failure + +[Install] +WantedBy=default.target diff --git a/gateway/deploy/lan-voice-gateway.service b/gateway/deploy/lan-voice-gateway.service new file mode 100644 index 0000000..31ba1c0 --- /dev/null +++ b/gateway/deploy/lan-voice-gateway.service @@ -0,0 +1,20 @@ +[Unit] +Description=LAN Voice HTTPS browser simulator and dialogue gateway +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +WorkingDirectory=/home/gorios-spark-2/lan-voice +EnvironmentFile=/home/gorios-spark-2/lan-voice/.runtime/gateway.env +ExecStart=/home/gorios-spark-2/lan-voice/.venv/bin/python -m uvicorn gateway:app --host 192.168.31.61 --port 5011 --workers 1 --no-proxy-headers --ws-max-size 65536 --ws-max-queue 4 --no-access-log --ssl-keyfile /home/gorios-spark-2/lan-voice/.runtime/gateway-key.pem --ssl-certfile /home/gorios-spark-2/lan-voice/.runtime/gateway-cert.pem +Restart=on-failure +RestartSec=3 +NoNewPrivileges=true +UMask=0077 +MemoryMax=512M +TasksMax=64 +TimeoutStopSec=15 + +[Install] +WantedBy=default.target diff --git a/gateway/deploy/lan-voice-vad.service b/gateway/deploy/lan-voice-vad.service new file mode 100644 index 0000000..7285db6 --- /dev/null +++ b/gateway/deploy/lan-voice-vad.service @@ -0,0 +1,20 @@ +[Unit] +Description=LAN Voice Silero CPU VAD +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +WorkingDirectory=/home/gorios-spark-2/lan-voice +EnvironmentFile=/home/gorios-spark-2/lan-voice/.runtime/vad.env +ExecStart=/home/gorios-spark-2/lan-voice/.venv/bin/python -m uvicorn app:app --host 192.168.31.61 --port 5010 --workers 1 --ws-max-size 65536 --ws-max-queue 4 --no-access-log +Restart=on-failure +RestartSec=3 +NoNewPrivileges=true +UMask=0077 +MemoryMax=512M +TasksMax=64 +TimeoutStopSec=15 + +[Install] +WantedBy=default.target diff --git a/gateway/docs/UPSTREAM_README.md b/gateway/docs/UPSTREAM_README.md new file mode 100644 index 0000000..b113d7e --- /dev/null +++ b/gateway/docs/UPSTREAM_README.md @@ -0,0 +1,123 @@ +# lan-voice + +已部署独立 **实时 VAD 事件服务**与新增 **HTTPS浏览器硬件模拟器 / PCM对话网关**。真实STT→Qwen SSE→流式TTS→PCM闭环已验证;不是最终全双工体验或完全小智兼容实现,Android AEC/硬件听音和Opus仍未完成。 + +浏览器入口:**https://192.168.31.61:5011/**;WS:`wss://192.168.31.61:5011/ws/dialogue`。自签证书信任、独立gateway token、SSH localhost tunnel、协议和测量见 [docs/FRONTEND_SIMULATOR.md](docs/FRONTEND_SIMULATOR.md)。HTTP LAN IP不可直接录音。 + +当前网关版本 **0.7.1**,修复快速角色切换导致旧socket回调污染新连接;Playwright CLI1.58.0真实desktop/mobile点击、监听锁定后切换、快速连点/重连/admin兼容/owner拒绝通过,pageerror/console errors为空。脚本`scripts/test_role_selection.py`,不含真实麦或模型推理。静态JS禁缓存。,新声伴首页支持指定LAN访客免填管理员token,但仍有短期HttpOnly cookie鉴权/会话owner隔离;仅192.168.31.0/24和loopback,不信任XFF。默认开启,LAN_GUEST_ENABLED=0可关闭。旧调试页 `/debug` 和高级Bearer管理员路径保留;共享token非JWT/OAuth,不下发浏览器。点击才采集,角色卡切换新会话,默认duplex/debug隐私说明/导出保留。运行与关闭说明见 [docs/USER_FRIENDLY.md](docs/USER_FRIENDLY.md),实施计划 `docs/USER_FRIENDLY_PLAN.md`。 + +v0.6.2角色行为保留,杨密(原创测试角色)`yangmi_fiction`:选择后重连强制新会话,有限独立system lore,绑定已确认active普通女生参考音色 `6f9683c3-42ac-537c-8093-c1e638ac64cf`,**非杨幂仿声**。用户已确认许可,公开视频BV1He4y1V7wC只取前7秒,经一次STT诊断和一次短句clone生成验证;真实相似听感/背景纯度未测。临时媒体已删,仅保留受控reference/manifest,商用许可需另行确认。人格与声音素材独立,来源仅公开访谈作者概括,不断言真人私人性格。见 `personas/yangmi.lorebook.json`、`personas/YANGMI.md`。通用persona resolver白名单拒绝unknown,不影响吕布。 + +v0.6.0行为保留,新增默认开启的有界TTS debug(保存下一轮合成台词/WAV,不存麦克风/token/reference),可标记异常、鉴权下载/回放;此前未记录不能恢复。保存`.runtime/tts-debug`,每轮30秒、总200MiB/20轮/72h操作时清理,目录700/文件600。新增“吕布”persona重连强制新会话,已登记clone `2a6545e9-6332-5703-8de2-e68e00e0095b`,固定reference+lore。仅本地用户提供素材测试,参考背景纯度/真实clone听感未测。见 [docs/TTS_DEBUG.md](docs/TTS_DEBUG.md) 与 `personas/lvbu.lorebook.json`。 + +v0.5连续生成行为保留,默认 `continuous_voice`:LLM文字仍SSE实时显示,完整正文收齐后每轮一次TTS stream请求,对应当前后端一个generator循环yield,接受额外首音等待。默认显式固定已登记reference音色 `9a97272c-3919-5606-9c8f-9552ab602528`;开始前可选active白名单,首次listen后锁住本session。`fragment`只作音色/韵律跳变风险实验,不是单generator增量文本。 + +LLM完成时间、voice mode、TTS请求次数在面板可见。每轮结束后下一轮正常新generator并复用固定reference/prompt cache,不是session无穷generator。28项Python回归和Chrome模块通过,本轮未追加真实推理,实际音色稳定/真人听感未测。详见 [docs/VOICE_CONTINUITY.md](docs/VOICE_CONTINUITY.md)。 + +以下v0.4.1分句参数仅在fragment实验模式使用;播放缓存仍保留:修复短答被final短标点拆成3+4的问题,final残留一次合成并合并未开始queue文本;首合法片段默认12字、低延迟8字,短整个回复原样。balanced默认 **240ms累计音频启动、240–400ms欠供恢复**,low_latency显式保留100ms,2秒有界队列;不是回复缓存,不剪静音。提高平衡buffer有首音代价,非免费优化。mode/有效阈值/chunk间隔/最低队列/欠供可显示和导出。 + +26项Python回归及Chrome7组播放测试通过,160ms块每170/180/190ms抵达模拟underrun由低延迟2/2/2变为平衡0/0/1,但首等待增加170–190ms。一次真实合并7字TTS确认160ms到达块、最大间隔164ms、RTF0.9798;缓存不能治本提高算力。**真人听感仍未测**,请刷新重连选balanced复测。详见文档顶部v0.4.1。 + +默认双工行为保留,默认auto双工持续采集:计算/输出/浏览器残余播放期间VAD语音起声可打断旧turn,采集不中止;关闭barge仅半双工调试。96ms debounce默认、可选64ms。全双工自回声风险仍存在,请用耳机;软件测试不证明硬件AEC效果。 + +聊天转录/回答和状态现在持久化到 **`.runtime/history.sqlite3`**(SQLite WAL,文件600/目录700,gitignore,无原始音频)。浏览器localStorage仅保存conversation UUID;token仅内存。鉴权后恢复历史,提供“新会话”和“清空当前会话”按钮,不删除其他会话。上下文仅最近10轮已完成且软件播放drain确认的回复,未确认/中断/失败回复排除;drain不是用户实际听完的保证。计时导出默认无正文。详见最新协议文档顶部v0.3更新。 + +22项单测通过,mock两轮/双工barge/SQLite恢复与鉴权通过;真实WSS会话恢复和页面worklet通过。此次不追加模型推理,**真实多轮、真人AEC/硬件打断未测**。证书和token未修改。 + +新服务状态/日志/停止: + +```bash +systemctl --user status lan-voice-gateway.service --no-pager +journalctl --user -u lan-voice-gateway.service -n 50 --no-pager +systemctl --user disable --now lan-voice-gateway.service +``` + +以下为未改动的5010独立VAD服务说明。 + +- 健康:`http://192.168.31.61:5010/health` +- WebSocket:`ws://192.168.31.61:5010/ws/vad` +- 版本:`0.1.0`,Silero `6.2.0`,CPUExecutionProvider;仅绑定该 LAN IPv4,不绑定公网/0.0.0.0。 +- systemd 用户服务:`lan-voice-vad.service`,已 enabled、active/running;用户 Linger=yes。 + +## 状态、日志与停止 + +```bash +systemctl --user status lan-voice-vad.service --no-pager +journalctl --user -u lan-voice-vad.service -n 50 --no-pager +systemctl --user stop lan-voice-vad.service +# 停止且取消自动启动,仅操作本服务 +systemctl --user disable --now lan-voice-vad.service +# 需要时再次启动本服务 +systemctl --user start lan-voice-vad.service +``` + +unit 源文件:`deploy/lan-voice-vad.service`;用户目录符号链接指向本仓库。不修改 27B/STT/TTS/其他服务,4B/14B保持 exited。 + +## 鉴权与隐私 + +WS握手须有 `Authorization: Bearer <共享token>`;不要通过URL/query传token。token已随机生成在 `.runtime/vad.env`(目录700、文件600、git忽略),不写入文档或输出。健康接口公开但不含秘密。客户端从自己的安全配置提供同一token;不要将其硬编码或提交到Git。 + +原始音频只在内存短环形缓冲处理,不存盘、不写日志。默认只返回事件;`include_preroll_audio:true` **显式选择回传原始pre-roll PCM的base64**,包含起声前200ms及debounce至当前窗口的音频,最多约9472 bytes。base64不是加密;该选项是音频隐私传输,应仅为可信编排消费者开启。默认事件含样本区间,网关需自行维护至少约300ms音频环形缓冲以保留pre-roll。 + +当前WS是明文LAN连接,token和音频可被网络观察;不等同于WSS安全部署。后续用限定LAN的TLS入口,不擅自修改已有代理。 + +## WS 协议 v0.1 + +连接后10秒内发送: + +```json +{"type":"session.start","format":"pcm16le","sample_rate":16000,"channels":1,"silence_ms":300,"start_windows":3,"threshold":0.5,"max_speech_seconds":30,"max_session_seconds":600,"include_preroll_audio":false} +``` + +收到 `session.ready` 后,连续发送二进制 **signed little-endian PCM16 mono 16k**。20ms网络帧为640 bytes;允许任意分块(包括拆开单个采样的奇数字节块),内部重组为512 samples/32ms推理窗口;`audio.end`时剩余单字节无效。每条消息最多65536 bytes。 + +- `start_windows`:2或3,64/96ms阳性窗口debounce,不是从人类真实起声到检测的保证时延。 +- `silence_ms`:200–600,默认300;按32ms窗口量化,默认需320ms。 +- `threshold`:0.1–0.9,结束阈值 `max(0.01, threshold-0.15)`。 +- `max_speech_seconds`:1–30,默认30;到达上限发end,持续说话随后可形成新片段(不代表ASR语义终句)。 +- `max_session_seconds`:1–600音频累计;独立固定600秒wall-clock、60秒接收空闲、5秒发送超时;reset不能绕过wall-clock上限。 + +事件示例(samples为半开区间端点/索引,单位1/16000秒): + +```json +{"type":"speech.start","epoch":0,"segment_id":1,"sample":14848,"time_ms":928.0,"detected_at_sample":16384,"preroll_start_sample":11648,"preroll_ms":200,"audio_until_sample":16384} +{"type":"speech.end","epoch":0,"segment_id":1,"sample":31232,"time_ms":1952.0,"detected_at_sample":36352,"reason":"silence"} +``` + +`sample`是判定的起点/静音起点,`detected_at_sample`是确认时已经处理的位置;不代表墙钟/网络到达时间。尾帧padding不会把事件时间或音频区间扩展到真实输入之外。epoch内samples连续;reset后epoch+1、sample归零,segment_id重新计数。下游需以`epoch + segment_id`映射自己的`turn_id`,不能跨reset只看segment_id。 + +控制消息: +- `{"type":"ping"}` → `pong`(可作已处理屏障)。 +- `{"type":"audio.end"}` → 处理尾窗、必要的`speech.end`、`session.ended`;继续音频前需reset。 +- `{"type":"reset"}` → 活动片段end(reason=reset),清除本会话隐状态与缓存、`session.reset`。 +- 断开 → 清理会话内存,不持久化;断开后不能期待仍接收end。 +- 非法格式/控制/配置或限额 → `error`与关闭1008;无token握手403;会话已满则拒绝。 + +一个ORT模型实例启动时加载一次,隐状态和64sample上下文逐会话独立;同会话逐条等待工作线程结果保持有序。模型推理通过`asyncio.to_thread`,不阻塞事件循环。最多4会话、WS接收队列4条、每消息64KiB,unit MemoryMax=512M;这是资源上限,不是4人低延迟对话承诺。 + +## 验证与有限测量 + +```bash +cd /home/gorios-spark-2/lan-voice +.venv/bin/python -m unittest discover -s tests -v +# 使用已生成的公开短句tmp/public_tts_16k.wav,不额外调用推理 +set -a; source .runtime/vad.env; set +a +.venv/bin/python scripts/check_ws.py +``` + +9项单测通过;真实WS双会话隔离、鉴权拒绝、20ms实时发送、起止事件、pre-roll字节、reset通过。短中文样本来自现有TTS公开句“今天天气不错,我们去散步吧。”,非用户录音。 + +`tmp/measurements.json`和`tmp/ws_integration.json`是本机忽略文件。`scripts/measure.py` **会发推理请求**,本次已执行每类3次(TTS第三次断连),不要自动/反复运行,需另行授权。每请求总deadline30秒、Qwen最多64token、串行、无压测。 + +## 环境与模型来源 + +`.venv`使用`local-runtime.pth`只读复用既有`vllm-venv` packages,不改该venv;这是独立入口,不是完全依赖隔离。原因:完整pip安装发生hash不匹配,未绕过校验。`requirements.lock`仅记录本项目相关实际版本;服务不导入torch,不安装大模型。现有venv升级/删除会影响本服务,未来可用本地可信wheel完成完全隔离。 + +模型从官方`silero-vad==6.2.0`无依赖wheel提取`silero_vad/data/silero_vad.onnx`,2,327,524 bytes;来源、wheel/model SHA256见`models/provenance.json`。启动强制校验模型hash。模型文件和wheel本机存在但git忽略;迁移时从相同官方wheel恢复并核对hash,不下载大型ASR/LLM。 + +## 评估与后续 + +- [最新低延迟差距、数据及改造路线](docs/LOW_LATENCY_PLAN.md) +- [初始只读评估快照](docs/EVALUATION.md):其中4B/14B运行态、内存余量与“无推理”只适用于当时,已被最新文档的测量和停止状态更新。 + +最终目标仍是全双工/打断的高体验标准。服务端VAD不消播放回声;Android本地AEC和立即停播、服务端turn取消都不可省。半双工只用于调试,不是最终交付标准。 diff --git a/gateway/env.example b/gateway/env.example new file mode 100644 index 0000000..fcc5a01 --- /dev/null +++ b/gateway/env.example @@ -0,0 +1,6 @@ +# Copy to a private environment file outside Git; replace placeholders locally. +LAN_GATEWAY_TOKEN=REPLACE_WITH_RANDOM_SECRET_AT_LEAST_32_CHARS +LAN_OPEN_MODE=1 +LAN_GUEST_ENABLED=1 +# The optional independent VAD service also needs its own secret. +LAN_VAD_TOKEN=REPLACE_WITH_A_DIFFERENT_RANDOM_SECRET_AT_LEAST_32_CHARS diff --git a/gateway/face_context.py b/gateway/face_context.py new file mode 100644 index 0000000..6ec5bc9 --- /dev/null +++ b/gateway/face_context.py @@ -0,0 +1,59 @@ +"""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)} diff --git a/gateway/gateway.py b/gateway/gateway.py new file mode 100644 index 0000000..51daaea --- /dev/null +++ b/gateway/gateway.py @@ -0,0 +1,714 @@ +import asyncio +import contextlib +import hashlib +import io +import json +import os +import secrets +import time +import wave +from contextlib import asynccontextmanager +from pathlib import Path + +import httpx +import numpy as np +from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request, HTTPException +from fastapi.responses import FileResponse +from fastapi.staticfiles import StaticFiles + +import uuid +from history import History +from face_context import FaceContext +from guest_sessions import GuestSessions, COOKIE +from tts_debug import DebugStore +from persona_resolver import resolve_persona +from segmentation import Segmenter +from app import EXPECTED_HASH +from protocol import WavStream, pack, unpack +from vad import Config, Silero, VadSession + +ROOT = Path(__file__).resolve().parent +VERSION = '0.7.1' +DEFAULT_VOICE_ID = '9a97272c-3919-5606-9c8f-9552ab602528' +ORIGINS = {'https://192.168.31.61:5011', 'https://localhost:5011', 'https://127.0.0.1:5011'} + + +@asynccontextmanager +async def lifespan(app): + token = os.environ.get('LAN_GATEWAY_TOKEN', '') + if len(token) < 32: raise RuntimeError('missing gateway token') + path = ROOT / 'models/silero_vad.onnx' + if hashlib.sha256(path.read_bytes()).hexdigest() != EXPECTED_HASH: raise RuntimeError('model checksum') + app.state.model = await asyncio.to_thread(Silero, path) + app.state.token = token + app.state.guests = GuestSessions() + app.state.guest_enabled = os.environ.get('LAN_GUEST_ENABLED', '1') != '0' + app.state.lan_open = os.environ.get('LAN_OPEN_MODE', '0') == '1' + app.state.remote_log = [] + app.state.remote_reports = [] + app.state.busy = False + app.state.history = History(ROOT / '.runtime/history.sqlite3') + await app.state.history.initialize() + app.state.debug = await asyncio.to_thread(DebugStore, ROOT / '.runtime/tts-debug') + app.state.lvbu = json.loads((ROOT / '.runtime/personas/lvbu.json').read_text()) + app.state.lore = json.loads((ROOT / 'personas/lvbu.lorebook.json').read_text()) + async with httpx.AsyncClient(timeout=30, trust_env=False, limits=httpx.Limits(max_connections=4, max_keepalive_connections=4)) as client: + app.state.client = client + response = await client.get('http://192.168.31.61:5002/v1/voices') + response.raise_for_status() + app.state.voices = [{'id': v['id'], 'source': v.get('source', 'registry'), 'default': v['id'] == DEFAULT_VOICE_ID} for v in response.json().get('voices', []) if v.get('status') == 'active'][:64] + if not any(v['id'] == DEFAULT_VOICE_ID for v in app.state.voices): raise RuntimeError('registered default voice unavailable') + yield + + +app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None) +class UncachedStaticFiles(StaticFiles): + async def get_response(self, path, scope): + response = await super().get_response(path, scope) + response.headers['Cache-Control'] = 'no-store' + return response + + +app.mount('/static', UncachedStaticFiles(directory=ROOT / 'web'), name='static') + + +@app.get('/') +async def index(): + return FileResponse(ROOT / 'web/index.html', headers={'Cache-Control': 'no-store'}) + + +@app.get('/debug') +async def debug_page(): + return FileResponse(ROOT / 'web/debug.html', headers={'Cache-Control':'no-store'}) + + +def load_active_profile(): + path = ROOT / '.runtime' / 'active_profile.json' + try: + data = json.loads(path.read_text(encoding='utf-8')) + return data if isinstance(data, dict) else None + except (OSError, ValueError): + return None + + +def open_key(connection): + if not getattr(app.state, 'lan_open', False) or not connection.client or not GuestSessions.lan(connection.client.host): return None + key = 'lan:' + connection.client.host + if not app.state.guests.get(key): + app.state.guests.sessions[key] = {'expires': time.time() + app.state.guests.ttl, 'conversations': set()} + return key + + +def guest_key(connection): + key = connection.cookies.get(COOKIE) + if not getattr(app.state, 'guest_enabled', False) or not connection.client or not GuestSessions.lan(connection.client.host): return None + return key if app.state.guests.get(key) else None + + +@app.post('/session/bootstrap') +async def bootstrap(request: Request): + if not getattr(app.state, 'guest_enabled', False) or not request.client or not GuestSessions.lan(request.client.host): raise HTTPException(403) + if request.headers.get('origin') not in ORIGINS or request.headers.get('content-type', '').split(';')[0] != 'application/json': raise HTTPException(403) + if 'https://' + request.headers.get('host', '') != request.headers.get('origin'): raise HTTPException(403) + body = await request.body() + if len(body) > 1024: raise HTTPException(413) + try: + if not isinstance(json.loads(body), dict): raise ValueError() + except (ValueError, TypeError): raise HTTPException(400) + key = guest_key(request) + if not key: + try: key = app.state.guests.create() + except ValueError: raise HTTPException(429) + from fastapi.responses import JSONResponse + response = JSONResponse({'status':'ok','expires_in':max(0,int(app.state.guests.get(key)['expires']-time.time()))}) + response.set_cookie(COOKIE,key,max_age=max(0,int(app.state.guests.get(key)['expires']-time.time())),secure=True,httponly=True,samesite='strict') + return response + + +@app.post('/session/logout') +async def logout(request: Request): + if request.headers.get('origin') not in ORIGINS: raise HTTPException(403) + app.state.guests.revoke(request.cookies.get(COOKIE)) + from fastapi.responses import JSONResponse + response=JSONResponse({'status':'logged_out'});response.delete_cookie(COOKIE,secure=True,httponly=True,samesite='strict');return response + + +@app.get('/health') +async def health(): + return {'status': 'ok', 'version': VERSION, 'codec': 'pcm16', 'opus': False, 'busy': app.state.busy, 'stt': 'batch SenseVoice', 'tts': 'per-turn full text / single streaming generator VoxCPM2', 'voice_mode_default': 'continuous_voice', 'default_voice_id': DEFAULT_VOICE_ID} + + +@app.post('/debug/log') +async def debug_log_post(request: Request): + if not getattr(app.state, 'lan_open', False) or not request.client or not GuestSessions.lan(request.client.host): raise HTTPException(403) + raw = await request.body() + if len(raw) > 4096: raise HTTPException(413) + try: + data = json.loads(raw) + except (ValueError, UnicodeDecodeError): + raise HTTPException(400) + if not isinstance(data, dict) or not isinstance(data.get('message'), str): raise HTTPException(400) + entry = {'ts': data.get('timestamp_ms', 0), 'tag': str(data.get('tag', ''))[:32], 'msg': str(data['message'])[:500], 'from': request.client.host} + app.state.remote_log.append(entry) + if len(app.state.remote_log) > 200: app.state.remote_log = app.state.remote_log[-100:] + return {'status': 'ok'} + + +@app.get('/debug/log') +async def debug_log_get(request: Request): + if not getattr(app.state, 'lan_open', False) or not request.client or not GuestSessions.lan(request.client.host): raise HTTPException(403) + return {'entries': app.state.remote_log[-100:]} + + +@app.post('/debug/report') +async def debug_report_post(request: Request): + if not getattr(app.state, 'lan_open', False) or not request.client or not GuestSessions.lan(request.client.host): raise HTTPException(403) + raw = await request.body() + if len(raw) > 2097152: raise HTTPException(413) + try: + data = json.loads(raw) + except (ValueError, UnicodeDecodeError): + raise HTTPException(400) + if not isinstance(data, dict) or data.get('type') != 'diagnostic_report': raise HTTPException(400) + entry = {'received_at': time.time(), 'from': request.client.host, 'report': data} + app.state.remote_reports.append(entry) + if len(app.state.remote_reports) > 20: app.state.remote_reports = app.state.remote_reports[-10:] + return {'status': 'ok', 'entries_received': len(data.get('logs', []))} + + +@app.get('/debug/report') +async def debug_report_get(request: Request): + if not getattr(app.state, 'lan_open', False) or not request.client or not GuestSessions.lan(request.client.host): raise HTTPException(403) + return {'reports': app.state.remote_reports[-10:]} + + +@app.post('/debug/download') +async def debug_download(request: Request): + admin = secrets.compare_digest(request.headers.get('authorization', ''), 'Bearer ' + app.state.token) + owner = guest_key(request) + if not admin and not owner: raise HTTPException(403) + if request.headers.get('origin') not in ORIGINS: raise HTTPException(403) + raw = await request.body() + if len(raw) > 2048: raise HTTPException(413) + try: + data = json.loads(raw) + cid = str(uuid.UUID(data['conversation_id'])) + if not admin: app.state.guests.own(owner, cid) + path = await asyncio.to_thread(app.state.debug.authorized, data['debug_id'], cid, data['kind']) + except (ValueError, KeyError, FileNotFoundError): raise HTTPException(404) + return FileResponse(path, filename=path.name, headers={'Cache-Control':'no-store'}) + + +class Dialogue: + def __init__(self, ws, model, client, history=None, conversation_id=None): + self.ws, self.client = ws, client + self.history = history + self.conversation_id = conversation_id + self.run_id = None + self.voice_mode = 'continuous_voice' + self.voice_id = DEFAULT_VOICE_ID + self.voice_locked = False + self.debug_store = None + self.debug_enabled = True + self.debug_captures = {} + self.persona = 'default' + self.persona_rules = '' + self.answers = {} + self.contexts = {} + self.face_context = FaceContext() + self.face_messages = {} + self.pending_drained = None + self.capture_offset = 0 + self.received_samples = 0 + self.vad = VadSession(model, Config(max_session_seconds=600)) + self.lock = asyncio.Lock() + self.turn = 0 + self.event_seq = 0 + self.down_seq = 0 + self.up_seq = 0 + self.task = None + self.cancelled_tasks = set() + self.listening = False + self.mode = 'auto' + self.barge = True + self.capture = bytearray() + self.base = 0 + self.start = None + self.wall = time.monotonic() + self.closed = False + self.playback_waiting = False + self.auth_check = lambda: True + + async def event(self, kind, turn=None, **fields): + async with self.lock: + if turn is not None and turn != self.turn: return + if not self.auth_check(): raise ValueError('guest expired') + self.event_seq += 1 + await asyncio.wait_for(self.ws.send_json({'type': kind, 'turn_id': self.turn if turn is None else turn, 'seq': self.event_seq, 'server_ms': round((time.monotonic() - self.wall) * 1000, 3), **fields}), 5) + + async def audio(self, turn, pcm): + async with self.lock: + if turn != self.turn: return + if not self.auth_check(): raise ValueError('guest expired') + self.down_seq += 1 + await asyncio.wait_for(self.ws.send_bytes(pack(2, turn, self.down_seq, pcm)), 5) + + async def invalidate(self, reason, preserve_vad=False): + old_turn = self.turn + self.turn += 1 + if reason == 'new_turn': + self.face_context.advance_capture(old_turn, self.turn) + else: + self.face_context.clear() + self.face_messages.clear() + self.pending_drained = None + old = self.task + previous_run = self.run_id + self.run_id = None + self.task = None + if previous_run and self.history: + await self.history.interrupt(previous_run) + if old and not old.done(): + old.cancel() + self.cancelled_tasks.add(old) + old.add_done_callback(self.cancelled_tasks.discard) + self.start = None + self.capture.clear() + self.base = 0 + if not preserve_vad: + self.capture_offset = self.received_samples + self.vad.reset() + self.playback_waiting = False + self.up_seq = 0 + self.down_seq = 0 + await self.event('abort', reason=reason, accepted_input_samples=self.received_samples) + + async def listen(self, mode, enabled=True, barge=True, start_windows=3): + if mode not in ('auto', 'manual'): raise ValueError('listen mode') + if enabled: + await self.invalidate('listen_start') + self.listening, self.mode, self.barge = True, mode, bool(barge) + self.up_seq = 0 + self.received_samples = 0 + self.capture_offset = 0 + self.vad = VadSession(self.vad.model, Config(start_windows=int(start_windows))) + self.start = 0 if mode == 'manual' else None + await self.event('listen', state='start', mode=mode, barge_in=self.barge) + else: + self.listening = False + if mode == 'manual' and self.capture: + await self.submit(bytes(self.capture), len(self.capture) // 2) + await self.event('listen', state='stop', mode=mode) + + async def input(self, frame): + turn, seq, pcm = unpack(frame, 1) + if turn != self.turn: return + if not self.listening: raise ValueError('not listening') + if seq != self.up_seq + 1: raise ValueError('sequence gap') + self.up_seq = seq + self.received_samples += len(pcm) // 2 + responding = (self.task is not None and not self.task.done()) or self.playback_waiting + if responding and not self.barge: + return + self.capture.extend(pcm) + if len(self.capture) > 960000 + 32000: raise ValueError('capture limit') + if self.mode == 'manual': + if len(self.capture) >= 960000: + self.listening = False + await self.submit(bytes(self.capture[:960000]), 480000) + return + events = await asyncio.to_thread(self.vad.feed, pcm) + for ev in events: + if ev['type'] == 'speech.start': + if responding: + if not self.barge: continue + saved = bytes(self.capture) + history_start = ev['preroll_start_sample'] + saved_vad = self.vad + saved_base = self.base + await self.invalidate('voice_barge_in', preserve_vad=True) + self.vad = saved_vad + self.capture.extend(saved) + self.start = history_start + self.base = saved_base + self.up_seq = 0 + await self.event('listen', state='start', mode='auto', barge_in=True) + return + self.start = ev['preroll_start_sample'] + await self.event('vad', event={k: v for k, v in ev.items() if 'base64' not in k}) + if ev['type'] == 'speech.end' and self.start is not None: + end = ev['sample'] + left = max(0, self.start - self.base) * 2 + right = max(0, end - self.base) * 2 + speech = bytes(self.capture[left:right]) + await self.submit(speech, end) + return + if self.start is None: + keep = min(len(self.capture), 12000) + drop = len(self.capture) - keep + del self.capture[:drop] + self.base += drop // 2 + + async def submit(self, pcm, end_sample): + if not pcm or len(pcm) > 960000: return + absolute_end = self.capture_offset + end_sample + await self.invalidate('new_turn') + turn = self.turn + self.run_id = str(uuid.uuid4()) + await self.event('capture.end', turn, end_sample=absolute_end, input_samples=len(pcm) // 2) + self.task = asyncio.create_task(self.run(turn, pcm)) + + async def send_history(self): + if self.history: + await self.event('history', conversation_id=self.conversation_id, messages=await self.history.rows(self.conversation_id)) + + async def change_history(self, action): + await self.invalidate('history_' + action) + self.listening = False + if self.cancelled_tasks: + await asyncio.gather(*list(self.cancelled_tasks), return_exceptions=True) + if action == 'clear': + await self.history.clear(self.conversation_id) + elif action == 'new': + self.conversation_id = await self.history.conversation() + await self.send_history() + + async def request_drained(self, turn): + if turn != self.turn or not self.playback_waiting: return + if self.task is not None and not self.task.done(): + # tts.stop may reach Android before history/debug finalization completes. + self.pending_drained = turn + else: + await self.drained() + + async def drained(self): + self.pending_drained = None + self.playback_waiting = False + if self.history and self.run_id: + await self.history.drained(self.run_id) + await self.send_history() + if not self.barge: + self.capture.clear(); self.start = None; self.base = 0 + self.capture_offset = self.received_samples + self.vad.reset() + await self.event('listen', state='resumed', mode=self.mode) + + async def run(self, turn, pcm): + metrics = {'debug_enabled_for_turn': self.debug_enabled} + began = time.perf_counter() + rid = self.run_id or str(uuid.uuid4()) + self.answers[turn] = '' + status = 'failed' + recorded = False + try: + async with asyncio.timeout(90): + wav = io.BytesIO() + with wave.open(wav, 'wb') as file: + file.setnchannels(1); file.setsampwidth(2); file.setframerate(16000); file.writeframes(pcm) + before = time.perf_counter() + async with asyncio.timeout(30): + result = await self.client.post('http://192.168.31.61:5001/v1/audio/transcriptions', files={'file': ('speech.wav', wav.getvalue(), 'audio/wav')}) + result.raise_for_status() + metrics['stt_ms'] = round((time.perf_counter() - before) * 1000, 2) + text = result.json().get('text', '').strip() + if turn != self.turn: return + await self.event('stt', turn, state='final', text=text) + if not text: + self.face_context.clear() + await self.event('listen', turn, state='resumed', mode=self.mode) + return + # Snapshot after ASR: no camera wait, no persistent/history context. + face_message = self.face_context.take(turn) + if face_message is not None: self.face_messages[turn] = [face_message] + metrics['face_cue_used'] = face_message is not None + text = text[:2000] + if self.history: + recorded = True + await self.history.begin(self.conversation_id, rid, text) + self.contexts[turn] = await self.history.context(self.conversation_id, rid) + if turn != self.turn: return + await self.send_history() + self.playback_waiting = True + await self.event('tts', turn, state='start', sample_rate=48000, codec='pcm16', frame_duration=20) + queue = asyncio.Queue(maxsize=2) + async with asyncio.TaskGroup() as group: + group.create_task(self.generate(turn, text, queue, metrics, began)) + group.create_task(self.synthesize(turn, queue, metrics, began)) + metrics['total_ms'] = round((time.perf_counter() - began) * 1000, 2) + await self.event('metrics', turn, values=metrics) + await self.event('tts', turn, state='stop') + status = 'completed' + except asyncio.CancelledError: + status = 'interrupted' + raise + except Exception: + await self.event('error', turn, code='backend_failed', message='Backend timeout, format or synthesis failure') + await self.event('tts', turn, state='stop') + finally: + answer = self.answers.pop(turn, '') + self.contexts.pop(turn, None) + self.face_messages.pop(turn, None) + capture = self.debug_captures.pop(turn, None) + if capture: + capture.meta['metrics'] = metrics + debug_id = await asyncio.to_thread(capture.finalize, status if turn == self.turn else 'interrupted') + if not self.closed: await self.event('debug.saved', debug_id=debug_id, captured_turn=turn) + if recorded: + await self.history.finish(rid, answer, status if turn == self.turn else 'interrupted') + if turn == self.turn and not self.closed: + await self.send_history() + if turn == self.turn and not self.closed and self.pending_drained == turn: + await self.drained() + + async def generate(self, turn, text, queue, metrics, began): + segmenter = Segmenter(getattr(self, 'synthesis_mode', 'balanced')) + request_start = time.perf_counter() + continuous = self.voice_mode == 'continuous_voice' + full_text = '' + metrics.update(voice_mode=self.voice_mode, voice_id=self.voice_id, tts_request_count=0) + async def enqueue(fragment): + if fragment: + if 'first_fragment_ms' not in metrics: metrics['first_fragment_ms'] = round((time.perf_counter() - began) * 1000, 2) + metrics['segment_hardcuts'] = segmenter.hardcuts + metrics['segment_last_cut'] = segmenter.last_cut + await queue.put(fragment) + async with asyncio.timeout(30): + async with self.client.stream('POST', 'http://127.0.0.1:8888/v1/chat/completions', json={'model': 'qwen3.8-27b', 'messages': [{'role': 'system', 'content': '用简短中文直接回答,不输出思考过程、动作旁白、Markdown或JSON。最多两小句。' + self.persona_rules + ''.join('\n\n' + item['content'] for item in self.face_messages.get(turn, []))}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}], 'max_tokens': 64, 'temperature': 0.3, 'stream': True, 'chat_template_kwargs': {'enable_thinking': False}}) as response: + response.raise_for_status() + lines = response.aiter_lines().__aiter__() + pending = asyncio.create_task(anext(lines)) + event_data = [] + try: + while True: + timeout = None if continuous else segmenter.timeout(time.perf_counter()) + done, _ = await asyncio.wait({pending}, timeout=timeout) + if not done: + await enqueue(segmenter.take(time.perf_counter())); continue + try: line = pending.result() + except StopAsyncIteration: break + pending = asyncio.create_task(anext(lines)) + if line.startswith('data:'): event_data.append(line[5:].lstrip()) + if line != '' or not event_data: continue + raw = '\n'.join(event_data); event_data = [] + if raw == '[DONE]': break + data = json.loads(raw) + for choice in data.get('choices', []): + delta = choice.get('delta', {}).get('content') or '' + if not delta: continue + if 'llm_first_body_ms' not in metrics: + metrics['llm_first_body_ms'] = round((time.perf_counter() - request_start) * 1000, 2) + if turn != self.turn: return + self.answers[turn] = (self.answers.get(turn, '') + delta)[:2000] + await self.event('llm', turn, text=delta) + full_text += delta + if len(full_text) > 1000: raise ValueError('TTS full text limit') + if not continuous: + await enqueue(segmenter.add(delta, time.perf_counter())) + while True: + fragment = segmenter.take(time.perf_counter()) + if not fragment: break + await enqueue(fragment) + if turn != self.turn: return + if not full_text.strip(): raise ValueError('empty LLM body') + metrics['llm_finished_ms'] = round((time.perf_counter() - began) * 1000, 2) + await self.event('llm.finished', turn, voice_mode=self.voice_mode, llm_finished_ms=metrics['llm_finished_ms']) + if continuous: + await enqueue(full_text.strip()) + else: + remainder = segmenter.take(time.perf_counter(), final=True) + queued = [] + while not queue.empty(): + queued.append(queue.get_nowait()) + combined = ''.join(queued) + (remainder or '') + if combined: + metrics['final_queued_merge_chars'] = len(combined) + await enqueue(combined) + finally: + pending.cancel() + with contextlib.suppress(asyncio.CancelledError, StopAsyncIteration): await pending + await queue.put(None) + + async def synthesize(self, turn, queue, metrics, began): + sentence = 0 + previous_end = None + previous_pcm = None + metrics['tts_segments'] = [] + while True: + ready_ahead = not queue.empty() + text = await queue.get() + if text is None: return + if turn != self.turn: return + sentence += 1 + await self.event('tts', turn, state='sentence_start', text=text, sentence_id=sentence) + parser = WavStream() + pending = bytearray() + request_start = time.perf_counter() + segment = {'sentence_id': sentence, 'text_chars': len(text), 'ready_ahead': ready_ahead, 'request_ms': round((request_start - began) * 1000, 2), 'schedule_gap_ms': round((request_start - previous_end) * 1000, 2) if previous_end else 0, 'first_pcm_ms': None, 'first_voiced_ms': None, 'pcm_arrival_gap_ms': None} + audio_bytes = 0 + last_chunk = None + segment.update(pcm_chunks=0, first_chunk_audio_ms=None, max_chunk_audio_ms=0, max_chunk_interarrival_ms=0) + metrics['tts_request_count'] = metrics.get('tts_request_count', 0) + 1 + await self.event('voice.metrics', turn, voice_mode=self.voice_mode, voice_id=self.voice_id, tts_request_count=metrics['tts_request_count']) + if self.debug_store and metrics.get('debug_enabled_for_turn', self.debug_enabled) and turn not in self.debug_captures: + self.debug_captures[turn] = await asyncio.to_thread(self.debug_store.create, {'run_id':self.run_id,'conversation_id':self.conversation_id,'turn_id':turn,'voice_id':self.voice_id,'voice_mode':self.voice_mode,'persona':self.persona,'tts_requests':[]}) + capture = self.debug_captures.get(turn) + if capture: + capture.meta['tts_requests'].append({'input':text,'parameters':{'model':'openbmb/VoxCPM2','voice':self.voice_id,'stream':True},'request_number':sentence}) + async with asyncio.timeout(30): + async with self.client.stream('POST', 'http://192.168.31.61:5002/v1/audio/speech', json={'model': 'openbmb/VoxCPM2', 'input': text, 'voice': self.voice_id, 'stream': True}) as response: + response.raise_for_status() + async for block in response.aiter_bytes(): + if turn != self.turn: return + pcm = parser.feed(block) + if pcm: + now = time.perf_counter() + if capture: capture.enqueue(pcm, (now-began)*1000, sentence) + audio_bytes += len(pcm) + chunk_ms = len(pcm) / 96 + segment['pcm_chunks'] += 1 + if segment['first_chunk_audio_ms'] is None: segment['first_chunk_audio_ms'] = round(chunk_ms, 2) + segment['max_chunk_audio_ms'] = max(segment['max_chunk_audio_ms'], round(chunk_ms, 2)) + if last_chunk is not None: segment['max_chunk_interarrival_ms'] = max(segment['max_chunk_interarrival_ms'], round((now - last_chunk) * 1000, 2)) + last_chunk = now + if segment['first_pcm_ms'] is None: + segment['first_pcm_ms'] = round((now - request_start) * 1000, 2) + segment['pcm_arrival_gap_ms'] = round((now - previous_pcm) * 1000, 2) if previous_pcm else None + previous_pcm = now + if segment['first_voiced_ms'] is None and np.any(np.abs(np.frombuffer(pcm, dtype=' 327): + segment['first_voiced_ms'] = round((now - request_start) * 1000, 2) + if 'tts_first_pcm_ms' not in metrics: + metrics['tts_first_pcm_ms'] = round((time.perf_counter() - request_start) * 1000, 2) + metrics['capture_to_first_pcm_ms'] = round((time.perf_counter() - began) * 1000, 2) + if 'tts_first_voiced_block_ms' not in metrics and np.any(np.abs(np.frombuffer(pcm, dtype=' 327): + metrics['tts_first_voiced_block_ms'] = round((time.perf_counter() - request_start) * 1000, 2) + metrics['capture_to_voiced_block_ms'] = round((time.perf_counter() - began) * 1000, 2) + pending.extend(pcm) + while len(pending) >= 1920: + await self.audio(turn, bytes(pending[:1920])); del pending[:1920] + parser.finish() + if not audio_bytes: raise ValueError('empty TTS PCM') + if pending: await self.audio(turn, bytes(pending)) + previous_end = time.perf_counter() + seconds = audio_bytes / 96000 + segment.update(total_ms=round((previous_end - request_start) * 1000, 2), audio_seconds=round(seconds, 4), rtf=round((previous_end - request_start) / seconds, 4) if seconds else None) + if len(metrics['tts_segments']) < 16: metrics['tts_segments'].append(segment) + await self.event('tts.metrics', turn, values=segment) + + async def close(self): + self.closed = True + self.turn += 1 + tasks = list(self.cancelled_tasks) + if self.task: tasks.append(self.task) + for task in tasks: task.cancel() + if tasks: await asyncio.gather(*tasks, return_exceptions=True) + if self.history and self.run_id: + await self.history.interrupt(self.run_id) + self.face_context.clear(); self.face_messages.clear() + self.capture.clear(); self.vad.reset() + + +@app.websocket('/ws/dialogue') +async def dialogue(ws: WebSocket): + if ws.headers.get('origin') not in ORIGINS: + await ws.close(code=1008); return + if app.state.busy: + await ws.close(code=1013); return + app.state.busy = True + session = None + try: + await ws.accept() + owner = guest_key(ws) or open_key(ws) + if not owner: + raw = await asyncio.wait_for(ws.receive_text(), 5) + if len(raw) > 2048: raise ValueError('auth size') + auth = json.loads(raw) + if not isinstance(auth, dict) or auth.get('type') != 'auth' or not isinstance(auth.get('token'), str) or not secrets.compare_digest(auth['token'], app.state.token): + raise ValueError('auth') + await ws.send_json({'type': 'auth', 'state': 'ok', 'method':'guest_cookie' if owner else 'admin_bearer'}) + raw = await asyncio.wait_for(ws.receive_text(), 5) + if len(raw) > 2048: raise ValueError('hello size') + hello = json.loads(raw) + if hello.get('type') != 'hello' or hello.get('codec') != 'pcm16' or hello.get('sample_rate') != 16000 or hello.get('frame_duration') != 20: + raise ValueError('hello supports pcm16 mono 16k 20ms only') + profile = load_active_profile() if hello.get('persona', 'default') == 'default' else None + persona = profile.get('persona', 'default') if profile else hello.get('persona', 'default') + resolved = resolve_persona(ROOT, persona, [v['id'] for v in app.state.voices]) + requested = None if resolved['fresh_conversation'] else hello.get('conversation_id') + if owner and requested: app.state.guests.own(owner, requested) + cid = await app.state.history.conversation(requested) + if owner and not requested: app.state.guests.bind(owner, cid) + synthesis_mode = hello.get('synthesis_mode', 'balanced') + Segmenter(synthesis_mode) + session = Dialogue(ws, app.state.model, app.state.client, app.state.history, cid) + session.synthesis_mode = synthesis_mode + if owner: session.auth_check = lambda: bool(app.state.guests.get(owner)) + voice_mode = hello.get('voice_mode', 'continuous_voice') + if voice_mode not in ('continuous_voice', 'fragment'): raise ValueError('voice mode') + session.voice_mode = voice_mode + voice_id = hello.get('voice_id', DEFAULT_VOICE_ID) + if profile and profile.get('voice_id'): voice_id = profile['voice_id'] + if voice_id not in [v['id'] for v in app.state.voices]: raise ValueError('voice not active') + session.persona = persona + session.persona_rules = resolved['rules'] + if resolved['locked']: + voice_id = resolved['voice_id'] + session.voice_id = voice_id + session.debug_store = app.state.debug + session.debug_enabled = hello.get('tts_debug', True) is True + await session.event('hello', context_face_cue_version=1, version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices) + await session.send_history() + started = time.monotonic() + while time.monotonic() - started < 600: + message = await asyncio.wait_for(ws.receive(), 60) + if message['type'] == 'websocket.disconnect': break + if owner: + app.state.guests.own(owner, session.conversation_id) + if message.get('bytes') is not None: + await session.input(message['bytes']) + else: + raw = message.get('text') or '' + if len(raw) > 4096: raise ValueError('control size') + data = json.loads(raw) + if not isinstance(data, dict): raise ValueError('control object') + if data.get('type') == 'context.face_cue': + if len(raw.encode('utf-8')) > 512: + session.face_context.clear() + else: + session.face_context.update(data, session.turn) + elif data.get('type') == 'debug': + action = data.get('action', 'list') + if action == 'set': session.debug_enabled = data.get('enabled') is True + elif action == 'mark': await asyncio.to_thread(app.state.debug.mark, data['debug_id'], session.conversation_id) + elif action != 'list': raise ValueError('debug action') + await session.event('debug.list', enabled=session.debug_enabled, items=await asyncio.to_thread(app.state.debug.list, session.conversation_id)) + elif data.get('type') == 'voice': + if session.voice_locked or session.persona != 'default': raise ValueError('voice locked for session/persona') + if data.get('voice_id') not in [v['id'] for v in app.state.voices]: raise ValueError('voice not active') + session.voice_id = data['voice_id'] + await session.event('voice', voice_id=session.voice_id, source='registered_reference', locked=False) + elif data.get('type') == 'listen': + session.voice_locked = True + await session.event('voice', voice_id=session.voice_id, source='registered_reference', locked=True) + await session.listen(data.get('mode', 'auto'), data.get('state') == 'start', data.get('barge_in', True) is True, data.get('start_windows', 3)) + elif data.get('type') == 'abort': + await session.invalidate('client_abort') + elif data.get('type') == 'history': + if data.get('conversation_id') != session.conversation_id: raise ValueError('conversation mismatch') + action = data.get('action', 'get') + if action in ('new', 'clear'): + if owner and action == 'new' and len(app.state.guests.get(owner)['conversations']) >= 20: raise ValueError('conversation limit') + await session.change_history(action) + if owner and action == 'new': app.state.guests.bind(owner, session.conversation_id) + elif action == 'get': await session.send_history() + else: raise ValueError('history action') + elif data.get('type') == 'playback.drained': + await session.request_drained(data.get('turn_id')) + elif data.get('type') == 'ping': await session.event('pong') + else: raise ValueError('control') + except (WebSocketDisconnect, RuntimeError): + pass + except (ValueError, TypeError, KeyError, asyncio.TimeoutError): + with contextlib.suppress(Exception): await ws.close(code=1008) + finally: + if session: await session.close() + app.state.busy = False diff --git a/gateway/guest_sessions.py b/gateway/guest_sessions.py new file mode 100644 index 0000000..deb6166 --- /dev/null +++ b/gateway/guest_sessions.py @@ -0,0 +1,39 @@ +import ipaddress +import secrets +import time + +COOKIE = 'lan_voice_guest' + + +class GuestSessions: + def __init__(self, ttl=8*3600, capacity=128): + self.ttl=min(ttl,8*3600);self.capacity=min(capacity,128);self.sessions={} + + @staticmethod + def lan(ip): + try: + value=ipaddress.ip_address(ip) + return value.is_loopback or value in ipaddress.ip_network('192.168.31.0/24') or value in ipaddress.ip_network('10.6.0.0/24') + except (ValueError,TypeError):return False + + def get(self,key): + entry=self.sessions.get(key) + if entry and entry['expires']>time.time():return entry + if key in self.sessions:self.sessions.pop(key) + return None + + def create(self): + self.sessions={k:v for k,v in self.sessions.items() if v['expires']>time.time()} + if len(self.sessions)>=self.capacity:raise ValueError('session capacity') + key=secrets.token_urlsafe(32);self.sessions[key]={'expires':time.time()+self.ttl,'conversations':set()};return key + + def own(self,key,cid): + entry=self.get(key) + if not entry or cid not in entry['conversations']:raise ValueError('conversation not owned') + + def bind(self,key,cid): + entry=self.get(key) + if not entry or len(entry['conversations'])>=20:raise ValueError('conversation capacity') + entry['conversations'].add(cid) + + def revoke(self,key):self.sessions.pop(key,None) diff --git a/gateway/history.py b/gateway/history.py new file mode 100644 index 0000000..bd87e94 --- /dev/null +++ b/gateway/history.py @@ -0,0 +1,85 @@ +import asyncio +from contextlib import closing +import os +import sqlite3 +import time +import uuid +from pathlib import Path + + +class History: + def __init__(self, path): + self.path = Path(path) + self.lock = asyncio.Lock() + + async def call(self, fn): + async with self.lock: + task = asyncio.create_task(asyncio.to_thread(self.transaction, fn)) + try: + return await asyncio.shield(task) + except asyncio.CancelledError: + await task + raise + + def transaction(self, fn): + self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + if not self.path.exists(): + fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + os.close(fd) + os.chmod(self.path, 0o600) + with closing(sqlite3.connect(self.path, timeout=5)) as db: + db.row_factory = sqlite3.Row + db.execute('PRAGMA journal_mode=WAL') + db.execute('PRAGMA foreign_keys=ON') + with db: + result = fn(db) + for suffix in ('-wal', '-shm'): + p = Path(str(self.path) + suffix) + if p.exists(): os.chmod(p, 0o600) + return result + + async def initialize(self): + def init(db): + db.executescript('''CREATE TABLE IF NOT EXISTS conversations(id TEXT PRIMARY KEY, created REAL NOT NULL); +CREATE TABLE IF NOT EXISTS messages(id INTEGER PRIMARY KEY AUTOINCREMENT, conversation_id TEXT NOT NULL REFERENCES conversations(id), run_id TEXT NOT NULL, role TEXT NOT NULL, text TEXT NOT NULL, status TEXT NOT NULL, playback TEXT NOT NULL DEFAULT 'not_started', created REAL NOT NULL, updated REAL NOT NULL, UNIQUE(run_id,role));''') + db.execute("UPDATE messages SET status='interrupted', playback='unconfirmed' WHERE status='generating'") + await self.call(init) + + async def conversation(self, requested=None): + if requested is not None: + if not isinstance(requested, str) or len(requested) != 36 or str(uuid.UUID(requested)) != requested: + raise ValueError('invalid conversation UUID') + value = requested or str(uuid.uuid4()) + await self.call(lambda db: db.execute('INSERT OR IGNORE INTO conversations VALUES (?,?)', (value, time.time()))) + return value + + async def rows(self, cid): + return await self.call(lambda db: [dict(r) for r in db.execute('SELECT id,run_id,role,text,status,playback,created,updated FROM (SELECT * FROM messages WHERE conversation_id=? ORDER BY id DESC LIMIT 100) ORDER BY id', (cid,))]) + + async def context(self, cid, current): + def query(db): + rows = list(db.execute("SELECT u.text user,a.text assistant FROM messages u JOIN messages a ON u.run_id=a.run_id AND u.conversation_id=a.conversation_id WHERE u.conversation_id=? AND u.run_id<>? AND u.role='user' AND a.role='assistant' AND u.status='completed' AND a.status='completed' AND a.playback='confirmed' ORDER BY u.id DESC LIMIT 10", (cid, current))) + out = [] + for r in reversed(rows): + out += [{'role': 'user', 'content': r['user'][:2000]}, {'role': 'assistant', 'content': r['assistant'][:2000]}] + return out + return await self.call(query) + + async def begin(self, cid, rid, text): + def insert(db): + now = time.time() + db.execute('INSERT INTO messages(conversation_id,run_id,role,text,status,created,updated) VALUES (?,?,?,?,?,?,?)', (cid, rid, 'user', text[:2000], 'completed', now, now)) + db.execute('INSERT INTO messages(conversation_id,run_id,role,text,status,created,updated) VALUES (?,?,?,?,?,?,?)', (cid, rid, 'assistant', '', 'generating', now, now)) + await self.call(insert) + + async def finish(self, rid, text, status): + await self.call(lambda db: db.execute("UPDATE messages SET text=?, status=?, playback=CASE WHEN ?='completed' THEN 'awaiting_drain' ELSE 'unconfirmed' END,updated=? WHERE run_id=? AND role='assistant' AND (status='generating' OR (status='interrupted' AND ?='interrupted'))", (text[:2000], status, status, time.time(), rid, status))) + + async def interrupt(self, rid): + await self.call(lambda db: db.execute("UPDATE messages SET status=CASE WHEN status='completed' THEN status ELSE 'interrupted' END,playback='interrupted',updated=? WHERE run_id=? AND role='assistant' AND playback<>'confirmed'", (time.time(), rid))) + + async def drained(self, rid): + await self.call(lambda db: db.execute("UPDATE messages SET playback='confirmed',updated=? WHERE run_id=? AND role='assistant' AND status='completed' AND playback='awaiting_drain'", (time.time(), rid))) + + async def clear(self, cid): + await self.call(lambda db: db.execute('DELETE FROM messages WHERE conversation_id=?', (cid,))) diff --git a/gateway/persona_resolver.py b/gateway/persona_resolver.py new file mode 100644 index 0000000..fde7d42 --- /dev/null +++ b/gateway/persona_resolver.py @@ -0,0 +1,21 @@ +import json +from pathlib import Path + +DEFAULT_VOICE_ID = '9a97272c-3919-5606-9c8f-9552ab602528' +PERSONAS = {'default': None, 'lvbu': ('lvbu.lorebook.json', 'lvbu.json'), 'yangmi_fiction': ('yangmi.lorebook.json', 'yangmi_fiction.json')} + + +def resolve_persona(root, name, active_ids): + if not isinstance(name, str) or name not in PERSONAS: + raise ValueError('unknown persona') + if name == 'default': + return {'id': name, 'rules': '', 'voice_id': DEFAULT_VOICE_ID, 'fresh_conversation': False, 'locked': False, 'name': '普通助手'} + lore_file, manifest_file = PERSONAS[name] + root = Path(root) + lore = json.loads((root / 'personas' / lore_file).read_text()) + manifest = json.loads((root / '.runtime/personas' / manifest_file).read_text()) + voice = manifest['voice_id'] + if voice not in active_ids: raise ValueError('persona voice inactive') + rules = lore['rules'] + '\n' + '\n'.join(e['label'] + ': ' + e['text'] for e in lore['entries']) + if len(rules) > 1400: raise ValueError('persona lore exceeds budget') + return {'id': name, 'name': lore['name'], 'rules': rules, 'voice_id': voice, 'fresh_conversation': True, 'locked': True} diff --git a/gateway/personas/LVBU.md b/gateway/personas/LVBU.md new file mode 100644 index 0000000..b1b23d9 --- /dev/null +++ b/gateway/personas/LVBU.md @@ -0,0 +1,11 @@ +# 吕布角色设定 + +仅本地用户提供素材角色扮演测试,不公开发布。音色参考文件与clone ID只在.runtime,不提交Git。 + +- 历史标签:吕布字奉先,并州五原郡九原;勇武骑射,依附关系反复,识人与谋略弱点不可抹去。 +- 三国演义/虚构标签:方天画戟、赤兔、貂蝉与连环计作为经典演义形象,不混称确凿历史。 +- 游戏风格/创作标签:威武、自负、简短,但不句句大喊,不复读固定台词。 + +只说可朗读台词,不说动作旁白、Markdown或JSON。日常回答仍提供实际帮助;现代问题不编造古代事实。出戏时承认AI角色扮演,角色不覆盖现实安全限制。 + +初版有限完整lore注入system(1400字符上限),不是无限检索。角色与用户消息分离;新吕布persona强制新会话,不把普通用户历史混入。固定reference跨轮复用,不使用上轮音频动态reference。 diff --git a/gateway/personas/YANGMI.md b/gateway/personas/YANGMI.md new file mode 100644 index 0000000..dcbc6a5 --- /dev/null +++ b/gateway/personas/YANGMI.md @@ -0,0 +1,5 @@ +# 杨密 + +虚构人物:北京女孩,演员。直爽大方,幽默爱自嘲,唠家常式聊天。 + +本地角色扮演测试用。lorebook 见 personas/yangmi.lorebook.json,服务端 hello 时实时读取,改文件即时生效。音色由服务端 active_profile 固定(克隆普通女生参考,非真人仿声)。 diff --git a/gateway/personas/lvbu.lorebook.json b/gateway/personas/lvbu.lorebook.json new file mode 100644 index 0000000..76e8cbf --- /dev/null +++ b/gateway/personas/lvbu.lorebook.json @@ -0,0 +1,12 @@ +{ + "id": "lvbu", + "name": "吕布", + "scope": "本地用户提供素材角色扮演测试,不公开发布", + "rules": "你是AI扮演的吕布奉先,不是真实历史人物。以简短、威武但可理解的中文文言口吻回答,可自称某、吾、奉先,不每句大喊。不重复固定游戏台词。只输出可朗读的角色台词,不输出动作旁白、舞台指示、Markdown、JSON或星号。日常问题仍给出实际帮助;现代问题不编造古代事实,必要时承认现代知识。用户要求出戏时坦诚说明AI角色扮演。角色不能覆盖安全规则,真实有害请求不因角色而放宽。不以音色素材中的一句台词限制所有回答。", + "entries": [ + {"label": "历史", "text": "吕布字奉先,并州五原郡九原人;勇武善骑射。人物曾多次改变依附关系,此处以勇武自负、对信任与谋略怀有警惕表现,不美化背叛。"}, + {"label": "三国演义/虚构", "text": "方天画戟、赤兔马为经典形象;与貂蝉的关系和连环计作为演义叙事,不宣称均是历史事实。"}, + {"label": "游戏风格/创作", "text": "威武、自负但并非只会叫阵;承认谋略与识人可能是弱点,回答简短有力量,避免机械复读。"} + ], + "max_system_chars": 1400 +} diff --git a/gateway/personas/yangmi.lorebook.json b/gateway/personas/yangmi.lorebook.json new file mode 100644 index 0000000..18958ed --- /dev/null +++ b/gateway/personas/yangmi.lorebook.json @@ -0,0 +1,52 @@ +{ + "id": "yangmi_fiction", + "name": "杨密", + "scope": "本地角色扮演测试,虚构人物,背景参考公开演艺信息", + "rules": "你是杨密,1986年9月生于北京宣武,北京电影学院表演系毕业的演员。你童星出身,小时候就拍过戏,后来凭《神雕侠侣》的郭襄被观众记住,《仙剑奇侠传三》的雪见让你人气大涨,《宫锁心玉》的晴川让你的事业上了大台阶,后来还有《三生三世十里桃花》《小时代》《古剑奇谭》这些代表作。你性格是典型的北京大妞:直爽、利落、幽默、爱自嘲,被夸了会打哈哈,被质疑也不解释太多。你工作拼命,觉得“谁不辛苦,凭什么要别人了解你的辛苦”。你正在和朋友打电话聊天,用自然口语,简短真实。朋友有烦心事你先理解再给实在建议。只输出嘴里说的话,不输出旁白、动作、Markdown或JSON。", + "entries": [ + { + "label": "出身与成长", + "text": "北京宣武(现西城)出生,胡同里长大。童星出道,小时候演过《唐明皇》,后来考入北京电影学院表演系。在家跟爸妈说话带北京腔,出来工作说普通话,口音来去自如。" + }, + { + "label": "演艺经历", + "text": "从《神雕侠侣》郭襄崭露头角,《仙剑三》唐雪见人气急升,《宫锁心玉》洛晴川红遍大江南北并拿了白玉兰最具人气女演员,《三生三世十里桃花》刷新网播纪录,电影有《小时代》系列、《逆时营救》《刺杀小说家》《绣春刀Ⅱ》等。" + }, + { + "label": "性格与态度", + "text": "直爽不装,被夸演技也不当真,说“结果顺其自然”。处女座式的较真,工作上一部接一部不喊累。面对质疑和热搜的态度是:该澄清澄清,然后继续干活。觉得“角色只代表一个阶段,过去了就往前看”。" + }, + { + "label": "说话方式", + "text": "口语化、节奏快、偶尔蹦出北京腔的幽默。聊到剧组会说背台词、吊威亚、熬夜的事。劝朋友时不说大道理,就说“先把今天能做的做了”。不开心时承认不开心,但转头就去找下一顿饭了。" + } + ], + "max_system_chars": 1400, + "sources": [ + { + "title": "百度百科:杨幂", + "url": "https://baike.baidu.com/item/杨幂/149851", + "use": "出生、教育、代表作品等公开事实" + }, + { + "title": "维基百科:杨幂", + "url": "https://zh.wikipedia.org/wiki/杨幂", + "use": "童星出道、作品年表" + }, + { + "title": "中新网专访2017", + "url": "https://www.chinanews.com.cn/m/yl/2017/07-20/8282668.shtml", + "use": "北京腔、人民艺术女演员、工作态度" + }, + { + "title": "环球人物2015", + "url": "https://paper.people.com.cn/hqrw/html/2015-10/26/content_1666564.htm", + "use": "处女座较真、劳模精神、不喊苦" + }, + { + "title": "澎湃封面故事2021", + "url": "https://www.thepaper.cn/newsDetail_forward_22123010", + "use": "角色过去时、往前看的态度" + } + ] +} diff --git a/gateway/protocol.py b/gateway/protocol.py new file mode 100644 index 0000000..6a56e42 --- /dev/null +++ b/gateway/protocol.py @@ -0,0 +1,65 @@ +import struct + +HEADER = struct.Struct('!2sBBII') + + +def pack(direction, turn_id, seq, pcm): + if direction not in (1, 2) or len(pcm) % 2 or not 0 < len(pcm) <= 64000: + raise ValueError('invalid PCM frame') + return HEADER.pack(b'LV', 1, direction, turn_id, seq) + pcm + + +def unpack(data, direction): + if len(data) < HEADER.size: + raise ValueError('short header') + magic, version, actual, turn, seq = HEADER.unpack_from(data) + pcm = data[HEADER.size:] + if magic != b'LV' or version != 1 or actual != direction or not pcm or len(pcm) % 2 or len(pcm) > 64000: + raise ValueError('invalid header or PCM') + return turn, seq, pcm + + +class WavStream: + def __init__(self): + self.buffer = bytearray() + self.ready = False + self.fmt = None + + def feed(self, data): + self.buffer.extend(data) + if not self.ready: + if len(self.buffer) > 65536: + raise ValueError('WAV header too large') + if len(self.buffer) < 12: + return b'' + if self.buffer[:4] != b'RIFF' or self.buffer[8:12] != b'WAVE': + raise ValueError('not WAV') + pos = 12 + while pos + 8 <= len(self.buffer): + tag = self.buffer[pos:pos + 4] + size = struct.unpack_from(' 65536: + raise ValueError('WAV chunk too large') + if pos + 8 + size > len(self.buffer): + return b'' + if tag == b'fmt ': + if size < 16: raise ValueError('short fmt') + code, channels, rate, _, _, bits = struct.unpack_from(' 0 + await ws.send(json.dumps({'type':'playback.drained','turn_id':turn})) + ack = json.loads(await ws.recv()); assert ack['state'] == 'resumed' + await ws.send(json.dumps({'type':'abort'})); await ws.recv() + result = {'status':'passed','mode':'auto','downlink_frames':frames,'drain_ack':'passed','events':events} + (ROOT/'tmp/auto_integration.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n') + print(json.dumps(result,ensure_ascii=False)) + + +if __name__=='__main__': asyncio.run(main()) diff --git a/gateway/scripts/check_browser.py b/gateway/scripts/check_browser.py new file mode 100644 index 0000000..66573a3 --- /dev/null +++ b/gateway/scripts/check_browser.py @@ -0,0 +1,80 @@ +import asyncio +import json +import subprocess +import tempfile +import time +from pathlib import Path + +import httpx +import websockets + +ROOT = Path(__file__).resolve().parents[1] +CHROME = '/home/gorios-spark-2/.cache/ms-playwright/chromium_headless_shell-1243/chrome-headless-shell-linux-arm64/chrome-headless-shell' + + +async def main(): + with tempfile.TemporaryDirectory(prefix='lan-voice-browser-') as profile: + process = subprocess.Popen([CHROME, '--headless', '--no-sandbox', '--ignore-certificate-errors', '--autoplay-policy=no-user-gesture-required', '--remote-debugging-address=127.0.0.1', '--remote-debugging-port=0', '--user-data-dir=' + profile, 'https://192.168.31.61:5011'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + portfile = Path(profile) / 'DevToolsActivePort' + for _ in range(100): + if portfile.exists(): break + await asyncio.sleep(0.05) + port = portfile.read_text().splitlines()[0] + async with httpx.AsyncClient(trust_env=False) as client: + pages = (await client.get(f'http://127.0.0.1:{port}/json')).json() + target = next(p for p in pages if p['type'] == 'page') + async with websockets.connect(target['webSocketDebuggerUrl'], proxy=None) as ws: + counter = 0 + async def cdp(method, params): + nonlocal counter + counter += 1; current = counter + await ws.send(json.dumps({'id': current, 'method': method, 'params': params})) + while True: + message = json.loads(await ws.recv()) + if message.get('id') == current: return message + await asyncio.sleep(0.5) + result = await cdp('Runtime.evaluate', {'expression': '''(async()=>{ + const {Resampler}=await import('/static/audio-core.js'); + const {runPlaybackTests}=await import('/static/playback-test.js'); + const playbackTests=runPlaybackTests(); + const checks=[]; + for(const rate of [44100,48000]){ + const signal=Float32Array.from({length:rate*2},(_,i)=>Math.sin(i*.01)); + const all=new Resampler(rate,16000).push(signal); + const r=new Resampler(rate,16000);let pieces=[]; + for(let i=0;iMath.abs(x-pieces[i])>1e-7))throw Error('resample drift'); + checks.push({rate,outputSamples:pieces.length,chunkInvariant:true}); + } + const context=new AudioContext();await context.resume(); + await context.audioWorklet.addModule('/static/capture-worklet.js'); + await context.audioWorklet.addModule('/static/play-worklet.js'); + const node=new AudioWorkletNode(context,'playback');node.connect(context.destination); + const events=[];node.port.onmessage=e=>events.push(e.data); + node.port.postMessage({type:'clear',turn:1}); + node.port.postMessage({type:'pcm',turn:1,pcm:new Float32Array(6000).fill(.1)}); + node.port.postMessage({type:'end',turn:1}); + await new Promise(r=>setTimeout(r,200));node.port.postMessage({type:'clear',turn:2}); + await new Promise(r=>setTimeout(r,50));await context.close(); + let microphone; + try{const stream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:true,noiseSuppression:true,autoGainControl:true}});microphone={available:true,settings:stream.getAudioTracks()[0].getSettings()};stream.getTracks().forEach(t=>t.stop());}catch(e){microphone={available:false,error:e.name};} + return {secureContext:isSecureContext,title:document.title,checks,playbackTests,workletEvents:events,microphone,opusDisabled:document.querySelector('#codec option:nth-child(2)').disabled}; + })()''', 'awaitPromise': True, 'returnByValue': True}) + if 'exceptionDetails' in result.get('result', {}): raise RuntimeError(result) + await cdp('Page.captureScreenshot', {'format':'png'}) + for width,name in [(1100,'desktop'),(390,'mobile')]: + await cdp('Emulation.setDeviceMetricsOverride', {'width':width,'height':900,'deviceScaleFactor':1,'mobile':width<500}) + shot=await cdp('Page.captureScreenshot', {'format':'png'}) + import base64 + (ROOT / ('tmp/home-'+name+'.png')).write_bytes(base64.b64decode(shot['result']['data'])) + data = result['result']['result']['value'] + print(json.dumps(data, ensure_ascii=False)) + (ROOT / 'tmp/browser_validation.json').write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n') + finally: + process.terminate() + try: process.wait(timeout=5) + except subprocess.TimeoutExpired: process.kill(); process.wait() + + +if __name__ == '__main__': asyncio.run(main()) diff --git a/gateway/scripts/check_gateway.py b/gateway/scripts/check_gateway.py new file mode 100644 index 0000000..2823be4 --- /dev/null +++ b/gateway/scripts/check_gateway.py @@ -0,0 +1,64 @@ +import asyncio +import json +import os +import ssl +import sys +import time +import wave +from pathlib import Path + +import websockets + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from protocol import pack, unpack + + +async def main(): + ssl_context = ssl.create_default_context(cafile=str(ROOT / '.runtime/gateway-cert.pem')) + kwargs = dict(ssl=ssl_context, origin='https://192.168.31.61:5011', proxy=None) + url = 'wss://192.168.31.61:5011/ws/dialogue' + async with websockets.connect(url, **kwargs) as ws: + await ws.send(json.dumps({'type': 'auth', 'token': 'invalid'})) + try: await ws.recv(); raise AssertionError('bad auth accepted') + except websockets.exceptions.ConnectionClosed: pass + with wave.open(str(ROOT / 'tmp/public_tts_16k.wav')) as file: pcm = file.readframes(file.getnframes()) + events = []; frames = 0; first = None; last_seq = 0 + async with websockets.connect(url, **kwargs) as ws: + await ws.send(json.dumps({'type': 'auth', 'token': os.environ['LAN_GATEWAY_TOKEN']})) + assert json.loads(await ws.recv())['state'] == 'ok' + await ws.send(json.dumps({'type': 'hello', 'codec': 'pcm16', 'sample_rate': 16000, 'frame_duration': 20})) + assert json.loads(await ws.recv())['type'] == 'hello' + await ws.send(json.dumps({'type': 'listen', 'mode': 'manual', 'state': 'start'})) + turn = json.loads(await ws.recv())['turn_id'] + assert json.loads(await ws.recv())['type'] == 'listen' + for i in range(0, len(pcm), 640): + await ws.send(pack(1, turn, i // 640 + 1, pcm[i:i + 640])); await asyncio.sleep(0.02) + start = time.perf_counter() + await ws.send(json.dumps({'type': 'listen', 'mode': 'manual', 'state': 'stop'})) + 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 + last_seq = seq; frames += 1 + if first is None: first = (time.perf_counter() - start) * 1000 + else: + event = json.loads(raw); events.append(event) + if event['type'] == 'abort': turn = event['turn_id']; last_seq = 0 + if event['type'] == 'error': raise AssertionError(event) + if event['type'] == 'tts' and event['state'] == 'stop': break + await ws.send(json.dumps({'type': 'abort'})) + while True: + raw = await ws.recv() + if isinstance(raw, str) and json.loads(raw)['type'] == 'abort': break + assert frames > 0 + assert any(e['type'] == 'stt' and e['text'] for e in events) + assert any(e['type'] == 'llm' and e['text'] for e in events) + result = {'status': 'passed', 'mode': 'manual', 'backend_calls': 'one real full chain; TTS fragment calls bounded by max_tokens=64', 'first_downlink_after_manual_end_ms': round(first, 2), 'downlink_frames': frames, 'events': events} + (ROOT / 'tmp/gateway_integration.json').write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') + print(json.dumps(result, ensure_ascii=False)) + + +if __name__ == '__main__': asyncio.run(main()) diff --git a/gateway/scripts/check_ws.py b/gateway/scripts/check_ws.py new file mode 100644 index 0000000..6e57b79 --- /dev/null +++ b/gateway/scripts/check_ws.py @@ -0,0 +1,74 @@ +import asyncio +import base64 +import json +import os +import sys +import time +import wave +from pathlib import Path + +import httpx +import websockets + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + + +def token(): + value = os.environ.get('LAN_VAD_TOKEN') + if not value: + raise RuntimeError('provide LAN_VAD_TOKEN in process environment') + return value + + +async def check(): + url = 'ws://192.168.31.61:5010/ws/vad' + try: + async with websockets.connect(url, proxy=None): + raise AssertionError('unauthenticated websocket accepted') + except websockets.exceptions.InvalidStatus as exc: + assert exc.response.status_code == 403 + headers = {'Authorization': 'Bearer ' + token()} + events = [] + with wave.open(str(ROOT / 'tmp/public_tts_16k.wav')) as w: + pcm = bytes(16000) + w.readframes(w.getnframes()) + bytes(32000) + started = time.perf_counter() + async with websockets.connect(url, additional_headers=headers, proxy=None) as a, websockets.connect(url, additional_headers=headers, proxy=None) as b: + for ws in (a, b): + await ws.send(json.dumps({'type': 'session.start', 'include_preroll_audio': ws is a})) + assert json.loads(await ws.recv())['type'] == 'session.ready' + await b.send(bytes(32000)) + await b.send(json.dumps({'type': 'ping'})) + assert json.loads(await b.recv())['type'] == 'pong' + + async def receive(): + while True: + data = json.loads(await a.recv()) + if data['type'] == 'speech.start': + decoded = base64.b64decode(data.pop('preroll_pcm16_base64')) + expected = pcm[data['preroll_start_sample'] * 2:data['audio_until_sample'] * 2] + assert decoded == expected + data['preroll_bytes_verified'] = len(decoded) + events.append(data) + if data['type'] == 'session.ended': return + + task = asyncio.create_task(receive()) + for i in range(0, len(pcm), 640): + await a.send(pcm[i:i + 640]) + await asyncio.sleep(0.02) + await a.send(json.dumps({'type': 'audio.end'})) + await asyncio.wait_for(task, 10) + assert any(e['type'] == 'speech.start' for e in events) + assert any(e['type'] == 'speech.end' and e['reason'] == 'silence' for e in events) + await a.send(json.dumps({'type': 'reset'})) + assert json.loads(await a.recv())['type'] == 'session.reset' + await a.send(bytes(32000)) + await a.send(json.dumps({'type': 'ping'})) + assert json.loads(await a.recv())['type'] == 'pong' + result = {'status': 'passed', 'checks': ['auth_rejected', 'real_silero_speech_start_end', 'preroll_bytes', 'two_session_isolation', 'reset', 'real_time_20ms_pacing'], 'elapsed_seconds': round(time.perf_counter() - started, 3), 'events': events} + print(json.dumps(result, ensure_ascii=False)) + (ROOT / 'tmp/ws_integration.json').write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') + + +if __name__ == '__main__': + asyncio.run(check()) diff --git a/gateway/scripts/measure.py b/gateway/scripts/measure.py new file mode 100644 index 0000000..4e9af4d --- /dev/null +++ b/gateway/scripts/measure.py @@ -0,0 +1,135 @@ +import asyncio +import io +import json +import struct +import sys +import time +import wave +from pathlib import Path + +import httpx +import numpy as np + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +TEXT = '今天天气不错,我们去散步吧。' + + +def wav_header(data): + if len(data) < 12 or data[:4] != b'RIFF' or data[8:12] != b'WAVE': + return None + pos = 12 + fmt = None + while pos + 8 <= len(data): + tag = data[pos:pos + 4] + size = struct.unpack_from(' len(data): + return None + if tag == b'fmt ': + fmt = struct.unpack_from(' 327): + audible = elapsed + if cancel and first is not None: + break + result = {'kind': 'tts', 'index': index, 'first_pcm_ms': round(first * 1000, 2) if first else None, 'first_above_minus40dbfs_ms': round(audible * 1000, 2) if audible else None, 'total_ms': round((time.perf_counter() - start) * 1000, 2), 'cancel_after_first_pcm': cancel, 'network_blocks': len(times)} + if header: + offset, fmt = header + result.update({'format_tag': fmt[0], 'channels': fmt[1], 'sample_rate': fmt[2], 'bits': fmt[5], 'audio_seconds': (len(body) - offset) / fmt[3]}) + if not cancel: + with wave.open(str(ROOT / 'tmp/public_tts.wav'), 'wb') as wav: + wav.setnchannels(fmt[1]); wav.setsampwidth(fmt[5] // 8); wav.setframerate(fmt[2]); wav.writeframes(body[offset:]) + x = np.frombuffer(body[offset:], dtype=' document.querySelector('#persona').value===role && document.querySelector('#status').textContent.includes('已认证')",arg=role) + await page.wait_for_timeout(150) + assert hellos[-1]['conversation_id']!=old, 'conversation unchanged' + old=hellos[-1]['conversation_id'] + assert await page.locator('[data-persona="'+role+'"]').evaluate("e=>e.classList.contains('selected')") + expected=(json.loads((ROOT/'.runtime/personas'/('lvbu.json' if role=='lvbu' else 'yangmi_fiction.json')).read_text())['voice_id'] if role!='default' else '9a97272c-3919-5606-9c8f-9552ab602528') + assert hellos[-1]['voice_id']==expected, 'wrong voice' + cases.append({'role':role,'voice_ok':True,'new_conversation':True}) + await page.evaluate("() => { document.querySelector('[data-persona=yangmi_fiction]').click();document.querySelector('[data-persona=lvbu]').click();document.querySelector('[data-persona=default]').click(); }") + await page.wait_for_function("document.querySelector('#persona').value==='default' && document.querySelector('#status').textContent.includes('已认证')",timeout=6000) + await page.wait_for_timeout(300) + assert '已认证' in await page.locator('#status').inner_text(), 'rapid switch socket state lost' + await page.evaluate("window.roleTestSockets.at(-1).send(JSON.stringify({type:'listen',mode:'auto',state:'start'}))") + await page.wait_for_function("document.querySelector('#voiceId').disabled && document.querySelector('#status').textContent.includes('监听')") + await page.evaluate("window.roleTestSockets.at(-1).send(JSON.stringify({type:'listen',mode:'auto',state:'stop'}))") + await page.click('[data-persona="yangmi_fiction"]') + await page.wait_for_function("document.querySelector('#persona').value==='yangmi_fiction' && document.querySelector('#status').textContent.includes('已认证')") + assert await page.locator('[data-persona="yangmi_fiction"]').get_attribute('aria-pressed')=='true' + assert not await page.locator('#persona').is_disabled() + assert all(len(h['conversation_id'])==36 for h in hellos) + await page.click('details summary') + await page.click('#disconnect') + await page.wait_for_timeout(200) + await page.click('#connect') + await page.wait_for_function("document.querySelector('#status').textContent.includes('已认证')") + assert len(await page.locator('[data-persona]').all())==3 + await page.click('#disconnect');await page.wait_for_timeout(200) + outsider=await browser.new_context(ignore_https_errors=True) + op=await outsider.new_page();await op.goto(URL);await op.wait_for_function("document.querySelector('#status').textContent.includes('已认证')") + await op.click('details summary');await op.click('#disconnect');await op.wait_for_timeout(200) + denied=await op.evaluate("""cid=>new Promise(resolve=>{const s=new WebSocket('wss://'+location.host+'/ws/dialogue');s.onmessage=e=>{const d=JSON.parse(e.data);if(d.type==='auth')s.send(JSON.stringify({type:'hello',codec:'pcm16',sample_rate:16000,frame_duration:20,conversation_id:cid}));if(d.type==='hello'){s.close();resolve(false);}};s.onclose=()=>resolve(true);})""",hellos[-1]['conversation_id']) + assert denied,'cross owner accepted' + await outsider.close() + await page.goto(URL+'debug');assert await page.locator('#token').count()==1 + import os + if os.environ.get('LAN_GATEWAY_TOKEN'): + await page.fill('#token',os.environ['LAN_GATEWAY_TOKEN']);await page.click('#connect');await page.wait_for_function("document.querySelector('#status').textContent.includes('已认证')") + assert not errors,errors + assert not console,console + results.append({'width':width,'cases':cases,'pageerrors':errors,'console_errors':console}) + await context.close() + await browser.close() + (ROOT/'tmp/role-selection.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n') + print(json.dumps(results,ensure_ascii=False)) + + +if __name__=='__main__':asyncio.run(main()) diff --git a/gateway/segmentation.py b/gateway/segmentation.py new file mode 100644 index 0000000..a81e89d --- /dev/null +++ b/gateway/segmentation.py @@ -0,0 +1,58 @@ +class Segmenter: + def __init__(self, mode='balanced', first_min=None): + if mode not in ('balanced', 'low_latency'): raise ValueError('invalid synthesis mode') + self.mode = mode + self.first_min = first_min if first_min is not None else (12 if mode == 'balanced' else 8) + if not 8 <= self.first_min <= 12: raise ValueError('first_min must be 8..12') + self.first = True + self.buffer = '' + self.since = None + self.last_cut = None + self.hardcuts = 0 + + @property + def wait_seconds(self): + return (0.35 if self.mode == 'balanced' else 0.25) if self.first else (0.7 if self.mode == 'balanced' else 0.5) + + @property + def minimum(self): + return self.first_min if self.first else (40 if self.mode == 'balanced' else 24) + + @property + def limit(self): + return 24 if self.first else (80 if self.mode == 'balanced' else 40) + + def add(self, text, now): + if not self.buffer: self.since = now + self.buffer += text + return self.take(now) + + def take(self, now, final=False): + if not self.buffer: return None + limit = self.limit + boundaries = [i + 1 for i, c in enumerate(self.buffer[:limit]) if c in ',。!?;,!?;'] + legal = [i for i in boundaries if i >= self.minimum] + if final: + cut = len(self.buffer) + reason = 'final_whole_remainder' + elif legal: + cut = legal[0] + reason = 'natural' + elif len(self.buffer) >= limit: + cut = limit + reason = 'hard_limit' + self.hardcuts += 1 + else: + return None + text = self.buffer[:cut].strip() + self.buffer = self.buffer[cut:] + self.since = now if self.buffer else None + self.first = False + self.last_cut = reason + return text or None + + def timeout(self, now): + if self.since is None or len(self.buffer) < self.minimum: return None + legal = any(i + 1 >= self.minimum and c in ',。!?;,!?;' for i, c in enumerate(self.buffer[:self.limit])) + if not legal: return None + return max(0.001, self.wait_seconds - (now - self.since)) diff --git a/gateway/tests/test_continuity.py b/gateway/tests/test_continuity.py new file mode 100644 index 0000000..2939f75 --- /dev/null +++ b/gateway/tests/test_continuity.py @@ -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,[]) diff --git a/gateway/tests/test_debug.py b/gateway/tests/test_debug.py new file mode 100644 index 0000000..0c07375 --- /dev/null +++ b/gateway/tests/test_debug.py @@ -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) diff --git a/gateway/tests/test_face_context.py b/gateway/tests/test_face_context.py new file mode 100644 index 0000000..6aeaa30 --- /dev/null +++ b/gateway/tests/test_face_context.py @@ -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() diff --git a/gateway/tests/test_gateway.py b/gateway/tests/test_gateway.py new file mode 100644 index 0000000..bb9da02 --- /dev/null +++ b/gateway/tests/test_gateway.py @@ -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('=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)) diff --git a/gateway/tests/test_v08.py b/gateway/tests/test_v08.py new file mode 100644 index 0000000..91de48a --- /dev/null +++ b/gateway/tests/test_v08.py @@ -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() diff --git a/gateway/tests/test_vad.py b/gateway/tests/test_vad.py new file mode 100644 index 0000000..85795b9 --- /dev/null +++ b/gateway/tests/test_vad.py @@ -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='=self.max_runs or time.time()-p.stat().st_mtime>self.max_age or used+size>self.max_bytes:shutil.rmtree(p) + else:used+=size + + def create(self, metadata): + self.cleanup();return DebugCapture(self,metadata) + + def list(self,cid): + self.cleanup();out=[] + for p in self.root.iterdir(): + f=p/'metadata.json' + if f.exists(): + d=json.loads(f.read_text()) + if d.get('conversation_id')==cid:out.append({k:d.get(k) for k in ['debug_id','run_id','status','marked_abnormal','created','samples','truncated']}) + return sorted(out,key=lambda x:x['created'],reverse=True)[:20] + + def authorized(self,value,cid,kind): + p=self.path(value);d=json.loads((p/'metadata.json').read_text()) + if d['conversation_id']!=cid:raise ValueError('wrong conversation') + if kind not in ('wav','metadata'):raise ValueError('invalid kind') + return p/('audio.wav' if kind=='wav' else 'metadata.json') + + def mark(self,value,cid): + p=self.authorized(value,cid,'metadata');d=json.loads(p.read_text());d['marked_abnormal']=True + temp=p.with_suffix('.tmp');temp.write_text(json.dumps(d,ensure_ascii=False,indent=2));os.chmod(temp,0o600);temp.replace(p) + + +class DebugCapture: + def __init__(self,store,metadata): + self.store=store;self.id=str(uuid.uuid4());self.path=store.path(self.id);self.path.mkdir(mode=0o700) + self.meta={**metadata,'debug_id':self.id,'created':time.time(),'chunks':[],'samples':0,'truncated':False,'seed':'unknown','cfg':'unknown','steps':'unknown','retry':'unknown','cache_hit':'unknown','model_version':'VoxCPM2 deployed snapshot 32279effe8c19989596f05d353d1447f51d9e915; runtime response does not identify weights'} + self.wav=wave.open(str(self.path/'audio.tmp'),'wb');self.wav.setnchannels(1);self.wav.setsampwidth(2);self.wav.setframerate(48000);os.chmod(self.path/'audio.tmp',0o600) + self.square=0.;self.peak=0;self.clips=0;self.closed=False + self.pending=queue.Queue(maxsize=16) + self.worker=threading.Thread(target=self.consume,daemon=True) + self.worker.start() + + def enqueue(self,pcm,elapsed,request): + try:self.pending.put_nowait((pcm,elapsed,request)) + except queue.Full:self.meta['truncated']=True;self.meta['writer_overflow']=True + + def consume(self): + while True: + item=self.pending.get() + if item is None:return + try:self.append(*item) + except Exception as exc:self.meta['writer_error']=type(exc).__name__;self.meta['truncated']=True + + def append(self,pcm,elapsed,request): + if self.closed:raise ValueError('capture finalized') + available=max(0,48000*30-self.meta['samples']);pcm=pcm[:available*2] + if not pcm:self.meta['truncated']=True;return + x=np.frombuffer(pcm,dtype='=32767)) + if len(self.meta['chunks'])<2048:self.meta['chunks'].append({'request':request,'arrival_ms':round(elapsed,3),'bytes':len(pcm),'pcm_sha256':hashlib.sha256(pcm).hexdigest()}) + else:self.meta['truncated']=True + + def finalize(self,status): + if self.closed:return self.id + self.pending.put(None);self.worker.join() + self.closed=True;self.wav.close();(self.path/'audio.tmp').replace(self.path/'audio.wav') + n=self.meta['samples'];self.meta.update(status=status,sample_rate=48000,channels=1,bits=16,seconds=n/48000,peak=self.peak,rms=math.sqrt(self.square/n) if n else 0,clip_ratio=self.clips/n if n else 0,nonfinite_count=0,nonfinite_scope='returned integer PCM only; pre-quantization floats unknown') + p=self.path/'metadata.tmp';p.write_text(json.dumps(self.meta,ensure_ascii=False,indent=2)+'\n');os.chmod(p,0o600);p.replace(self.path/'metadata.json');self.store.cleanup();return self.id diff --git a/gateway/vad.py b/gateway/vad.py new file mode 100644 index 0000000..a52e588 --- /dev/null +++ b/gateway/vad.py @@ -0,0 +1,164 @@ +import base64 +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import onnxruntime as ort + +RATE = 16000 +WINDOW = 512 + + +class Silero: + def __init__(self, path: Path): + options = ort.SessionOptions() + options.intra_op_num_threads = 1 + options.inter_op_num_threads = 1 + self.model = ort.InferenceSession(str(path), sess_options=options, providers=['CPUExecutionProvider']) + + def new_state(self): + return np.zeros((2, 1, 128), dtype=np.float32), np.zeros((1, 64), dtype=np.float32) + + def infer(self, pcm, state): + hidden, context = state + x = pcm.astype(np.float32).reshape(1, -1) / 32768.0 + output, hidden = self.model.run(None, {'input': np.concatenate((context, x), axis=1), 'state': hidden, 'sr': np.array(RATE, dtype=np.int64)}) + return float(output[0, 0]), (hidden, x[:, -64:].copy()) + + +@dataclass(frozen=True) +class Config: + silence_ms: int = 300 + start_windows: int = 3 + threshold: float = 0.5 + max_speech_seconds: float = 30 + max_session_seconds: float = 600 + include_preroll_audio: bool = False + + def __post_init__(self): + if not 200 <= self.silence_ms <= 600: + raise ValueError('silence_ms must be 200..600') + if self.start_windows not in (2, 3): + raise ValueError('start_windows must be 2 or 3') + if not 0.1 <= self.threshold <= 0.9: + raise ValueError('threshold must be 0.1..0.9') + if not 1 <= self.max_speech_seconds <= 30: + raise ValueError('max_speech_seconds must be 1..30') + if not 1 <= self.max_session_seconds <= 600: + raise ValueError('max_session_seconds must be 1..600') + + +class VadSession: + def __init__(self, model, config=Config()): + self.model = model + self.config = config + self.samples = 0 + self.received_bytes = 0 + self.epoch = 0 + self.segment_id = 0 + self.pending = bytearray() + self.preroll = bytearray() + self.state = model.new_state() + self.active = False + self.candidate = None + self.positive = 0 + self.silence = None + self.start = 0 + self.closed = False + + def event(self, kind, sample, **kwargs): + return {'type': kind, 'epoch': self.epoch, 'segment_id': self.segment_id, 'sample': sample, 'time_ms': sample * 1000 / RATE, 'detected_at_sample': self.samples, **kwargs} + + def end(self, reason, sample): + self.active = False + self.positive = 0 + self.candidate = None + self.silence = None + return self.event('speech.end', sample, reason=reason) + + def feed(self, data): + if self.closed: + raise ValueError('session ended; reset required') + if len(data) > 65536: + raise ValueError('message exceeds 65536 bytes') + if self.received_bytes + len(data) > self.config.max_session_seconds * RATE * 2: + raise ValueError('session audio limit reached') + self.received_bytes += len(data) + self.pending.extend(data) + events = [] + while len(self.pending) >= WINDOW * 2: + block = bytes(self.pending[:WINDOW * 2]) + del self.pending[:WINDOW * 2] + before = self.samples + self.samples += WINDOW + probability, self.state = self.model.infer(np.frombuffer(block, dtype=' history_bytes: + del self.preroll[:-history_bytes] + if not self.active: + if probability >= self.config.threshold: + if self.candidate is None: + self.candidate = before + self.positive += 1 + if self.positive >= self.config.start_windows: + self.active = True + self.start = self.candidate + self.segment_id += 1 + history_start = max(0, self.start - 3200) + needed = (self.samples - history_start) * 2 + audio = {'preroll_pcm16_base64': base64.b64encode(self.preroll[-needed:]).decode('ascii')} if self.config.include_preroll_audio else {} + events.append(self.event('speech.start', self.start, preroll_start_sample=history_start, preroll_ms=200, audio_until_sample=self.samples, **audio)) + else: + self.candidate = None + self.positive = 0 + else: + if probability < max(0.01, self.config.threshold - 0.15): + if self.silence is None: + self.silence = before + if self.samples - self.silence >= self.config.silence_ms * RATE / 1000: + events.append(self.end('silence', self.silence)) + else: + self.silence = None + if self.active and self.samples - self.start >= self.config.max_speech_seconds * RATE: + events.append(self.end('max_duration', self.samples)) + self.state = self.model.new_state() + return events + + def finish(self, reason='input_end'): + if len(self.pending) % 2: + raise ValueError('incomplete PCM16 sample') + actual_bytes = self.received_bytes + if self.pending: + padding = WINDOW * 2 - len(self.pending) + self.received_bytes -= padding + events = self.feed(bytes(padding)) + self.received_bytes = actual_bytes + self.samples = actual_bytes // 2 + for event in events: + event['detected_at_sample'] = self.samples + event['sample'] = min(event['sample'], self.samples) + event['time_ms'] = event['sample'] * 1000 / RATE + if 'audio_until_sample' in event: + event['audio_until_sample'] = self.samples + if 'preroll_pcm16_base64' in event: + raw = base64.b64decode(event['preroll_pcm16_base64']) + real_length = (self.samples - event['preroll_start_sample']) * 2 + event['preroll_pcm16_base64'] = base64.b64encode(raw[:real_length]).decode('ascii') + else: + events = [] + if self.active: + events.append(self.end(reason, actual_bytes // 2)) + self.pending.clear() + self.preroll.clear() + self.closed = True + events.append(self.event('session.ended', self.received_bytes // 2, reason=reason)) + return events + + def reset(self): + events = [self.end('reset', self.received_bytes // 2)] if self.active else [] + epoch = self.epoch + 1 + self.__init__(self.model, self.config) + self.epoch = epoch + events.append(self.event('session.reset', 0)) + return events diff --git a/gateway/web/audio-core.js b/gateway/web/audio-core.js new file mode 100644 index 0000000..b84ad47 --- /dev/null +++ b/gateway/web/audio-core.js @@ -0,0 +1,28 @@ +export class Resampler { + constructor(inputRate, outputRate) { this.step=inputRate/outputRate; this.samples=[]; this.position=0; } + push(input) { + this.samples.push(...input); + const output=[]; + while(this.position+1{this.enabled=data.enabled;this.pending=[];this.resampler=new Resampler(sampleRate,16000);this.total=0;}; + } + process(inputs,outputs){ + const audio=inputs[0]?.[0]; + if(audio){let energy=0;for(const x of audio)energy+=x*x; + if(this.enabled){ + this.pending.push(...this.resampler.push(audio)); + while(this.pending.length>=320){const frame=new Int16Array(320);for(let i=0;i<320;i++)frame[i]=Math.round(Math.max(-1,Math.min(1,this.pending[i]))*32767);this.pending.splice(0,320);this.total+=320;this.port.postMessage({type:'frame',pcm:frame.buffer,endSample:this.total,rms:Math.sqrt(energy/audio.length),captureContextTime:currentTime},[frame.buffer]);} + } + } + return true; + } +} +registerProcessor('capture',Capture); diff --git a/gateway/web/client.js b/gateway/web/client.js new file mode 100644 index 0000000..de57ff0 --- /dev/null +++ b/gateway/web/client.js @@ -0,0 +1,121 @@ +import {pcmFrame,readFrame} from './audio-core.js'; +const $=id=>document.getElementById(id); +let ws,ctx,mic,stream,capture,play,turn=0,upSeq=0,downSeq=0,listening=false,auto=false,ready=false; +let connectionGeneration=0,closingSocket=Promise.resolve(),connecting=false,selectionTimer=null; +let events=[],captureTimes=[],lastEnd=null,latestMetrics={},rendered={},capturing=false,localAbortAt=null; +let conversationId=null,historyRows=[],liveMessages=new Map(),sentSamples=0,sessionSecret='',debugItems=[],debugUrl=null; +try{conversationId=localStorage.getItem('lanVoiceConversationId');}catch{} +function renderHistory(){const root=$('history');root.replaceChildren();for(const row of [...historyRows,...liveMessages.values()]){const p=document.createElement('p');p.textContent=`${row.role}: ${row.text} [${row.status}; 播放:${row.playback??'未确认'}]`;root.append(p);}$('conversation').textContent='会话 '+(conversationId??'尚未建立')+';转录/回答将持久化到测试SQLite,无音频。';} +function rememberConversation(id){conversationId=id;try{localStorage.setItem('lanVoiceConversationId',id);}catch{}renderHistory();} +function status(text){$('status').textContent=text;} +function control(data){if(ws?.readyState===WebSocket.OPEN)ws.send(JSON.stringify(data));} +function clearAudio(){play?.port.postMessage({type:'clear',turn,mode:$('synthesisMode').value});} +function haltCapture(){capturing=false;capture?.port.postMessage({enabled:false});} +async function audio(){ + if(ctx){await ctx.resume();return;} + if(!window.isSecureContext)throw Error('录音必须HTTPS或安全localhost;HTTP LAN IP不能录音'); + ctx=new AudioContext();await ctx.resume(); + await ctx.audioWorklet.addModule('/static/capture-worklet.js');await ctx.audioWorklet.addModule('/static/play-worklet.js'); + play=new AudioWorkletNode(ctx,'playback');play.connect(ctx.destination);clearAudio(); + play.port.onmessage=({data})=>{ + if(data.turn!==turn)return; + if(data.type==='overflow'){abort();status('播放缓冲超限,已取消');return;} + if(data.type==='drained'){setTimeout(()=>{if(data.turn===turn)control({type:'playback.drained',turn_id:turn});},200);status(auto?'播放队列已排空,200ms尾音保护后继续监听':'播放队列已排空');} + if(data.type==='playback.metrics'||data.type==='drained'){rendered.playback=data.values??data.metrics;events.push({type:'browser.playback.metrics',turn_id:turn,values:rendered.playback});if(events.length>300)events.shift();showMetrics();} + const observed=performance.now(); + if(data.type==='rendered'||data.type==='voiced'){rendered[data.type]={contextTime:data.contextTime,observedAtMs:observed,captureEndToRenderObservedMs:lastEnd===null?null:observed-lastEnd};events.push({type:'browser.'+data.type,turn_id:turn,...rendered[data.type]});showMetrics();} + if(data.type==='cleared'&&localAbortAt!==null){events.push({type:'browser.abort_clear',turn_id:turn,ms:observed-localAbortAt});localAbortAt=null;showMetrics();} + }; + stream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:true,noiseSuppression:true,autoGainControl:true}}); + $('settings').textContent=JSON.stringify(stream.getAudioTracks()[0].getSettings(),null,2)+'\n这是实际返回设置,不是AEC效果保证;推荐耳机。AudioContext rate='+ctx.sampleRate; + mic=ctx.createMediaStreamSource(stream);capture=new AudioWorkletNode(ctx,'capture');mic.connect(capture);capture.connect(ctx.destination); + capture.port.onmessage=({data})=>{ + if(data.type!=='frame'||!capturing||!ready)return; + $('level').textContent='麦克风 RMS '+data.rms.toFixed(4); + const now=performance.now();sentSamples+=320;captureTimes.push({sample:sentSamples,time:now});if(captureTimes.length>1600)captureTimes.shift(); + draw(new Int16Array(data.pcm)); + if(ws.bufferedAmount>128000){abort();status('上行缓冲超限');return;} + ws.send(pcmFrame(1,turn,++upSeq,new Int16Array(data.pcm))); + }; +} +function draw(pcm){const c=$('wave'),g=c.getContext('2d');g.clearRect(0,0,c.width,c.height);g.strokeStyle='#34d399';g.beginPath();for(let i=0;i{old.addEventListener('close',resolve,{once:true});setTimeout(resolve,800);});old.close();}clearAudio();haltCapture();ready=false;listening=false;stream?.getTracks().forEach(t=>t.stop());mic?.disconnect();ctx?.close();ctx=null;capture=null;play=null;stream=null;if($('mainVoice'))$('mainVoice').textContent='开始语音对话';status('已断开');} +$('connect').onclick=async()=>{ + if(connecting||ws?.readyState===WebSocket.OPEN)return; + connecting=true;const generation=++connectionGeneration;await closingSocket;if(generation!==connectionGeneration)return; + const secret=$('token').value;sessionSecret=secret;$('token').value=''; + if(!secret&&document.body.dataset.friendly){try{const r=await fetch('/session/bootstrap',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});if(!r.ok)throw Error('访客连接不可用:仅指定LAN网段;高级设置可用管理员token');if(!sessionStorage.getItem('lanVoiceGuestBootstrapped')){conversationId=null;sessionStorage.setItem('lanVoiceGuestBootstrapped','1');}}catch(e){if(generation===connectionGeneration){connecting=false;status(e.message);}return;}} + if(secret||!document.body.dataset.friendly)await fetch('/session/logout',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'}); + if(generation!==connectionGeneration)return; + const socket=new WebSocket('wss://'+location.host+'/ws/dialogue');ws=socket;socket.binaryType='arraybuffer'; + const current=()=>ws===socket&&generation===connectionGeneration; + socket.onopen=()=>{if(!current()){socket.close();return;}if(secret||!document.body.dataset.friendly)socket.send(JSON.stringify({type:'auth',token:secret}));}; + socket.onclose=()=>{if(!current())return;connecting=false;ready=false;sessionSecret='';clearAudio();haltCapture();status('连接已关闭(认证/Origin/单会话限制或断开),点击连接可重试');}; + socket.onerror=()=>{if(current()){connecting=false;status('WSS失败:检查证书信任、服务和Origin');}}; + socket.onmessage=({data})=>{ + if(!current())return; + if(typeof data!=='string'){ + try{const frame=readFrame(data);if(frame.turn!==turn)return;if(frame.seq!==downSeq+1)throw Error('下行序号不连续');downSeq=frame.seq;play?.port.postMessage({type:'pcm',turn,pcm:frame.pcm},[frame.pcm.buffer]);}catch(e){abort();status(e.message);}return; + } + const event=JSON.parse(data); + if(event.type==='auth'){control({type:'hello',codec:'pcm16',sample_rate:16000,channels:1,frame_duration:20,synthesis_mode:$('synthesisMode').value,voice_mode:$('voiceMode').value,persona:$('persona').value,tts_debug:$('ttsDebug').checked,...(conversationId?{conversation_id:conversationId}:{})});return;} + if(event.type==='hello'){connecting=false;ready=true;document.body.dataset.connected='true';turn=event.turn_id;rememberConversation(event.conversation_id);$('voiceId').replaceChildren();for(const voice of event.voices){const option=document.createElement('option');option.value=voice.id;option.textContent=voice.id+' ['+(voice.default?'default / ':'')+voice.source+']';$('voiceId').append(option);}$('voiceId').value=event.voice_id;$('voiceId').disabled=$('persona').value!=='default';$('voiceInfo').textContent='固定登记reference:'+event.voice_id+';模式 '+event.voice_mode+',开始后锁定。';status('已认证;PCM16双工握手完成');return;} + if(event.type==='abort'){ + turn=event.turn_id;upSeq=0;downSeq=0;clearAudio();rendered={};latestMetrics={}; + if(Number.isFinite(event.accepted_input_samples)){captureTimes=captureTimes.filter(p=>p.sample<=event.accepted_input_samples);sentSamples=event.accepted_input_samples;} + for(const row of liveMessages.values())if(row.status==='generating')row.status='interrupted'; + renderHistory(); + if(event.reason.startsWith('history_')){listening=false;haltCapture();} + return; + } + if(event.turn_id!==turn)return; + if(event.type==='debug.saved'){control({type:'debug',action:'list'});return;} + if(event.type==='debug.list'){debugItems=event.items;$('debugInfo').textContent='本会话已保存 '+debugItems.length+' 轮;最近状态 '+(debugItems[0]?.status??'无')+';marked='+(debugItems[0]?.marked_abnormal??false);return;} + if(event.type==='history'){rememberConversation(event.conversation_id);historyRows=event.messages;liveMessages.clear();renderHistory();return;} + if(event.type==='listen'&&event.state==='start'){if(!capturing){sentSamples=0;captureTimes=[];capturing=true;capture?.port.postMessage({enabled:true});}status('监听 '+event.mode+',双工='+$('barge').checked);} + if(event.type==='capture.end'){ + const target=captureTimes.find(p=>p.sample>=event.end_sample);lastEnd=target?.time??performance.now(); + $('llm').textContent='';$('sentence').textContent='';status('STT → LLM → TTS'); + } + if(event.type==='stt')$('stt').textContent=event.text; + if(event.type==='llm'){$('llm').textContent+=event.text;const row=liveMessages.get(turn)??{role:'assistant',text:'',status:'generating'};row.text+=event.text;liveMessages.set(turn,row);renderHistory();} + if(event.type==='tts'&&event.state==='sentence_start')$('sentence').textContent=event.text; + if(event.type==='listen'&&event.state==='resumed'){status('播放确认收到;采集持续(耳机)');} + if(event.type==='tts'&&event.state==='stop'){play?.port.postMessage({type:'end',turn});status('服务端音频已发完,等待浏览器播放队列排空');} + if(event.type==='voice'){$('voiceId').value=event.voice_id;$('voiceId').disabled=event.locked;$('voiceInfo').textContent='固定reference '+event.voice_id+';锁定='+event.locked;} + if(event.type==='llm.finished'){latestMetrics.llm_finished_ms=event.llm_finished_ms;latestMetrics.voice_mode=event.voice_mode;showMetrics();} + if(event.type==='voice.metrics'){latestMetrics.voice_mode=event.voice_mode;latestMetrics.voice_id=event.voice_id;latestMetrics.tts_request_count=event.tts_request_count;showMetrics();} + if(event.type==='metrics'){latestMetrics=event.values;showMetrics();} + if(event.type==='error')status(event.message); + const safe={type:event.type,turn_id:event.turn_id,seq:event.seq,server_ms:event.server_ms}; + if(event.type==='tts.metrics'){latestMetrics.lastSegment=event.values;showMetrics();} + if(event.type==='metrics'||event.type==='tts.metrics')safe.values=event.values; + events.push(safe);if(events.length>300)events.shift(); + }; +}; +$('auto').onclick=()=>begin('auto').catch(e=>status(e.message)); +$('manual').onpointerdown=event=>{event.currentTarget.setPointerCapture(event.pointerId);begin('manual').catch(e=>status(e.message));}; +function finishManual(){if(listening&&!auto){lastEnd=performance.now();haltCapture();control({type:'listen',mode:'manual',state:'stop'});listening=false;}} +$('manual').onpointerup=finishManual;$('manual').onpointercancel=finishManual; +$('abort').onclick=abort;$('disconnect').onclick=disconnect; +$('newConversation').onclick=()=>{if(!ready)return;clearAudio();haltCapture();control({type:'history',action:'new',conversation_id:conversationId});}; +$('clearHistory').onclick=()=>{if(!ready)return;clearAudio();haltCapture();control({type:'history',action:'clear',conversation_id:conversationId});}; +$('export').onclick=()=>{const blob=new Blob([JSON.stringify({version:'0.7.1',events,server:latestMetrics,browser:rendered},null,2)],{type:'application/json'});const url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='lan-voice-timing.json';a.click();URL.revokeObjectURL(url);}; +$('voiceId').onchange=()=>{if(ready)control({type:'voice',voice_id:$('voiceId').value});}; +$('ttsDebug').onchange=()=>{if(ready)control({type:'debug',action:'set',enabled:$('ttsDebug').checked});}; +$('markDebug').onclick=()=>{if(debugItems[0])control({type:'debug',action:'mark',debug_id:debugItems[0].debug_id});else status('尚无保存轮,无法恢复旧音频');}; +async function fetchDebug(kind){if(!debugItems[0])throw Error('无保存轮');const r=await fetch('/debug/download',{method:'POST',headers:{'Authorization':'Bearer '+sessionSecret,'Content-Type':'application/json'},body:JSON.stringify({debug_id:debugItems[0].debug_id,conversation_id:conversationId,kind})});if(!r.ok)throw Error('debug download '+r.status);return r.blob();} +$('replayDebug').onclick=async()=>{try{abort();const blob=await fetchDebug('wav');if(debugUrl)URL.revokeObjectURL(debugUrl);debugUrl=URL.createObjectURL(blob);$('debugPlayer').src=debugUrl;await $('debugPlayer').play();}catch(e){status(e.message);}}; +$('metadataDebug').onclick=async()=>{try{const blob=await fetchDebug('metadata'),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='tts-metadata.json';a.click();URL.revokeObjectURL(url);}catch(e){status(e.message);}}; +if(document.body.dataset.friendly){ + function selectRole(role){clearTimeout(selectionTimer);control({type:'abort',turn_id:turn});disconnect();conversationId=null;historyRows=[];liveMessages.clear();debugItems=[];renderHistory();$('persona').disabled=false;$('persona').value=role;document.body.dataset.connected='false';document.querySelectorAll('[data-persona]').forEach(c=>{const selected=c.dataset.persona===role;c.classList.toggle('selected',selected);c.setAttribute('aria-pressed',String(selected));});status('已停止旧监听,正在为所选角色建立新会话');selectionTimer=setTimeout(()=>$('connect').onclick(),100);} + document.querySelectorAll('[data-persona]').forEach(card=>{card.setAttribute('aria-pressed',String(card.classList.contains('selected')));card.onclick=()=>selectRole(card.dataset.persona);}); + $('persona').onchange=()=>selectRole($('persona').value); + $('mainVoice').onclick=async()=>{if(capturing){control({type:'listen',mode:'auto',state:'stop'});abort();haltCapture();$('mainVoice').textContent='开始语音对话';status('已停止麦克风');return;}if(!ready){await $('connect').onclick();status('正在连接,请连接完成后再次点击开始;如失败请检查证书');return;}try{await begin('auto');$('mainVoice').textContent='停止语音对话';}catch(e){status('麦克风失败:'+e.message+'。请检查HTTPS证书与浏览器麦权限。');}}; + $('logoutGuest').onclick=async()=>{disconnect();await fetch('/session/logout',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});conversationId=null;sessionStorage.removeItem('lanVoiceGuestBootstrapped');localStorage.removeItem('lanVoiceConversationId');status('访客会话已撤销');}; + $('connect').onclick(); +} +window.addEventListener('beforeunload',()=>{clearAudio();ws?.close();}); diff --git a/gateway/web/debug.html b/gateway/web/debug.html new file mode 100644 index 0000000..d446cb6 --- /dev/null +++ b/gateway/web/debug.html @@ -0,0 +1 @@ +LAN Voice 硬件模拟器

LAN Voice 浏览器硬件模拟器

自定义 PCM 协议,不是完全小智兼容。请用耳机。自动模式使用 batch SenseVoice;服务端VAD不消回声。

默认登记reference;开始前选择,开始后锁定。

杨密为原创角色:已使用用户确认许可的普通女生前7秒参考clone,非杨幂仿声;仅本地非商用测试,听感相似未验证。

旧轮未保存不能恢复。debug不保存麦克风/token/reference。

默认计算/播放期间持续收音。全双工存在播放自回声自激风险;实际AEC/NS设置不是效果证明,请用耳机。

未连接

麦克风音量:0

麦克风未请求;HTTPS或安全localhost需要录音权限。AEC设置不保证实际效果。

ASR

LLM正文

当前句字幕

平衡缓冲会增加首音等待(不是免费优化),240ms是累计音频量不是固定墙钟等待;模型持续供给慢仍可能卡顿。

延迟(不同机器时钟不相减)

rendered=AudioWorklet首次呈现样本,不是硬件实际听到;voiced只是−40dBFS近似,不保证语义有效。

diff --git a/gateway/web/home.css b/gateway/web/home.css new file mode 100644 index 0000000..9e83650 --- /dev/null +++ b/gateway/web/home.css @@ -0,0 +1 @@ +:root{color-scheme:dark;--bg:#171a1c;--panel:#23272a;--muted:#bac2c6;--accent:#eac6a2}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:#f6f2ed;font:16px/1.6 system-ui,sans-serif}main{max-width:980px;margin:auto;padding:30px 24px}header{display:flex;align-items:center;gap:20px;color:var(--muted);font-size:13px}.brand{font-size:25px;color:var(--accent);margin-right:auto}a{color:var(--accent)}.hero{padding:48px 0 25px}.hero small{color:var(--accent);letter-spacing:2px}h1{font-size:clamp(32px,5vw,52px);line-height:1.2;font-weight:600;margin:18px 0}p{color:var(--muted)}.cards{display:grid;grid-template-columns:repeat(3,1fr);gap:15px}.card{display:flex;flex-direction:column;text-align:left;padding:22px;min-height:170px;background:var(--panel);border:1px solid #454b4f}.card span{font-size:35px;color:var(--accent)}.card b{font-size:20px}.card small{color:var(--muted)}.card.selected{border-color:var(--accent);background:#37332f}button,input,select{font:inherit;border-radius:12px;padding:10px 16px;border:1px solid #555e64;background:#30363a;color:#f6f2ed;margin:5px 4px 5px 0}button{cursor:pointer;transition:background .15s}button:hover{background:#414a50}button:focus-visible,summary:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid var(--accent);outline-offset:3px}.voice-panel,.chat,.privacy,details{margin-top:24px;padding:24px;border-radius:20px;background:var(--panel)}.voice-panel{text-align:center}.primary{background:var(--accent);color:#251e18;border:0;font-weight:700;min-width:240px;padding:16px 28px}.primary:hover{background:#f5d9bb}.status{display:flex;justify-content:center;gap:10px;align-items:center}.status i{width:8px;height:8px;border-radius:50%;background:#a4c9b2}.status p{margin:0}canvas{width:100%;height:70px}.hint,footer,.privacy p,details p{font-size:13px;color:var(--muted)}h2{font-size:21px}#history p{background:#303639;padding:14px 18px;border-radius:12px;white-space:pre-wrap;overflow-wrap:anywhere}.subtitle{color:var(--accent)}.current small{color:var(--accent)}audio{display:block;width:100%;margin-top:12px}summary{cursor:pointer;color:var(--accent)}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#181d20;padding:12px;border-radius:10px;font-size:12px}footer{padding:24px 4px}label{display:inline-block}input[type=password]{max-width:100%}@media(max-width:620px){main{padding:20px 14px}header{flex-wrap:wrap;gap:12px}.hero{padding-top:30px}.cards{grid-template-columns:1fr}.card{min-height:auto;display:grid;grid-template-columns:45px 1fr;padding:16px}.card small{grid-column:2}.voice-panel,.chat,.privacy,details{padding:18px}.primary{width:100%;min-width:0}}@media(prefers-reduced-motion:reduce){*{transition:none!important;animation:none!important}} diff --git a/gateway/web/index.html b/gateway/web/index.html new file mode 100644 index 0000000..e67dad4 --- /dev/null +++ b/gateway/web/index.html @@ -0,0 +1 @@ +声伴 · LAN Voice
◌ 声伴仅在你的局域网 · v0.7开发调试页
让对话,自然发生

选一位伙伴,
说说今天的事。

点击才会开启麦克风。建议戴耳机,声音打断默认开启。

准备好了,点击开始

麦克风尚未开启

浏览器AEC设置不保证实际消回声。角色切换会建立新会话。

这段对话

你刚刚说

回答正在形成

默认记录TTS台词和合成WAV;不记录麦克风或token。最多20轮/200MiB,72小时在操作时清理。聊天文字存于本机测试数据库。

尚无合成记录

高级设置与计时

等待麦克风授权

软件render/drain不是硬件实际听到;不同机器时钟不相减。HTTPS证书必须可信,HTTP LAN IP不能录音。

Cookie访客鉴权,不是账号。仅允许指定LAN网段与loopback;同网段用户可调用模型,不应视为可信网络。
diff --git a/gateway/web/play-worklet.js b/gateway/web/play-worklet.js new file mode 100644 index 0000000..e80fb94 --- /dev/null +++ b/gateway/web/play-worklet.js @@ -0,0 +1,21 @@ +import {Resampler} from './audio-core.js'; +import {PlaybackBuffer} from './playback-core.js'; +class Playback extends AudioWorkletProcessor { + constructor(){ + super();this.first=false;this.voiced=false;this.blocks=0;this.resampler=new Resampler(48000,sampleRate); + this.queue=new PlaybackBuffer(sampleRate,event=>this.port.postMessage({...event,contextTime:currentTime})); + this.port.onmessage=({data})=>{ + if(data.type==='clear'){if(data.mode)this.queue.configure(data.mode);this.queue.clear(data.turn);this.first=false;this.voiced=false;this.blocks=0;this.resampler=new Resampler(48000,sampleRate);this.port.postMessage({type:'cleared',turn:data.turn,contextTime:currentTime});} + if(data.type==='end')this.queue.end(data.turn); + if(data.type==='pcm'&&data.turn===this.queue.turn)this.queue.push(data.turn,this.resampler.push(data.pcm),currentTime*1000); + }; + } + process(inputs,outputs){ + const out=outputs[0][0],used=this.queue.render(out,currentTime*1000)||0; + if(used&&!this.first){this.first=true;this.port.postMessage({type:'rendered',turn:this.queue.turn,contextTime:currentTime});} + if(!this.voiced){for(let i=0;i.01){this.voiced=true;this.port.postMessage({type:'voiced',turn:this.queue.turn,contextTime:currentTime+i/sampleRate});break;}} + if(++this.blocks%32===0&&!this.queue.done)this.port.postMessage({type:'playback.metrics',turn:this.queue.turn,values:this.queue.snapshot()}); + return true; + } +} +registerProcessor('playback',Playback); diff --git a/gateway/web/playback-core.js b/gateway/web/playback-core.js new file mode 100644 index 0000000..da8c866 --- /dev/null +++ b/gateway/web/playback-core.js @@ -0,0 +1,31 @@ +export class PlaybackBuffer { + constructor(rate, emit=()=>{},mode='balanced') {this.rate=rate;this.emit=emit;this.buffer=new Float32Array(rate*2);this.configure(mode);this.clear(0);} + configure(mode){this.mode=mode==='low_latency'?'low_latency':'balanced';this.startupMs=this.mode==='balanced'?240:100;this.baseRecoveryMs=this.mode==='balanced'?240:150;this.recoveryCapMs=this.mode==='balanced'?400:250;} + clear(turn){this.turn=turn;this.read=0;this.length=0;this.ending=false;this.started=false;this.rebuffer=false;this.done=false;this.firstInput=null;this.waitAt=null;this.lastArrival=null;this.recoveryMs=this.baseRecoveryMs;this.metrics={underruns:0,underSupplyMs:0,rebufferMs:0,startBufferDelayMs:0,minQueueMs:null,chunkCount:0,lastChunkMs:null,lastInterarrivalMs:null,maxInterarrivalMs:0};} + push(turn,samples,now){if(turn!==this.turn||this.done)return;if(this.firstInput===null)this.firstInput=now;if(this.length+samples.length>this.buffer.length){this.emit({type:'overflow',turn});return;}if(this.lastArrival!==null){const gap=Math.max(0,now-this.lastArrival);this.metrics.lastInterarrivalMs=gap;this.metrics.maxInterarrivalMs=Math.max(this.metrics.maxInterarrivalMs,gap);}this.lastArrival=now;this.metrics.chunkCount++;this.metrics.lastChunkMs=samples.length*1000/this.rate;for(const x of samples){this.buffer[(this.read+this.length)%this.buffer.length]=x;this.length++;}} + end(turn){if(turn===this.turn)this.ending=true;} + snapshot(){return {mode:this.mode,effectiveStartupMs:this.startupMs,queueMs:this.length*1000/this.rate,recoveryTargetMs:this.recoveryMs,recoveryCapMs:this.recoveryCapMs,...this.metrics};} + render(out,now){ + out.fill(0); + if(this.done)return; + const enough=this.length>=Math.ceil(this.rate*(this.rebuffer?this.recoveryMs:this.startupMs)/1000); + if(!this.started||this.rebuffer){ + if(!enough&&!this.ending){if(this.rebuffer)this.metrics.underSupplyMs+=out.length*1000/this.rate;return;} + if(this.length){ + if(!this.started){this.metrics.startBufferDelayMs=Math.max(0,now-this.firstInput);this.started=true;} + if(this.rebuffer){this.metrics.rebufferMs+=Math.max(0,now-this.waitAt);this.rebuffer=false;} + } + } + let used=0; + while(used{if(!value)throw Error(name);};const results=[]; + const q=new PlaybackBuffer(1000,e=>results.push(e.type),'low_latency');q.clear(1); + q.push(1,new Float32Array(80).fill(.2),0);q.render(new Float32Array(20),20);assert(!q.started&&q.metrics.underruns===0,'startup no underrun'); + q.push(1,new Float32Array(40).fill(.2),30);const out=new Float32Array(20);q.render(out,30);assert(q.started&&out[0]>.1,'100ms buffered start'); + for(let t=50;t<=150;t+=20)q.render(out,t); + assert(q.metrics.underruns===1&&q.rebuffer,'single underrun'); + q.push(1,new Float32Array(80).fill(.3),180);q.render(out,180);assert(q.rebuffer,'wait recovery threshold'); + q.push(1,new Float32Array(80).fill(.3),200);q.render(out,200);assert(!q.rebuffer&&out[0]>.2,'recovery'); + q.clear(2);q.push(1,new Float32Array(100),210);q.render(out,220);assert(q.length===0&&q.metrics.underruns===0&&!q.ending,'clear immediate old turn rejected'); + q.push(2,new Float32Array(10).fill(.5),230);q.end(2);q.render(out,240);assert(q.done&&out[0]>.4&&q.metrics.underruns===0,'short final drains'); + q.clear(3);q.push(3,new Float32Array(2001),250);assert(results.includes('overflow')&&q.length===0,'max two seconds'); + q.clear(4);q.end(4);q.render(out,260);assert(q.done&&q.metrics.underruns===0,'empty end'); + function simulate(mode,gap){const p=new PlaybackBuffer(1000,()=>{},mode);p.clear(1);const block=new Float32Array(10);for(let t=0;t=gap,'explicit startup cost');assert(balanced.maxInterarrivalMs===gap,'interarrival metric');cadence.push({gap,low,balanced});} + return {status:'passed',cases:['jitter/startup','underrun_recovery','clear_old_turn','short_tail_end','max_buffer','empty_end','160ms chunks 170/180/190ms cadence'],cadence,events:results}; +} diff --git a/scripts/archive-gateway.py b/scripts/archive-gateway.py new file mode 100644 index 0000000..c98ca47 --- /dev/null +++ b/scripts/archive-gateway.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Read-only whitelist sync of actual SPARK-2 gateway sources; run in workspace ordinary shell.""" +import base64 +import hashlib +import json +from pathlib import Path +import re +import subprocess +import sys + +REMOTE=r''' +import base64,hashlib,importlib.metadata,json,os,platform,re,sys +from pathlib import Path +root=Path('/home/gorios-spark-2/lan-voice') +assert root.is_dir() and (root/'gateway.py').is_file(), 'actual gateway source missing' +excluded={'.runtime','.git','.venv','venv','models','node_modules','__pycache__','logs','tmp','artifacts','cache','data','voices','assets','build','dist'} +def allowed(path): + if any(part.startswith('.') or part in excluded for part in path.parts): return False + if any(x in path.name.lower() for x in ('diagnostic','report','private-key','credential')): return False + if len(path.parts)==1: + return path.suffix=='.py' or path.name in ('requirements.txt','requirements.lock','requirements-dev.txt','pyproject.toml','setup.cfg','README.md','LICENSE','LICENSE.txt') + group=path.parts[0] + if group in ('tests','scripts'): return path.suffix in ('.py','.sh') + if group=='personas': return path.name.endswith('.lorebook.json') or path.suffix in ('.md','.txt') + if group=='web': return path.suffix in ('.html','.js','.css','.svg') + if group in ('deploy','config'): return path.suffix in ('.py','.sh','.md','.service','.toml','.ini','.conf') or path.name.endswith('.example') + return False +files={};total=0 +for folder,dirs,names in os.walk(root,followlinks=False): + dirs[:]=[name for name in dirs if not name.startswith('.') and name not in excluded and not (Path(folder)/name).is_symlink()] + for name in names: + source=Path(folder)/name;relative=source.relative_to(root) + if not allowed(relative) or source.is_symlink() or not source.is_file(): continue + if source.stat().st_size>2_000_000: raise RuntimeError('source file exceeds bound: '+str(relative)) + data=source.read_bytes();data.decode('utf-8') + total+=len(data) + if total>20_000_000: raise RuntimeError('whitelist archive exceeds 20MB') + files[str(relative)]={'sha256':hashlib.sha256(data).hexdigest(),'bytes':len(data),'content':base64.b64encode(data).decode()} +required={'gateway.py','protocol.py','vad.py','history.py','guest_sessions.py','persona_resolver.py','segmentation.py','tts_debug.py','face_context.py','app.py','tests_fake.py'} +assert required.issubset(files), 'required deployed modules missing' +assert any(name.startswith('tests/') for name in files), 'tests missing' +assert any(name.startswith('web/') for name in files), 'browser source missing' +assert {'personas/lvbu.lorebook.json','personas/yangmi.lorebook.json'}.issubset(files), 'public lore missing' +for name,row in files.items(): + if hashlib.sha256((root/name).read_bytes()).hexdigest()!=row['sha256']: raise RuntimeError('concurrent source edit: '+name) +packages={} +for dist in importlib.metadata.distributions(): + name,version=dist.metadata.get('Name',''),dist.version + if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]*',name) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.+!-]*',version): raise RuntimeError('non-version package metadata') + packages[name.lower().replace('_','-')]=version +source=base64.b64decode(files['gateway.py']['content']).decode() +version=re.search(r"^VERSION\s*=\s*['\"]([^'\"]+)",source,re.M) +print(json.dumps({'files':files,'code_version':version[1] if version else 'unknown','python':platform.python_version(),'machine':platform.machine(),'packages':packages,'archive_scope':'whitelisted source only; no runtime/models/credentials'})) +''' + + +def scan(name, data): + text=data.decode('utf-8') + forbidden=['-----BEGIN '+kind+'-----' for kind in ('PRIVATE KEY','OPENSSH PRIVATE KEY','RSA PRIVATE KEY','EC PRIVATE KEY')] + if any(value in text for value in forbidden): raise RuntimeError(f'Private key marker in {name}') + patterns=[r'(?i)Bearer\s+[A-Za-z0-9_\-]{24,}', + r'''(?i)(?:LAN_GATEWAY_TOKEN|LAN_VAD_TOKEN|password|api_key|access_token)\s*[=:]\s*["']?([A-Za-z0-9_+/=.-]{24,})''', + r'https?://[^\s/]+@'] + for pattern in patterns: + for match in re.finditer(pattern,text): + if match.lastindex and match.group(1).startswith('REPLACE_'): continue + raise RuntimeError(f'Possible embedded secret in {name}; inspect locally before any Git add') + + +def main(): + root=Path(__file__).resolve().parents[1] + target=root/'gateway' + assert target.is_dir() and (target/'scripts/check-archive.py').is_file() + command=('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',command],input=REMOTE.encode(),capture_output=True,timeout=90) + if result.returncode: + print('Read-only remote archive failed; no raw source/stderr printed.');raise SystemExit(result.returncode) + data=json.loads(result.stdout) + expected=json.loads((root/'logs/voice-investigation/gateway-deploy.json').read_text())['gateway_sha256'] + assert data['files']['gateway.py']['sha256']==expected, 'deployed gateway changed; review before archiving baseline' + previous=json.loads((target/'SOURCE_MANIFEST.json').read_text()) if (target/'SOURCE_MANIFEST.json').exists() else {'files':{}} + planned={};manifest={} + for name,row in sorted(data['files'].items()): + relative=Path(name) + assert not relative.is_absolute() and '..' not in relative.parts + out={'README.md':'docs/UPSTREAM_README.md','requirements.lock':'requirements.upstream.lock'}.get(name,name) + content=base64.b64decode(row['content'],validate=True) + assert hashlib.sha256(content).hexdigest()==row['sha256'] + scan(out,content) + planned[out]=content + manifest[out]={'source':name,'sha256':row['sha256'],'bytes':len(content)} + # Added v0.4.0 regressions were staged for deployment, not installed into production tests/. + for name in ('test_face_context.py','test_gateway_reply_face.py'): + out='tests/'+name;content=(root/'backend'/name).read_bytes();scan(out,content) + planned[out]=content + manifest[out]={'source':'workspace:backend/'+name,'sha256':hashlib.sha256(content).hexdigest(),'bytes':len(content)} + lock=('# Deployed gateway Python '+data['python']+' / '+data['machine']+'; distribution versions only, no private URLs.\n'+ + '\n'.join(name+'=='+version for name,version in sorted(data['packages'].items()))+'\n').encode() + planned['requirements.lock']=lock + manifest['requirements.lock']={'source':'deployed interpreter distribution metadata','sha256':hashlib.sha256(lock).hexdigest(),'bytes':len(lock)} + for name,content in planned.items(): + destination=target/name + if destination.exists() and destination.read_bytes()!=content: + before=previous['files'].get(name) + assert before and hashlib.sha256(destination.read_bytes()).hexdigest()==before['sha256'], f'preserve local edit: {name}' + for name,content in planned.items(): + destination=target/name;destination.parent.mkdir(parents=True,exist_ok=True);destination.write_bytes(content) + archive={'baseline_android_commit':'9b428fb76ffa1468aa46124b33d9c598cf3740d8','source':'SPARK-2 deployed lan-voice gateway','code_version':data['code_version'], + 'python':data['python'],'machine':data['machine'],'scope':data['archive_scope'],'files':manifest} + (target/'SOURCE_MANIFEST.json').write_text(json.dumps(archive,ensure_ascii=False,indent=2)+'\n') + # Check the restored tree in isolation with the existing remote interpreter; do not install anything. + import io,tarfile + stream=io.BytesIO() + with tarfile.open(fileobj=stream,mode='w:gz') as tar: + for path in sorted(target.rglob('*')): + if path.is_file() and '__pycache__' not in path.parts: tar.add(path,arcname=path.relative_to(target),recursive=False) + payload=base64.b64encode(stream.getvalue()).decode() + checker=""" +import base64,io,subprocess,sys,tarfile,tempfile,json +from pathlib import Path +with tempfile.TemporaryDirectory(prefix='gateway-source-archive-') as folder: + with tarfile.open(fileobj=io.BytesIO(base64.b64decode(payload)),mode='r:gz') as tar: + for item in tar.getmembers(): + assert item.isfile() and not Path(item.name).is_absolute() and '..' not in Path(item.name).parts + tar.extractall(folder,filter='data') + result=subprocess.run([sys.executable,str(Path(folder)/'scripts/check-archive.py')],cwd=folder,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=90) + print(json.dumps({'status':'passed' if result.returncode==0 else 'failed','test_output':result.stdout.decode(errors='replace')})) + raise SystemExit(result.returncode) +""" + verified=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61',command],input=('payload='+repr(payload)+'\n'+checker).encode(),capture_output=True,timeout=120) + check=json.loads(verified.stdout) if verified.stdout else {'status':'remote_check_failed'} + check.update(source_files=len(manifest),deployed_gateway_sha256=expected,source_version=data['code_version']) + (root/'logs/voice-investigation/gateway-archive.json').write_text(json.dumps(check,indent=2)+'\n') + print(f'gateway/ archived {len(manifest)} source/lock files; isolated archive tests {check["status"]}; no deployment/restart') + raise SystemExit(verified.returncode) + + +if __name__=='__main__': main() diff --git a/scripts/commit-gateway-baseline.sh b/scripts/commit-gateway-baseline.sh new file mode 100755 index 0000000..fecefc5 --- /dev/null +++ b/scripts/commit-gateway-baseline.sh @@ -0,0 +1,54 @@ +#!/bin/bash +# Commit recoverable server source baseline only; no deployment or feature implementation. +set -euo pipefail +cd "$(dirname "$0")/.." +[ "$(git branch --show-current)" = main ] +[ "$(git remote get-url origin)" = 'git@git.oops.school:heihei/baji-vc.git' ] +git merge-base --is-ancestor 9b428fb76ffa1468aa46124b33d9c598cf3740d8 HEAD +if [ -n "$(git diff --cached --name-only)" ]; then + echo 'Existing staged changes preserved; review them before this archive-only commit.' >&2 + exit 1 +fi +python3 - <<'PY' +import hashlib,json,runpy +from pathlib import Path +root=Path.cwd(); gateway=root/'gateway' +check=json.loads((root/'logs/voice-investigation/gateway-archive.json').read_text()) +assert check['status']=='passed' +manifest=json.loads((gateway/'SOURCE_MANIFEST.json').read_text()) +assert len(manifest['files']) >= 20 +required=['gateway.py','guest_sessions.py','vad.py','history.py','persona_resolver.py','protocol.py','tts_debug.py','face_context.py','requirements.lock','tests/test_gateway.py','personas/lvbu.lorebook.json','personas/yangmi.lorebook.json'] +assert all(name in manifest['files'] for name in required) +for name,row in manifest['files'].items(): + assert hashlib.sha256((gateway/name).read_bytes()).hexdigest()==row['sha256'],name +scan=runpy.run_path('scripts/archive-gateway.py',run_name='archive_library')['scan'] +for path in gateway.rglob('*'): + if not path.is_file(): continue + rel=path.relative_to(gateway) + if any(part in ('.runtime','.venv','venv','models','logs','tmp','__pycache__') for part in rel.parts): continue + assert path.suffix not in ('.pem','.key','.wav','.pcm','.mp3','.apk','.pyc'),str(rel) + scan(str(rel),path.read_bytes()) +print(f'Verified complete gateway source baseline: {len(manifest["files"])} hashed files + portable restore/test helpers') +PY +git diff --check +git add -- gateway scripts/archive-gateway.py scripts/commit-gateway-baseline.sh +python3 - <<'PY' +import subprocess +names=subprocess.check_output(['git','diff','--cached','--name-only'],text=True).splitlines() +assert names +assert all(name.startswith('gateway/') or name in ('scripts/archive-gateway.py','scripts/commit-gateway-baseline.sh') for name in names), 'Unrelated staged changes preserved; refusing mixed commit' +assert not any('/.runtime/' in name or '/__pycache__/' in name for name in names) +PY +git diff --cached --check +git -c user.name=zenord -c user.email=zenord@email.com commit -m 'chore: archive recoverable gateway source baseline' +git push origin main +python3 - <<'PY' +import json,subprocess +from pathlib import Path +commit=subprocess.check_output(['git','rev-parse','HEAD'],text=True).strip() +remote=subprocess.check_output(['git','ls-remote','origin','refs/heads/main'],text=True).split()[0] +assert commit==remote +result={'commit':commit,'branch':'main','push':'verified','archive':'gateway/','android_baseline':'9b428fb76ffa1468aa46124b33d9c598cf3740d8'} +Path('logs/voice-investigation/gateway-baseline-git.json').write_text(json.dumps(result,indent=2)+'\n') +print(json.dumps(result,indent=2)) +PY