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
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
"""FREESTREAM MVP end-to-end latency harness (win condition, docs/LATENCY.md).

In ONE container: downloads livekit-server, runs it in dev mode, pulls the
FREESTREAM repo from the Hub, then:

  1. `freestream join` (the real CLI) spawns the bot into a LiveKit room
  2. a test client connects, asks a question via a Piper-generated mic track
  3. measures speech-end -> first bot audio frame (t_perceived), verifies the
     answer by transcribing the bot's audio, and checks the mouth moved
  4. `freestream leave` (the real CLI) closes the session
  5. verifies the hash-chained replay logs

Win condition: agent joins, answers within 4s with a moving mouth, leaves,
and generates a valid replay log.

Stdlib + livekit + faster-whisper + piper-tts + pillow + numpy.
"""

from __future__ import annotations

import asyncio
import json
import os
import shutil
import socket
import subprocess
import sys
import tarfile
import time
import urllib.request
import wave
from pathlib import Path

import numpy as np

ROOT = Path("/tmp/freestream")
REPO = "https://huggingface.co/datasets/LoveLogicAI/freestream/resolve/main"
VOICE_URL = ("https://huggingface.co/rhasspy/piper-voices/resolve/main/"
             "en/en_US/amy/medium/en_US-amy-medium{ext}")
GH_LATEST = "https://api.github.com/repos/livekit/livekit-server/releases/latest"

BOT_NAME = "Streamy"
QUESTION = "What is your name and what can you do?"
ANSWER_KEYWORDS = ("streamy", "assistant")
QUESTION2 = "What can you do?"
ANSWER_KEYWORDS2 = ("avatar", "listen", "voice")

os.environ["HF_HOME"] = "/tmp/hf"
os.environ["FREESTREAM_VOICE_DIR"] = str(ROOT / "voices")
os.environ["FREESTREAM_WHISPER_MODEL"] = "tiny.en"  # measured best: RTF 0.25 @1 thread
os.environ["FREESTREAM_WHISPER_THREADS"] = "1"
os.environ["PYTHONPATH"] = str(ROOT)
sys.path.insert(0, str(ROOT))  # harness imports the package below (log verification)
os.environ.setdefault("FREESTREAM_LIVEKIT_URL", "ws://localhost:7880")
os.environ.setdefault("FREESTREAM_LIVEKIT_KEY", "devkey")
os.environ.setdefault("FREESTREAM_LIVEKIT_SECRET", "secret")

results = []


def check(name, ok, detail=""):
    results.append((name, ok))
    print(f"{'PASS' if ok else 'FAIL'}  {name}" + (f"  — {detail}" if detail else ""), flush=True)


def fetch_hub(repo_id: str, filename: str, dest: Path, repo_type: str = "model"):
    """Token-authenticated Hub download (robust vs flaky resolve/redirect reads)."""
    dest.parent.mkdir(parents=True, exist_ok=True)
    from huggingface_hub import hf_hub_download
    p = hf_hub_download(repo_id=repo_id, filename=filename, repo_type=repo_type,
                        token=os.environ.get("HF_TOKEN"))
    shutil.copyfile(p, dest)


def fetch(url: str, dest: Path | None = None) -> bytes:
    with urllib.request.urlopen(url, timeout=120) as r:
        data = r.read()
    if dest is not None:
        dest.parent.mkdir(parents=True, exist_ok=True)
        dest.write_bytes(data)
    return data


def run_cli(*args, timeout=240):
    return subprocess.run([sys.executable, str(ROOT / "scripts/freestream.py"), *args],
                          cwd=str(ROOT), capture_output=True, text=True, timeout=timeout)


# --------------------------------------------------------------------------- setup

FILES = ["scripts/freestream.py", "requirements.txt",
         "freestream/__init__.py", "freestream/events.py", "freestream/presence.py",
         "freestream/persona.py", "freestream/mcp_server.py", "freestream/bot.py",
         "freestream/asr.py", "freestream/avatar.py", "freestream/agent.py"]
missing = []
for f in FILES:
    try:
        fetch_hub("LoveLogicAI/freestream", f, ROOT / f, repo_type="dataset")
    except Exception as e:
        missing.append((f, str(e)))
check("fetch code from Hub", not missing, str(missing[:2]))
if missing:
    sys.exit(1)

# livekit-server binary
lk_bin = ROOT / "livekit-server"
if not lk_bin.exists():
    try:
        req = urllib.request.Request(GH_LATEST, headers={"Accept": "application/vnd.github+json"})
        with urllib.request.urlopen(req, timeout=60) as r:
            release = json.loads(r.read())
        asset = next(a for a in release["assets"]
                     if "linux_amd64" in a["name"] and a["name"].endswith(".tar.gz"))
        tgz = ROOT / asset["name"]
        fetch(asset["browser_download_url"], tgz)
        with tarfile.open(tgz) as tf:
            tf.extract("livekit-server", str(ROOT))
        check("download livekit-server", True, release["tag_name"])
    except Exception as e:
        check("download livekit-server", False, str(e)[:200])
        sys.exit(1)

# dev-mode config: explicit keys + loopback-friendly RTC (avoids the
# known UDP bind issue in containers, per livekit issue tracker)
config = ROOT / "lk.yaml"
config.write_text("""
port: 7880
rtc:
  use_external_ip: false
  use_ice_lite: true
  tcp_port: 7881
  port_range_start: 50000
  port_range_end: 50100
keys:
  devkey: secret
""")
server_log = open(ROOT / "server.log", "w")
server = subprocess.Popen([str(lk_bin), "--config", str(config)],
                          stdout=server_log, stderr=subprocess.STDOUT)
t0 = time.perf_counter()
up = False
while time.perf_counter() - t0 < 30:
    try:
        with socket.create_connection(("127.0.0.1", 7880), timeout=1):
            up = True
        break
    except OSError:
        time.sleep(0.5)
check("livekit-server up on :7880", up and server.poll() is None)
if not up:
    print(open(ROOT / "server.log").read()[-1500:])
    sys.exit(1)

# piper voice
vdir = ROOT / "voices"
try:
    for name in ("en/en_US/amy/medium/en_US-amy-medium.onnx",
                 "en/en_US/amy/medium/en_US-amy-medium.onnx.json"):
        dest = vdir / Path(name).name
        if not dest.exists():
            fetch_hub("rhasspy/piper-voices", name, dest)
    check("download piper voice", (vdir / "en_US-amy-medium.onnx").stat().st_size > 50_000_000)
except Exception as e:
    check("download piper voice", False, str(e)[:200])
    sys.exit(1)

# avatar via the real CLI
r = run_cli("generate-avatar", "--output", "identity/videomeeting-avatar.png")
avatar_ok = r.returncode == 0 and (ROOT / "identity/videomeeting-avatar.png").stat().st_size > 1024
check("generate-avatar (procedural, exit 0)", avatar_ok, r.stderr[:150] if not avatar_ok else "")

# warm the whisper cache so the bot and the verifier share it
# (tiny @ 2 threads is the measured optimum under the 8-core cgroup quota:
#  8 threads collapsed to 39.5s vs 1.27s at 1 thread — see ml-intern-freestream-debug-perf)
from faster_whisper import WhisperModel  # noqa: E402

t0 = time.perf_counter()
WhisperModel("tiny", device="cpu", compute_type="int8", cpu_threads=2)
print(f"[setup] whisper tiny int8 cached in {time.perf_counter() - t0:.1f}s", flush=True)

from livekit import api, rtc  # noqa: E402
from piper import PiperVoice  # noqa: E402


# --------------------------------------------------------------------------- join via CLI


def attempt_join(timeout_sec):
    proc = subprocess.Popen(
        [sys.executable, str(ROOT / "scripts/freestream.py"), "join",
         "--meet-url", "https://livekit.local/qa-room", "--platform", "livekit",
         "--bot-name", BOT_NAME, "--image", "identity/videomeeting-avatar.png",
         "--timeout-sec", str(timeout_sec)],
        cwd=str(ROOT), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    t0 = time.perf_counter()
    sid, ready = None, False
    for line in proc.stdout:
        try:
            d = json.loads(line)
        except ValueError:
            continue
        if "session_id" in d and sid is None:
            sid = d["session_id"]
        if d.get("status") == "ready":
            ready = True
            break
    return proc, sid, ready, time.perf_counter() - t0


def dump_session_files(sid):
    if not sid:
        return
    sd = ROOT / ".freestream/sessions" / sid
    for name in ("bot.err", "bot.out", "state.json", "driver.json"):
        f = sd / name
        if f.exists():
            print(f"--- session {name} ---\n{f.read_text()[-2500:]}", flush=True)


join_proc, session_id, ready, t_ready = attempt_join(90)
if not ready:
    print(f"[harness] join attempt 1 timed out (t={t_ready:.1f}s); dumping bot output", flush=True)
    dump_session_files(session_id)
    print("[harness] retrying join once...", flush=True)
    join_proc, session_id, ready, t_ready = attempt_join(90)

check(f"CLI join -> ready (session {session_id})", ready and join_proc.poll() is None,
      f"t_ready={t_ready:.1f}s")
if not ready:
    dump_session_files(session_id)
    print(join_proc.stderr.read()[:800])
    sys.exit(1)

# --------------------------------------------------------------------------- test client

token = (api.AccessToken("devkey", "secret")
         .with_identity("tester").with_name("Tester")
         .with_grants(api.VideoGrants(room_join=True, room="qa-room",
                                      can_publish=True, can_subscribe=True)).to_jwt())


async def test_client():
    room = rtc.Room()
    bot_audio = {"chunks": [], "first_arrival": None, "last_arrival": None}
    video_diffs = {"times": [], "diffs": []}

    @room.on("track_subscribed")
    def on_track(track, publication, participant):
        if track.kind == rtc.TrackKind.KIND_AUDIO:
            asyncio.ensure_future(record_audio(track))
        else:
            asyncio.ensure_future(sample_video(track))

    async def record_audio(track):
        stream = rtc.AudioStream(track, sample_rate=16000, num_channels=1)
        async for ev in stream:
            pcm = np.frombuffer(ev.frame.data, dtype=np.int16)
            # the bot's audio track idles with zero-frames between turns;
            # gate arrivals on real speech energy so t_perceived is honest
            rms = float(np.sqrt(np.mean(pcm.astype(np.float32) ** 2))) / 32768.0
            if rms < 0.004:
                continue
            now = time.perf_counter()
            if bot_audio["first_arrival"] is None:
                bot_audio["first_arrival"] = now
                bot_audio["first_arrival_abs"] = time.time()
                print(f"[client] first bot AUDIO (speech) at {now:.3f} "
                      f"(abs {time.time():.3f})", flush=True)
            bot_audio["last_arrival"] = now
            bot_audio["chunks"].append(pcm)

    async def sample_video(track):
        last_img = None
        stream = rtc.VideoStream(track)
        async for ev in stream:
            f = ev.frame
            w, h = f.width, f.height
            data = bytes(f.data)
            if len(data) >= w * h * 1.5 and len(data) < w * h * 4:  # I420 → luminance plane
                img = np.frombuffer(data[: w * h], dtype=np.uint8)
            elif len(data) == w * h * 4:  # RGBA → luma approx
                rgba = np.frombuffer(data, dtype=np.uint8).reshape(h, w, 4)
                img = rgba[:, :, :3].mean(axis=2).astype(np.uint8).ravel()
            else:
                continue
            now = time.perf_counter()
            if last_img is not None and len(img) == len(last_img):
                video_diffs["times"].append(now)
                video_diffs["diffs"].append(float(np.abs(img.astype(np.int16)
                                                          - last_img.astype(np.int16)).mean()))
            last_img = img

    await room.connect("ws://localhost:7880", token,
                       options=rtc.RoomOptions(auto_subscribe=True))
    await asyncio.sleep(2.0)  # ensure bot tracks subscribed

    # synthesize the question
    voice = PiperVoice.load(str(ROOT / "voices/en_US-amy-medium.onnx"))
    chunks = list(voice.synthesize(QUESTION))
    q_pcm = np.concatenate([np.frombuffer(c.audio_int16_bytes, dtype=np.int16)
                            for c in chunks])
    q_sr = int(json.loads((ROOT / "voices/en_US-amy-medium.onnx.json").read_text())
               ["audio"]["sample_rate"])
    wav = wave.open("/tmp/question.wav", "wb")
    wav.setnchannels(1); wav.setsampwidth(2); wav.setframerate(q_sr)
    wav.writeframes(q_pcm.tobytes()); wav.close()

    source = rtc.AudioSource(q_sr, 1)
    track = rtc.LocalAudioTrack.create_audio_track("tester-mic", source)
    opts = rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_MICROPHONE)
    await room.local_participant.publish_track(track, opts)

    verifier = WhisperModel("tiny.en", device="cpu", compute_type="int8", cpu_threads=1)
    chunk = int(q_sr * 0.01)  # 10ms push granularity for the mic track
    turns = []
    for turn_i, (q_text, keywords) in enumerate(
            [(QUESTION, ANSWER_KEYWORDS), (QUESTION2, ANSWER_KEYWORDS2)], start=1):
        q_chunks = list(voice.synthesize(q_text))
        q_pcm = np.concatenate([np.frombuffer(c.audio_int16_bytes, np.int16)
                                for c in q_chunks])
        bot_audio["chunks"] = []
        bot_audio["first_arrival"] = None
        bot_audio["last_arrival"] = None
        t0 = None
        for i in range(0, len(q_pcm), chunk):
            piece = q_pcm[i : i + chunk]
            frame = rtc.AudioFrame.create(q_sr, 1, len(piece))
            np.copyto(np.frombuffer(frame.data, dtype=np.int16), piece)
            await source.capture_frame(frame)
            if t0 is None:
                t0 = time.perf_counter()
        t_speech_end = time.perf_counter()
        print(f"[client] turn {turn_i}: question pushed, speech end at {t_speech_end:.3f} "
              f"(abs {time.time():.3f})", flush=True)

        # wait for the bot's answer: first audio + until silence (bounded — a
        # silent bot must fail the harness, not hang it)
        while bot_audio["first_arrival"] is None:
            await asyncio.sleep(0.05)
            if time.perf_counter() - t_speech_end > 45:
                break
        if bot_audio["first_arrival"] is None:
            print(f"[client] turn {turn_i}: NO bot audio within 45s of speech end", flush=True)
            await room.disconnect()
            return {"t_perceived": 999.0, "turns": turns, "t_ready": t_ready,
                    "answer_text": "", "no_answer": True}
        t_perceived = bot_audio["first_arrival"] - t_speech_end
        while time.perf_counter() - bot_audio["last_arrival"] < 4.0:
            await asyncio.sleep(0.1)
            if time.perf_counter() - t_speech_end > 60:
                break
        answer_s = (bot_audio["last_arrival"] - bot_audio["first_arrival"])

        bot_pcm = np.concatenate(bot_audio["chunks"])
        segments, _ = verifier.transcribe(bot_pcm.astype(np.float32) / 32768.0, language="en")
        answer_text = " ".join(s.text.strip() for s in segments).strip()
        kw_ok = any(k in answer_text.lower() for k in keywords)
        check(f"turn {turn_i}: bot answered (transcript contains keyword)",
              kw_ok, answer_text[:160])

        # mouth movement during the answer
        last_arr = bot_audio["last_arrival"] or t_speech_end
        window = [d for t, d in zip(video_diffs["times"], video_diffs["diffs"])
                  if t_speech_end <= t <= last_arr + 0.5]
        moving = len(window) > 5 and sorted(window)[len(window) // 2] > 0.3
        check(f"turn {turn_i}: avatar mouth moved", moving,
              f"{len(window)} frames, median diff {sorted(window)[len(window)//2] if window else 0:.2f}")
        turns.append({"t_perceived": t_perceived, "answer_s": answer_s,
                      "answer_text": answer_text,
                      "first_arrival_abs": bot_audio["first_arrival_abs"]})
        await asyncio.sleep(0.5)

    await room.disconnect()
    return {"t_perceived": min(t["t_perceived"] for t in turns),
            "turns": turns, "t_ready": t_ready,
            "answer_text": turns[-1]["answer_text"]}


timings = asyncio.run(test_client())

# bot forensics — always, success or failure
sdir0 = ROOT / ".freestream/sessions" / session_id
for name in ("bot.err", "bot.out"):
    f = sdir0 / name
    if f.exists() and f.stat().st_size > 0:
        print(f"\n--- {name} (tail) ---\n{f.read_text()[-1500:]}", flush=True)

# --------------------------------------------------------------------------- leave via CLI

r = run_cli("leave", "--session-id", session_id)
out = {}
try:
    out = json.loads(r.stdout.strip().splitlines()[-1])
except (ValueError, IndexError):
    pass
check("CLI leave exits 0 with closed:true", r.returncode == 0 and out.get("closed") is True,
      f"rc={r.returncode} out={str(out)[:100]}")

# replay logs valid
from freestream.events import EventLog  # noqa: E402

sdir = ROOT / ".freestream/sessions" / session_id
cli_ok, cli_bad = EventLog(sdir / "events.jsonl").verify()
bot_ok, bot_bad = EventLog(sdir / "bot-events.jsonl").verify()
check("CLI event log verifies", cli_ok, f"bad_seq={cli_bad}")
check("bot event log verifies", bot_ok, f"bad_seq={bot_bad}")

# --------------------------------------------------------------------------- summary

print("\n--- latency (speech-end -> first bot audio at client) ---", flush=True)
print(f"t_ready (CLI join -> bot ready):        {timings['t_ready']:.2f}s")
for i, t in enumerate(timings["turns"], start=1):
    print(f"turn {i} t_perceived:                     {t['t_perceived']:.2f}s")
print(f"t_perceived best (WIN CONDITION <= 4.0s): {timings['t_perceived']:.2f}s"
      f"   {'PASS' if timings['t_perceived'] <= 4.0 else 'FAIL'}")
print(f"answer transcript (last turn):          {timings['answer_text'][:200]}")

# transport-gap forensics: bot's absolute first-push vs client's absolute arrival
try:
    pushes = []
    for line in (sdir0 / "bot.out").read_text().splitlines():
        if "abs_first_push" in line:
            pushes.append(json.loads(line).get("abs_first_push"))
    arrivals = [t["first_arrival_abs"] for t in timings["turns"]]
    for i, (p, a) in enumerate(zip(pushes, arrivals), start=1):
        print(f"turn {i} bot->client transport gap:         {a - p:.2f}s "
              f"(push@{p:.3f} -> arrival@{a:.3f})")
except Exception as e:
    print(f"transport-gap forensics skipped: {e}")
try:
    bot_log = EventLog(ROOT / ".freestream/sessions" / session_id / "bot-events.jsonl").events()
    synth = [e for e in bot_log if e["type"] == "tts.synthesized"]
    turns = [e for e in bot_log if e["type"] == "turn.completed"]
    if synth:
        print(f"bot-side tts synth time:             {synth[-1]['payload']['seconds']}s")
    if turns:
        print(f"bot-side turn total (speech-end -> done): {turns[-1]['payload']['total_s']}s")
    print("\n--- what the bot heard and said (bot-events.jsonl) ---")
    for e in bot_log:
        if e["type"] in ("asr.final", "agent.speak"):
            extra = e["payload"].get("seconds")
            print(f"  {e['type']:12s} ts=+{e['ts'] % 1000:8.2f}s"
                  + (f" (asr {extra}s)" if extra else "")
                  + f"  {e['payload'].get('text', '')[:140]}")
        elif e["type"] in ("turn.completed", "session.error"):
            print(f"  {e['type']:12s} {e['payload']}")
except Exception as e:
    print(f"bot log summary skipped: {e}")

# server shutdown
server.terminate()

failed = [n for n, ok in results if not ok]
win = timings["t_perceived"] <= 4.0
print(f"\n{len(results) - len(failed)}/{len(results)} checks passed"
      + ("" if win else "; WIN CONDITION MISSED"))
if failed or not win:
    print("FAILED: " + ", ".join(failed + ([] if win else ["t_perceived > 4s"])))
    sys.exit(1)
print("E2E OK — WIN CONDITION MET")