freestream / tests /debug_join.py
LoveLogicAI's picture
v0.1.0
bb18e70 verified
Raw History Blame Contribute Delete
4.83 kB
"""Debug the join->ready hang: server up? client connect OK? bot crash visible?
Runs the three join-path stages in the foreground and prints everything.
"""
import asyncio
import json
import os
import socket
import subprocess
import sys
import tarfile
import time
import urllib.request
from pathlib import Path
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"
os.environ["HF_HOME"] = "/tmp/hf"
os.environ["FREESTREAM_VOICE_DIR"] = str(ROOT / "voices")
os.environ["FREESTREAM_WHISPER_MODEL"] = "base"
os.environ["PYTHONPATH"] = str(ROOT)
def fetch(url, dest):
dest.parent.mkdir(parents=True, exist_ok=True)
with urllib.request.urlopen(url, timeout=120) as r:
data = r.read()
dest.write_bytes(data)
return data
FILES = ["scripts/freestream.py",
"freestream/__init__.py", "freestream/events.py", "freestream/presence.py",
"freestream/persona.py", "freestream/bot.py",
"freestream/asr.py", "freestream/avatar.py", "freestream/agent.py"]
for f in FILES:
fetch(f"{REPO}/{f}", ROOT / f)
print("[debug] code fetched", flush=True)
if not (ROOT / "livekit-server").exists():
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"))
fetch(asset["browser_download_url"], ROOT / asset["name"])
with tarfile.open(ROOT / asset["name"]) as tf:
tf.extract("livekit-server", str(ROOT))
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(ROOT / "livekit-server"), "--config", str(config)],
stdout=server_log, stderr=subprocess.STDOUT)
for _ in range(60):
try:
with socket.create_connection(("127.0.0.1", 7880), timeout=1):
break
except OSError:
time.sleep(0.5)
print("[debug] server up", flush=True)
for ext, name in ((".onnx", "en_US-amy-medium.onnx"), (".onnx.json", "en_US-amy-medium.onnx.json")):
dest = ROOT / "voices" / name
if not dest.exists():
fetch(VOICE_URL.format(ext=ext), dest)
from livekit import api, rtc # noqa: E402
# stage 1: can a plain client connect?
token = (api.AccessToken("devkey", "secret").with_identity("debugger")
.with_grants(api.VideoGrants(room_join=True, room="qa-room")).to_jwt())
async def plain_connect():
room = rtc.Room()
t0 = time.perf_counter()
await asyncio.wait_for(room.connect("ws://localhost:7880", token), timeout=30)
print(f"[debug] stage1 plain client connect OK in {time.perf_counter()-t0:.2f}s",
flush=True)
await room.disconnect()
asyncio.run(plain_connect())
# stage 2: run the bot directly in the foreground for 90s and show its output
sdir = ROOT / "dbg-session"
sdir.mkdir(exist_ok=True)
bot_token = (api.AccessToken("devkey", "secret").with_identity("freestream-bot-dbg")
.with_name("Bot").with_grants(api.VideoGrants(room_join=True, room="qa-room",
can_publish=True,
can_subscribe=True)).to_jwt())
env = dict(os.environ)
env["PYTHONPATH"] = str(ROOT)
print("[debug] stage2 launching bot in foreground (90s cap)...", flush=True)
try:
r = subprocess.run(
[sys.executable, "-m", "freestream.bot",
"--url", "ws://localhost:7880", "--token", bot_token, "--room", "qa-room",
"--bot-name", "DebugBot", "--image", "identity/x.png",
"--voice", "piper-en_US-amy-medium",
"--session-id", "dbg001", "--session-dir", str(sdir)],
cwd=str(ROOT), capture_output=True, text=True, timeout=90, env=env)
print("[debug] bot exit", r.returncode)
print("[debug] bot stdout:\n" + r.stdout[-3000:])
print("[debug] bot stderr:\n" + r.stderr[-3000:])
except subprocess.TimeoutExpired as e:
print("[debug] bot ran the full 90s (no crash). stdout:\n"
+ (e.stdout or b"").decode()[-3000:]
+ "\nstderr:\n" + (e.stderr or b"").decode()[-3000:], flush=True)
state = (sdir / "state.json")
print("[debug] state.json:", state.read_text() if state.exists() else "MISSING", flush=True)
server.terminate()
print("[debug] done", flush=True)