LoveLogicAI commited on
Commit
b93f90b
·
verified ·
1 Parent(s): 05ecbd7

Two-turn harness + transport-gap forensics; bot v12 render-pause knob

Browse files
Files changed (1) hide show
  1. tests/e2e_livekit.py +287 -413
tests/e2e_livekit.py CHANGED
@@ -1,432 +1,306 @@
1
- """FREESTREAM MVP end-to-end latency harness (win condition, docs/LATENCY.md).
2
 
3
- In ONE container: downloads livekit-server, runs it in dev mode, pulls the
4
- FREESTREAM repo from the Hub, then:
 
 
5
 
6
- 1. `freestream join` (the real CLI) spawns the bot into a LiveKit room
7
- 2. a test client connects, asks a question via a Piper-generated mic track
8
- 3. measures speech-end -> first bot audio frame (t_perceived), verifies the
9
- answer by transcribing the bot's audio, and checks the mouth moved
10
- 4. `freestream leave` (the real CLI) closes the session
11
- 5. verifies the hash-chained replay logs
12
-
13
- Win condition: agent joins, answers within 4s with a moving mouth, leaves,
14
- and generates a valid replay log.
15
-
16
- Stdlib + livekit + faster-whisper + piper-tts + pillow + numpy.
17
  """
18
 
19
  from __future__ import annotations
20
 
 
21
  import asyncio
22
  import json
23
  import os
24
- import shutil
25
- import socket
26
- import subprocess
27
  import sys
28
- import tarfile
29
  import time
30
- import urllib.request
31
- import wave
32
  from pathlib import Path
33
 
34
  import numpy as np
35
 
36
- ROOT = Path("/tmp/freestream")
37
- REPO = "https://huggingface.co/datasets/LoveLogicAI/freestream/resolve/main"
38
- VOICE_URL = ("https://huggingface.co/rhasspy/piper-voices/resolve/main/"
39
- "en/en_US/amy/medium/en_US-amy-medium{ext}")
40
- GH_LATEST = "https://api.github.com/repos/livekit/livekit-server/releases/latest"
41
-
42
- BOT_NAME = "Streamy"
43
- QUESTION = "What is your name and what can you do?"
44
- ANSWER_KEYWORDS = ("streamy", "assistant")
45
-
46
- os.environ["HF_HOME"] = "/tmp/hf"
47
- os.environ["FREESTREAM_VOICE_DIR"] = str(ROOT / "voices")
48
- os.environ["FREESTREAM_WHISPER_MODEL"] = "tiny.en" # measured best: RTF 0.25 @1 thread
49
- os.environ["FREESTREAM_WHISPER_THREADS"] = "1"
50
- os.environ["PYTHONPATH"] = str(ROOT)
51
- sys.path.insert(0, str(ROOT)) # harness imports the package below (log verification)
52
- os.environ.setdefault("FREESTREAM_LIVEKIT_URL", "ws://localhost:7880")
53
- os.environ.setdefault("FREESTREAM_LIVEKIT_KEY", "devkey")
54
- os.environ.setdefault("FREESTREAM_LIVEKIT_SECRET", "secret")
55
-
56
- results = []
57
-
58
-
59
- def check(name, ok, detail=""):
60
- results.append((name, ok))
61
- print(f"{'PASS' if ok else 'FAIL'} {name}" + (f" — {detail}" if detail else ""), flush=True)
62
-
63
-
64
- def fetch_hub(repo_id: str, filename: str, dest: Path, repo_type: str = "model"):
65
- """Token-authenticated Hub download (robust vs flaky resolve/redirect reads)."""
66
- dest.parent.mkdir(parents=True, exist_ok=True)
67
- from huggingface_hub import hf_hub_download
68
- p = hf_hub_download(repo_id=repo_id, filename=filename, repo_type=repo_type,
69
- token=os.environ.get("HF_TOKEN"))
70
- shutil.copyfile(p, dest)
71
-
72
-
73
- def fetch(url: str, dest: Path | None = None) -> bytes:
74
- with urllib.request.urlopen(url, timeout=120) as r:
75
- data = r.read()
76
- if dest is not None:
77
- dest.parent.mkdir(parents=True, exist_ok=True)
78
- dest.write_bytes(data)
79
- return data
80
-
81
-
82
- def run_cli(*args, timeout=240):
83
- return subprocess.run([sys.executable, str(ROOT / "scripts/freestream.py"), *args],
84
- cwd=str(ROOT), capture_output=True, text=True, timeout=timeout)
85
-
86
-
87
- # --------------------------------------------------------------------------- setup
88
-
89
- FILES = ["scripts/freestream.py", "requirements.txt",
90
- "freestream/__init__.py", "freestream/events.py", "freestream/presence.py",
91
- "freestream/persona.py", "freestream/mcp_server.py", "freestream/bot.py",
92
- "freestream/asr.py", "freestream/avatar.py", "freestream/agent.py"]
93
- missing = []
94
- for f in FILES:
95
- try:
96
- fetch_hub("LoveLogicAI/freestream", f, ROOT / f, repo_type="dataset")
97
- except Exception as e:
98
- missing.append((f, str(e)))
99
- check("fetch code from Hub", not missing, str(missing[:2]))
100
- if missing:
101
- sys.exit(1)
102
-
103
- # livekit-server binary
104
- lk_bin = ROOT / "livekit-server"
105
- if not lk_bin.exists():
106
- try:
107
- req = urllib.request.Request(GH_LATEST, headers={"Accept": "application/vnd.github+json"})
108
- with urllib.request.urlopen(req, timeout=60) as r:
109
- release = json.loads(r.read())
110
- asset = next(a for a in release["assets"]
111
- if "linux_amd64" in a["name"] and a["name"].endswith(".tar.gz"))
112
- tgz = ROOT / asset["name"]
113
- fetch(asset["browser_download_url"], tgz)
114
- with tarfile.open(tgz) as tf:
115
- tf.extract("livekit-server", str(ROOT))
116
- check("download livekit-server", True, release["tag_name"])
117
- except Exception as e:
118
- check("download livekit-server", False, str(e)[:200])
119
- sys.exit(1)
120
-
121
- # dev-mode config: explicit keys + loopback-friendly RTC (avoids the
122
- # known UDP bind issue in containers, per livekit issue tracker)
123
- config = ROOT / "lk.yaml"
124
- config.write_text("""
125
- port: 7880
126
- rtc:
127
- use_external_ip: false
128
- use_ice_lite: true
129
- tcp_port: 7881
130
- port_range_start: 50000
131
- port_range_end: 50100
132
- keys:
133
- devkey: secret
134
- """)
135
- server_log = open(ROOT / "server.log", "w")
136
- server = subprocess.Popen([str(lk_bin), "--config", str(config)],
137
- stdout=server_log, stderr=subprocess.STDOUT)
138
- t0 = time.perf_counter()
139
- up = False
140
- while time.perf_counter() - t0 < 30:
141
- try:
142
- with socket.create_connection(("127.0.0.1", 7880), timeout=1):
143
- up = True
144
- break
145
- except OSError:
146
- time.sleep(0.5)
147
- check("livekit-server up on :7880", up and server.poll() is None)
148
- if not up:
149
- print(open(ROOT / "server.log").read()[-1500:])
150
- sys.exit(1)
151
-
152
- # piper voice
153
- vdir = ROOT / "voices"
154
- try:
155
- for name in ("en/en_US/amy/medium/en_US-amy-medium.onnx",
156
- "en/en_US/amy/medium/en_US-amy-medium.onnx.json"):
157
- dest = vdir / Path(name).name
158
- if not dest.exists():
159
- fetch_hub("rhasspy/piper-voices", name, dest)
160
- check("download piper voice", (vdir / "en_US-amy-medium.onnx").stat().st_size > 50_000_000)
161
- except Exception as e:
162
- check("download piper voice", False, str(e)[:200])
163
- sys.exit(1)
164
-
165
- # avatar via the real CLI
166
- r = run_cli("generate-avatar", "--output", "identity/videomeeting-avatar.png")
167
- avatar_ok = r.returncode == 0 and (ROOT / "identity/videomeeting-avatar.png").stat().st_size > 1024
168
- check("generate-avatar (procedural, exit 0)", avatar_ok, r.stderr[:150] if not avatar_ok else "")
169
-
170
- # warm the whisper cache so the bot and the verifier share it
171
- # (tiny @ 2 threads is the measured optimum under the 8-core cgroup quota:
172
- # 8 threads collapsed to 39.5s vs 1.27s at 1 thread — see ml-intern-freestream-debug-perf)
173
- from faster_whisper import WhisperModel # noqa: E402
174
-
175
- t0 = time.perf_counter()
176
- WhisperModel("tiny", device="cpu", compute_type="int8", cpu_threads=2)
177
- print(f"[setup] whisper tiny int8 cached in {time.perf_counter() - t0:.1f}s", flush=True)
178
-
179
- from livekit import api, rtc # noqa: E402
180
- from piper import PiperVoice # noqa: E402
181
-
182
-
183
- # --------------------------------------------------------------------------- join via CLI
184
-
185
-
186
- def attempt_join(timeout_sec):
187
- proc = subprocess.Popen(
188
- [sys.executable, str(ROOT / "scripts/freestream.py"), "join",
189
- "--meet-url", "https://livekit.local/qa-room", "--platform", "livekit",
190
- "--bot-name", BOT_NAME, "--image", "identity/videomeeting-avatar.png",
191
- "--timeout-sec", str(timeout_sec)],
192
- cwd=str(ROOT), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
193
- t0 = time.perf_counter()
194
- sid, ready = None, False
195
- for line in proc.stdout:
196
- try:
197
- d = json.loads(line)
198
- except ValueError:
199
- continue
200
- if "session_id" in d and sid is None:
201
- sid = d["session_id"]
202
- if d.get("status") == "ready":
203
- ready = True
204
- break
205
- return proc, sid, ready, time.perf_counter() - t0
206
-
207
-
208
- def dump_session_files(sid):
209
- if not sid:
210
- return
211
- sd = ROOT / ".freestream/sessions" / sid
212
- for name in ("bot.err", "bot.out", "state.json", "driver.json"):
213
- f = sd / name
214
- if f.exists():
215
- print(f"--- session {name} ---\n{f.read_text()[-2500:]}", flush=True)
216
-
217
-
218
- join_proc, session_id, ready, t_ready = attempt_join(90)
219
- if not ready:
220
- print(f"[harness] join attempt 1 timed out (t={t_ready:.1f}s); dumping bot output", flush=True)
221
- dump_session_files(session_id)
222
- print("[harness] retrying join once...", flush=True)
223
- join_proc, session_id, ready, t_ready = attempt_join(90)
224
-
225
- check(f"CLI join -> ready (session {session_id})", ready and join_proc.poll() is None,
226
- f"t_ready={t_ready:.1f}s")
227
- if not ready:
228
- dump_session_files(session_id)
229
- print(join_proc.stderr.read()[:800])
230
- sys.exit(1)
231
-
232
- # --------------------------------------------------------------------------- test client
233
-
234
- token = (api.AccessToken("devkey", "secret")
235
- .with_identity("tester").with_name("Tester")
236
- .with_grants(api.VideoGrants(room_join=True, room="qa-room",
237
- can_publish=True, can_subscribe=True)).to_jwt())
238
-
239
-
240
- async def test_client():
241
- room = rtc.Room()
242
- bot_audio = {"chunks": [], "first_arrival": None, "last_arrival": None}
243
- video_diffs = {"times": [], "diffs": []}
244
-
245
- @room.on("track_subscribed")
246
- def on_track(track, publication, participant):
247
- if track.kind == rtc.TrackKind.KIND_AUDIO:
248
- asyncio.ensure_future(record_audio(track))
249
- else:
250
- asyncio.ensure_future(sample_video(track))
251
-
252
- async def record_audio(track):
253
- stream = rtc.AudioStream(track, sample_rate=16000, num_channels=1)
254
- async for ev in stream:
255
- pcm = np.frombuffer(ev.frame.data, dtype=np.int16)
256
- # the bot's audio track idles with zero-frames between turns;
257
- # gate arrivals on real speech energy so t_perceived is honest
258
- rms = float(np.sqrt(np.mean(pcm.astype(np.float32) ** 2))) / 32768.0
259
- if rms < 0.004:
260
  continue
 
 
 
 
 
261
  now = time.perf_counter()
262
- if bot_audio["first_arrival"] is None:
263
- bot_audio["first_arrival"] = now
264
- print(f"[client] first bot AUDIO (speech) at {now:.3f}", flush=True)
265
- bot_audio["last_arrival"] = now
266
- bot_audio["chunks"].append(pcm)
267
-
268
- async def sample_video(track):
269
- last_img = None
270
- stream = rtc.VideoStream(track)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  async for ev in stream:
272
- f = ev.frame
273
- w, h = f.width, f.height
274
- data = bytes(f.data)
275
- if len(data) >= w * h * 1.5 and len(data) < w * h * 4: # I420 → luminance plane
276
- img = np.frombuffer(data[: w * h], dtype=np.uint8)
277
- elif len(data) == w * h * 4: # RGBA → luma approx
278
- rgba = np.frombuffer(data, dtype=np.uint8).reshape(h, w, 4)
279
- img = rgba[:, :, :3].mean(axis=2).astype(np.uint8).ravel()
280
- else:
281
- continue
282
- now = time.perf_counter()
283
- if last_img is not None and len(img) == len(last_img):
284
- video_diffs["times"].append(now)
285
- video_diffs["diffs"].append(float(np.abs(img.astype(np.int16)
286
- - last_img.astype(np.int16)).mean()))
287
- last_img = img
288
-
289
- await room.connect("ws://localhost:7880", token,
290
- options=rtc.RoomOptions(auto_subscribe=True))
291
- await asyncio.sleep(2.0) # ensure bot tracks subscribed
292
-
293
- # synthesize the question
294
- voice = PiperVoice.load(str(ROOT / "voices/en_US-amy-medium.onnx"))
295
- chunks = list(voice.synthesize(QUESTION))
296
- q_pcm = np.concatenate([np.frombuffer(c.audio_int16_bytes, dtype=np.int16)
297
- for c in chunks])
298
- q_sr = int(json.loads((ROOT / "voices/en_US-amy-medium.onnx.json").read_text())
299
- ["audio"]["sample_rate"])
300
- wav = wave.open("/tmp/question.wav", "wb")
301
- wav.setnchannels(1); wav.setsampwidth(2); wav.setframerate(q_sr)
302
- wav.writeframes(q_pcm.tobytes()); wav.close()
303
-
304
- source = rtc.AudioSource(q_sr, 1)
305
- track = rtc.LocalAudioTrack.create_audio_track("tester-mic", source)
306
- opts = rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_MICROPHONE)
307
- await room.local_participant.publish_track(track, opts)
308
-
309
- chunk = int(q_sr * 0.01)
310
- t0 = None
311
- for i in range(0, len(q_pcm), chunk):
312
- piece = q_pcm[i : i + chunk]
313
- frame = rtc.AudioFrame.create(q_sr, 1, len(piece))
314
- np.copyto(np.frombuffer(frame.data, dtype=np.int16), piece)
315
- await source.capture_frame(frame)
316
- if t0 is None:
317
- t0 = time.perf_counter()
318
- t_speech_end = time.perf_counter()
319
- print(f"[client] question pushed, speech end at {t_speech_end:.3f}", flush=True)
320
-
321
- # wait for the bot's answer: first audio + until silence (bounded — a
322
- # silent bot must fail the harness, not hang it)
323
- while bot_audio["first_arrival"] is None:
324
- await asyncio.sleep(0.05)
325
- if time.perf_counter() - t_speech_end > 45:
326
- break
327
- if bot_audio["first_arrival"] is None:
328
- print("[client] NO bot audio within 45s of speech end", flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  await room.disconnect()
330
- return {"t_perceived": 999.0, "answer_s": 0.0, "answer_text": "",
331
- "t_ready": t_ready, "no_answer": True}
332
- t_perceived = bot_audio["first_arrival"] - t_speech_end
333
- while time.perf_counter() - bot_audio["last_arrival"] < 4.0:
334
- await asyncio.sleep(0.1)
335
- if time.perf_counter() - t_speech_end > 60:
336
- break
337
- answer_s = (bot_audio["last_arrival"] - bot_audio["first_arrival"])
338
-
339
- bot_pcm = np.concatenate(bot_audio["chunks"]) if bot_audio["chunks"] else np.zeros(0, np.int16)
340
- wav = wave.open("/tmp/answer.wav", "wb")
341
- wav.setnchannels(1); wav.setsampwidth(2); wav.setframerate(16000)
342
- wav.writeframes(bot_pcm.tobytes()); wav.close()
343
-
344
- # verify the answer by transcribing it (same model profile as the bot)
345
- model = WhisperModel("tiny", device="cpu", compute_type="int8", cpu_threads=2)
346
- segments, _ = model.transcribe(bot_pcm.astype(np.float32) / 32768.0, language="en")
347
- answer_text = " ".join(s.text.strip() for s in segments).strip()
348
- lower = answer_text.lower()
349
- kw_ok = any(k in lower for k in ANSWER_KEYWORDS)
350
- check("bot answered (transcript contains keyword)", kw_ok, answer_text[:160])
351
-
352
- # mouth movement during the answer
353
- last_arr = bot_audio["last_arrival"] or t_speech_end
354
- window = [d for t, d in zip(video_diffs["times"], video_diffs["diffs"])
355
- if t_speech_end <= t <= last_arr + 0.5]
356
- moving = len(window) > 5 and sorted(window)[len(window) // 2] > 0.3
357
- check("avatar mouth moved during speech", moving,
358
- f"{len(window)} frames, median diff {sorted(window)[len(window)//2] if window else 0:.2f}")
359
-
360
- await room.disconnect()
361
- return {"t_perceived": t_perceived, "answer_s": answer_s,
362
- "answer_text": answer_text, "t_ready": t_ready}
363
-
364
-
365
- timings = asyncio.run(test_client())
366
-
367
- # bot forensics — always, success or failure
368
- sdir0 = ROOT / ".freestream/sessions" / session_id
369
- for name in ("bot.err", "bot.out"):
370
- f = sdir0 / name
371
- if f.exists() and f.stat().st_size > 0:
372
- print(f"\n--- {name} (tail) ---\n{f.read_text()[-1500:]}", flush=True)
373
-
374
- # --------------------------------------------------------------------------- leave via CLI
375
-
376
- r = run_cli("leave", "--session-id", session_id)
377
- out = {}
378
- try:
379
- out = json.loads(r.stdout.strip().splitlines()[-1])
380
- except (ValueError, IndexError):
381
- pass
382
- check("CLI leave exits 0 with closed:true", r.returncode == 0 and out.get("closed") is True,
383
- f"rc={r.returncode} out={str(out)[:100]}")
384
-
385
- # replay logs valid
386
- from freestream.events import EventLog # noqa: E402
387
-
388
- sdir = ROOT / ".freestream/sessions" / session_id
389
- cli_ok, cli_bad = EventLog(sdir / "events.jsonl").verify()
390
- bot_ok, bot_bad = EventLog(sdir / "bot-events.jsonl").verify()
391
- check("CLI event log verifies", cli_ok, f"bad_seq={cli_bad}")
392
- check("bot event log verifies", bot_ok, f"bad_seq={bot_bad}")
393
-
394
- # --------------------------------------------------------------------------- summary
395
-
396
- print("\n--- latency (speech-end -> first bot audio at client) ---", flush=True)
397
- print(f"t_ready (CLI join -> bot ready): {timings['t_ready']:.2f}s")
398
- print(f"t_perceived (WIN CONDITION <= 4.0s): {timings['t_perceived']:.2f}s"
399
- f" {'PASS' if timings['t_perceived'] <= 4.0 else 'FAIL'}")
400
- print(f"bot answer duration: {timings['answer_s']:.2f}s")
401
- print(f"answer transcript: {timings['answer_text'][:200]}")
402
- try:
403
- bot_log = EventLog(ROOT / ".freestream/sessions" / session_id / "bot-events.jsonl").events()
404
- synth = [e for e in bot_log if e["type"] == "tts.synthesized"]
405
- turns = [e for e in bot_log if e["type"] == "turn.completed"]
406
- if synth:
407
- print(f"bot-side tts synth time: {synth[-1]['payload']['seconds']}s")
408
- if turns:
409
- print(f"bot-side turn total (speech-end -> done): {turns[-1]['payload']['total_s']}s")
410
- print("\n--- what the bot heard and said (bot-events.jsonl) ---")
411
- for e in bot_log:
412
- if e["type"] in ("asr.final", "agent.speak"):
413
- extra = e["payload"].get("seconds")
414
- print(f" {e['type']:12s} ts=+{e['ts'] % 1000:8.2f}s"
415
- + (f" (asr {extra}s)" if extra else "")
416
- + f" {e['payload'].get('text', '')[:140]}")
417
- elif e["type"] in ("turn.completed", "session.error"):
418
- print(f" {e['type']:12s} {e['payload']}")
419
- except Exception as e:
420
- print(f"bot log summary skipped: {e}")
421
-
422
- # server shutdown
423
- server.terminate()
424
-
425
- failed = [n for n, ok in results if not ok]
426
- win = timings["t_perceived"] <= 4.0
427
- print(f"\n{len(results) - len(failed)}/{len(results)} checks passed"
428
- + ("" if win else "; WIN CONDITION MISSED"))
429
- if failed or not win:
430
- print("FAILED: " + ", ".join(failed + ([] if win else ["t_perceived > 4s"])))
431
- sys.exit(1)
432
- print("E2E OK — WIN CONDITION MET")
 
1
+ """FREESTREAM bot — the MVP LiveKit session process (run with -m freestream.bot).
2
 
3
+ One bot = one LiveKit session:
4
+ join room -> publish mic (Piper audio) + camera (animated face) tracks
5
+ -> subscribe remote audio -> energy-VAD -> faster-whisper -> agent reply
6
+ -> Piper synthesis -> audio push with 150ms avatar pre-roll.
7
 
8
+ Status protocol: JSON lines on stdout ("status"/"timing" events) plus
9
+ state.json in the session dir (what the CLI polls). SIGTERM closes the
10
+ session gracefully.
 
 
 
 
 
 
 
 
11
  """
12
 
13
  from __future__ import annotations
14
 
15
+ import argparse
16
  import asyncio
17
  import json
18
  import os
19
+ import signal
 
 
20
  import sys
 
21
  import time
 
 
22
  from pathlib import Path
23
 
24
  import numpy as np
25
 
26
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
27
+
28
+ from freestream import avatar as avatar_mod
29
+ from freestream.agent import load_agent
30
+ from freestream.asr import Segmenter, Transcriber
31
+ from freestream.events import EventLog
32
+ from freestream.persona import VoiceBackend
33
+
34
+ AVATAR_FPS = avatar_mod.FPS
35
+ PRE_ROLL_S = 0.15
36
+ IDLE_FPS = 2 # static face refresh when not speaking
37
+
38
+
39
+ def emit(obj: dict):
40
+ print(json.dumps(obj), flush=True)
41
+
42
+
43
+ class BotSession:
44
+ def __init__(self, url: str, token: str, room_name: str, bot_name: str,
45
+ image: Path, voice: str, session_dir: Path, session_id: str,
46
+ system_prompt: str | None):
47
+ self.url, self.token, self.room_name = url, token, room_name
48
+ self.bot_name = bot_name
49
+ self.image = image
50
+ self.voice_backend = VoiceBackend(voice)
51
+ self.session_dir = Path(session_dir)
52
+ self.session_dir.mkdir(parents=True, exist_ok=True)
53
+ self.session_id = session_id
54
+ self.state = "connecting"
55
+ self.log = EventLog(self.session_dir / "bot-events.jsonl") # separate chain from the CLI log
56
+ self.agent = load_agent(system_prompt, bot_name)
57
+ self.renderer = avatar_mod.AvatarRenderer(image if image.exists() else None)
58
+ self.mouth = 0.0 # current openness, driven by the speak loop
59
+ self.speaking_until = 0.0
60
+ self.transcriber = Transcriber()
61
+ self.segmenter = Segmenter()
62
+ self.first_utterance_done = False
63
+ self.disclosure_segment = None # (pcm, sr) consent line, cached at warmup
64
+
65
+ # -- state ---------------------------------------------------------------
66
+ def set_state(self, s: str, **extra):
67
+ self.state = s
68
+ payload = {"session_id": self.session_id, "status": s, **extra}
69
+ (self.session_dir / "state.json").write_text(json.dumps(payload))
70
+ self.log.append("session.status", status=s)
71
+ emit({"event": "status", **payload})
72
+
73
+ # -- tracks ---------------------------------------------------------------
74
+ async def publish_tracks(self, room):
75
+ import livekit.rtc as rtc
76
+
77
+ # camera
78
+ self.video_source = rtc.VideoSource(avatar_mod.SIZE, avatar_mod.SIZE)
79
+ vtrack = rtc.LocalVideoTrack.create_video_track("freestream-face", self.video_source)
80
+ vopts = rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_CAMERA)
81
+ vopts.video_encoding.max_framerate = float(AVATAR_FPS) # proto message: set subfields,
82
+ vopts.video_encoding.max_bitrate = 800_000 # not the whole sub-message
83
+ await room.local_participant.publish_track(vtrack, vopts)
84
+
85
+ # microphone
86
+ self.audio_source = rtc.AudioSource(22050, 1)
87
+ atrack = rtc.LocalAudioTrack.create_audio_track("freestream-voice", self.audio_source)
88
+ aopts = rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_MICROPHONE)
89
+ await room.local_participant.publish_track(atrack, aopts)
90
+
91
+ async def video_loop(self):
92
+ """Render the face continuously; mouth openness follows speech energy.
93
+
94
+ FREESTREAM_PAUSE_RENDER=1 skips rendering while the bot is not
95
+ speaking (thinking/ASR) — experiment knob for in-context contention.
96
+ """
97
+ import livekit.rtc as rtc
98
+
99
+ pause_render = os.environ.get("FREESTREAM_PAUSE_RENDER") == "1"
100
+ frame_us = int(1e6 / (AVATAR_FPS if self.mouth > 0 else IDLE_FPS))
101
+ last = time.perf_counter()
102
+ while True:
103
+ if pause_render and self.mouth <= 0 and time.perf_counter() >= self.speaking_until:
104
+ await asyncio.sleep(0.25) # idle: no render, no encode work
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  continue
106
+ img = self.renderer.frame(self.mouth)
107
+ rgba = np.ascontiguousarray(np.asarray(img))
108
+ vf = rtc.VideoFrame(avatar_mod.SIZE, avatar_mod.SIZE,
109
+ rtc.VideoBufferType.RGBA, rgba.tobytes())
110
+ self.video_source.capture_frame(vf, timestamp_us=int(time.time() * 1e6))
111
  now = time.perf_counter()
112
+ fps = AVATAR_FPS if time.perf_counter() < self.speaking_until or self.mouth > 0 else IDLE_FPS
113
+ await asyncio.sleep(max(0.0, 1.0 / fps - (now - last)))
114
+ last = time.perf_counter()
115
+
116
+ async def push_audio(self, pcm: np.ndarray, sr: int):
117
+ import livekit.rtc as rtc
118
+
119
+ chunk = int(sr * 0.01) # 10ms
120
+ for i in range(0, len(pcm), chunk):
121
+ piece = pcm[i : i + chunk]
122
+ frame = rtc.AudioFrame.create(sr, 1, len(piece))
123
+ np.copyto(np.frombuffer(frame.data, dtype=np.int16), piece)
124
+ await self.audio_source.capture_frame(frame)
125
+
126
+ async def speak(self, text: str, pre_segment=None, **timing):
127
+ """Pipelined sentence synthesis (docs/LATENCY.md #2): playback starts
128
+ while later sentences are still synthesizing. pre_segment is an
129
+ optional (pcm, sr) already synthesized at session start — the fixed
130
+ consent disclosure — so the first audible output pays no synth cost."""
131
+ import re
132
+
133
+ sentences = [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]
134
+ if not sentences:
135
+ sentences = [text]
136
+ t0 = timing["t0"]
137
+ first_audio = None
138
+ total_audio = 0.0
139
+ total_chars = 0
140
+
141
+ rest_q: asyncio.Queue = asyncio.Queue()
142
+
143
+ async def synth_rest():
144
+ for s in sentences:
145
+ p, r = await asyncio.to_thread(self.voice_backend.synthesize, s)
146
+ await rest_q.put((p, r, len(s)))
147
+ await rest_q.put(None)
148
+
149
+ rest_task = asyncio.create_task(synth_rest()) # synthesizes while we play
150
+
151
+ async def play_one(pcm_i, sr_i, chars):
152
+ nonlocal total_audio, total_chars, first_audio
153
+ mouth = avatar_mod.build_mouth_sequence(pcm_i, sr_i)
154
+ duration = len(pcm_i) / sr_i
155
+ total_audio += duration
156
+ total_chars += chars
157
+ self.speaking_until = time.perf_counter() + duration + 0.3
158
+
159
+ async def mouth_driver(seq=mouth):
160
+ for openness in seq:
161
+ self.mouth = float(openness)
162
+ await asyncio.sleep(1.0 / AVATAR_FPS)
163
+ self.mouth = 0.0
164
+
165
+ task = asyncio.create_task(mouth_driver())
166
+ if first_audio is None:
167
+ await asyncio.sleep(PRE_ROLL_S) # avatar starts moving first
168
+ first_audio = time.perf_counter()
169
+ # absolute wall-clock, cross-process comparable with the harness
170
+ emit({"event": "timing", "session_id": self.session_id,
171
+ "abs_first_push": time.time()})
172
+ await self.push_audio(pcm_i, sr_i)
173
+ await task
174
+
175
+ if pre_segment is not None:
176
+ await play_one(pre_segment[0], pre_segment[1], 0)
177
+ while True:
178
+ item = await rest_q.get()
179
+ if item is None:
180
+ break
181
+ p, r, chars = item
182
+ await play_one(p, r, chars)
183
+ await rest_task
184
+ if first_audio is None:
185
+ raise RuntimeError("synthesis produced no audio")
186
+ self.log.append("tts.synthesized", text=text, chars=total_chars,
187
+ backend="piper", seconds=round(first_audio - t0, 3),
188
+ sentences=len(sentences), pre_cached=pre_segment is not None)
189
+ emit({"event": "timing", "session_id": self.session_id,
190
+ "tts_first_s": round(first_audio - t0, 3),
191
+ "spoken_chars": total_chars, "audio_s": round(total_audio, 3)})
192
+
193
+ # -- receive loop ----------------------------------------------------------
194
+ async def on_track(self, room, track, publication, participant):
195
+ import livekit.rtc as rtc
196
+
197
+ if track.kind != rtc.TrackKind.KIND_AUDIO:
198
+ return
199
+ stream = rtc.AudioStream(track, sample_rate=16000, num_channels=1)
200
  async for ev in stream:
201
+ pcm = np.frombuffer(ev.frame.data, dtype=np.int16).astype(np.float32) / 32768.0
202
+ for utt in self.segmenter.feed(pcm):
203
+ await self.handle_utterance(utt)
204
+
205
+ async def handle_utterance(self, utt: np.ndarray):
206
+ t_speech_end = time.perf_counter()
207
+ self.set_state("thinking")
208
+ text, asr_s = await asyncio.to_thread(self.transcriber.transcribe, utt)
209
+ t_asr = time.perf_counter()
210
+ if not text:
211
+ self.set_state("listening")
212
+ return
213
+ self.log.append("asr.final", text=text, seconds=round(asr_s, 3),
214
+ audio_s=round(len(utt) / 16000, 2))
215
+ reply = self.agent.reply(text)
216
+ pre = None
217
+ if not self.first_utterance_done:
218
+ pre = self.disclosure_segment # cached consent line, zero synth cost
219
+ self.first_utterance_done = True
220
+ self.log.append("agent.speak", text=reply)
221
+ self.set_state("speaking")
222
+ try:
223
+ await self.speak(reply, pre_segment=pre, t0=t_speech_end)
224
+ except Exception as e: # noqa: BLE001 — surface as session error, keep bot alive
225
+ import traceback
226
+ self.log.append("session.error", error=str(e)[:200],
227
+ traceback=traceback.format_exc()[-600:])
228
+ self.set_state("listening")
229
+ return
230
+ total = time.perf_counter() - t_speech_end
231
+ self.log.append("turn.completed", total_s=round(total, 3),
232
+ asr_s=round(t_asr - t_speech_end, 3))
233
+ self.set_state("listening")
234
+
235
+ # -- lifecycle ---------------------------------------------------------------
236
+ async def run(self):
237
+ import livekit.rtc as rtc
238
+
239
+ room = rtc.Room()
240
+ self.set_state("connecting")
241
+ await room.connect(self.url, self.token,
242
+ options=rtc.RoomOptions(auto_subscribe=True))
243
+ t_connected = time.perf_counter()
244
+ await self.publish_tracks(room)
245
+ # Warm identity assets before reporting ready, so the first turn
246
+ # doesn't pay whisper/piper model-load cost (docs/LATENCY.md #4).
247
+ try:
248
+ await asyncio.to_thread(self.transcriber._load)
249
+ await asyncio.to_thread(self.voice_backend.synthesize, "Warmup.")
250
+ # Pre-synthesize the fixed consent disclosure (CONSENT.md #2): it is
251
+ # static text, so the first turn's first audio never pays Piper's
252
+ # in-context synth latency (measured RTF ~1.2 in-process).
253
+ self.disclosure_segment = await asyncio.to_thread(
254
+ self.voice_backend.synthesize, self.agent.first_utterance())
255
+ except Exception as e: # noqa: BLE001
256
+ self.log.append("session.error", error=f"warmup failed: {e}")
257
+ self.set_state("error", error=str(e)[:200])
258
+ return
259
+ self.set_state("ready", video_published=True, room=self.room_name)
260
+
261
+ @room.on("track_subscribed")
262
+ def _on_track(track, publication, participant):
263
+ asyncio.ensure_future(self.on_track(room, track, publication, participant))
264
+
265
+ video_task = asyncio.create_task(self.video_loop())
266
+
267
+ stop = asyncio.Event()
268
+ loop = asyncio.get_event_loop()
269
+ for sig in (signal.SIGTERM, signal.SIGINT):
270
+ loop.add_signal_handler(sig, stop.set)
271
+
272
+ emit({"event": "timing", "session_id": self.session_id,
273
+ "join_s": round(time.perf_counter() - t_connected, 3)})
274
+ await stop.wait()
275
+ self.set_state("closed")
276
  await room.disconnect()
277
+ video_task.cancel()
278
+
279
+
280
+ def main():
281
+ # Measured (ml-intern-freestream-debug-perf): piper's default ONNX session
282
+ # runs at RTF 0.33-0.65 while an OMP_NUM_THREADS=8 override degraded the
283
+ # bot to RTF ~1.5 — do not set OMP threads for onnxruntime here.
284
+ p = argparse.ArgumentParser(prog="freestream-bot")
285
+ p.add_argument("--url", required=True)
286
+ p.add_argument("--token", required=True)
287
+ p.add_argument("--room", required=True)
288
+ p.add_argument("--bot-name", required=True)
289
+ p.add_argument("--image", required=True)
290
+ p.add_argument("--voice", required=True)
291
+ p.add_argument("--session-id", required=True)
292
+ p.add_argument("--session-dir", required=True)
293
+ p.add_argument("--system-prompt", default=None)
294
+ args = p.parse_args()
295
+
296
+ session = BotSession(args.url, args.token, args.room, args.bot_name,
297
+ Path(args.image), args.voice, Path(args.session_dir),
298
+ args.session_id, args.system_prompt)
299
+ try:
300
+ asyncio.run(session.run())
301
+ except KeyboardInterrupt:
302
+ pass
303
+
304
+
305
+ if __name__ == "__main__":
306
+ main()