LoveLogicAI commited on
Commit
c302c17
·
verified ·
1 Parent(s): d20808f

Absolute first-push timestamp + FREESTREAM_PAUSE_RENDER knob (correct path)

Browse files
Files changed (1) hide show
  1. freestream/bot.py +286 -439
freestream/bot.py CHANGED
@@ -1,459 +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
- QUESTION2 = "What can you do?"
46
- ANSWER_KEYWORDS2 = ("avatar", "listen", "voice")
47
-
48
- os.environ["HF_HOME"] = "/tmp/hf"
49
- os.environ["FREESTREAM_VOICE_DIR"] = str(ROOT / "voices")
50
- os.environ["FREESTREAM_WHISPER_MODEL"] = "tiny.en" # measured best: RTF 0.25 @1 thread
51
- os.environ["FREESTREAM_WHISPER_THREADS"] = "1"
52
- os.environ["PYTHONPATH"] = str(ROOT)
53
- sys.path.insert(0, str(ROOT)) # harness imports the package below (log verification)
54
- os.environ.setdefault("FREESTREAM_LIVEKIT_URL", "ws://localhost:7880")
55
- os.environ.setdefault("FREESTREAM_LIVEKIT_KEY", "devkey")
56
- os.environ.setdefault("FREESTREAM_LIVEKIT_SECRET", "secret")
57
-
58
- results = []
59
-
60
-
61
- def check(name, ok, detail=""):
62
- results.append((name, ok))
63
- print(f"{'PASS' if ok else 'FAIL'} {name}" + (f" — {detail}" if detail else ""), flush=True)
64
-
65
-
66
- def fetch_hub(repo_id: str, filename: str, dest: Path, repo_type: str = "model"):
67
- """Token-authenticated Hub download (robust vs flaky resolve/redirect reads)."""
68
- dest.parent.mkdir(parents=True, exist_ok=True)
69
- from huggingface_hub import hf_hub_download
70
- p = hf_hub_download(repo_id=repo_id, filename=filename, repo_type=repo_type,
71
- token=os.environ.get("HF_TOKEN"))
72
- shutil.copyfile(p, dest)
73
-
74
-
75
- def fetch(url: str, dest: Path | None = None) -> bytes:
76
- with urllib.request.urlopen(url, timeout=120) as r:
77
- data = r.read()
78
- if dest is not None:
79
- dest.parent.mkdir(parents=True, exist_ok=True)
80
- dest.write_bytes(data)
81
- return data
82
-
83
-
84
- def run_cli(*args, timeout=240):
85
- return subprocess.run([sys.executable, str(ROOT / "scripts/freestream.py"), *args],
86
- cwd=str(ROOT), capture_output=True, text=True, timeout=timeout)
87
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
- # --------------------------------------------------------------------------- setup
 
90
 
91
- FILES = ["scripts/freestream.py", "requirements.txt",
92
- "freestream/__init__.py", "freestream/events.py", "freestream/presence.py",
93
- "freestream/persona.py", "freestream/mcp_server.py", "freestream/bot.py",
94
- "freestream/asr.py", "freestream/avatar.py", "freestream/agent.py"]
95
- missing = []
96
- for f in FILES:
97
- try:
98
- fetch_hub("LoveLogicAI/freestream", f, ROOT / f, repo_type="dataset")
99
- except Exception as e:
100
- missing.append((f, str(e)))
101
- check("fetch code from Hub", not missing, str(missing[:2]))
102
- if missing:
103
- sys.exit(1)
104
-
105
- # livekit-server binary
106
- lk_bin = ROOT / "livekit-server"
107
- if not lk_bin.exists():
108
- try:
109
- req = urllib.request.Request(GH_LATEST, headers={"Accept": "application/vnd.github+json"})
110
- with urllib.request.urlopen(req, timeout=60) as r:
111
- release = json.loads(r.read())
112
- asset = next(a for a in release["assets"]
113
- if "linux_amd64" in a["name"] and a["name"].endswith(".tar.gz"))
114
- tgz = ROOT / asset["name"]
115
- fetch(asset["browser_download_url"], tgz)
116
- with tarfile.open(tgz) as tf:
117
- tf.extract("livekit-server", str(ROOT))
118
- check("download livekit-server", True, release["tag_name"])
119
- except Exception as e:
120
- check("download livekit-server", False, str(e)[:200])
121
- sys.exit(1)
122
-
123
- # dev-mode config: explicit keys + loopback-friendly RTC (avoids the
124
- # known UDP bind issue in containers, per livekit issue tracker)
125
- config = ROOT / "lk.yaml"
126
- config.write_text("""
127
- port: 7880
128
- rtc:
129
- use_external_ip: false
130
- use_ice_lite: true
131
- tcp_port: 7881
132
- port_range_start: 50000
133
- port_range_end: 50100
134
- keys:
135
- devkey: secret
136
- """)
137
- server_log = open(ROOT / "server.log", "w")
138
- server = subprocess.Popen([str(lk_bin), "--config", str(config)],
139
- stdout=server_log, stderr=subprocess.STDOUT)
140
- t0 = time.perf_counter()
141
- up = False
142
- while time.perf_counter() - t0 < 30:
143
- try:
144
- with socket.create_connection(("127.0.0.1", 7880), timeout=1):
145
- up = True
146
- break
147
- except OSError:
148
- time.sleep(0.5)
149
- check("livekit-server up on :7880", up and server.poll() is None)
150
- if not up:
151
- print(open(ROOT / "server.log").read()[-1500:])
152
- sys.exit(1)
153
-
154
- # piper voice
155
- vdir = ROOT / "voices"
156
- try:
157
- for name in ("en/en_US/amy/medium/en_US-amy-medium.onnx",
158
- "en/en_US/amy/medium/en_US-amy-medium.onnx.json"):
159
- dest = vdir / Path(name).name
160
- if not dest.exists():
161
- fetch_hub("rhasspy/piper-voices", name, dest)
162
- check("download piper voice", (vdir / "en_US-amy-medium.onnx").stat().st_size > 50_000_000)
163
- except Exception as e:
164
- check("download piper voice", False, str(e)[:200])
165
- sys.exit(1)
166
-
167
- # avatar via the real CLI
168
- r = run_cli("generate-avatar", "--output", "identity/videomeeting-avatar.png")
169
- avatar_ok = r.returncode == 0 and (ROOT / "identity/videomeeting-avatar.png").stat().st_size > 1024
170
- check("generate-avatar (procedural, exit 0)", avatar_ok, r.stderr[:150] if not avatar_ok else "")
171
-
172
- # warm the whisper cache so the bot and the verifier share it
173
- # (tiny @ 2 threads is the measured optimum under the 8-core cgroup quota:
174
- # 8 threads collapsed to 39.5s vs 1.27s at 1 thread — see ml-intern-freestream-debug-perf)
175
- from faster_whisper import WhisperModel # noqa: E402
176
-
177
- t0 = time.perf_counter()
178
- WhisperModel("tiny", device="cpu", compute_type="int8", cpu_threads=2)
179
- print(f"[setup] whisper tiny int8 cached in {time.perf_counter() - t0:.1f}s", flush=True)
180
-
181
- from livekit import api, rtc # noqa: E402
182
- from piper import PiperVoice # noqa: E402
183
-
184
-
185
- # --------------------------------------------------------------------------- join via CLI
186
-
187
-
188
- def attempt_join(timeout_sec):
189
- proc = subprocess.Popen(
190
- [sys.executable, str(ROOT / "scripts/freestream.py"), "join",
191
- "--meet-url", "https://livekit.local/qa-room", "--platform", "livekit",
192
- "--bot-name", BOT_NAME, "--image", "identity/videomeeting-avatar.png",
193
- "--timeout-sec", str(timeout_sec)],
194
- cwd=str(ROOT), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
195
- t0 = time.perf_counter()
196
- sid, ready = None, False
197
- for line in proc.stdout:
198
- try:
199
- d = json.loads(line)
200
- except ValueError:
201
- continue
202
- if "session_id" in d and sid is None:
203
- sid = d["session_id"]
204
- if d.get("status") == "ready":
205
- ready = True
206
- break
207
- return proc, sid, ready, time.perf_counter() - t0
208
-
209
-
210
- def dump_session_files(sid):
211
- if not sid:
212
- return
213
- sd = ROOT / ".freestream/sessions" / sid
214
- for name in ("bot.err", "bot.out", "state.json", "driver.json"):
215
- f = sd / name
216
- if f.exists():
217
- print(f"--- session {name} ---\n{f.read_text()[-2500:]}", flush=True)
218
-
219
-
220
- join_proc, session_id, ready, t_ready = attempt_join(90)
221
- if not ready:
222
- print(f"[harness] join attempt 1 timed out (t={t_ready:.1f}s); dumping bot output", flush=True)
223
- dump_session_files(session_id)
224
- print("[harness] retrying join once...", flush=True)
225
- join_proc, session_id, ready, t_ready = attempt_join(90)
226
-
227
- check(f"CLI join -> ready (session {session_id})", ready and join_proc.poll() is None,
228
- f"t_ready={t_ready:.1f}s")
229
- if not ready:
230
- dump_session_files(session_id)
231
- print(join_proc.stderr.read()[:800])
232
- sys.exit(1)
233
-
234
- # --------------------------------------------------------------------------- test client
235
-
236
- token = (api.AccessToken("devkey", "secret")
237
- .with_identity("tester").with_name("Tester")
238
- .with_grants(api.VideoGrants(room_join=True, room="qa-room",
239
- can_publish=True, can_subscribe=True)).to_jwt())
240
-
241
-
242
- async def test_client():
243
- room = rtc.Room()
244
- bot_audio = {"chunks": [], "first_arrival": None, "last_arrival": None}
245
- video_diffs = {"times": [], "diffs": []}
246
-
247
- @room.on("track_subscribed")
248
- def on_track(track, publication, participant):
249
- if track.kind == rtc.TrackKind.KIND_AUDIO:
250
- asyncio.ensure_future(record_audio(track))
251
- else:
252
- asyncio.ensure_future(sample_video(track))
253
-
254
- async def record_audio(track):
255
  stream = rtc.AudioStream(track, sample_rate=16000, num_channels=1)
256
  async for ev in stream:
257
- pcm = np.frombuffer(ev.frame.data, dtype=np.int16)
258
- # the bot's audio track idles with zero-frames between turns;
259
- # gate arrivals on real speech energy so t_perceived is honest
260
- rms = float(np.sqrt(np.mean(pcm.astype(np.float32) ** 2))) / 32768.0
261
- if rms < 0.004:
262
- continue
263
- now = time.perf_counter()
264
- if bot_audio["first_arrival"] is None:
265
- bot_audio["first_arrival"] = now
266
- bot_audio["first_arrival_abs"] = time.time()
267
- print(f"[client] first bot AUDIO (speech) at {now:.3f} "
268
- f"(abs {time.time():.3f})", flush=True)
269
- bot_audio["last_arrival"] = now
270
- bot_audio["chunks"].append(pcm)
271
-
272
- async def sample_video(track):
273
- last_img = None
274
- stream = rtc.VideoStream(track)
275
- async for ev in stream:
276
- f = ev.frame
277
- w, h = f.width, f.height
278
- data = bytes(f.data)
279
- if len(data) >= w * h * 1.5 and len(data) < w * h * 4: # I420 → luminance plane
280
- img = np.frombuffer(data[: w * h], dtype=np.uint8)
281
- elif len(data) == w * h * 4: # RGBA → luma approx
282
- rgba = np.frombuffer(data, dtype=np.uint8).reshape(h, w, 4)
283
- img = rgba[:, :, :3].mean(axis=2).astype(np.uint8).ravel()
284
- else:
285
- continue
286
- now = time.perf_counter()
287
- if last_img is not None and len(img) == len(last_img):
288
- video_diffs["times"].append(now)
289
- video_diffs["diffs"].append(float(np.abs(img.astype(np.int16)
290
- - last_img.astype(np.int16)).mean()))
291
- last_img = img
292
-
293
- await room.connect("ws://localhost:7880", token,
294
- options=rtc.RoomOptions(auto_subscribe=True))
295
- await asyncio.sleep(2.0) # ensure bot tracks subscribed
296
-
297
- # synthesize the question
298
- voice = PiperVoice.load(str(ROOT / "voices/en_US-amy-medium.onnx"))
299
- chunks = list(voice.synthesize(QUESTION))
300
- q_pcm = np.concatenate([np.frombuffer(c.audio_int16_bytes, dtype=np.int16)
301
- for c in chunks])
302
- q_sr = int(json.loads((ROOT / "voices/en_US-amy-medium.onnx.json").read_text())
303
- ["audio"]["sample_rate"])
304
- wav = wave.open("/tmp/question.wav", "wb")
305
- wav.setnchannels(1); wav.setsampwidth(2); wav.setframerate(q_sr)
306
- wav.writeframes(q_pcm.tobytes()); wav.close()
307
-
308
- source = rtc.AudioSource(q_sr, 1)
309
- track = rtc.LocalAudioTrack.create_audio_track("tester-mic", source)
310
- opts = rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_MICROPHONE)
311
- await room.local_participant.publish_track(track, opts)
312
-
313
- verifier = WhisperModel("tiny.en", device="cpu", compute_type="int8", cpu_threads=1)
314
- turns = []
315
- for turn_i, (q_text, keywords) in enumerate(
316
- [(QUESTION, ANSWER_KEYWORDS), (QUESTION2, ANSWER_KEYWORDS2)], start=1):
317
- q_chunks = list(voice.synthesize(q_text))
318
- q_pcm = np.concatenate([np.frombuffer(c.audio_int16_bytes, np.int16)
319
- for c in q_chunks])
320
- bot_audio["chunks"] = []
321
- bot_audio["first_arrival"] = None
322
- bot_audio["last_arrival"] = None
323
- t0 = None
324
- for i in range(0, len(q_pcm), chunk):
325
- piece = q_pcm[i : i + chunk]
326
- frame = rtc.AudioFrame.create(q_sr, 1, len(piece))
327
- np.copyto(np.frombuffer(frame.data, dtype=np.int16), piece)
328
- await source.capture_frame(frame)
329
- if t0 is None:
330
- t0 = time.perf_counter()
331
  t_speech_end = time.perf_counter()
332
- print(f"[client] turn {turn_i}: question pushed, speech end at {t_speech_end:.3f} "
333
- f"(abs {time.time():.3f})", flush=True)
334
-
335
- # wait for the bot's answer: first audio + until silence (bounded — a
336
- # silent bot must fail the harness, not hang it)
337
- while bot_audio["first_arrival"] is None:
338
- await asyncio.sleep(0.05)
339
- if time.perf_counter() - t_speech_end > 45:
340
- break
341
- if bot_audio["first_arrival"] is None:
342
- print(f"[client] turn {turn_i}: NO bot audio within 45s of speech end", flush=True)
343
- await room.disconnect()
344
- return {"t_perceived": 999.0, "turns": turns, "t_ready": t_ready,
345
- "answer_text": "", "no_answer": True}
346
- t_perceived = bot_audio["first_arrival"] - t_speech_end
347
- while time.perf_counter() - bot_audio["last_arrival"] < 4.0:
348
- await asyncio.sleep(0.1)
349
- if time.perf_counter() - t_speech_end > 60:
350
- break
351
- answer_s = (bot_audio["last_arrival"] - bot_audio["first_arrival"])
352
-
353
- bot_pcm = np.concatenate(bot_audio["chunks"])
354
- segments, _ = verifier.transcribe(bot_pcm.astype(np.float32) / 32768.0, language="en")
355
- answer_text = " ".join(s.text.strip() for s in segments).strip()
356
- kw_ok = any(k in answer_text.lower() for k in keywords)
357
- check(f"turn {turn_i}: bot answered (transcript contains keyword)",
358
- kw_ok, answer_text[:160])
359
-
360
- # mouth movement during the answer
361
- last_arr = bot_audio["last_arrival"] or t_speech_end
362
- window = [d for t, d in zip(video_diffs["times"], video_diffs["diffs"])
363
- if t_speech_end <= t <= last_arr + 0.5]
364
- moving = len(window) > 5 and sorted(window)[len(window) // 2] > 0.3
365
- check(f"turn {turn_i}: avatar mouth moved", moving,
366
- f"{len(window)} frames, median diff {sorted(window)[len(window)//2] if window else 0:.2f}")
367
- turns.append({"t_perceived": t_perceived, "answer_s": answer_s,
368
- "answer_text": answer_text,
369
- "first_arrival_abs": bot_audio["first_arrival_abs"]})
370
- await asyncio.sleep(0.5)
371
-
372
- await room.disconnect()
373
- return {"t_perceived": min(t["t_perceived"] for t in turns),
374
- "turns": turns, "t_ready": t_ready,
375
- "answer_text": turns[-1]["answer_text"]}
376
-
377
-
378
- timings = asyncio.run(test_client())
379
-
380
- # bot forensics — always, success or failure
381
- sdir0 = ROOT / ".freestream/sessions" / session_id
382
- for name in ("bot.err", "bot.out"):
383
- f = sdir0 / name
384
- if f.exists() and f.stat().st_size > 0:
385
- print(f"\n--- {name} (tail) ---\n{f.read_text()[-1500:]}", flush=True)
386
-
387
- # --------------------------------------------------------------------------- leave via CLI
388
-
389
- r = run_cli("leave", "--session-id", session_id)
390
- out = {}
391
- try:
392
- out = json.loads(r.stdout.strip().splitlines()[-1])
393
- except (ValueError, IndexError):
394
- pass
395
- check("CLI leave exits 0 with closed:true", r.returncode == 0 and out.get("closed") is True,
396
- f"rc={r.returncode} out={str(out)[:100]}")
397
-
398
- # replay logs valid
399
- from freestream.events import EventLog # noqa: E402
400
-
401
- sdir = ROOT / ".freestream/sessions" / session_id
402
- cli_ok, cli_bad = EventLog(sdir / "events.jsonl").verify()
403
- bot_ok, bot_bad = EventLog(sdir / "bot-events.jsonl").verify()
404
- check("CLI event log verifies", cli_ok, f"bad_seq={cli_bad}")
405
- check("bot event log verifies", bot_ok, f"bad_seq={bot_bad}")
406
-
407
- # --------------------------------------------------------------------------- summary
408
-
409
- print("\n--- latency (speech-end -> first bot audio at client) ---", flush=True)
410
- print(f"t_ready (CLI join -> bot ready): {timings['t_ready']:.2f}s")
411
- for i, t in enumerate(timings["turns"], start=1):
412
- print(f"turn {i} t_perceived: {t['t_perceived']:.2f}s")
413
- print(f"t_perceived best (WIN CONDITION <= 4.0s): {timings['t_perceived']:.2f}s"
414
- f" {'PASS' if timings['t_perceived'] <= 4.0 else 'FAIL'}")
415
- print(f"answer transcript (last turn): {timings['answer_text'][:200]}")
416
-
417
- # transport-gap forensics: bot's absolute first-push vs client's absolute arrival
418
- try:
419
- pushes = []
420
- for line in (sdir0 / "bot.out").read_text().splitlines():
421
- if "abs_first_push" in line:
422
- pushes.append(json.loads(line).get("abs_first_push"))
423
- arrivals = [t["first_arrival_abs"] for t in timings["turns"]]
424
- for i, (p, a) in enumerate(zip(pushes, arrivals), start=1):
425
- print(f"turn {i} bot->client transport gap: {a - p:.2f}s "
426
- f"(push@{p:.3f} -> arrival@{a:.3f})")
427
- except Exception as e:
428
- print(f"transport-gap forensics skipped: {e}")
429
- try:
430
- bot_log = EventLog(ROOT / ".freestream/sessions" / session_id / "bot-events.jsonl").events()
431
- synth = [e for e in bot_log if e["type"] == "tts.synthesized"]
432
- turns = [e for e in bot_log if e["type"] == "turn.completed"]
433
- if synth:
434
- print(f"bot-side tts synth time: {synth[-1]['payload']['seconds']}s")
435
- if turns:
436
- print(f"bot-side turn total (speech-end -> done): {turns[-1]['payload']['total_s']}s")
437
- print("\n--- what the bot heard and said (bot-events.jsonl) ---")
438
- for e in bot_log:
439
- if e["type"] in ("asr.final", "agent.speak"):
440
- extra = e["payload"].get("seconds")
441
- print(f" {e['type']:12s} ts=+{e['ts'] % 1000:8.2f}s"
442
- + (f" (asr {extra}s)" if extra else "")
443
- + f" {e['payload'].get('text', '')[:140]}")
444
- elif e["type"] in ("turn.completed", "session.error"):
445
- print(f" {e['type']:12s} {e['payload']}")
446
- except Exception as e:
447
- print(f"bot log summary skipped: {e}")
448
-
449
- # server shutdown
450
- server.terminate()
451
-
452
- failed = [n for n, ok in results if not ok]
453
- win = timings["t_perceived"] <= 4.0
454
- print(f"\n{len(results) - len(failed)}/{len(results)} checks passed"
455
- + ("" if win else "; WIN CONDITION MISSED"))
456
- if failed or not win:
457
- print("FAILED: " + ", ".join(failed + ([] if win else ["t_perceived > 4s"])))
458
- sys.exit(1)
459
- 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()