Download scripts/freestream.py from LoveLogicAI/freestream: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/datasets/LoveLogicAI/freestream/resolve/main/scripts/freestream.py
- Command line
-
hf download hf://datasets/LoveLogicAI/freestream/scripts/freestream.py
-
curl -L -o freestream.py https://huggingface.co/datasets/LoveLogicAI/freestream/resolve/main/scripts/freestream.py
12 kB
| #!/usr/bin/env python | |
| # FREESTREAM — universal free-tier avatar-meeting skill. | |
| # | |
| # Clean-room reimplementation, CLI-compatible with: | |
| # Pika-Labs/Pika-Skills — pikastream-video-meeting (Apache-2.0) | |
| # | |
| # Exit codes (Pika-compatible, one addition): | |
| # 0 = ok | |
| # 1 = configuration error (FREESTREAM-specific: invalid config file / no driver) | |
| # 2 = validation error | |
| # 3 = transport error | |
| # 4 = session error | |
| # 5 = timeout | |
| # 6 = capability shortfall (repurposed from Pika's "funding": | |
| # stdout JSON carries "capability" and "remediation" instead of "checkout_url") | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| from pathlib import Path | |
| # Make the freestream package importable when run from the repo checkout. | |
| sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) | |
| from freestream.events import EventLog | |
| from freestream.presence import ( | |
| SESSIONS_DIR, | |
| CapabilityShortfall, | |
| DriverError, | |
| ValidationError, | |
| get_driver, | |
| infer_platform, | |
| list_drivers, | |
| shutdown_session, | |
| ) | |
| from freestream.persona import FidelityRung, VoiceBackend, select_rung | |
| SKILL_DIR = Path(__file__).resolve().parent.parent | |
| DEFAULT_IMAGE = SKILL_DIR / "assets" / "placeholder-avatar.jpg" | |
| DEFAULT_VOICE = "piper-en_US-amy-medium" | |
| EX_OK, EX_CONFIG, EX_VALIDATION, EX_TRANSPORT, EX_SESSION, EX_TIMEOUT, EX_CAPABILITY = 0, 1, 2, 3, 4, 5, 6 | |
| def eprint(*a): | |
| print(*a, file=sys.stderr) | |
| def emit(obj: dict) -> None: | |
| print(json.dumps(obj)) | |
| sys.stdout.flush() | |
| def resolve_voice(voice_id: str | None) -> str: | |
| """Pika-compatible voice resolution: flag > life/voice_id.txt > default.""" | |
| if voice_id: | |
| return voice_id | |
| life_file = Path("life") / "voice_id.txt" | |
| if life_file.exists(): | |
| cached = life_file.read_text().strip() | |
| if cached: | |
| return cached | |
| return DEFAULT_VOICE | |
| # --------------------------------------------------------------------------- join | |
| def cmd_join(args) -> int: | |
| if not args.meet_url.startswith(("http://", "https://")): | |
| eprint(f"Error: not a meeting URL: {args.meet_url}") | |
| return EX_VALIDATION | |
| platform = args.platform or infer_platform(args.meet_url) | |
| if not platform: | |
| eprint("Error: can't infer platform from URL; pass --platform") | |
| return EX_VALIDATION | |
| image = Path(args.image or str(DEFAULT_IMAGE)) | |
| if not image.exists() or image.stat().st_size < 1024: | |
| eprint(f"Error: avatar image missing or too small (<1KB): {image}") | |
| return EX_VALIDATION | |
| system_prompt = args.system_prompt | |
| if args.system_prompt_file: | |
| sp = Path(args.system_prompt_file) | |
| if not sp.exists(): | |
| eprint(f"Error: system prompt file not found: {sp}") | |
| return EX_VALIDATION | |
| system_prompt = sp.read_text().strip() | |
| voice = resolve_voice(args.voice_id) | |
| # ---- driver selection ------------------------------------------------- | |
| driver_name = args.driver | |
| if driver_name and driver_name not in list_drivers(): | |
| eprint(f"Error: unknown presence driver '{driver_name}'. Available: {', '.join(sorted(list_drivers()))}") | |
| return EX_CONFIG | |
| if not driver_name: | |
| driver_name = "livekit" if platform == "livekit" else "browser" | |
| eprint(f"No --driver given; selected '{driver_name}' for platform '{platform}'") | |
| # ---- capability negotiation ------------------------------------------ | |
| backend = VoiceBackend(voice) | |
| rung = select_rung(prefer_gpu=not args.cpu_only) | |
| eprint(f"Fidelity rung: {rung.name} | voice: {backend.name}") | |
| session_id = __import__("uuid").uuid4().hex[:12] | |
| session_root = SESSIONS_DIR / session_id | |
| session_root.mkdir(parents=True, exist_ok=True) | |
| log = EventLog(session_root / "events.jsonl") | |
| log.append("session.requested", platform=platform, driver=driver_name, bot_name=args.bot_name, | |
| voice=voice, rung=rung.name, meet_url=args.meet_url) | |
| try: | |
| drv = get_driver(driver_name, log=log) | |
| sid = drv.join( | |
| meet_url=args.meet_url, | |
| platform=platform, | |
| bot_name=args.bot_name, | |
| image=image, | |
| voice=voice, | |
| system_prompt=system_prompt, | |
| meeting_password=args.meeting_password, | |
| session_id=session_id, | |
| session_dir=session_root, | |
| ) | |
| except ValidationError as e: | |
| eprint(f"Error: {e}") | |
| return EX_VALIDATION | |
| except CapabilityShortfall as e: | |
| emit({"status": "capability_shortfall", "capability": e.capability, | |
| "remediation": e.remediation, "driver": driver_name}) | |
| return EX_CAPABILITY | |
| except DriverError as e: | |
| eprint(f"Error: transport: {e}") | |
| return EX_TRANSPORT | |
| except NotImplementedError as e: | |
| eprint(f"Error: driver '{driver_name}' not implemented in this scaffold: {e}") | |
| emit({"status": "not_implemented", "driver": driver_name, | |
| "note": "MVP slice targets the livekit driver (Jitsi/LiveKit)"}) | |
| return EX_CONFIG | |
| # Rename the session directory to the real id so replay paths are stable. | |
| sid = session_id | |
| # Pika-compatible first output: emitted immediately so the agent can capture it. | |
| emit({"session_id": sid, "platform": platform, "status": "created"}) | |
| log.append("session.created", session_id=sid, driver=driver_name) | |
| # ---- poll until ready (Pika-compatible status stream) ----------------- | |
| deadline = __import__("time").time() + args.timeout_sec | |
| last_status = None | |
| while __import__("time").time() < deadline: | |
| __import__("time").sleep(2) | |
| status = drv.status(sid) | |
| if status != last_status: | |
| emit({"session_id": sid, "status": status, "video": drv.video_connected(sid), | |
| "bot": drv.bot_connected(sid)}) | |
| last_status = status | |
| log.append("session.status", status=status) | |
| if status == "ready" or status in ("speaking", "thinking", "listening"): | |
| log.append("session.ready", session_id=sid) | |
| return EX_OK | |
| if status in ("error", "closed"): | |
| log.append("session.failed", status=status) | |
| return EX_SESSION | |
| eprint("Error: timeout") | |
| log.append("session.timeout") | |
| return EX_TIMEOUT | |
| # --------------------------------------------------------------------------- leave | |
| def cmd_leave(args) -> int: | |
| try: | |
| detail = shutdown_session(args.session_id) | |
| except DriverError as e: | |
| eprint(f"Error: transport: {e}") | |
| return EX_TRANSPORT | |
| emit({"session_id": args.session_id, "closed": True}) | |
| return EX_OK | |
| # --------------------------------------------------------------------------- generate-avatar | |
| def cmd_generate_avatar(args) -> int: | |
| out = Path(args.output) | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| prompt = args.prompt or ("A friendly, approachable portrait headshot of a virtual assistant " | |
| "avatar. Clean background, warm expression, centered face, suitable " | |
| "for video calls.") | |
| # Local-first: bundled procedural avatar (freestream.avatar) — no model, | |
| # no network, always available. A heavy local generator can plug in later. | |
| try: | |
| import freestream.avatar as avatar_mod | |
| except ImportError: | |
| avatar_mod = None | |
| if avatar_mod is not None: | |
| path = avatar_mod.generate_placeholder(out) | |
| emit({"path": str(path), "size_bytes": Path(path).stat().st_size, | |
| "generated": True, "generator": "procedural-face"}) | |
| return EX_OK | |
| emit({"status": "capability_shortfall", "capability": "image_generation", | |
| "remediation": "install a local backend (e.g. `pip install freestream[avatar-gen]`) " | |
| "or place a portrait at assets/placeholder-avatar.jpg"}) | |
| return EX_CAPABILITY | |
| # --------------------------------------------------------------------------- clone-voice | |
| def cmd_clone_voice(args) -> int: | |
| audio = Path(args.audio) | |
| if not audio.exists(): | |
| eprint(f"Error: audio file not found: {audio}") | |
| return EX_VALIDATION | |
| backend = VoiceBackend(args.name) | |
| try: | |
| result = backend.clone(audio, name=args.name, noise_reduction=args.noise_reduction) | |
| except CapabilityShortfall as e: | |
| emit({"status": "capability_shortfall", "capability": e.capability, "remediation": e.remediation}) | |
| return EX_CAPABILITY | |
| # Pika-compatible identity files (local-only; clones never leave the device). | |
| life = Path("life") | |
| life.mkdir(parents=True, exist_ok=True) | |
| (life / "voice_id.txt").write_text(result["voice_id"]) | |
| import json as _json | |
| (life / "voice_config.json").write_text(_json.dumps(result, indent=2)) | |
| emit(result) | |
| return EX_OK | |
| # --------------------------------------------------------------------------- probe | |
| def cmd_probe(args) -> int: | |
| """Capability negotiation: report the best pipeline for this hardware.""" | |
| import platform as _platform | |
| probe = { | |
| "platform": _platform.system(), | |
| "machine": _platform.machine(), | |
| "drivers": sorted(list_drivers()), | |
| "voice": VoiceBackend().probe(), | |
| "fidelity_rung": select_rung(prefer_gpu=not args.cpu_only).name, | |
| "gpu": probe_gpu(), | |
| "exit_code_meanings": { | |
| "0": "ok", "1": "configuration", "2": "validation", "3": "transport", | |
| "4": "session", "5": "timeout", "6": "capability_shortfall", | |
| }, | |
| } | |
| emit(probe) | |
| return EX_OK | |
| def probe_gpu() -> dict: | |
| info = {"cuda": False, "mps": False, "ane": False} | |
| try: | |
| import torch # optional | |
| info["cuda"] = bool(torch.cuda.is_available()) | |
| info["mps"] = bool(getattr(torch.backends, "mps", None) and torch.backends.mps.is_available()) | |
| info["torch"] = torch.__version__ | |
| except ImportError: | |
| pass | |
| return info | |
| # --------------------------------------------------------------------------- main | |
| def main(): | |
| p = argparse.ArgumentParser(prog="freestream", | |
| description="Free-tier avatar-meeting skill (Pika-CLI-compatible)") | |
| sub = p.add_subparsers(dest="cmd", required=True) | |
| j = sub.add_parser("join") | |
| j.add_argument("--meet-url", required=True) | |
| j.add_argument("--platform", choices=["google_meet", "zoom", "jitsi", "livekit"]) | |
| j.add_argument("--driver", help="presence driver: browser | livekit | sip") | |
| j.add_argument("--bot-name", required=True) | |
| j.add_argument("--voice-id") | |
| j.add_argument("--meeting-password") | |
| j.add_argument("--system-prompt", help="System prompt text for the meeting agent") | |
| j.add_argument("--system-prompt-file", help="Path to file containing system prompt") | |
| j.add_argument("--image") | |
| j.add_argument("--timeout-sec", type=int, default=90) | |
| j.add_argument("--cpu-only", action="store_true", help="Force the fidelity ladder to CPU rungs") | |
| j.set_defaults(func=cmd_join) | |
| lv = sub.add_parser("leave") | |
| lv.add_argument("--session-id", required=True) | |
| lv.add_argument("--driver") | |
| lv.set_defaults(func=cmd_leave) | |
| ga = sub.add_parser("generate-avatar") | |
| ga.add_argument("--output", required=True) | |
| ga.add_argument("--prompt", help="Custom prompt for avatar generation") | |
| ga.add_argument("--model", default="local", help="[compat] ignored; kept for Pika CLI parity") | |
| ga.set_defaults(func=cmd_generate_avatar) | |
| cv = sub.add_parser("clone-voice") | |
| cv.add_argument("--audio", required=True, help="Audio file (10s-5min, clear speech)") | |
| cv.add_argument("--name", required=True) | |
| cv.add_argument("--noise-reduction", action="store_true") | |
| cv.set_defaults(func=cmd_clone_voice) | |
| pr = sub.add_parser("probe") | |
| pr.add_argument("--cpu-only", action="store_true") | |
| pr.set_defaults(func=cmd_probe) | |
| args = p.parse_args() | |
| return args.func(args) | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) |