LoveLogicAI commited on
Commit
ed293bb
·
verified ·
1 Parent(s): e3f8004

Bounded answer wait + bot forensics dumps

Browse files
Files changed (1) hide show
  1. tests/e2e_livekit.py +93 -33
tests/e2e_livekit.py CHANGED
@@ -21,6 +21,7 @@ from __future__ import annotations
21
  import asyncio
22
  import json
23
  import os
 
24
  import socket
25
  import subprocess
26
  import sys
@@ -46,6 +47,7 @@ os.environ["HF_HOME"] = "/tmp/hf"
46
  os.environ["FREESTREAM_VOICE_DIR"] = str(ROOT / "voices")
47
  os.environ["FREESTREAM_WHISPER_MODEL"] = "base"
48
  os.environ["PYTHONPATH"] = str(ROOT)
 
49
  os.environ.setdefault("FREESTREAM_LIVEKIT_URL", "ws://localhost:7880")
50
  os.environ.setdefault("FREESTREAM_LIVEKIT_KEY", "devkey")
51
  os.environ.setdefault("FREESTREAM_LIVEKIT_SECRET", "secret")
@@ -58,10 +60,22 @@ def check(name, ok, detail=""):
58
  print(f"{'PASS' if ok else 'FAIL'} {name}" + (f" — {detail}" if detail else ""), flush=True)
59
 
60
 
61
- def fetch(url: str, dest: Path):
 
62
  dest.parent.mkdir(parents=True, exist_ok=True)
63
- with urllib.request.urlopen(url, timeout=120) as r, open(dest, "wb") as f:
64
- f.write(r.read())
 
 
 
 
 
 
 
 
 
 
 
65
 
66
 
67
  def run_cli(*args, timeout=240):
@@ -78,8 +92,7 @@ FILES = ["scripts/freestream.py", "requirements.txt",
78
  missing = []
79
  for f in FILES:
80
  try:
81
- (ROOT / f).parent.mkdir(parents=True, exist_ok=True)
82
- (ROOT / f).write_bytes(fetch(f"{REPO}/{f}", ROOT / f))
83
  except Exception as e:
84
  missing.append((f, str(e)))
85
  check("fetch code from Hub", not missing, str(missing[:2]))
@@ -138,11 +151,11 @@ if not up:
138
  # piper voice
139
  vdir = ROOT / "voices"
140
  try:
141
- for ext, name in ((".onnx", "en_US-amy-medium.onnx"),
142
- (".onnx.json", "en_US-amy-medium.onnx.json")):
143
- dest = vdir / name
144
  if not dest.exists():
145
- fetch(VOICE_URL.format(ext=ext), dest)
146
  check("download piper voice", (vdir / "en_US-amy-medium.onnx").stat().st_size > 50_000_000)
147
  except Exception as e:
148
  check("download piper voice", False, str(e)[:200])
@@ -166,30 +179,50 @@ from piper import PiperVoice # noqa: E402
166
 
167
  # --------------------------------------------------------------------------- join via CLI
168
 
169
- join_proc = subprocess.Popen(
170
- [sys.executable, str(ROOT / "scripts/freestream.py"), "join",
171
- "--meet-url", "https://livekit.local/qa-room", "--platform", "livekit",
172
- "--bot-name", BOT_NAME, "--image", "identity/videomeeting-avatar.png",
173
- "--timeout-sec", "240"],
174
- cwd=str(ROOT), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
175
 
176
- t0 = time.perf_counter()
177
- session_id = None
178
- ready = False
179
- for line in join_proc.stdout:
180
- try:
181
- d = json.loads(line)
182
- except ValueError:
183
- continue
184
- if "session_id" in d and session_id is None:
185
- session_id = d["session_id"]
186
- if d.get("status") == "ready":
187
- ready = True
188
- break
189
- t_ready = time.perf_counter() - t0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  check(f"CLI join -> ready (session {session_id})", ready and join_proc.poll() is None,
191
  f"t_ready={t_ready:.1f}s")
192
  if not ready:
 
193
  print(join_proc.stderr.read()[:800])
194
  sys.exit(1)
195
 
@@ -217,10 +250,15 @@ async def test_client():
217
  stream = rtc.AudioStream(track, sample_rate=16000, num_channels=1)
218
  async for ev in stream:
219
  pcm = np.frombuffer(ev.frame.data, dtype=np.int16)
 
 
 
 
 
220
  now = time.perf_counter()
221
  if bot_audio["first_arrival"] is None:
222
  bot_audio["first_arrival"] = now
223
- print(f"[client] first bot audio frame at {now:.3f}", flush=True)
224
  bot_audio["last_arrival"] = now
225
  bot_audio["chunks"].append(pcm)
226
 
@@ -277,9 +315,17 @@ async def test_client():
277
  t_speech_end = time.perf_counter()
278
  print(f"[client] question pushed, speech end at {t_speech_end:.3f}", flush=True)
279
 
280
- # wait for the bot's answer: first audio + until silence
 
281
  while bot_audio["first_arrival"] is None:
282
  await asyncio.sleep(0.05)
 
 
 
 
 
 
 
283
  t_perceived = bot_audio["first_arrival"] - t_speech_end
284
  while time.perf_counter() - bot_audio["last_arrival"] < 2.0:
285
  await asyncio.sleep(0.1)
@@ -301,9 +347,10 @@ async def test_client():
301
  check("bot answered (transcript contains keyword)", kw_ok, answer_text[:160])
302
 
303
  # mouth movement during the answer
 
304
  window = [d for t, d in zip(video_diffs["times"], video_diffs["diffs"])
305
- if t_speech_end <= t <= bot_audio["last_arrival"] + 0.5]
306
- moving = len(window) > 5 and sorted(window)[len(window) // 2] > 0.8
307
  check("avatar mouth moved during speech", moving,
308
  f"{len(window)} frames, median diff {sorted(window)[len(window)//2] if window else 0:.2f}")
309
 
@@ -314,6 +361,13 @@ async def test_client():
314
 
315
  timings = asyncio.run(test_client())
316
 
 
 
 
 
 
 
 
317
  # --------------------------------------------------------------------------- leave via CLI
318
 
319
  r = run_cli("leave", "--session-id", session_id)
@@ -350,6 +404,12 @@ try:
350
  print(f"bot-side tts synth time: {synth[-1]['payload']['seconds']}s")
351
  if turns:
352
  print(f"bot-side turn total (speech-end -> done): {turns[-1]['payload']['total_s']}s")
 
 
 
 
 
 
353
  except Exception as e:
354
  print(f"bot log summary skipped: {e}")
355
 
 
21
  import asyncio
22
  import json
23
  import os
24
+ import shutil
25
  import socket
26
  import subprocess
27
  import sys
 
47
  os.environ["FREESTREAM_VOICE_DIR"] = str(ROOT / "voices")
48
  os.environ["FREESTREAM_WHISPER_MODEL"] = "base"
49
  os.environ["PYTHONPATH"] = str(ROOT)
50
+ sys.path.insert(0, str(ROOT)) # harness imports the package below (log verification)
51
  os.environ.setdefault("FREESTREAM_LIVEKIT_URL", "ws://localhost:7880")
52
  os.environ.setdefault("FREESTREAM_LIVEKIT_KEY", "devkey")
53
  os.environ.setdefault("FREESTREAM_LIVEKIT_SECRET", "secret")
 
60
  print(f"{'PASS' if ok else 'FAIL'} {name}" + (f" — {detail}" if detail else ""), flush=True)
61
 
62
 
63
+ def fetch_hub(repo_id: str, filename: str, dest: Path, repo_type: str = "model"):
64
+ """Token-authenticated Hub download (robust vs flaky resolve/redirect reads)."""
65
  dest.parent.mkdir(parents=True, exist_ok=True)
66
+ from huggingface_hub import hf_hub_download
67
+ p = hf_hub_download(repo_id=repo_id, filename=filename, repo_type=repo_type,
68
+ token=os.environ.get("HF_TOKEN"))
69
+ shutil.copyfile(p, dest)
70
+
71
+
72
+ def fetch(url: str, dest: Path | None = None) -> bytes:
73
+ with urllib.request.urlopen(url, timeout=120) as r:
74
+ data = r.read()
75
+ if dest is not None:
76
+ dest.parent.mkdir(parents=True, exist_ok=True)
77
+ dest.write_bytes(data)
78
+ return data
79
 
80
 
81
  def run_cli(*args, timeout=240):
 
92
  missing = []
93
  for f in FILES:
94
  try:
95
+ fetch_hub("LoveLogicAI/freestream", f, ROOT / f, repo_type="dataset")
 
96
  except Exception as e:
97
  missing.append((f, str(e)))
98
  check("fetch code from Hub", not missing, str(missing[:2]))
 
151
  # piper voice
152
  vdir = ROOT / "voices"
153
  try:
154
+ for name in ("en/en_US/amy/medium/en_US-amy-medium.onnx",
155
+ "en/en_US/amy/medium/en_US-amy-medium.onnx.json"):
156
+ dest = vdir / Path(name).name
157
  if not dest.exists():
158
+ fetch_hub("rhasspy/piper-voices", name, dest)
159
  check("download piper voice", (vdir / "en_US-amy-medium.onnx").stat().st_size > 50_000_000)
160
  except Exception as e:
161
  check("download piper voice", False, str(e)[:200])
 
179
 
180
  # --------------------------------------------------------------------------- join via CLI
181
 
 
 
 
 
 
 
182
 
183
+ def attempt_join(timeout_sec):
184
+ proc = subprocess.Popen(
185
+ [sys.executable, str(ROOT / "scripts/freestream.py"), "join",
186
+ "--meet-url", "https://livekit.local/qa-room", "--platform", "livekit",
187
+ "--bot-name", BOT_NAME, "--image", "identity/videomeeting-avatar.png",
188
+ "--timeout-sec", str(timeout_sec)],
189
+ cwd=str(ROOT), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
190
+ t0 = time.perf_counter()
191
+ sid, ready = None, False
192
+ for line in proc.stdout:
193
+ try:
194
+ d = json.loads(line)
195
+ except ValueError:
196
+ continue
197
+ if "session_id" in d and sid is None:
198
+ sid = d["session_id"]
199
+ if d.get("status") == "ready":
200
+ ready = True
201
+ break
202
+ return proc, sid, ready, time.perf_counter() - t0
203
+
204
+
205
+ def dump_session_files(sid):
206
+ if not sid:
207
+ return
208
+ sd = ROOT / ".freestream/sessions" / sid
209
+ for name in ("bot.err", "bot.out", "state.json", "driver.json"):
210
+ f = sd / name
211
+ if f.exists():
212
+ print(f"--- session {name} ---\n{f.read_text()[-2500:]}", flush=True)
213
+
214
+
215
+ join_proc, session_id, ready, t_ready = attempt_join(90)
216
+ if not ready:
217
+ print(f"[harness] join attempt 1 timed out (t={t_ready:.1f}s); dumping bot output", flush=True)
218
+ dump_session_files(session_id)
219
+ print("[harness] retrying join once...", flush=True)
220
+ join_proc, session_id, ready, t_ready = attempt_join(90)
221
+
222
  check(f"CLI join -> ready (session {session_id})", ready and join_proc.poll() is None,
223
  f"t_ready={t_ready:.1f}s")
224
  if not ready:
225
+ dump_session_files(session_id)
226
  print(join_proc.stderr.read()[:800])
227
  sys.exit(1)
228
 
 
250
  stream = rtc.AudioStream(track, sample_rate=16000, num_channels=1)
251
  async for ev in stream:
252
  pcm = np.frombuffer(ev.frame.data, dtype=np.int16)
253
+ # the bot's audio track idles with zero-frames between turns;
254
+ # gate arrivals on real speech energy so t_perceived is honest
255
+ rms = float(np.sqrt(np.mean(pcm.astype(np.float32) ** 2))) / 32768.0
256
+ if rms < 0.004:
257
+ continue
258
  now = time.perf_counter()
259
  if bot_audio["first_arrival"] is None:
260
  bot_audio["first_arrival"] = now
261
+ print(f"[client] first bot AUDIO (speech) at {now:.3f}", flush=True)
262
  bot_audio["last_arrival"] = now
263
  bot_audio["chunks"].append(pcm)
264
 
 
315
  t_speech_end = time.perf_counter()
316
  print(f"[client] question pushed, speech end at {t_speech_end:.3f}", flush=True)
317
 
318
+ # wait for the bot's answer: first audio + until silence (bounded — a
319
+ # silent bot must fail the harness, not hang it)
320
  while bot_audio["first_arrival"] is None:
321
  await asyncio.sleep(0.05)
322
+ if time.perf_counter() - t_speech_end > 45:
323
+ break
324
+ if bot_audio["first_arrival"] is None:
325
+ print("[client] NO bot audio within 45s of speech end", flush=True)
326
+ await room.disconnect()
327
+ return {"t_perceived": 999.0, "answer_s": 0.0, "answer_text": "",
328
+ "t_ready": t_ready, "no_answer": True}
329
  t_perceived = bot_audio["first_arrival"] - t_speech_end
330
  while time.perf_counter() - bot_audio["last_arrival"] < 2.0:
331
  await asyncio.sleep(0.1)
 
347
  check("bot answered (transcript contains keyword)", kw_ok, answer_text[:160])
348
 
349
  # mouth movement during the answer
350
+ last_arr = bot_audio["last_arrival"] or t_speech_end
351
  window = [d for t, d in zip(video_diffs["times"], video_diffs["diffs"])
352
+ if t_speech_end <= t <= last_arr + 0.5]
353
+ moving = len(window) > 5 and sorted(window)[len(window) // 2] > 0.3
354
  check("avatar mouth moved during speech", moving,
355
  f"{len(window)} frames, median diff {sorted(window)[len(window)//2] if window else 0:.2f}")
356
 
 
361
 
362
  timings = asyncio.run(test_client())
363
 
364
+ # bot forensics — always, success or failure
365
+ sdir0 = ROOT / ".freestream/sessions" / session_id
366
+ for name in ("bot.err", "bot.out"):
367
+ f = sdir0 / name
368
+ if f.exists() and f.stat().st_size > 0:
369
+ print(f"\n--- {name} (tail) ---\n{f.read_text()[-1500:]}", flush=True)
370
+
371
  # --------------------------------------------------------------------------- leave via CLI
372
 
373
  r = run_cli("leave", "--session-id", session_id)
 
404
  print(f"bot-side tts synth time: {synth[-1]['payload']['seconds']}s")
405
  if turns:
406
  print(f"bot-side turn total (speech-end -> done): {turns[-1]['payload']['total_s']}s")
407
+ print("\n--- what the bot heard and said (bot-events.jsonl) ---")
408
+ for e in bot_log:
409
+ if e["type"] in ("asr.final", "agent.speak"):
410
+ print(f" {e['type']:12s} ts=+{e['ts'] % 1000:8.2f}s {e['payload'].get('text', '')[:140]}")
411
+ elif e["type"] in ("turn.completed", "session.error"):
412
+ print(f" {e['type']:12s} {e['payload']}")
413
  except Exception as e:
414
  print(f"bot log summary skipped: {e}")
415