Absolute first-push timestamp + FREESTREAM_PAUSE_RENDER knob (correct path)
Browse files- freestream/bot.py +286 -439
freestream/bot.py
CHANGED
|
@@ -1,459 +1,306 @@
|
|
| 1 |
-
"""FREESTREAM MVP
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 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
|
| 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 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
def
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
-
|
|
|
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 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 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 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 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
await
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
# -
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|