LoveLogicAI commited on
Commit
2eb033f
·
verified ·
1 Parent(s): 6bf8d45
Files changed (1) hide show
  1. scripts/freestream.py +334 -0
scripts/freestream.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # FREESTREAM — universal free-tier avatar-meeting skill.
3
+ #
4
+ # Clean-room reimplementation, CLI-compatible with:
5
+ # Pika-Labs/Pika-Skills — pikastream-video-meeting (Apache-2.0)
6
+ #
7
+ # Exit codes (Pika-compatible, one addition):
8
+ # 0 = ok
9
+ # 1 = configuration error (FREESTREAM-specific: invalid config file / no driver)
10
+ # 2 = validation error
11
+ # 3 = transport error
12
+ # 4 = session error
13
+ # 5 = timeout
14
+ # 6 = capability shortfall (repurposed from Pika's "funding":
15
+ # stdout JSON carries "capability" and "remediation" instead of "checkout_url")
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ # Make the freestream package importable when run from the repo checkout.
25
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
26
+
27
+ from freestream.events import EventLog
28
+ from freestream.presence import (
29
+ CapabilityShortfall,
30
+ DriverError,
31
+ ValidationError,
32
+ get_driver,
33
+ infer_platform,
34
+ list_drivers,
35
+ )
36
+ from freestream.persona import FidelityRung, VoiceBackend, select_rung
37
+
38
+ SKILL_DIR = Path(__file__).resolve().parent.parent
39
+ DEFAULT_IMAGE = SKILL_DIR / "assets" / "placeholder-avatar.jpg"
40
+ DEFAULT_VOICE = "piper-en_US-amy-medium"
41
+ SESSIONS_DIR = SKILL_DIR / ".freestream" / "sessions"
42
+
43
+ EX_OK, EX_CONFIG, EX_VALIDATION, EX_TRANSPORT, EX_SESSION, EX_TIMEOUT, EX_CAPABILITY = 0, 1, 2, 3, 4, 5, 6
44
+
45
+
46
+ def eprint(*a):
47
+ print(*a, file=sys.stderr)
48
+
49
+
50
+ def emit(obj: dict) -> None:
51
+ print(json.dumps(obj))
52
+ sys.stdout.flush()
53
+
54
+
55
+ def resolve_voice(voice_id: str | None) -> str:
56
+ """Pika-compatible voice resolution: flag > life/voice_id.txt > default."""
57
+ if voice_id:
58
+ return voice_id
59
+ life_file = Path("life") / "voice_id.txt"
60
+ if life_file.exists():
61
+ cached = life_file.read_text().strip()
62
+ if cached:
63
+ return cached
64
+ return DEFAULT_VOICE
65
+
66
+
67
+ # --------------------------------------------------------------------------- join
68
+
69
+
70
+ def cmd_join(args) -> int:
71
+ if not args.meet_url.startswith(("http://", "https://")):
72
+ eprint(f"Error: not a meeting URL: {args.meet_url}")
73
+ return EX_VALIDATION
74
+
75
+ platform = args.platform or infer_platform(args.meet_url)
76
+ if not platform:
77
+ eprint("Error: can't infer platform from URL; pass --platform")
78
+ return EX_VALIDATION
79
+
80
+ image = Path(args.image or str(DEFAULT_IMAGE))
81
+ if not image.exists() or image.stat().st_size < 1024:
82
+ eprint(f"Error: avatar image missing or too small (<1KB): {image}")
83
+ return EX_VALIDATION
84
+
85
+ system_prompt = args.system_prompt
86
+ if args.system_prompt_file:
87
+ sp = Path(args.system_prompt_file)
88
+ if not sp.exists():
89
+ eprint(f"Error: system prompt file not found: {sp}")
90
+ return EX_VALIDATION
91
+ system_prompt = sp.read_text().strip()
92
+
93
+ voice = resolve_voice(args.voice_id)
94
+
95
+ # ---- driver selection -------------------------------------------------
96
+ driver_name = args.driver
97
+ if driver_name and driver_name not in list_drivers():
98
+ eprint(f"Error: unknown presence driver '{driver_name}'. Available: {', '.join(sorted(list_drivers()))}")
99
+ return EX_CONFIG
100
+ if not driver_name:
101
+ driver_name = "livekit" if platform == "livekit" else "browser"
102
+ eprint(f"No --driver given; selected '{driver_name}' for platform '{platform}'")
103
+
104
+ # ---- capability negotiation ------------------------------------------
105
+ backend = VoiceBackend(voice)
106
+ rung = select_rung(prefer_gpu=not args.cpu_only)
107
+ eprint(f"Fidelity rung: {rung.name} | voice: {backend.name}")
108
+
109
+ session_root = SESSIONS_DIR / f"pending-{int(__import__('time').time())}"
110
+ session_root.mkdir(parents=True, exist_ok=True)
111
+ log = EventLog(session_root / "events.jsonl")
112
+ log.append("session.requested", platform=platform, driver=driver_name, bot_name=args.bot_name,
113
+ voice=voice, rung=rung.name, meet_url=args.meet_url)
114
+
115
+ try:
116
+ drv = get_driver(driver_name, log=log)
117
+ sid = drv.join(
118
+ meet_url=args.meet_url,
119
+ platform=platform,
120
+ bot_name=args.bot_name,
121
+ image=image,
122
+ voice=voice,
123
+ system_prompt=system_prompt,
124
+ meeting_password=args.meeting_password,
125
+ )
126
+ except ValidationError as e:
127
+ eprint(f"Error: {e}")
128
+ return EX_VALIDATION
129
+ except CapabilityShortfall as e:
130
+ emit({"status": "capability_shortfall", "capability": e.capability,
131
+ "remediation": e.remediation, "driver": driver_name})
132
+ return EX_CAPABILITY
133
+ except DriverError as e:
134
+ eprint(f"Error: transport: {e}")
135
+ return EX_TRANSPORT
136
+ except NotImplementedError as e:
137
+ eprint(f"Error: driver '{driver_name}' not implemented in this scaffold: {e}")
138
+ emit({"status": "not_implemented", "driver": driver_name,
139
+ "note": "MVP slice targets the livekit driver (Jitsi/LiveKit)"})
140
+ return EX_CONFIG
141
+
142
+ # Rename the session directory to the real id so replay paths are stable.
143
+ session_root = session_root.rename(SESSIONS_DIR / sid)
144
+
145
+ # Pika-compatible first output: emitted immediately so the agent can capture it.
146
+ emit({"session_id": sid, "platform": platform, "status": "created"})
147
+ log.append("session.created", session_id=sid, driver=driver_name)
148
+
149
+ # ---- poll until ready (Pika-compatible status stream) -----------------
150
+ deadline = __import__("time").time() + args.timeout_sec
151
+ last_status = None
152
+ while __import__("time").time() < deadline:
153
+ __import__("time").sleep(2)
154
+ status = drv.status(sid)
155
+ if status != last_status:
156
+ emit({"session_id": sid, "status": status, "video": drv.video_connected(sid),
157
+ "bot": drv.bot_connected(sid)})
158
+ last_status = status
159
+ log.append("session.status", status=status)
160
+ if status == "ready":
161
+ log.append("session.ready", session_id=sid)
162
+ return EX_OK
163
+ if status in ("error", "closed"):
164
+ log.append("session.failed", status=status)
165
+ return EX_SESSION
166
+
167
+ eprint("Error: timeout")
168
+ log.append("session.timeout")
169
+ return EX_TIMEOUT
170
+
171
+
172
+ # --------------------------------------------------------------------------- leave
173
+
174
+
175
+ def cmd_leave(args) -> int:
176
+ drv = get_driver(args.driver or "browser")
177
+ try:
178
+ drv.leave(args.session_id)
179
+ except CapabilityShortfall as e:
180
+ emit({"status": "capability_shortfall", "capability": e.capability, "remediation": e.remediation})
181
+ return EX_CAPABILITY
182
+ except DriverError as e:
183
+ eprint(f"Error: transport: {e}")
184
+ return EX_TRANSPORT
185
+ emit({"session_id": args.session_id, "closed": True})
186
+ return EX_OK
187
+
188
+
189
+ # --------------------------------------------------------------------------- generate-avatar
190
+
191
+
192
+ def cmd_generate_avatar(args) -> int:
193
+ out = Path(args.output)
194
+ out.parent.mkdir(parents=True, exist_ok=True)
195
+ prompt = args.prompt or ("A friendly, approachable portrait headshot of a virtual assistant "
196
+ "avatar. Clean background, warm expression, centered face, suitable "
197
+ "for video calls.")
198
+
199
+ # Local-first: bundled placeholder avatar, unless a generation backend exists.
200
+ local_gen = None
201
+ try:
202
+ import freestream.avatar_gen as avatar_gen # optional module, heavy deps
203
+ local_gen = avatar_gen.available()
204
+ except ImportError:
205
+ pass
206
+
207
+ if local_gen:
208
+ path = local_gen.generate(prompt, out)
209
+ emit({"path": str(path), "size_bytes": Path(path).stat().st_size})
210
+ return EX_OK
211
+
212
+ if DEFAULT_IMAGE.exists():
213
+ import shutil
214
+ shutil.copyfile(DEFAULT_IMAGE, out)
215
+ eprint("No local image-generation backend available; copied bundled placeholder avatar.")
216
+ emit({"path": str(out), "size_bytes": out.stat().st_size, "generated": False})
217
+ return EX_OK
218
+
219
+ emit({"status": "capability_shortfall", "capability": "image_generation",
220
+ "remediation": "install a local backend (e.g. `pip install freestream[avatar-gen]`) "
221
+ "or place a portrait at assets/placeholder-avatar.jpg"})
222
+ return EX_CAPABILITY
223
+
224
+
225
+ # --------------------------------------------------------------------------- clone-voice
226
+
227
+
228
+ def cmd_clone_voice(args) -> int:
229
+ audio = Path(args.audio)
230
+ if not audio.exists():
231
+ eprint(f"Error: audio file not found: {audio}")
232
+ return EX_VALIDATION
233
+
234
+ backend = VoiceBackend(args.name)
235
+ try:
236
+ result = backend.clone(audio, name=args.name, noise_reduction=args.noise_reduction)
237
+ except CapabilityShortfall as e:
238
+ emit({"status": "capability_shortfall", "capability": e.capability, "remediation": e.remediation})
239
+ return EX_CAPABILITY
240
+
241
+ # Pika-compatible identity files (local-only; clones never leave the device).
242
+ life = Path("life")
243
+ life.mkdir(parents=True, exist_ok=True)
244
+ (life / "voice_id.txt").write_text(result["voice_id"])
245
+ import json as _json
246
+ (life / "voice_config.json").write_text(_json.dumps(result, indent=2))
247
+
248
+ emit(result)
249
+ return EX_OK
250
+
251
+
252
+ # --------------------------------------------------------------------------- probe
253
+
254
+
255
+ def cmd_probe(args) -> int:
256
+ """Capability negotiation: report the best pipeline for this hardware."""
257
+ import platform as _platform
258
+ probe = {
259
+ "platform": _platform.system(),
260
+ "machine": _platform.machine(),
261
+ "drivers": sorted(list_drivers()),
262
+ "voice": VoiceBackend.probe(),
263
+ "fidelity_rung": select_rung(prefer_gpu=not args.cpu_only).name,
264
+ "gpu": probe_gpu(),
265
+ "exit_code_meanings": {
266
+ "0": "ok", "1": "configuration", "2": "validation", "3": "transport",
267
+ "4": "session", "5": "timeout", "6": "capability_shortfall",
268
+ },
269
+ }
270
+ emit(probe)
271
+ return EX_OK
272
+
273
+
274
+ def probe_gpu() -> dict:
275
+ info = {"cuda": False, "mps": False, "ane": False}
276
+ try:
277
+ import torch # optional
278
+ info["cuda"] = bool(torch.cuda.is_available())
279
+ info["mps"] = bool(getattr(torch.backends, "mps", None) and torch.backends.mps.is_available())
280
+ info["torch"] = torch.__version__
281
+ except ImportError:
282
+ pass
283
+ return info
284
+
285
+
286
+ # --------------------------------------------------------------------------- main
287
+
288
+
289
+ def main():
290
+ p = argparse.ArgumentParser(prog="freestream",
291
+ description="Free-tier avatar-meeting skill (Pika-CLI-compatible)")
292
+ sub = p.add_subparsers(dest="cmd", required=True)
293
+
294
+ j = sub.add_parser("join")
295
+ j.add_argument("--meet-url", required=True)
296
+ j.add_argument("--platform", choices=["google_meet", "zoom", "jitsi", "livekit"])
297
+ j.add_argument("--driver", help="presence driver: browser | livekit | sip")
298
+ j.add_argument("--bot-name", required=True)
299
+ j.add_argument("--voice-id")
300
+ j.add_argument("--meeting-password")
301
+ j.add_argument("--system-prompt", help="System prompt text for the meeting agent")
302
+ j.add_argument("--system-prompt-file", help="Path to file containing system prompt")
303
+ j.add_argument("--image")
304
+ j.add_argument("--timeout-sec", type=int, default=90)
305
+ j.add_argument("--cpu-only", action="store_true", help="Force the fidelity ladder to CPU rungs")
306
+ j.set_defaults(func=cmd_join)
307
+
308
+ lv = sub.add_parser("leave")
309
+ lv.add_argument("--session-id", required=True)
310
+ lv.add_argument("--driver")
311
+ lv.set_defaults(func=cmd_leave)
312
+
313
+ ga = sub.add_parser("generate-avatar")
314
+ ga.add_argument("--output", required=True)
315
+ ga.add_argument("--prompt", help="Custom prompt for avatar generation")
316
+ ga.add_argument("--model", default="local", help="[compat] ignored; kept for Pika CLI parity")
317
+ ga.set_defaults(func=cmd_generate_avatar)
318
+
319
+ cv = sub.add_parser("clone-voice")
320
+ cv.add_argument("--audio", required=True, help="Audio file (10s-5min, clear speech)")
321
+ cv.add_argument("--name", required=True)
322
+ cv.add_argument("--noise-reduction", action="store_true")
323
+ cv.set_defaults(func=cmd_clone_voice)
324
+
325
+ pr = sub.add_parser("probe")
326
+ pr.add_argument("--cpu-only", action="store_true")
327
+ pr.set_defaults(func=cmd_probe)
328
+
329
+ args = p.parse_args()
330
+ return args.func(args)
331
+
332
+
333
+ if __name__ == "__main__":
334
+ raise SystemExit(main())