chore: archive recoverable gateway source baseline
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
.runtime/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
venv/
|
||||
.venv/
|
||||
models/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
logs/
|
||||
tmp/
|
||||
*.wav
|
||||
*.pcm
|
||||
*.key
|
||||
*.pem
|
||||
@@ -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 <PRIVATE_CERT_PATH> --ssl-keyfile <PRIVATE_KEY_PATH>`. 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.
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
+110
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
{"persona":"yangmi_fiction","voice_id":"REPLACE_WITH_REGISTERED_YANGMI_VOICE_ID"}
|
||||
@@ -0,0 +1 @@
|
||||
{"voice_id":"REPLACE_WITH_REGISTERED_LVBU_VOICE_ID"}
|
||||
@@ -0,0 +1 @@
|
||||
{"voice_id":"REPLACE_WITH_REGISTERED_YANGMI_VOICE_ID"}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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取消都不可省。半双工只用于调试,不是最终交付标准。
|
||||
@@ -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
|
||||
@@ -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)}
|
||||
@@ -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='<i2').astype(np.int32)) > 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='<i2').astype(np.int32)) > 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
|
||||
@@ -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)
|
||||
@@ -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,)))
|
||||
@@ -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}
|
||||
@@ -0,0 +1,11 @@
|
||||
# 吕布角色设定
|
||||
|
||||
仅本地用户提供素材角色扮演测试,不公开发布。音色参考文件与clone ID只在.runtime,不提交Git。
|
||||
|
||||
- 历史标签:吕布字奉先,并州五原郡九原;勇武骑射,依附关系反复,识人与谋略弱点不可抹去。
|
||||
- 三国演义/虚构标签:方天画戟、赤兔、貂蝉与连环计作为经典演义形象,不混称确凿历史。
|
||||
- 游戏风格/创作标签:威武、自负、简短,但不句句大喊,不复读固定台词。
|
||||
|
||||
只说可朗读台词,不说动作旁白、Markdown或JSON。日常回答仍提供实际帮助;现代问题不编造古代事实。出戏时承认AI角色扮演,角色不覆盖现实安全限制。
|
||||
|
||||
初版有限完整lore注入system(1400字符上限),不是无限检索。角色与用户消息分离;新吕布persona强制新会话,不把普通用户历史混入。固定reference跨轮复用,不使用上轮音频动态reference。
|
||||
@@ -0,0 +1,5 @@
|
||||
# 杨密
|
||||
|
||||
虚构人物:北京女孩,演员。直爽大方,幽默爱自嘲,唠家常式聊天。
|
||||
|
||||
本地角色扮演测试用。lorebook 见 personas/yangmi.lorebook.json,服务端 hello 时实时读取,改文件即时生效。音色由服务端 active_profile 固定(克隆普通女生参考,非真人仿声)。
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"id": "lvbu",
|
||||
"name": "吕布",
|
||||
"scope": "本地用户提供素材角色扮演测试,不公开发布",
|
||||
"rules": "你是AI扮演的吕布奉先,不是真实历史人物。以简短、威武但可理解的中文文言口吻回答,可自称某、吾、奉先,不每句大喊。不重复固定游戏台词。只输出可朗读的角色台词,不输出动作旁白、舞台指示、Markdown、JSON或星号。日常问题仍给出实际帮助;现代问题不编造古代事实,必要时承认现代知识。用户要求出戏时坦诚说明AI角色扮演。角色不能覆盖安全规则,真实有害请求不因角色而放宽。不以音色素材中的一句台词限制所有回答。",
|
||||
"entries": [
|
||||
{"label": "历史", "text": "吕布字奉先,并州五原郡九原人;勇武善骑射。人物曾多次改变依附关系,此处以勇武自负、对信任与谋略怀有警惕表现,不美化背叛。"},
|
||||
{"label": "三国演义/虚构", "text": "方天画戟、赤兔马为经典形象;与貂蝉的关系和连环计作为演义叙事,不宣称均是历史事实。"},
|
||||
{"label": "游戏风格/创作", "text": "威武、自负但并非只会叫阵;承认谋略与识人可能是弱点,回答简短有力量,避免机械复读。"}
|
||||
],
|
||||
"max_system_chars": 1400
|
||||
}
|
||||
@@ -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": "角色过去时、往前看的态度"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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('<I', self.buffer, pos + 4)[0]
|
||||
if tag == b'data':
|
||||
if self.fmt != (1, 1, 48000, 16):
|
||||
raise ValueError('requires 48k mono PCM16')
|
||||
del self.buffer[:pos + 8]
|
||||
self.ready = True
|
||||
break
|
||||
if size > 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('<HHIIHH', self.buffer, pos + 8)
|
||||
self.fmt = (code, channels, rate, bits)
|
||||
pos += 8 + size + size % 2
|
||||
if not self.ready:
|
||||
return b''
|
||||
length = len(self.buffer) // 2 * 2
|
||||
output = bytes(self.buffer[:length])
|
||||
del self.buffer[:length]
|
||||
return output
|
||||
|
||||
def finish(self):
|
||||
if not self.ready or self.buffer:
|
||||
raise ValueError('truncated WAV stream')
|
||||
@@ -0,0 +1,4 @@
|
||||
[pytest]
|
||||
pythonpath = . tests
|
||||
# Model-free portable baseline is scripts/check-archive.py; full VAD test needs external model.
|
||||
testpaths = tests
|
||||
@@ -0,0 +1,271 @@
|
||||
# Deployed gateway Python 3.12.3 / aarch64; distribution versions only, no private URLs.
|
||||
accelerate==1.12.0
|
||||
aiohappyeyeballs==2.7.1
|
||||
aiohttp==3.14.3
|
||||
aiosignal==1.4.0
|
||||
aiosqlite==0.22.1
|
||||
alembic==1.20.0
|
||||
annotated-doc==0.0.5
|
||||
annotated-types==0.8.0
|
||||
anthropic==0.121.0
|
||||
anyio==4.14.2
|
||||
apache-tvm-ffi==0.1.11
|
||||
astor==0.8.1
|
||||
asyncpg==0.31.0
|
||||
attrs==26.1.0
|
||||
authlib==1.8.0
|
||||
av==17.1.0
|
||||
bcrypt==5.0.0
|
||||
beautifulsoup4==4.15.0
|
||||
blake3==1.0.9
|
||||
cachetools==7.1.7
|
||||
canopy==0.1.0
|
||||
cbor2==6.1.4
|
||||
certifi==2026.7.22
|
||||
cffi==2.1.1
|
||||
charset-normalizer==3.4.9
|
||||
click==8.4.2
|
||||
cloudpickle==3.1.2
|
||||
compressed-tensors==0.17.0
|
||||
cryptography==50.0.0
|
||||
cuda-bindings==13.3.1
|
||||
cuda-core==1.0.1
|
||||
cuda-pathfinder==1.6.0
|
||||
cuda-python==13.3.1
|
||||
cuda-tile==1.5.0
|
||||
cuda-toolkit==13.0.3.0
|
||||
decorator==5.3.1
|
||||
defusedxml==0.7.1
|
||||
depyf==0.20.0
|
||||
detect-installer==0.1.0
|
||||
dill==0.4.1
|
||||
distro==1.9.0
|
||||
dnspython==2.8.0
|
||||
docstring-parser==0.18.0
|
||||
einops==0.8.2
|
||||
email-validator==2.3.0
|
||||
et-xmlfile==2.0.0
|
||||
fastapi==0.136.3
|
||||
fastapi-cli==0.0.32
|
||||
fastapi-cloud-cli==0.23.0
|
||||
fastar==0.11.0
|
||||
fastsafetensors==0.3.3
|
||||
filelock==3.32.2
|
||||
flashinfer-python==0.6.16.post3
|
||||
flatbuffers==25.12.19
|
||||
frozenlist==1.8.0
|
||||
fsspec==2026.7.0
|
||||
googleapis-common-protos==1.75.1
|
||||
goridrive==2.0.0
|
||||
greenlet==3.5.6
|
||||
grpcio==1.83.0
|
||||
h11==0.16.0
|
||||
hf-xet==1.6.0
|
||||
httpcore==1.0.9
|
||||
httpcore2==2.10.0
|
||||
httptools==0.8.0
|
||||
httpx==0.28.1
|
||||
httpx2==2.10.0
|
||||
huggingface-hub==1.27.0
|
||||
humming-kernels==0.1.10
|
||||
idna==3.18
|
||||
ijson==3.5.1
|
||||
iniconfig==2.3.0
|
||||
interegular==0.3.3
|
||||
jinja2==3.1.6
|
||||
jiter==0.16.0
|
||||
jmespath==1.1.0
|
||||
joblib==1.6.0
|
||||
joserfc==1.7.5
|
||||
jsonpatch==1.33
|
||||
jsonpointer==3.1.1
|
||||
jsonschema==4.26.0
|
||||
jsonschema-specifications==2025.9.1
|
||||
langchain-core==1.6.5
|
||||
langchain-protocol==0.0.19
|
||||
langgraph==1.2.12
|
||||
langgraph-checkpoint==4.2.0
|
||||
langgraph-prebuilt==1.1.0
|
||||
langgraph-sdk==0.4.5
|
||||
langsmith==0.14.1
|
||||
lark==1.2.2
|
||||
lazy-loader==0.5
|
||||
librosa==1.0.0
|
||||
llguidance==1.7.6
|
||||
llvmlite==0.47.0
|
||||
lm-format-enforcer==0.11.3
|
||||
loguru==0.7.3
|
||||
lxml==6.1.3
|
||||
magika==0.6.3
|
||||
mako==1.4.3
|
||||
markdown-it-py==4.2.0
|
||||
markdownify==1.2.3
|
||||
markitdown==0.1.8
|
||||
markupsafe==3.0.3
|
||||
mcp==2.0.0
|
||||
mcp-types==2.0.0
|
||||
mdurl==0.1.2
|
||||
minicpmo-utils==1.0.6
|
||||
mistral-common==1.11.7
|
||||
ml-dtypes==0.5.4
|
||||
model-hosting-container-standards==0.1.16
|
||||
modelscope==1.40.1
|
||||
modelscope-hub==0.4.3
|
||||
mpmath==1.3.0
|
||||
msgpack==1.2.2
|
||||
msgspec==0.21.1
|
||||
multidict==6.7.1
|
||||
narwhals==2.26.0
|
||||
nccl4py==0.3.1
|
||||
networkx==3.6.1
|
||||
ninja==1.13.0
|
||||
numba==0.65.0
|
||||
numpy==2.3.5
|
||||
nvidia-cublas==13.1.1.3
|
||||
nvidia-cuda-cccl==13.3.3.4.1
|
||||
nvidia-cuda-crt==13.3.73
|
||||
nvidia-cuda-cupti==13.0.85
|
||||
nvidia-cuda-nvcc==13.3.73
|
||||
nvidia-cuda-nvdisasm==13.3.73
|
||||
nvidia-cuda-nvrtc==13.0.88
|
||||
nvidia-cuda-runtime==13.0.96
|
||||
nvidia-cudnn-cu13==9.20.0.48
|
||||
nvidia-cudnn-frontend==1.27.0
|
||||
nvidia-cufft==12.0.0.61
|
||||
nvidia-cufile==1.15.1.6
|
||||
nvidia-curand==10.4.0.35
|
||||
nvidia-cusolver==12.0.4.66
|
||||
nvidia-cusparse==12.6.3.3
|
||||
nvidia-cusparselt-cu13==0.8.1
|
||||
nvidia-cutlass-dsl==4.6.0
|
||||
nvidia-cutlass-dsl-libs-base==4.6.0
|
||||
nvidia-cutlass-dsl-libs-core==4.6.0
|
||||
nvidia-cutlass-dsl-libs-cu12==4.6.0
|
||||
nvidia-cutlass-dsl-libs-cu13==4.6.0
|
||||
nvidia-ml-py==13.610.43
|
||||
nvidia-nccl-cu13==2.29.7
|
||||
nvidia-nvjitlink==13.3.33
|
||||
nvidia-nvshmem-cu13==3.4.5
|
||||
nvidia-nvtx==13.0.85
|
||||
nvidia-nvvm==13.3.73
|
||||
nvtx==0.2.15
|
||||
onnxruntime==1.30.0
|
||||
openai==2.53.0
|
||||
openai-harmony==0.0.8
|
||||
opencv-python-headless==5.0.0.93
|
||||
openpyxl==3.1.5
|
||||
opentelemetry-api==1.44.0
|
||||
opentelemetry-exporter-otlp==1.44.0
|
||||
opentelemetry-exporter-otlp-proto-common==1.44.0
|
||||
opentelemetry-exporter-otlp-proto-grpc==1.44.0
|
||||
opentelemetry-exporter-otlp-proto-http==1.44.0
|
||||
opentelemetry-proto==1.44.0
|
||||
opentelemetry-sdk==1.44.0
|
||||
opentelemetry-semantic-conventions==0.65b0
|
||||
opentelemetry-semantic-conventions-ai==0.5.1
|
||||
orjson==3.12.0
|
||||
ormsgpack==1.12.2
|
||||
outlines-core==0.2.14
|
||||
packaging==26.3
|
||||
pandas==3.0.6
|
||||
partial-json-parser==0.2.1.1.post7
|
||||
pillow==12.3.0
|
||||
pip==26.2.1
|
||||
platformdirs==4.11.8
|
||||
playwright==1.58.0
|
||||
pluggy==1.6.0
|
||||
pooch==1.9.0
|
||||
prometheus-client==0.26.0
|
||||
prometheus-fastapi-instrumentator==8.1.0
|
||||
propcache==0.5.2
|
||||
protobuf==6.33.6
|
||||
psutil==7.2.2
|
||||
psycopg==3.3.6
|
||||
psycopg-binary==3.3.6
|
||||
psycopg2-binary==2.9.13
|
||||
py-cpuinfo==9.0.0
|
||||
pybase64==1.5.0
|
||||
pycountry==26.2.16
|
||||
pycparser==3.0
|
||||
pydantic==2.13.4
|
||||
pydantic-core==2.46.4
|
||||
pydantic-extra-types==2.11.1
|
||||
pydantic-settings==2.15.0
|
||||
pyee==13.0.1
|
||||
pyelftools==0.33
|
||||
pygments==2.20.0
|
||||
pyjwt==2.13.0
|
||||
pynvvideocodec==2.0.4
|
||||
pypdf==6.19.0
|
||||
pytest==8.4.2
|
||||
pytest-asyncio==0.26.0
|
||||
python-dateutil==2.9.0.post0
|
||||
python-dotenv==1.2.2
|
||||
python-json-logger==4.1.0
|
||||
python-multipart==0.0.32
|
||||
python-pptx==1.0.2
|
||||
pyyaml==6.0.3
|
||||
pyzmq==27.1.0
|
||||
quack-kernels==0.6.1
|
||||
referencing==0.37.0
|
||||
regex==2026.7.19
|
||||
requests==2.34.2
|
||||
requests-toolbelt==1.0.0
|
||||
rich==15.0.0
|
||||
rich-toolkit==0.20.3
|
||||
rignore==0.8.1
|
||||
rpds-py==2026.6.3
|
||||
ruff==0.16.10
|
||||
safetensors==0.8.0
|
||||
scikit-learn==1.9.0
|
||||
scipy==1.18.1
|
||||
sentence-transformers==6.0.1
|
||||
sentencepiece==0.2.2
|
||||
sentry-sdk==2.67.1
|
||||
setproctitle==1.3.7
|
||||
setuptools==80.10.2
|
||||
shellingham==1.5.4
|
||||
six==1.17.0
|
||||
sniffio==1.3.1
|
||||
soundfile==0.14.0
|
||||
soupsieve==2.10
|
||||
soxr==1.1.0
|
||||
sqlalchemy==2.1.3
|
||||
sse-starlette==3.4.8
|
||||
starlette==1.6.0
|
||||
supervisor==4.3.0
|
||||
sympy==1.14.0
|
||||
tabulate==0.10.0
|
||||
tenacity==9.1.4
|
||||
threadpoolctl==3.6.0
|
||||
tiktoken==0.13.0
|
||||
tilelang==0.1.12
|
||||
tokenizers==0.22.2
|
||||
tokenspeed-mla==0.1.8
|
||||
tokenspeed-triton==3.8.10.post20260721
|
||||
torch==2.13.0+cu130
|
||||
torch-c-dlpack-ext==0.1.5
|
||||
torchaudio==2.11.0+cu130
|
||||
torchcodec==0.15.0+cu130
|
||||
torchvision==0.28.0+cu130
|
||||
tqdm==4.70.0
|
||||
transformers==5.15.0
|
||||
triton==3.7.1
|
||||
truststore==0.10.4
|
||||
typer==0.27.1
|
||||
typing-extensions==4.16.0
|
||||
typing-inspection==0.4.3
|
||||
urllib3==2.7.0
|
||||
uuid-utils==0.17.1
|
||||
uvicorn==0.52.1
|
||||
uvloop==0.22.1
|
||||
vllm==0.27.0
|
||||
watchfiles==1.2.0
|
||||
websockets==16.1.1
|
||||
xgrammar==0.2.3
|
||||
xlsxwriter==3.2.9
|
||||
xxhash==4.0.1
|
||||
yarl==1.24.5
|
||||
yt-dlp==2026.8.19
|
||||
z3-solver==4.15.4.0
|
||||
zstandard==0.25.0
|
||||
@@ -0,0 +1,26 @@
|
||||
annotated-doc==0.0.5
|
||||
annotated-types==0.8.0
|
||||
anyio==4.14.2
|
||||
certifi==2026.7.22
|
||||
click==8.4.2
|
||||
fastapi==0.136.3
|
||||
flatbuffers==25.12.19
|
||||
h11==0.16.0
|
||||
httpcore==1.0.9
|
||||
httpx==0.28.1
|
||||
idna==3.18
|
||||
numpy==2.3.5
|
||||
onnxruntime==1.30.0
|
||||
packaging==26.3
|
||||
protobuf==6.33.6
|
||||
pydantic==2.13.4
|
||||
pydantic_core==2.46.4
|
||||
starlette==1.6.0
|
||||
typing-inspection==0.4.3
|
||||
typing_extensions==4.16.0
|
||||
uvicorn==0.52.1
|
||||
websockets==16.1.1
|
||||
yt-dlp==2026.8.19
|
||||
playwright==1.58.0
|
||||
pyee==13.0.1
|
||||
greenlet==3.5.6
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Portable model-free archive regression: isolated temp root + synthetic persona manifests."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
with tempfile.TemporaryDirectory(prefix='lan-voice-archive-check-') as folder:
|
||||
stage = Path(folder)
|
||||
for source in root.glob('*.py'): shutil.copy2(source, stage/source.name)
|
||||
for name in ('tests','personas','web'):
|
||||
shutil.copytree(root/name, stage/name, ignore=shutil.ignore_patterns('__pycache__'))
|
||||
target=stage/'.runtime/personas'; target.mkdir(parents=True)
|
||||
for name in ('lvbu','yangmi_fiction'):
|
||||
# Public dummy IDs only; no production profile/reference audio/runtime copied.
|
||||
(target/(name+'.json')).write_text(json.dumps({'voice_id':'synthetic-'+name}))
|
||||
runner=r'''
|
||||
import sys,unittest
|
||||
sys.path[:0]=['.','tests']
|
||||
from pathlib import Path
|
||||
ordered=['test_gateway','test_continuity','test_history','test_v08','test_debug','test_segmentation','test_guests','test_personas','test_face_context','test_gateway_reply_face']
|
||||
ordered += sorted(p.stem for p in Path('tests').glob('test_*.py') if p.stem not in ordered)
|
||||
suite=unittest.TestSuite(unittest.defaultTestLoader.loadTestsFromName(name) for name in ordered)
|
||||
def safe(suite):
|
||||
result=unittest.TestSuite()
|
||||
for item in suite:
|
||||
if isinstance(item,unittest.TestSuite): result.addTest(safe(item))
|
||||
elif item.id().endswith('.test_silero_silence_and_state'):
|
||||
# Model artifacts are intentionally absent; never download/load a model in archive checks.
|
||||
item.setUp=lambda: (_ for _ in ()).throw(unittest.SkipTest('Silero artifact excluded from source archive'))
|
||||
result.addTest(item)
|
||||
else: result.addTest(item)
|
||||
return result
|
||||
out=unittest.TextTestRunner(verbosity=2).run(safe(suite))
|
||||
raise SystemExit(not out.wasSuccessful())
|
||||
'''
|
||||
raise SystemExit(subprocess.run([sys.executable,'-c',runner],cwd=stage,env={**os.environ,'PYTHONDONTWRITEBYTECODE':'1'}).returncode)
|
||||
@@ -0,0 +1,51 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
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'))
|
||||
with wave.open(str(ROOT / 'tmp/public_tts_16k.wav')) as f: pcm = f.readframes(f.getnframes())
|
||||
pcm += bytes(32000)
|
||||
events = []; frames = 0; turn = 0; seq = 0; stopped = asyncio.Event()
|
||||
async with websockets.connect('wss://192.168.31.61:5011/ws/dialogue', ssl=ssl_context, origin='https://192.168.31.61:5011', proxy=None) as ws:
|
||||
await ws.send(json.dumps({'type': 'auth', 'token': os.environ['LAN_GATEWAY_TOKEN']})); await ws.recv()
|
||||
await ws.send(json.dumps({'type': 'hello', 'codec': 'pcm16', 'sample_rate': 16000, 'frame_duration': 20})); await ws.recv()
|
||||
await ws.send(json.dumps({'type': 'listen', 'mode': 'auto', 'state': 'start'}))
|
||||
turn = json.loads(await ws.recv())['turn_id']; await ws.recv()
|
||||
async def receive():
|
||||
nonlocal turn, seq, frames
|
||||
while True:
|
||||
raw = await ws.recv()
|
||||
if isinstance(raw, bytes):
|
||||
actual, _, _ = unpack(raw, 2); assert actual == turn; frames += 1
|
||||
else:
|
||||
event = json.loads(raw); events.append(event)
|
||||
if event['type'] == 'abort': turn = event['turn_id']; seq = 0
|
||||
if event['type'] == 'error': raise AssertionError(event)
|
||||
if event['type'] == 'tts' and event['state'] == 'stop': stopped.set(); return
|
||||
task = asyncio.create_task(receive())
|
||||
for i in range(0, len(pcm), 640):
|
||||
if any(e['type'] == 'capture.end' for e in events): break
|
||||
seq += 1; await ws.send(pack(1, turn, seq, pcm[i:i+640])); await asyncio.sleep(.02)
|
||||
await asyncio.wait_for(task, 60)
|
||||
assert frames > 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())
|
||||
@@ -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;i<signal.length;i+=128)pieces.push(...r.push(signal.slice(i,i+128)));
|
||||
if(all.length!==pieces.length||all.some((x,i)=>Math.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())
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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('<I', data, pos + 4)[0]
|
||||
if tag == b'data':
|
||||
return (pos + 8, fmt) if fmt else None
|
||||
if pos + 8 + size > len(data):
|
||||
return None
|
||||
if tag == b'fmt ':
|
||||
fmt = struct.unpack_from('<HHIIHH', data, pos + 8)
|
||||
pos += 8 + size + (size % 2)
|
||||
return None
|
||||
|
||||
|
||||
async def tts(client, index, cancel=False):
|
||||
start = time.perf_counter()
|
||||
body = bytearray()
|
||||
first = None
|
||||
audible = None
|
||||
header = None
|
||||
times = []
|
||||
async with client.stream('POST', 'http://192.168.31.61:5002/v1/audio/speech', json={'model': 'openbmb/VoxCPM2', 'input': TEXT, 'stream': True}) as response:
|
||||
response.raise_for_status()
|
||||
async for block in response.aiter_bytes():
|
||||
elapsed = time.perf_counter() - start
|
||||
times.append(elapsed)
|
||||
body.extend(block)
|
||||
header = header or wav_header(body)
|
||||
if header:
|
||||
offset, fmt = header
|
||||
usable = (len(body) - offset) // 2 * 2
|
||||
if usable and first is None:
|
||||
first = elapsed
|
||||
if usable and audible is None:
|
||||
pcm = np.frombuffer(body[offset:offset + usable], dtype='<i2')
|
||||
if np.any(np.abs(pcm.astype(np.int32)) > 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='<i2')
|
||||
if fmt[2] != 48000 or fmt[1] != 1 or fmt[5] != 16:
|
||||
raise ValueError('unexpected TTS format')
|
||||
trim = len(x) // 3 * 3
|
||||
reduced = np.rint(x[:trim].reshape(-1, 3).astype(np.float64).mean(axis=1)).astype('<i2')
|
||||
with wave.open(str(ROOT / 'tmp/public_tts_16k.wav'), 'wb') as wav:
|
||||
wav.setnchannels(1); wav.setsampwidth(2); wav.setframerate(16000); wav.writeframes(reduced.tobytes())
|
||||
return result
|
||||
|
||||
|
||||
async def qwen(client, index):
|
||||
start = time.perf_counter()
|
||||
first = None
|
||||
text = ''
|
||||
reasoning = ''
|
||||
first_sentence = None
|
||||
finish = None
|
||||
usage = None
|
||||
async with client.stream('POST', 'http://127.0.0.1:8888/v1/chat/completions', json={'model': 'qwen3.8-27b', 'messages': [{'role': 'user', 'content': '请用一句不超过十五个汉字回答:为什么要喝水?不要思考过程。'}], 'stream': True, 'max_tokens': 64, 'temperature': 0, 'chat_template_kwargs': {'enable_thinking': False}, 'stream_options': {'include_usage': True}}) as response:
|
||||
response.raise_for_status()
|
||||
async for line in response.aiter_lines():
|
||||
if not line.startswith('data: ') or line == 'data: [DONE]':
|
||||
continue
|
||||
data = json.loads(line[6:])
|
||||
usage = data.get('usage') or usage
|
||||
for choice in data.get('choices', []):
|
||||
delta = choice.get('delta', {})
|
||||
reasoning += delta.get('reasoning_content') or ''
|
||||
content = delta.get('content') or ''
|
||||
if content:
|
||||
if first is None: first = time.perf_counter() - start
|
||||
text += content
|
||||
if first_sentence is None and any(c in text for c in '。!?!?'):
|
||||
first_sentence = time.perf_counter() - start
|
||||
finish = choice.get('finish_reason') or finish
|
||||
return {'kind': 'qwen', 'index': index, 'first_body_ms': round(first * 1000, 2) if first else None, 'first_sentence_ms': round(first_sentence * 1000, 2) if first_sentence else None, 'total_ms': round((time.perf_counter() - start) * 1000, 2), 'body': text, 'reasoning_chars': len(reasoning), 'finish_reason': finish, 'usage': usage, 'enable_thinking': False, 'max_tokens': 64}
|
||||
|
||||
|
||||
async def stt(client, index):
|
||||
data = (ROOT / 'tmp/public_tts_16k.wav').read_bytes()
|
||||
start = time.perf_counter()
|
||||
response = await client.post('http://192.168.31.61:5001/v1/audio/transcriptions', files={'file': ('public.wav', data, 'audio/wav')})
|
||||
response.raise_for_status()
|
||||
with wave.open(io.BytesIO(data)) as w: duration = w.getnframes() / w.getframerate()
|
||||
total = time.perf_counter() - start
|
||||
return {'kind': 'stt', 'index': index, 'total_ms': round(total * 1000, 2), 'audio_seconds': duration, 'rtf': round(total / duration, 4), 'text': response.json().get('text')}
|
||||
|
||||
|
||||
async def main():
|
||||
(ROOT / 'tmp').mkdir(exist_ok=True)
|
||||
results = []
|
||||
async with httpx.AsyncClient(timeout=30, trust_env=False) as client:
|
||||
for kind, fn, count in [('tts', tts, 3), ('qwen', qwen, 3), ('stt', stt, 3)]:
|
||||
for i in range(1, count + 1):
|
||||
if kind == 'stt' and not (ROOT / 'tmp/public_tts_16k.wav').exists(): break
|
||||
try:
|
||||
async with asyncio.timeout(30):
|
||||
result = await fn(client, i, cancel=i == 3) if kind == 'tts' else await fn(client, i)
|
||||
except Exception as exc:
|
||||
result = {'kind': kind, 'index': i, 'error_type': type(exc).__name__}
|
||||
results.append(result)
|
||||
print(json.dumps(result, ensure_ascii=False), flush=True)
|
||||
(ROOT / 'tmp/measurements.json').write_text(json.dumps(results, ensure_ascii=False, indent=2) + '\n')
|
||||
await asyncio.sleep(0.2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,83 @@
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
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'
|
||||
URL = 'https://192.168.31.61:5011/'
|
||||
|
||||
|
||||
async def main():
|
||||
results=[]
|
||||
async with async_playwright() as pw:
|
||||
browser=await pw.chromium.launch(executable_path=CHROME,headless=True,args=['--no-sandbox'])
|
||||
for width in (1100,390):
|
||||
context=await browser.new_context(ignore_https_errors=True,viewport={'width':width,'height':900})
|
||||
await context.add_init_script("""window.roleTestSockets=[];const NativeWS=window.WebSocket;window.WebSocket=class extends NativeWS{constructor(...args){super(...args);window.roleTestSockets.push(this);}};""")
|
||||
page=await context.new_page();errors=[];hellos=[];console=[]
|
||||
page.on('pageerror',lambda e:errors.append(str(e)))
|
||||
page.on('console',lambda m:console.append(m.text) if m.type=='error' else None)
|
||||
def socket(ws):
|
||||
def received(payload):
|
||||
if isinstance(payload,str):
|
||||
try:
|
||||
data=json.loads(payload)
|
||||
if data.get('type')=='hello':hellos.append(data)
|
||||
except ValueError:pass
|
||||
ws.on('framereceived',received)
|
||||
page.on('websocket',socket)
|
||||
await page.goto(URL)
|
||||
await page.wait_for_function("document.querySelector('#status').textContent.includes('已认证')")
|
||||
old=hellos[-1]['conversation_id']
|
||||
cases=[]
|
||||
for role in ('yangmi_fiction','lvbu','default'):
|
||||
await page.click('[data-persona="'+role+'"]')
|
||||
await page.wait_for_function("role => 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())
|
||||
@@ -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))
|
||||
@@ -0,0 +1,59 @@
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import time
|
||||
import unittest
|
||||
import wave
|
||||
|
||||
import httpx
|
||||
|
||||
from gateway import Dialogue, DEFAULT_VOICE_ID
|
||||
from tests_fake import FakeModel
|
||||
from test_gateway import Socket
|
||||
|
||||
|
||||
class ContinuityTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_multidelta_one_tts_and_realtime_text(self):
|
||||
socket=Socket();tts=[]
|
||||
wav=io.BytesIO()
|
||||
with wave.open(wav,'wb') as w:
|
||||
w.setnchannels(1);w.setsampwidth(2);w.setframerate(48000);w.writeframes(bytes(1920))
|
||||
parts=['你好,今天一起','去散步。','记得喝水!']
|
||||
def backend(request):
|
||||
if 'transcriptions' in request.url.path:return httpx.Response(200,json={'text':'公开问题'})
|
||||
if 'chat' in request.url.path:
|
||||
stream=''.join('data: '+json.dumps({'choices':[{'delta':{'content':x}}]},ensure_ascii=False)+'\n\n' for x in parts)+'data: [DONE]\n\n'
|
||||
return httpx.Response(200,text=stream)
|
||||
tts.append(json.loads(request.content))
|
||||
self.assertEqual(len([e for e in socket.events if e['type']=='llm']),3)
|
||||
return httpx.Response(200,content=wav.getvalue())
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
d=Dialogue(socket,FakeModel(),client)
|
||||
await d.run(0,bytes(640))
|
||||
self.assertEqual(len(tts),1)
|
||||
self.assertEqual(tts[0]['input'],''.join(parts))
|
||||
self.assertEqual(tts[0]['voice'],DEFAULT_VOICE_ID)
|
||||
metrics=next(e['values'] for e in socket.events if e['type']=='metrics')
|
||||
self.assertEqual(metrics['tts_request_count'],1)
|
||||
self.assertEqual(metrics['voice_mode'],'continuous_voice')
|
||||
self.assertIn('llm_finished_ms',metrics)
|
||||
|
||||
async def test_cancel_before_finish_never_starts_tts(self):
|
||||
started=asyncio.Event();tts=[]
|
||||
class Slow(httpx.AsyncByteStream):
|
||||
async def __aiter__(self):
|
||||
yield b'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n'
|
||||
started.set()
|
||||
await asyncio.sleep(10)
|
||||
yield b'data: [DONE]\n\n'
|
||||
def backend(request):
|
||||
if 'chat' in request.url.path:return httpx.Response(200,stream=Slow())
|
||||
tts.append(request);return httpx.Response(200)
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
d=Dialogue(Socket(),FakeModel(),client);q=asyncio.Queue(2);d.answers[0]=''
|
||||
task=asyncio.create_task(d.generate(0,'question',q,{},time.perf_counter()))
|
||||
await started.wait();d.task=task
|
||||
await d.invalidate('client_abort')
|
||||
await d.close()
|
||||
self.assertTrue(q.empty())
|
||||
self.assertEqual(tts,[])
|
||||
@@ -0,0 +1,47 @@
|
||||
import asyncio
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
import uuid
|
||||
import wave
|
||||
from pathlib import Path
|
||||
from fastapi.testclient import TestClient
|
||||
from gateway import app
|
||||
from tts_debug import DebugStore
|
||||
|
||||
|
||||
class DebugTests(unittest.TestCase):
|
||||
def test_complete_partial_permissions_and_retention(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
store=DebugStore(root,max_runs=2)
|
||||
cid=str(uuid.uuid4())
|
||||
for status in ['completed','interrupted','failed']:
|
||||
c=store.create({'conversation_id':cid,'run_id':str(uuid.uuid4()),'tts_requests':[{'input':'公开测试'}]})
|
||||
c.append(bytes(960),10,1);c.finalize(status)
|
||||
with wave.open(str(c.path/'audio.wav')) as w:self.assertEqual(w.getnframes(),480)
|
||||
self.assertEqual((c.path/'metadata.json').stat().st_mode&511,0o600)
|
||||
rows=store.list(cid);self.assertEqual(len(rows),2)
|
||||
store.mark(rows[0]['debug_id'],cid)
|
||||
self.assertTrue(store.list(cid)[0]['marked_abnormal'])
|
||||
with self.assertRaises(ValueError):store.authorized('../escape',cid,'wav')
|
||||
with self.assertRaises(ValueError):store.authorized(rows[0]['debug_id'],str(uuid.uuid4()),'wav')
|
||||
text=store.authorized(rows[0]['debug_id'],cid,'metadata').read_text()
|
||||
for secret in ['LAN_GATEWAY_TOKEN','Authorization','reference_wav_path']:self.assertNotIn(secret,text)
|
||||
capped=store.create({'conversation_id':cid});capped.append(bytes(48000*31*2),0,1);capped.finalize('interrupted')
|
||||
with wave.open(str(capped.path/'audio.wav')) as w:self.assertLessEqual(w.getnframes(),48000*30)
|
||||
|
||||
def test_download_requires_auth_origin_and_scoped_id(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
app.state.token='x'*40;app.state.debug=DebugStore(root);cid=str(uuid.uuid4());c=app.state.debug.create({'conversation_id':cid});c.append(bytes(960),0,1);c.finalize('completed')
|
||||
client=TestClient(app)
|
||||
payload={'conversation_id':cid,'debug_id':c.id,'kind':'wav'}
|
||||
self.assertEqual(client.post('/debug/download',json=payload).status_code,403)
|
||||
headers={'Authorization':'Bearer '+'x'*40,'Origin':'https://192.168.31.61:5011'}
|
||||
self.assertEqual(client.post('/debug/download',json=payload,headers=headers).status_code,200)
|
||||
payload['debug_id']='../bad'
|
||||
self.assertEqual(client.post('/debug/download',json=payload,headers=headers).status_code,404)
|
||||
|
||||
def test_lore_constraints_bounded(self):
|
||||
d=json.loads(Path('personas/lvbu.lorebook.json').read_text());text=d['rules']+'\n'+'\n'.join(e['text'] for e in d['entries'])
|
||||
self.assertLess(len(text),1400)
|
||||
for word in ['AI','安全','Markdown','日常','现代']:self.assertIn(word,text)
|
||||
@@ -0,0 +1,46 @@
|
||||
import unittest
|
||||
from face_context import FaceContext
|
||||
|
||||
|
||||
def cue(**changes):
|
||||
return dict({'type': 'context.face_cue', 'version': 1, 'turn_id': 1, 'valid': True,
|
||||
'cue': 'smiling', 'intensity': .8, 'duration_ms': 900, 'age_ms': 100}, **changes)
|
||||
|
||||
|
||||
class FaceContextTests(unittest.TestCase):
|
||||
def test_ttl_and_one_shot(self):
|
||||
state = FaceContext()
|
||||
self.assertTrue(state.update(cue(), 1, now=100))
|
||||
state.advance_capture(1, 2)
|
||||
self.assertEqual(state.take(2, now=102.9)['role'], 'system')
|
||||
self.assertIsNone(state.take(2, now=102.9))
|
||||
state.update(cue(), 1, now=100)
|
||||
self.assertIsNone(state.take(1, now=102.901))
|
||||
|
||||
def test_no_cue_is_no_message(self):
|
||||
state = FaceContext()
|
||||
self.assertIsNone(state.take(1))
|
||||
state.update(cue(), 1, now=10)
|
||||
state.clear()
|
||||
self.assertIsNone(state.take(1, now=10))
|
||||
|
||||
def test_whitelist_invalid_clears(self):
|
||||
for change in ({'cue':'angry'}, {'text':'untrusted prompt'}, {'intensity':float('nan')},
|
||||
{'intensity':True}, {'duration_ms':799}, {'age_ms':3001}, {'version':True},
|
||||
{'turn_id':2}, {'valid':'true'}, {'cue':'eyes_closed'}, {'landmarks':[]}):
|
||||
state = FaceContext()
|
||||
state.update(cue(), 1, now=1)
|
||||
self.assertFalse(state.update(cue(**change), 1, now=1))
|
||||
self.assertIsNone(state.take(1, now=1))
|
||||
|
||||
def test_unknown_clear_and_turn_scope(self):
|
||||
state = FaceContext()
|
||||
state.update(cue(), 1, now=1)
|
||||
self.assertTrue(state.update(cue(valid=False, cue='unknown', intensity=0, duration_ms=0), 1, now=1))
|
||||
self.assertIsNone(state.take(1, now=1))
|
||||
state.update(cue(), 1, now=1)
|
||||
self.assertIsNone(state.take(2, now=1))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,115 @@
|
||||
import asyncio
|
||||
import contextlib
|
||||
import io
|
||||
import struct
|
||||
import unittest
|
||||
import wave
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from gateway import Dialogue, app
|
||||
from protocol import WavStream, pack, unpack
|
||||
from tests_fake import FakeModel
|
||||
|
||||
|
||||
class Socket:
|
||||
def __init__(self): self.events = []; self.frames = []
|
||||
async def send_json(self, data): self.events.append(data)
|
||||
async def send_bytes(self, data): self.frames.append(data)
|
||||
|
||||
|
||||
class ProtocolTests(unittest.TestCase):
|
||||
def test_frame(self):
|
||||
self.assertEqual(unpack(pack(1, 7, 3, bytes(640)), 1), (7, 3, bytes(640)))
|
||||
for data in (b'', pack(2, 7, 3, bytes(640)), b'wrong header!'):
|
||||
with self.assertRaises(ValueError): unpack(data, 1)
|
||||
|
||||
def test_incremental_wav(self):
|
||||
wav = io.BytesIO()
|
||||
with wave.open(wav, 'wb') as w:
|
||||
w.setnchannels(1); w.setsampwidth(2); w.setframerate(48000); w.writeframes(bytes(3840))
|
||||
for size in (1, 3, 137, 4096):
|
||||
parser = WavStream(); out = b''; data = wav.getvalue()
|
||||
for i in range(0, len(data), size): out += parser.feed(data[i:i + size])
|
||||
parser.finish(); self.assertEqual(out, bytes(3840))
|
||||
|
||||
def test_auth_origin_and_no_pre_auth_audio(self):
|
||||
app.state.busy = False; app.state.token = 'x' * 40
|
||||
client = TestClient(app)
|
||||
with contextlib.nullcontext(client) as client:
|
||||
with self.assertRaises(Exception):
|
||||
with client.websocket_connect('/ws/dialogue', headers={'Origin': 'https://evil.invalid'}): pass
|
||||
with client.websocket_connect('/ws/dialogue', headers={'Origin': 'https://192.168.31.61:5011'}) as ws:
|
||||
ws.send_json({'type': 'auth', 'token': 'wrong'})
|
||||
with self.assertRaises(Exception): ws.receive_json()
|
||||
self.assertFalse(app.state.busy)
|
||||
with client.websocket_connect('/ws/dialogue', headers={'Origin': 'https://192.168.31.61:5011'}) as ws:
|
||||
ws.send_bytes(pack(1, 0, 1, bytes(640)))
|
||||
with self.assertRaises(Exception): ws.receive_json()
|
||||
|
||||
|
||||
class DialogueTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_cancel_and_sequence(self):
|
||||
socket = Socket(); dialogue = Dialogue(socket, FakeModel(), None)
|
||||
await dialogue.listen('manual')
|
||||
old = dialogue.turn
|
||||
await dialogue.input(pack(1, old, 1, bytes(640)))
|
||||
with self.assertRaises(ValueError): await dialogue.input(pack(1, old, 3, bytes(640)))
|
||||
dialogue.task = asyncio.create_task(asyncio.sleep(10))
|
||||
await dialogue.invalidate('test_abort')
|
||||
await dialogue.audio(old, bytes(1920))
|
||||
await dialogue.event('llm', old, text='stale')
|
||||
await dialogue.input(pack(1, old, 2, bytes(640)))
|
||||
self.assertEqual(socket.frames, [])
|
||||
self.assertFalse(any(e.get('text') == 'stale' for e in socket.events))
|
||||
self.assertEqual(len(dialogue.capture), 0)
|
||||
await dialogue.close()
|
||||
|
||||
async def test_barge_preserves_coordinates_and_submits(self):
|
||||
class SpeechModel(FakeModel):
|
||||
def infer(self, pcm, state): return (0.9 if pcm[0] else 0.0), state
|
||||
socket = Socket(); dialogue = Dialogue(socket, SpeechModel(), None)
|
||||
await dialogue.listen('auto', barge=True)
|
||||
old = dialogue.turn
|
||||
dialogue.task = asyncio.create_task(asyncio.sleep(10))
|
||||
await dialogue.input(pack(1, old, 1, struct.pack('<h', 1000) * 1536))
|
||||
self.assertGreater(dialogue.turn, old)
|
||||
self.assertTrue(dialogue.vad.active)
|
||||
submitted = []
|
||||
async def submit(pcm, end): submitted.append((len(pcm), end))
|
||||
dialogue.submit = submit
|
||||
await dialogue.input(pack(1, dialogue.turn, 1, bytes(10240)))
|
||||
self.assertEqual(submitted, [(3072, 1536)])
|
||||
await dialogue.close()
|
||||
|
||||
async def test_debug_half_duplex_drain_blocks_echo_input(self):
|
||||
dialogue = Dialogue(Socket(), FakeModel(), None)
|
||||
await dialogue.listen('auto', barge=False)
|
||||
dialogue.playback_waiting = True
|
||||
await dialogue.input(pack(1, dialogue.turn, 1, bytes(640)))
|
||||
self.assertEqual(dialogue.capture, b'')
|
||||
self.assertEqual(dialogue.vad.samples, 0)
|
||||
await dialogue.close()
|
||||
|
||||
async def test_stage_metrics_mock_pipeline(self):
|
||||
socket = Socket()
|
||||
wav = io.BytesIO()
|
||||
with wave.open(wav, 'wb') as w:
|
||||
w.setnchannels(1); w.setsampwidth(2); w.setframerate(48000); w.writeframes(struct.pack('<h', 1000) * 1920)
|
||||
def backend(request):
|
||||
if 'transcriptions' in request.url.path: return httpx.Response(200, json={'text': '喝水有什么用?'})
|
||||
if 'chat' in request.url.path:
|
||||
return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"补充水分。"}}]}\n\ndata: [DONE]\n\n', headers={'Content-Type': 'text/event-stream'})
|
||||
return httpx.Response(200, content=wav.getvalue())
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
dialogue = Dialogue(socket, FakeModel(), client)
|
||||
await dialogue.run(0, bytes(640))
|
||||
metrics = [e for e in socket.events if e['type'] == 'metrics'][0]['values']
|
||||
for key in ['stt_ms','llm_first_body_ms','first_fragment_ms','tts_first_pcm_ms','tts_first_voiced_block_ms']: self.assertIn(key, metrics)
|
||||
segment=metrics['tts_segments'][0]
|
||||
for key in ['first_pcm_ms','first_voiced_ms','total_ms','audio_seconds','rtf','schedule_gap_ms','pcm_arrival_gap_ms','ready_ahead']: self.assertIn(key,segment)
|
||||
self.assertNotIn('text',segment)
|
||||
self.assertEqual(segment['audio_seconds'],.04)
|
||||
self.assertEqual(len(socket.frames), 2)
|
||||
self.assertEqual(unpack(socket.frames[0], 2)[:2], (0, 1))
|
||||
@@ -0,0 +1,105 @@
|
||||
"""No live models/sockets: actual Dialogue + HTTP doubles, including drain/finalization race."""
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import time
|
||||
import unittest
|
||||
import wave
|
||||
import httpx
|
||||
from gateway import Dialogue
|
||||
from tests_fake import FakeModel
|
||||
from test_gateway import Socket
|
||||
from test_face_context import cue
|
||||
|
||||
|
||||
def wav(pcm):
|
||||
out = io.BytesIO()
|
||||
with wave.open(out, 'wb') as file:
|
||||
file.setnchannels(1); file.setsampwidth(2); file.setframerate(48000); file.writeframes(pcm)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
class ReplyFaceTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def round(self, observation=False, empty_llm=False, empty_tts=False, empty_stt=False):
|
||||
messages = []
|
||||
def backend(request):
|
||||
if 'transcriptions' in request.url.path:
|
||||
return httpx.Response(200, json={'text': '' if empty_stt else '公开合成测试'})
|
||||
if 'chat' in request.url.path:
|
||||
messages.append(json.loads(request.content)['messages'])
|
||||
# The actual deployed Qwen template accepts only one initial system.
|
||||
self.assertEqual(sum(m['role']=='system' for m in messages[-1]), 1)
|
||||
body = '' if empty_llm else '测试回答'
|
||||
return httpx.Response(200, text='data: '+json.dumps({'choices':[{'delta':{'content':body}}]})+'\n\ndata: [DONE]\n\n')
|
||||
return httpx.Response(200, content=wav(b'' if empty_tts else b'\x10\x01'*960))
|
||||
socket = Socket()
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
d = Dialogue(socket, FakeModel(), client)
|
||||
if observation:
|
||||
self.assertTrue(d.face_context.update(cue(turn_id=0), 0))
|
||||
await d.invalidate('new_turn')
|
||||
await d.run(d.turn, bytes(640))
|
||||
return d, socket, messages
|
||||
|
||||
async def test_optional_ephemeral_message(self):
|
||||
d, socket, messages = await self.round(observation=True)
|
||||
self.assertEqual([m['role'] for m in messages[0]], ['system','user'])
|
||||
self.assertIn('摄像头观察', messages[0][0]['content'])
|
||||
self.assertEqual(d.face_messages, {})
|
||||
self.assertIsNone(d.face_context.value)
|
||||
self.assertTrue(socket.frames)
|
||||
d, socket, messages = await self.round(observation=False)
|
||||
self.assertEqual([m['role'] for m in messages[0]], ['system','user'])
|
||||
self.assertNotIn('摄像头观察', messages[0][0]['content'])
|
||||
|
||||
async def test_expired_and_barge_clear(self):
|
||||
d = Dialogue(Socket(), FakeModel(), None)
|
||||
d.face_context.update(cue(turn_id=0),0,now=time.monotonic()-4)
|
||||
await d.invalidate('new_turn')
|
||||
self.assertIsNone(d.face_context.take(d.turn))
|
||||
for reason in ('listen_start','voice_barge_in','client_abort','history_new'):
|
||||
d.face_context.update(cue(turn_id=d.turn),d.turn)
|
||||
await d.invalidate(reason)
|
||||
self.assertIsNone(d.face_context.value)
|
||||
|
||||
async def test_empty_body_or_pcm_explicit_error(self):
|
||||
for options in ({'empty_llm':True}, {'empty_tts':True}):
|
||||
d, socket, _ = await self.round(**options)
|
||||
self.assertTrue(any(e['type']=='error' and e['code']=='backend_failed' for e in socket.events))
|
||||
self.assertFalse(socket.frames)
|
||||
|
||||
async def test_empty_stt_recovers_listening(self):
|
||||
d, socket, messages = await self.round(empty_stt=True)
|
||||
self.assertFalse(messages)
|
||||
self.assertTrue(any(e['type']=='listen' and e['state']=='resumed' for e in socket.events))
|
||||
|
||||
async def test_native_drain_during_history_finalize_not_lost(self):
|
||||
entered, finish = asyncio.Event(), asyncio.Event()
|
||||
class History:
|
||||
async def begin(self,*args): pass
|
||||
async def context(self,*args): return []
|
||||
async def rows(self,*args): return []
|
||||
async def finish(self,*args): entered.set(); await finish.wait()
|
||||
async def drained(self,*args): pass
|
||||
def backend(request):
|
||||
if 'transcriptions' in request.url.path: return httpx.Response(200,json={'text':'公开测试'})
|
||||
if 'chat' in request.url.path: return httpx.Response(200,text='data: {"choices":[{"delta":{"content":"回答"}}]}\n\ndata: [DONE]\n\n')
|
||||
return httpx.Response(200,content=wav(b'\x10\x01'*960))
|
||||
socket = Socket()
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
d=Dialogue(socket,FakeModel(),client,History(),'synthetic-conversation')
|
||||
d.run_id='synthetic-run'
|
||||
d.task=asyncio.create_task(d.run(0,bytes(640)))
|
||||
await asyncio.wait_for(entered.wait(),2)
|
||||
self.assertTrue(any(e['type']=='tts' and e.get('state')=='stop' for e in socket.events))
|
||||
await d.request_drained(0)
|
||||
self.assertEqual(d.pending_drained,0)
|
||||
finish.set()
|
||||
await asyncio.wait_for(d.task,2)
|
||||
self.assertFalse(d.playback_waiting)
|
||||
self.assertEqual(sum(e['type']=='listen' and e['state']=='resumed' for e in socket.events),1)
|
||||
await d.request_drained(0) # duplicate must not send another ack
|
||||
self.assertEqual(sum(e['type']=='listen' and e['state']=='resumed' for e in socket.events),1)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,28 @@
|
||||
import time
|
||||
import unittest
|
||||
from fastapi.testclient import TestClient
|
||||
from guest_sessions import GuestSessions, COOKIE
|
||||
from gateway import app
|
||||
|
||||
|
||||
class GuestTests(unittest.TestCase):
|
||||
def test_network_owner_expiry_capacity(self):
|
||||
for ip in ['192.168.31.2','127.0.0.1','::1']:self.assertTrue(GuestSessions.lan(ip))
|
||||
for ip in ['10.0.0.1','192.168.1.2','172.16.1.1','bad']:self.assertFalse(GuestSessions.lan(ip))
|
||||
g=GuestSessions(capacity=2);a=g.create();b=g.create();g.bind(a,'cid')
|
||||
with self.assertRaises(ValueError):g.own(b,'cid')
|
||||
with self.assertRaises(ValueError):g.create()
|
||||
g.sessions[a]['expires']=time.time()-1;self.assertIsNone(g.get(a));g.revoke(b);self.assertIsNone(g.get(b))
|
||||
|
||||
def test_bootstrap_origin_cookie_nonlan_and_logout(self):
|
||||
app.state.guests=GuestSessions();app.state.guest_enabled=True
|
||||
client=TestClient(app,base_url='https://192.168.31.61:5011',client=('192.168.31.2',4000))
|
||||
self.assertEqual(client.post('/session/bootstrap',json={}).status_code,403)
|
||||
self.assertEqual(client.post('/session/bootstrap',json={},headers={'Origin':'https://evil.test'}).status_code,403)
|
||||
r=client.post('/session/bootstrap',json={},headers={'Origin':'https://192.168.31.61:5011'})
|
||||
self.assertEqual(r.status_code,200)
|
||||
for flag in ['HttpOnly','Secure','SameSite=strict']:self.assertIn(flag,r.headers['set-cookie'])
|
||||
key=client.cookies.get(COOKIE);self.assertTrue(app.state.guests.get(key))
|
||||
bad=TestClient(app,client=('10.0.0.1',4000))
|
||||
self.assertEqual(bad.post('/session/bootstrap',json={},headers={'Origin':'https://192.168.31.61:5011','X-Forwarded-For':'192.168.31.2'}).status_code,403)
|
||||
client.post('/session/logout',headers={'Origin':'https://192.168.31.61:5011'});self.assertIsNone(app.state.guests.get(key))
|
||||
@@ -0,0 +1,168 @@
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import struct
|
||||
import tempfile
|
||||
import unittest
|
||||
import uuid
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
from unittest.mock import patch
|
||||
|
||||
from gateway import Dialogue, app
|
||||
from history import History
|
||||
from protocol import pack
|
||||
from tests_fake import FakeModel
|
||||
from test_gateway import Socket
|
||||
|
||||
|
||||
class SpeechModel(FakeModel):
|
||||
def infer(self, pcm, state): return (0.9 if pcm[0] else 0.0), state
|
||||
|
||||
|
||||
class HistoryTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.h = History(Path(self.temp.name) / 'history.sqlite3')
|
||||
await self.h.initialize()
|
||||
self.cid = await self.h.conversation()
|
||||
|
||||
async def asyncTearDown(self): self.temp.cleanup()
|
||||
|
||||
async def test_restore_window_clear_and_partial(self):
|
||||
for i in range(12):
|
||||
rid = str(uuid.uuid4())
|
||||
await self.h.begin(self.cid, rid, f'user{i}')
|
||||
await self.h.finish(rid, f'answer{i}', 'completed')
|
||||
await self.h.drained(rid)
|
||||
partial = str(uuid.uuid4())
|
||||
await self.h.begin(self.cid, partial, 'partial user')
|
||||
await self.h.finish(partial, 'unfinished', 'interrupted')
|
||||
restarted = History(self.h.path); await restarted.initialize()
|
||||
context = await restarted.context(self.cid, 'current')
|
||||
self.assertEqual(len(context), 20)
|
||||
self.assertEqual(context[0]['content'], 'user2')
|
||||
self.assertFalse(any(x['content'] == 'unfinished' for x in context))
|
||||
self.assertEqual(len(await restarted.rows(self.cid)), 26)
|
||||
other = await restarted.conversation()
|
||||
await restarted.begin(other, str(uuid.uuid4()), 'keep')
|
||||
await restarted.clear(self.cid)
|
||||
self.assertEqual(await restarted.rows(self.cid), [])
|
||||
self.assertEqual(len(await restarted.rows(other)), 2)
|
||||
self.assertEqual(self.h.path.stat().st_mode & 0o777, 0o600)
|
||||
with self.assertRaises(ValueError): await restarted.conversation('../bad')
|
||||
|
||||
async def test_stale_finalize_and_playback_separate(self):
|
||||
rid = str(uuid.uuid4())
|
||||
await self.h.begin(self.cid, rid, 'user')
|
||||
await self.h.interrupt(rid)
|
||||
await self.h.finish(rid, 'partial', 'interrupted')
|
||||
await self.h.finish(rid, 'old complete', 'completed')
|
||||
rows = await self.h.rows(self.cid)
|
||||
self.assertEqual(rows[-1]['text'], 'partial')
|
||||
self.assertEqual(rows[-1]['status'], 'interrupted')
|
||||
self.assertEqual(await self.h.context(self.cid, 'other'), [])
|
||||
rid2 = str(uuid.uuid4())
|
||||
await self.h.begin(self.cid, rid2, 'user2')
|
||||
await self.h.finish(rid2, 'answer2', 'completed')
|
||||
self.assertEqual((await self.h.rows(self.cid))[-1]['playback'], 'awaiting_drain')
|
||||
self.assertEqual(await self.h.context(self.cid, 'next'), [])
|
||||
rid3 = str(uuid.uuid4())
|
||||
await self.h.begin(self.cid, rid3, 'unheard user')
|
||||
await self.h.finish(rid3, 'unheard completed answer', 'completed')
|
||||
await self.h.interrupt(rid3)
|
||||
self.assertEqual(await self.h.context(self.cid, 'next'), [])
|
||||
self.assertEqual((await self.h.rows(self.cid))[-1]['status'], 'completed')
|
||||
await self.h.drained(rid2)
|
||||
rows = await self.h.rows(self.cid)
|
||||
self.assertEqual(next(r for r in rows if r['run_id'] == rid2 and r['role'] == 'assistant')['playback'], 'confirmed')
|
||||
self.assertEqual(len(await self.h.context(self.cid, 'next')), 2)
|
||||
|
||||
async def test_duplex_running_and_awaiting_drain_no_loop(self):
|
||||
for running in (True, False):
|
||||
socket = Socket(); d = Dialogue(socket, SpeechModel(), None)
|
||||
await d.listen('auto')
|
||||
old = d.turn
|
||||
if running: d.task = asyncio.create_task(asyncio.sleep(10))
|
||||
else: d.playback_waiting = True
|
||||
await d.input(pack(1, old, 1, struct.pack('<h', 1000) * 1536))
|
||||
self.assertEqual(d.turn, old + 1)
|
||||
after_start = d.turn
|
||||
await d.input(pack(1, d.turn, 1, struct.pack('<h', 1000) * 1536))
|
||||
self.assertEqual(d.turn, after_start)
|
||||
submitted = []
|
||||
async def submit(pcm, end): submitted.append((len(pcm), end))
|
||||
d.submit = submit
|
||||
await d.input(pack(1, d.turn, 2, bytes(10240)))
|
||||
self.assertEqual(submitted, [(6144, 3072)])
|
||||
self.assertEqual(len([e for e in socket.events if e.get('reason') == 'voice_barge_in']), 1)
|
||||
await d.close()
|
||||
|
||||
async def test_two_turn_mock_context_and_drain(self):
|
||||
calls = []
|
||||
wav = io.BytesIO()
|
||||
with wave.open(wav, 'wb') as w:
|
||||
w.setnchannels(1); w.setsampwidth(2); w.setframerate(48000); w.writeframes(struct.pack('<h', 1000) * 960)
|
||||
def backend(request):
|
||||
if 'transcriptions' in request.url.path: return httpx.Response(200, json={'text': '当前问题'})
|
||||
if 'chat' in request.url.path:
|
||||
calls.append(json.loads(request.content)['messages'])
|
||||
return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"直接回答。"}}]}\n\ndata: [DONE]\n\n')
|
||||
return httpx.Response(200, content=wav.getvalue())
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
d = Dialogue(Socket(), SpeechModel(), client, self.h, self.cid)
|
||||
for _ in range(2):
|
||||
await d.submit(bytes(640), 320)
|
||||
await d.task
|
||||
await d.drained()
|
||||
self.assertEqual(len(calls[0]), 2)
|
||||
self.assertEqual(len(calls[1]), 4)
|
||||
self.assertEqual(calls[1][-1], {'role':'user','content':'当前问题'})
|
||||
self.assertEqual(len(await self.h.rows(self.cid)), 4)
|
||||
await d.close()
|
||||
|
||||
async def test_interrupted_pipeline_keeps_partial_no_new_turn_pollution(self):
|
||||
socket = Socket(); d = Dialogue(socket, SpeechModel(), None, self.h, self.cid)
|
||||
rid = str(uuid.uuid4()); d.run_id = rid
|
||||
await self.h.begin(self.cid, rid, 'old question')
|
||||
async def old_pipeline():
|
||||
try: await asyncio.sleep(10)
|
||||
finally: await self.h.finish(rid, 'old partial', 'interrupted')
|
||||
d.task = asyncio.create_task(old_pipeline()); await asyncio.sleep(0)
|
||||
await d.invalidate('voice_barge_in')
|
||||
await asyncio.gather(*list(d.cancelled_tasks), return_exceptions=True)
|
||||
new_rid = str(uuid.uuid4())
|
||||
await self.h.begin(self.cid, new_rid, 'new question')
|
||||
await self.h.finish(new_rid, 'new answer', 'completed')
|
||||
await self.h.drained(new_rid)
|
||||
rows = await self.h.rows(self.cid)
|
||||
self.assertEqual([r['status'] for r in rows], ['completed','interrupted','completed','completed'])
|
||||
self.assertEqual(len(await self.h.context(self.cid, 'future')), 2)
|
||||
await d.close()
|
||||
|
||||
|
||||
class AuthHistoryTests(unittest.TestCase):
|
||||
def test_history_only_after_auth_and_scoped(self):
|
||||
with tempfile.TemporaryDirectory() as directory, patch.dict('os.environ', {'LAN_GATEWAY_TOKEN':'x'*40}), patch('gateway.ROOT', Path(directory)):
|
||||
app.state.busy = False; app.state.token = 'x'*40
|
||||
h = History(Path(directory)/'history.sqlite3')
|
||||
asyncio.run(h.initialize()); app.state.history = h
|
||||
app.state.model = FakeModel(); app.state.client = None
|
||||
from tts_debug import DebugStore
|
||||
app.state.debug = DebugStore(Path(directory)/'debug')
|
||||
from gateway import DEFAULT_VOICE_ID
|
||||
app.state.voices = [{'id':DEFAULT_VOICE_ID,'source':'design','default':True}]
|
||||
client = TestClient(app)
|
||||
with client.websocket_connect('/ws/dialogue', headers={'Origin':'https://192.168.31.61:5011'}) as ws:
|
||||
ws.send_json({'type':'history','action':'get'})
|
||||
with self.assertRaises(Exception): ws.receive_json()
|
||||
with client.websocket_connect('/ws/dialogue', headers={'Origin':'https://192.168.31.61:5011'}) as ws:
|
||||
ws.send_json({'type':'auth','token':'x'*40}); ws.receive_json()
|
||||
ws.send_json({'type':'hello','codec':'pcm16','sample_rate':16000,'frame_duration':20})
|
||||
cid = ws.receive_json()['conversation_id']; history = ws.receive_json()
|
||||
self.assertEqual(history['messages'], [])
|
||||
ws.send_json({'type':'history','action':'clear','conversation_id':str(uuid.uuid4())})
|
||||
with self.assertRaises(Exception): ws.receive_json()
|
||||
@@ -0,0 +1,23 @@
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from persona_resolver import resolve_persona, DEFAULT_VOICE_ID
|
||||
|
||||
|
||||
class PersonaTests(unittest.TestCase):
|
||||
def test_yangmi_authorized_voice_new_context_and_rules(self):
|
||||
import json
|
||||
vid=json.loads(Path('.runtime/personas/yangmi_fiction.json').read_text())['voice_id']
|
||||
p=resolve_persona(Path('.'),'yangmi_fiction',[vid])
|
||||
self.assertEqual(p['voice_id'],vid)
|
||||
self.assertTrue(p['fresh_conversation']);self.assertTrue(p['locked'])
|
||||
self.assertIn('北京',p['rules']);self.assertNotIn('奉先',p['rules'])
|
||||
self.assertNotIn('https://',p['rules']);self.assertLessEqual(len(p['rules']),1400)
|
||||
for value in ['北京','演员','旁白']:self.assertIn(value,p['rules'])
|
||||
|
||||
def test_lvbu_unchanged_and_unknown_rejected(self):
|
||||
import json
|
||||
vid=json.loads(Path('.runtime/personas/lvbu.json').read_text())['voice_id']
|
||||
p=resolve_persona('.','lvbu',[vid]);self.assertEqual(p['voice_id'],vid);self.assertIn('奉先',p['rules']);self.assertNotIn('杨密',p['rules'])
|
||||
for value in ['unknown','../lvbu',None]:
|
||||
with self.assertRaises(ValueError):resolve_persona('.',value,[vid])
|
||||
with self.assertRaises(ValueError):resolve_persona('.','yangmi_fiction',[])
|
||||
@@ -0,0 +1,50 @@
|
||||
import unittest
|
||||
from segmentation import Segmenter
|
||||
|
||||
|
||||
class SegmentTests(unittest.TestCase):
|
||||
def test_user_three_plus_four_short_final(self):
|
||||
for mode in ('balanced', 'low_latency'):
|
||||
for text in ('好的,我们去。', '好呀!一起走。', '是的,我们去散步。'):
|
||||
s = Segmenter(mode)
|
||||
first=s.add(text, 0)
|
||||
if first is not None:
|
||||
self.assertEqual(first,text)
|
||||
else:
|
||||
self.assertIsNone(s.take(2))
|
||||
self.assertEqual(s.take(2, final=True), text)
|
||||
self.assertEqual(s.buffer, '')
|
||||
|
||||
def test_natural_first_min_and_no_undersized_fallback(self):
|
||||
for mode, minimum in [('balanced', 12), ('low_latency', 8)]:
|
||||
s=Segmenter(mode)
|
||||
self.assertIsNone(s.add('好的,'+'甲'*(minimum-4),0))
|
||||
self.assertIsNone(s.take(3))
|
||||
self.assertEqual(s.add('乙'*30,3),('好的,'+'甲'*(minimum-4)+'乙'*30)[:24])
|
||||
self.assertEqual(s.last_cut,'hard_limit')
|
||||
self.assertEqual(s.hardcuts,1)
|
||||
s=Segmenter(mode)
|
||||
value=s.add('甲'*minimum+',后续。',0)
|
||||
self.assertEqual(value,'甲'*minimum+',')
|
||||
self.assertEqual(s.take(1,final=True),'后续。')
|
||||
|
||||
def test_limits_multi_delta_final_no_loss(self):
|
||||
for mode in ('balanced','low_latency'):
|
||||
s=Segmenter(mode);text=('甲'*12+',')*20;output=[]
|
||||
fragment=s.add(text,0)
|
||||
if fragment:output.append(fragment)
|
||||
while True:
|
||||
value=s.take(.1)
|
||||
if not value:break
|
||||
output.append(value)
|
||||
if s.buffer:output.append(s.take(1,final=True))
|
||||
self.assertEqual(''.join(output),text)
|
||||
self.assertTrue(all(len(x)>=s.first_min for x in output[:-1]))
|
||||
with self.assertRaises(ValueError):Segmenter('bad')
|
||||
|
||||
def test_final_remaining_whole_multiple_punctuation(self):
|
||||
s=Segmenter();s.add('甲'*12+',',0)
|
||||
tail='好的,走吧。慢慢来!'
|
||||
self.assertIsNone(s.add(tail,.1))
|
||||
self.assertEqual(s.take(1,final=True),tail)
|
||||
self.assertIsNone(s.take(1,final=True))
|
||||
@@ -0,0 +1,81 @@
|
||||
"""v0.8: LAN 直连授权 + active_profile 单元测试(不需要网络/模型)。"""
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import gateway
|
||||
from guest_sessions import GuestSessions
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, host):
|
||||
self.host = host
|
||||
|
||||
|
||||
class FakeConn:
|
||||
def __init__(self, host):
|
||||
self.client = FakeClient(host)
|
||||
|
||||
|
||||
class TestLanOpenMode(unittest.TestCase):
|
||||
def setUp(self):
|
||||
gateway.app.state.guests = GuestSessions()
|
||||
gateway.app.state.lan_open = True
|
||||
|
||||
def test_open_key_from_lan_ip(self):
|
||||
key = gateway.open_key(FakeConn('192.168.31.200'))
|
||||
self.assertEqual(key, 'lan:192.168.31.200')
|
||||
self.assertIsNotNone(gateway.app.state.guests.get(key))
|
||||
|
||||
def test_open_key_reusable_and_own_bind(self):
|
||||
key = gateway.open_key(FakeConn('192.168.31.200'))
|
||||
gateway.app.state.guests.bind(key, 'cid-1')
|
||||
gateway.app.state.guests.own(key, 'cid-1')
|
||||
with self.assertRaises(ValueError):
|
||||
gateway.app.state.guests.own(key, 'cid-other')
|
||||
|
||||
def test_open_key_none_when_disabled(self):
|
||||
gateway.app.state.lan_open = False
|
||||
self.assertIsNone(gateway.open_key(FakeConn('192.168.31.200')))
|
||||
|
||||
def test_open_key_none_for_foreign_ip(self):
|
||||
self.assertIsNone(gateway.open_key(FakeConn('10.9.9.9')))
|
||||
|
||||
|
||||
class TestActiveProfile(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.orig_root = gateway.ROOT
|
||||
root = Path(self.tmp.name)
|
||||
(root / '.runtime').mkdir()
|
||||
gateway.ROOT = root
|
||||
self.addCleanup(setattr, gateway, 'ROOT', self.orig_root)
|
||||
|
||||
def write(self, data):
|
||||
(gateway.ROOT / '.runtime' / 'active_profile.json').write_text(json.dumps(data), encoding='utf-8')
|
||||
|
||||
def test_missing_file_returns_none(self):
|
||||
self.assertIsNone(gateway.load_active_profile())
|
||||
|
||||
def test_valid_profile(self):
|
||||
self.write({'persona': 'yangmi_fiction', 'voice_id': 'v-1'})
|
||||
p = gateway.load_active_profile()
|
||||
self.assertEqual(p['persona'], 'yangmi_fiction')
|
||||
self.assertEqual(p['voice_id'], 'v-1')
|
||||
|
||||
def test_invalid_json_returns_none(self):
|
||||
(gateway.ROOT / '.runtime' / 'active_profile.json').write_text('{bad', encoding='utf-8')
|
||||
self.assertIsNone(gateway.load_active_profile())
|
||||
|
||||
def test_non_dict_returns_none(self):
|
||||
self.write([1, 2])
|
||||
self.assertIsNone(gateway.load_active_profile())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,123 @@
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vad import Config, Silero, VadSession, WINDOW
|
||||
|
||||
|
||||
class Fake:
|
||||
def new_state(self):
|
||||
return np.zeros(1)
|
||||
|
||||
def infer(self, pcm, state):
|
||||
state = state.copy() + 1
|
||||
return (0.9 if pcm[0] else 0.0), state
|
||||
|
||||
|
||||
class VadTests(unittest.TestCase):
|
||||
def test_chunks_and_frames_equal(self):
|
||||
data = np.concatenate([np.zeros(2048, dtype='<i2'), np.ones(4096, dtype='<i2'), np.zeros(8192, dtype='<i2')]).tobytes()
|
||||
outputs = []
|
||||
for size in (640, 1, 137, 65536):
|
||||
session = VadSession(Fake())
|
||||
events = []
|
||||
for i in range(0, len(data), size):
|
||||
events += session.feed(data[i:i + size])
|
||||
events += session.finish()
|
||||
outputs.append(events)
|
||||
self.assertLess(len(session.pending), 1024)
|
||||
self.assertTrue(all(x == outputs[0] for x in outputs))
|
||||
self.assertEqual([e['type'] for e in outputs[0]], ['speech.start', 'speech.end', 'session.ended'])
|
||||
|
||||
def test_isolation(self):
|
||||
model = Fake()
|
||||
a, b = VadSession(model), VadSession(model)
|
||||
a.feed(np.ones(1536, dtype='<i2').tobytes())
|
||||
self.assertTrue(a.active)
|
||||
self.assertFalse(b.active)
|
||||
self.assertEqual(b.state[0], 0)
|
||||
b.feed(bytes(4096))
|
||||
self.assertTrue(a.active)
|
||||
self.assertFalse(b.active)
|
||||
|
||||
def test_silero_silence_and_state(self):
|
||||
model = Silero(Path('models/silero_vad.onnx'))
|
||||
a, b = VadSession(model), VadSession(model)
|
||||
self.assertEqual(a.feed(bytes(32000)), [])
|
||||
self.assertTrue(np.all(b.state[0] == 0))
|
||||
b.feed(bytes(32000))
|
||||
np.testing.assert_array_equal(a.state[0], b.state[0])
|
||||
a.reset()
|
||||
self.assertTrue(np.all(a.state[0] == 0))
|
||||
|
||||
def test_reset_end(self):
|
||||
a = VadSession(Fake())
|
||||
a.feed(np.ones(1536, dtype='<i2').tobytes())
|
||||
events = a.reset()
|
||||
self.assertEqual(events[0]['reason'], 'reset')
|
||||
self.assertEqual(a.samples, 0)
|
||||
self.assertEqual(a.epoch, 1)
|
||||
a.feed(np.ones(1536, dtype='<i2').tobytes())
|
||||
self.assertEqual(a.finish()[0]['reason'], 'input_end')
|
||||
with self.assertRaises(ValueError):
|
||||
a.feed(bytes(2))
|
||||
a.reset()
|
||||
self.assertEqual(a.feed(bytes(2)), [])
|
||||
|
||||
def test_limits(self):
|
||||
a = VadSession(Fake(), Config(max_speech_seconds=1, max_session_seconds=2))
|
||||
events = a.feed(np.ones(20000, dtype='<i2').tobytes())
|
||||
self.assertIn('max_duration', [e.get('reason') for e in events])
|
||||
with self.assertRaises(ValueError):
|
||||
a.feed(bytes(30000))
|
||||
with self.assertRaises(ValueError):
|
||||
VadSession(Fake()).feed(bytes(65537))
|
||||
a = VadSession(Fake())
|
||||
a.feed(b'\x01')
|
||||
with self.assertRaises(ValueError):
|
||||
a.finish()
|
||||
for value in (199, 601):
|
||||
with self.assertRaises(ValueError):
|
||||
Config(silence_ms=value)
|
||||
|
||||
def test_debounce_silence_timestamps(self):
|
||||
a = VadSession(Fake())
|
||||
self.assertEqual(a.feed(np.ones(1024, dtype='<i2').tobytes()), [])
|
||||
start = a.feed(np.ones(512, dtype='<i2').tobytes())[0]
|
||||
self.assertEqual(start['sample'], 0)
|
||||
self.assertEqual(start['detected_at_sample'], 1536)
|
||||
ends = a.feed(bytes(1024 * 10))
|
||||
self.assertEqual(ends[0]['sample'], 1536)
|
||||
self.assertEqual(ends[0]['detected_at_sample'], 6656)
|
||||
|
||||
def test_low_threshold_ends_silence(self):
|
||||
a = VadSession(Fake(), Config(threshold=0.1))
|
||||
a.feed(np.ones(1536, dtype='<i2').tobytes())
|
||||
events = a.feed(bytes(1024 * 10))
|
||||
self.assertEqual(events[0]['reason'], 'silence')
|
||||
self.assertFalse(a.active)
|
||||
|
||||
def test_tail_timestamps_and_audio(self):
|
||||
for size in (513, 1025, 15999):
|
||||
a = VadSession(Fake(), Config(max_speech_seconds=1, start_windows=2, include_preroll_audio=True))
|
||||
a.feed(np.ones(size, dtype='<i2').tobytes())
|
||||
events = a.finish()
|
||||
for event in events:
|
||||
self.assertLessEqual(event['sample'], size)
|
||||
self.assertLessEqual(event['time_ms'], size / 16)
|
||||
self.assertLessEqual(event['detected_at_sample'], size)
|
||||
if 'audio_until_sample' in event:
|
||||
self.assertLessEqual(event['audio_until_sample'], size)
|
||||
import base64
|
||||
self.assertEqual(len(base64.b64decode(event['preroll_pcm16_base64'])), (event['audio_until_sample'] - event['preroll_start_sample']) * 2)
|
||||
self.assertEqual(events[-1]['sample'], size)
|
||||
|
||||
def test_preroll_audio_opt_in(self):
|
||||
a = VadSession(Fake())
|
||||
event = a.feed(np.ones(1536, dtype='<i2').tobytes())[0]
|
||||
self.assertNotIn('preroll_pcm16_base64', event)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,6 @@
|
||||
import numpy as np
|
||||
|
||||
|
||||
class FakeModel:
|
||||
def new_state(self): return np.zeros(1)
|
||||
def infer(self, pcm, state): return 0.0, state
|
||||
@@ -0,0 +1,94 @@
|
||||
import queue
|
||||
import threading
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import uuid
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
class DebugStore:
|
||||
def __init__(self, root, max_bytes=200*1024*1024, max_runs=20, max_age=72*3600):
|
||||
self.root=Path(root);self.root.mkdir(parents=True,exist_ok=True,mode=0o700);os.chmod(self.root,0o700)
|
||||
self.max_bytes=max_bytes;self.max_runs=max_runs;self.max_age=max_age
|
||||
|
||||
def path(self, value):
|
||||
if not isinstance(value,str) or str(uuid.UUID(value))!=value:raise ValueError('invalid debug UUID')
|
||||
return self.root/value
|
||||
|
||||
def cleanup(self):
|
||||
def created(p):
|
||||
f=p/'metadata.json'
|
||||
return json.loads(f.read_text()).get('created',p.stat().st_mtime) if f.exists() else p.stat().st_mtime
|
||||
folders=sorted([p for p in self.root.iterdir() if p.is_dir()],key=created,reverse=True)
|
||||
used=0
|
||||
for i,p in enumerate(folders):
|
||||
size=sum(f.stat().st_size for f in p.iterdir() if f.is_file())
|
||||
if i>=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='<i2').astype(np.int32);self.wav.writeframesraw(pcm)
|
||||
self.meta['samples']+=len(x);self.square+=float(np.sum(x.astype(float)**2));self.peak=max(self.peak,int(np.abs(x).max(initial=0)));self.clips+=int(np.sum(np.abs(x)>=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
|
||||
+164
@@ -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='<i2'), self.state)
|
||||
self.preroll.extend(block)
|
||||
history_bytes = 6400 + self.config.start_windows * WINDOW * 2
|
||||
if len(self.preroll) > 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
|
||||
@@ -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.samples.length) {
|
||||
const i=Math.floor(this.position), f=this.position-i;
|
||||
output.push(this.samples[i]*(1-f)+this.samples[i+1]*f); this.position+=this.step;
|
||||
}
|
||||
const used=Math.min(Math.floor(this.position),this.samples.length);
|
||||
if(used){this.samples.splice(0,used);this.position-=used;}
|
||||
return output;
|
||||
}
|
||||
}
|
||||
export function pcmFrame(direction,turn,seq,pcm) {
|
||||
const buffer=new ArrayBuffer(12+pcm.length*2), view=new DataView(buffer);
|
||||
view.setUint8(0,76);view.setUint8(1,86);view.setUint8(2,1);view.setUint8(3,direction);
|
||||
view.setUint32(4,turn);view.setUint32(8,seq);
|
||||
for(let i=0;i<pcm.length;i++)view.setInt16(12+i*2,pcm[i],true);
|
||||
return buffer;
|
||||
}
|
||||
export function readFrame(buffer) {
|
||||
const v=new DataView(buffer);
|
||||
if(v.byteLength<14 || v.getUint8(0)!==76 || v.getUint8(1)!==86 || v.getUint8(2)!==1 || v.getUint8(3)!==2 || (v.byteLength-12)%2)throw Error('Invalid audio header');
|
||||
const pcm=new Float32Array((v.byteLength-12)/2);
|
||||
for(let i=0;i<pcm.length;i++)pcm[i]=v.getInt16(12+2*i,true)/32768;
|
||||
return {turn:v.getUint32(4),seq:v.getUint32(8),pcm};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import {Resampler} from './audio-core.js';
|
||||
class Capture extends AudioWorkletProcessor {
|
||||
constructor(){super();this.resampler=new Resampler(sampleRate,16000);this.pending=[];this.enabled=false;this.total=0;
|
||||
this.port.onmessage=({data})=>{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);
|
||||
@@ -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<pcm.length;i++){const x=i*c.width/pcm.length,y=35-pcm[i]/32768*34;i?g.lineTo(x,y):g.moveTo(x,y);}g.stroke();}
|
||||
function showMetrics(){$('metrics').textContent=JSON.stringify({server:latestMetrics,browser:rendered,recent:events.slice(-6)},null,2);}
|
||||
function abort(){localAbortAt=performance.now();clearAudio();control({type:'abort',turn_id:turn});status('本地已停播,取消上游;持续采集保持');}
|
||||
async function begin(mode){if(!ready)throw Error('请先连接认证');await audio();haltCapture();clearAudio();auto=mode==='auto';listening=true;captureTimes=[];lastEnd=null;control({type:'listen',mode,state:'start',barge_in:$('barge').checked,start_windows:Number($('debounce').value)});}
|
||||
function disconnect(){connectionGeneration++;connecting=false;const old=ws;ws=null;if(old&&old.readyState!==WebSocket.CLOSED){closingSocket=new Promise(resolve=>{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();});
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>LAN Voice 硬件模拟器</title><style>body{font:16px system-ui;max-width:1000px;margin:24px auto;padding:16px;background:#111827;color:#e5e7eb}button,input,select{padding:10px;margin:5px;border-radius:6px}section{background:#1f2937;padding:15px;margin:12px 0;border-radius:8px}pre{white-space:pre-wrap;overflow-wrap:anywhere}canvas{width:100%;height:70px}#status{color:#93c5fd}label{display:inline-block}button:disabled{opacity:.4}</style></head><body><h1>LAN Voice 浏览器硬件模拟器</h1><p>自定义 PCM 协议,不是完全小智兼容。请用耳机。自动模式使用 batch SenseVoice;服务端VAD不消回声。</p><section><label>共享 token <input id="token" type="password" autocomplete="off" placeholder="仅内存,不保存"></label><select id="codec"><option value="pcm16">PCM16</option><option disabled>Opus:浏览器真实编码链路未实现</option></select><label>合成策略(重连生效)<select id="synthesisMode"><option value="balanced">平衡默认:240ms音频缓冲,少碎句</option><option value="low_latency">低延迟:100ms缓冲,欠供风险较高</option></select></label><label>声音生成(重连生效)<select id="voiceMode"><option value="continuous_voice">默认每轮单generator:等全文</option><option value="fragment">实验分片:音色/韵律跳变风险</option></select></label><label>已登记固定音色<select id="voiceId" disabled></select></label><p id="voiceInfo">默认登记reference;开始前选择,开始后锁定。</p><label>角色(重连;角色强制新会话)<select id="persona"><option value="default">普通助手</option><option value="lvbu">吕布:固定clone+lore</option><option value="yangmi_fiction">杨密(原创测试角色)</option></select></label><p>杨密为原创角色:已使用用户确认许可的普通女生前7秒参考clone,非杨幂仿声;仅本地非商用测试,听感相似未验证。</p><label><input type="checkbox" id="ttsDebug" checked>下一轮记录TTS debug(保存合成台词与音频,限额本地测试)</label><button id="markDebug">标记上一轮异常</button><button id="replayDebug">回放上一轮debug WAV</button><button id="metadataDebug">下载上一轮metadata</button><audio id="debugPlayer" controls></audio><p id="debugInfo">旧轮未保存不能恢复。debug不保存麦克风/token/reference。</p><button id="connect">连接</button><button id="auto">开始持续对话(耳机)</button><button id="manual">按住说话(调试)</button><button id="abort">打断</button><button id="disconnect">断开</button><label><input type="checkbox" id="barge" checked>双工语音打断(默认;关闭仅半双工调试)</label><label>起声debounce<select id="debounce"><option value="3">96ms默认</option><option value="2">64ms</option></select></label><p>默认计算/播放期间持续收音。全双工存在播放自回声自激风险;实际AEC/NS设置不是效果证明,请用耳机。</p><button id="newConversation">新会话</button><button id="clearHistory">清空当前会话历史</button><p id="conversation"></p><div id="history"></div><p id="status">未连接</p></section><section><canvas id="wave" width="900" height="70"></canvas><p id="level">麦克风音量:0</p><pre id="settings">麦克风未请求;HTTPS或安全localhost需要录音权限。AEC设置不保证实际效果。</pre></section><section><h3>ASR</h3><p id="stt"></p><h3>LLM正文</h3><p id="llm"></p><h3>当前句字幕</h3><p id="sentence"></p></section><section><p>平衡缓冲会增加首音等待(不是免费优化),240ms是累计音频量不是固定墙钟等待;模型持续供给慢仍可能卡顿。</p><h3>延迟(不同机器时钟不相减)</h3><pre id="metrics"></pre><button id="export">导出计时(无音频/token)</button><p>rendered=AudioWorklet首次呈现样本,不是硬件实际听到;voiced只是−40dBFS近似,不保证语义有效。</p></section><script type="module" src="/static/client.js"></script></body></html>
|
||||
@@ -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}}
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>声伴 · LAN Voice</title><link rel="stylesheet" href="/static/home.css"></head><body data-friendly="true"><main><header><span class="brand">◌ 声伴</span><span>仅在你的局域网 · v0.7</span><a href="/debug">开发调试页</a></header><section class="hero"><small>让对话,自然发生</small><h1>选一位伙伴,<br>说说今天的事。</h1><p>点击才会开启麦克风。建议戴耳机,声音打断默认开启。</p></section><section class="cards" aria-label="选择角色"><button class="card selected" data-persona="default"><span>◎</span><b>普通助手</b><small>清晰、实用,陪你理顺思路</small></button><button class="card" data-persona="yangmi_fiction"><span>✧</span><b>杨密</b><small>原创测试角色 · 机敏温暖<br>普通女生授权参考,非真人仿声</small></button><button class="card" data-persona="lvbu"><span>◇</span><b>吕布</b><small>威武而简短 · 本地角色测试</small></button></section><section class="voice-panel"><div class="status"><i></i><p id="status" role="status" aria-live="polite">准备好了,点击开始</p></div><canvas id="wave" width="900" height="70" aria-label="麦克风波形"></canvas><button id="mainVoice" class="primary">开始语音对话</button><button id="abort">打断回答</button><p id="level">麦克风尚未开启</p><p class="hint">浏览器AEC设置不保证实际消回声。角色切换会建立新会话。</p></section><section class="chat"><h2>这段对话</h2><p id="conversation"></p><div id="history" aria-live="polite"></div><div class="current"><small>你刚刚说</small><p id="stt"></p><small>回答正在形成</small><p id="llm"></p><p id="sentence" class="subtitle"></p></div></section><section class="privacy"><label><input type="checkbox" id="ttsDebug" checked>记录合成音频用于排查异常</label><p>默认记录TTS台词和合成WAV;不记录麦克风或token。最多20轮/200MiB,72小时在操作时清理。聊天文字存于本机测试数据库。</p><button id="markDebug">标记上一轮异常</button><button id="replayDebug">回放上一轮</button><button id="metadataDebug">下载记录</button><audio id="debugPlayer" controls></audio><p id="debugInfo">尚无合成记录</p><button id="newConversation">新会话</button><button id="clearHistory">清空当前历史</button><button id="logoutGuest">退出访客会话</button></section><details><summary>高级设置与计时</summary><label>管理员手动token<input id="token" type="password" autocomplete="off" placeholder="访客无需填写;仅内存"></label><button id="connect">连接 / 管理员连接</button><button id="disconnect">断开</button><button id="auto">持续监听</button><button id="manual">按住说话调试</button><select id="persona" aria-label="角色"><option value="default">普通助手</option><option value="yangmi_fiction">杨密(原创测试角色)</option><option value="lvbu">吕布</option></select><select id="codec" aria-label="编码"><option>pcm16</option><option disabled>Opus未实现</option></select><select id="synthesisMode" aria-label="缓冲模式"><option value="balanced">240ms平衡缓冲</option><option value="low_latency">100ms低延迟实验</option></select><select id="voiceMode" aria-label="声音连续性"><option value="continuous_voice">每轮单generator</option><option value="fragment">分片质量风险实验</option></select><select id="voiceId" disabled aria-label="固定音色"></select><p id="voiceInfo"></p><label><input id="barge" type="checkbox" checked>双工语音打断</label><select id="debounce" aria-label="起声确认"><option value="3">96ms</option><option value="2">64ms</option></select><pre id="settings">等待麦克风授权</pre><pre id="metrics"></pre><button id="export">导出计时(无正文/音频/token)</button><p>软件render/drain不是硬件实际听到;不同机器时钟不相减。HTTPS证书必须可信,HTTP LAN IP不能录音。</p></details><footer>Cookie访客鉴权,不是账号。仅允许指定LAN网段与loopback;同网段用户可调用模型,不应视为可信网络。</footer></main><script type="module" src="/static/client.js"></script></body></html>
|
||||
@@ -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<used;i++)if(Math.abs(out[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);
|
||||
@@ -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<out.length&&this.length){out[used++]=this.buffer[this.read];this.read=(this.read+1)%this.buffer.length;this.length--;}
|
||||
if(this.started&&!this.ending){const ms=this.length*1000/this.rate;this.metrics.minQueueMs=this.metrics.minQueueMs===null?ms:Math.min(this.metrics.minQueueMs,ms);}
|
||||
if(used<out.length&&this.started&&!this.ending&&!this.rebuffer){
|
||||
this.rebuffer=true;this.metrics.underruns++;this.recoveryMs=Math.min(this.recoveryCapMs,this.baseRecoveryMs+(this.metrics.underruns-1)*80);this.waitAt=now+used*1000/this.rate;this.metrics.underSupplyMs+=(out.length-used)*1000/this.rate;
|
||||
}
|
||||
if(this.ending&&!this.length){
|
||||
if(this.rebuffer){this.metrics.rebufferMs+=Math.max(0,now-this.waitAt);this.rebuffer=false;}
|
||||
this.done=true;this.emit({type:'drained',turn:this.turn,metrics:this.snapshot()});
|
||||
}
|
||||
return used;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import {PlaybackBuffer} from './playback-core.js';
|
||||
export function runPlaybackTests(){
|
||||
const assert=(value,name)=>{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*8+400;t+=10){if(t%gap===0&&t/gap<8)p.push(1,new Float32Array(160).fill(.2),t);if(t===gap*7)p.end(1);p.render(block,t);}return p.snapshot();}
|
||||
const cadence=[];
|
||||
for(const gap of [170,180,190]){const low=simulate('low_latency',gap),balanced=simulate('balanced',gap);assert(balanced.underruns<low.underruns,'balanced cadence reduces underruns '+gap);assert(balanced.startBufferDelayMs>=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};
|
||||
}
|
||||
Reference in New Issue
Block a user