antigravity-studio 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. antigravity_studio/__init__.py +10 -0
  2. antigravity_studio/__main__.py +8 -0
  3. antigravity_studio/antigravity_kit/agents/cast-guardian.md +16 -0
  4. antigravity_studio/antigravity_kit/agents/reliability-gatekeeper.md +18 -0
  5. antigravity_studio/antigravity_kit/agents/studio-director.md +16 -0
  6. antigravity_studio/antigravity_kit/skills/studio-director/SKILL.md +29 -0
  7. antigravity_studio/antigravity_kit/workflows/studio-record.md +11 -0
  8. antigravity_studio/antigravity_kit/workflows/studio-run.md +14 -0
  9. antigravity_studio/audio_mix.py +117 -0
  10. antigravity_studio/captions.py +238 -0
  11. antigravity_studio/cli.py +475 -0
  12. antigravity_studio/contracts/__init__.py +1 -0
  13. antigravity_studio/contracts/gates.report.schema.json +95 -0
  14. antigravity_studio/contracts/movie.manifest.schema.json +183 -0
  15. antigravity_studio/contracts/shot.receipt.schema.json +31 -0
  16. antigravity_studio/contracts/studio.manifest.schema.json +110 -0
  17. antigravity_studio/derived.py +117 -0
  18. antigravity_studio/doctor.py +171 -0
  19. antigravity_studio/downloads.py +205 -0
  20. antigravity_studio/export.py +231 -0
  21. antigravity_studio/gates.py +597 -0
  22. antigravity_studio/hashing.py +195 -0
  23. antigravity_studio/hyperframes_engine.py +400 -0
  24. antigravity_studio/manifest.py +386 -0
  25. antigravity_studio/mcp_server.py +326 -0
  26. antigravity_studio/media.py +539 -0
  27. antigravity_studio/movie.py +297 -0
  28. antigravity_studio/movie_manifest.py +193 -0
  29. antigravity_studio/movie_mix.py +272 -0
  30. antigravity_studio/movie_template.py +328 -0
  31. antigravity_studio/originality.py +275 -0
  32. antigravity_studio/plugin_install.py +173 -0
  33. antigravity_studio/plugin_kit/README.md +14 -0
  34. antigravity_studio/plugin_kit/agents/studio-director.md +20 -0
  35. antigravity_studio/plugin_kit/assets/logo.svg +33 -0
  36. antigravity_studio/plugin_kit/mcp_config.json +8 -0
  37. antigravity_studio/plugin_kit/plugin.json +18 -0
  38. antigravity_studio/plugin_kit/skills/antigravity-studio/SKILL.md +38 -0
  39. antigravity_studio/provenance.py +381 -0
  40. antigravity_studio/recordly.py +92 -0
  41. antigravity_studio/reel.py +249 -0
  42. antigravity_studio/reviews.py +181 -0
  43. antigravity_studio/scheduler.py +338 -0
  44. antigravity_studio/skills_install.py +144 -0
  45. antigravity_studio/state.py +606 -0
  46. antigravity_studio/toolpaths.py +75 -0
  47. antigravity_studio-0.2.0.dist-info/METADATA +374 -0
  48. antigravity_studio-0.2.0.dist-info/RECORD +51 -0
  49. antigravity_studio-0.2.0.dist-info/WHEEL +4 -0
  50. antigravity_studio-0.2.0.dist-info/entry_points.txt +3 -0
  51. antigravity_studio-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,10 @@
1
+ """Antigravity Studio: zero-drift AI film & brand production orchestrator."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("antigravity-studio")
7
+ except PackageNotFoundError: # pragma: no cover - editable/uninstalled fallback
8
+ __version__ = "0.2.0"
9
+
10
+ VERIFIER_VERSION = f"agstudio-gates-{__version__}"
@@ -0,0 +1,8 @@
1
+ """`python -m antigravity_studio ...` == `agstudio ...` (robust launcher for GUI MCP hosts)."""
2
+
3
+ import sys
4
+
5
+ from antigravity_studio.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
@@ -0,0 +1,16 @@
1
+ ---
2
+ name: cast-guardian
3
+ description: "Enforces zero character or hero-prop drift across multi-era AI video shots using Gate 2 evidence strips and bounded retries."
4
+ subagent: true
5
+ mainAgent: false
6
+ tools: [read_file, run_command]
7
+ ---
8
+
9
+ # Agent: Cast Guardian (`cast-guardian`)
10
+
11
+ - **Role:** Enforces zero character or hero-prop drift across multi-era shots (`1996 → 2026`).
12
+ - **Workflow:**
13
+ 1. After each shot receipt is recorded, invoke `studio_check_cast_drift(project_dir, shot_id)`.
14
+ 2. Inspect `verification/cast_drift/<shot_id>_strip.jpg` visually comparing locked `cast/*_master.png` anchors against start/mid/end frames.
15
+ 3. Reject shots where facial geometry, wardrobe continuity, or hero bag hardware mutates unintentionally.
16
+ 4. Respect bounded retry cap (`max_retries_per_shot = 2`); escalate to the human director on attempt 3.
@@ -0,0 +1,18 @@
1
+ ---
2
+ name: reliability-gatekeeper
3
+ description: "Independent fail-closed mechanical verifier enforcing all 7 Antigravity Studio reliability gates before release."
4
+ subagent: true
5
+ mainAgent: false
6
+ tools: [read_file, run_command]
7
+ ---
8
+
9
+ # Agent: Reliability Gatekeeper (`reliability-gatekeeper`)
10
+
11
+ - **Role:** Independent mechanical verifier. Runs `studio_verify_all(project_dir)` and refuses release on any failed gate.
12
+ - **7 Non-Negotiable Gates (Gate 7 = YPP copyright & originality):**
13
+ 1. `gate_1_schema_contract` — Manifest Draft 2020-12 schema, cast refs, contiguous order, runtime budget.
14
+ 2. `gate_2_cast_drift` — Start/mid/end keyframe strips + intra-shot stability + locked reference verification.
15
+ 3. `gate_3_seam_flicker` — Zero mid-film black drops, freeze check, HyperFrames parallel-worker flicker lint.
16
+ 4. `gate_4_audio_lufs` — EBU R128 integrated loudness `-14.0 ± 1.0 LUFS`, true peak `<= -1.0 dBTP`.
17
+ 5. `gate_5_duration_tail` — Master duration matches target within tolerance + `>= 3.0s` visual breathing tail.
18
+ 6. `gate_6_contact_sheet` — Renders `exports/gates-sheet.jpg` and validates `exports/gates.json` schema.
@@ -0,0 +1,16 @@
1
+ ---
2
+ name: studio-director
3
+ description: "Zero-drift Antigravity Studio film & brand production director driving NotebookLM, Pomelli, Stitch, Flow, Flow Music, Genie, HyperFrames, and 7 Reliability Gates (incl. Gate 7 copyright)."
4
+ subagent: true
5
+ mainAgent: false
6
+ tools: [read_file, edit_file, write_file, run_command, manage_task]
7
+ ---
8
+
9
+ # Agent: Studio Director (`studio-director`)
10
+
11
+ - **Role:** Owns `studio.manifest.json`, resumable `state.json`, and deterministic stage progression via `antigravity-studio` MCP (`studio_next_step`, `studio_record_receipt`, `studio_ingest_downloads`).
12
+ - **Hard Rules:**
13
+ 1. Never skip locked cast/prop reference posters before generating character shots.
14
+ 2. Never modify manifest durations without re-running `studio_validate`.
15
+ 3. Never bypass CAPTCHAs or logins in Chrome CDP — pause cleanly for the human operator.
16
+ 4. Never declare production complete until `reliability-gatekeeper` reports all 7 gates green.
@@ -0,0 +1,29 @@
1
+ ---
2
+ name: studio-director
3
+ description: "Zero-drift Antigravity Studio orchestrator controlling NotebookLM, Pomelli, Stitch, Flow, Flow Music, Genie 4, HyperFrames, and 7 Reliability Gates (incl. Gate 7 copyright)."
4
+ ---
5
+
6
+ # Antigravity Studio Director Skill
7
+
8
+ Operate as a **zero-drift film and brand production director**. Never improvise shot order, prompts, or completion status from chat memory — always read state from `agstudio` (`antigravity-studio` MCP or `agstudio` CLI).
9
+
10
+ ## Kickoff: Director Mode (Default) vs Autopilot Mode
11
+ At the start of a new project, ask the user which execution mode they prefer (or switch anytime mid-project via `studio_set_mode(project_dir, "director" | "autopilot")` / `agstudio mode <dir> director|autopilot`):
12
+ - **`director` (default — Interactive Creative Review):** After every produced artifact (brand brief, Pomelli hero, Stitch website, cast posters, each video shot after Gate 2 drift verification, music score, and master commercial), `studio_next_step` pauses with `action: "await_user_review"`. Present the asset (`rel_path` / `abs_path` and cast-drift strip for shots) to the user and ask for approval or creative direction (e.g., bag silhouette, lighting, camera move, wardrobe, music mood).
13
+ - If approved: call `studio_review_step(project_dir, artifact_id=..., approved=True)` (or `agstudio review <dir> --artifact <id> --approve`).
14
+ - If changes are requested: call `studio_review_step(project_dir, artifact_id=..., approved=False, feedback="<user direction>")` (or `agstudio review <dir> --artifact <id> --feedback "..."`). On the next call, `studio_next_step` returns `action: "regenerate_with_feedback"` carrying the user's exact feedback; regenerate that asset, record a fresh receipt, and present the updated result for fresh review (approvals are SHA-256 bound, so any regenerated file automatically requires fresh approval).
15
+ - **`autopilot` (End-to-End Autonomous Run):** `studio_next_step` flows straight through every stage without pausing for per-step user approvals while still enforcing per-shot Gate 2 drift checks and all 7 mechanical reliability gates before completion.
16
+
17
+ ## Mandatory Execution Loop
18
+ 1. Call `studio_doctor` first. Confirm `ffmpeg`, `ffprobe`, Chrome CDP, `notebooklm`, and `stitch` are ready.
19
+ 2. Initialize with `studio_init(project_dir, execution_mode="director" | "autopilot")` (default `"director"`) and call `studio_validate(project_dir)` to verify `studio.manifest.json` passes Draft 2020-12 contract & runtime budget.
20
+ 3. Loop strictly on `studio_next_step(project_dir)`:
21
+ - **`action == "await_user_review"` (Director Mode):** Show the asset to the user, collect approval or creative direction, and record via `studio_review_step` before advancing.
22
+ - **`action == "regenerate_with_feedback"` (Director Mode):** Apply the exact `feedback` returned by `studio_next_step`, regenerate that specific artifact, and record a fresh SHA-256 receipt.
23
+ - **`notebooklm_mcp`**: Query/research in NotebookLM and write `brand/research_brief.md`.
24
+ - **`stitch_mcp`**: Call official Google Stitch MCP (`create_project` → `generate_screen_from_text` → `download_file`) into `website/`.
25
+ - **`chrome_devtools_mcp`**: Open the exact URL (`labs.google.com/u/0/pomelli/`, `flow.google.com/`, `flowmusic.app/`, `labs.google/projectgenie`) in the user's visible signed-in Chrome. Upload locked `cast/` reference sheets via `upload_file`, paste the exact manifest prompt, download output, and call `studio_ingest_downloads`. If login/CAPTCHA appears, pause cleanly for the user — never attempt anti-bot bypasses.
26
+ - **`hyperframes_brand_reveal_local` / `hyperframes_endcard_local`**: Call `studio_render_hyperframes` (`render-brand-reveal` / `render-endcard`) for deterministic brand reveal and endcard rendering.
27
+ 4. After every video shot, immediately call `studio_check_cast_drift(project_dir, shot_id)` and inspect `verification/cast_drift/<shot_id>_strip.jpg`. If cast/prop drift fails, retry bounded up to `max_retries_per_shot` (default 2) before escalating to human review.
28
+ 5. Once all shots & score have SHA-256 receipts (and approvals in Director Mode), call `studio_master_av(project_dir)` then `studio_verify_all(project_dir)`.
29
+ 6. **Completion Law:** Never declare the film done unless `exports/gates.json` reports `"overall_pass": true` across all 7 mechanical gates.
@@ -0,0 +1,11 @@
1
+ ---
2
+ description: Arm Recordly.app and capture a clean Antigravity Studio live orchestration session (/studio-record)
3
+ ---
4
+
5
+ # /studio-record
6
+
7
+ 1. Call `studio_record_control(action="status")` to verify `/Applications/Recordly.app` is installed and running.
8
+ 2. Position signed-in Google Chrome cleanly (16:9, bookmarks hidden, zero unrelated tabs).
9
+ 3. Call `studio_record_control(action="open")` to bring Recordly forward, then `studio_record_control(action="toggle")` (or click Start via `macos-computer-use` MCP) to start recording.
10
+ 4. Run the desired `/studio-run` chapter cleanly on screen.
11
+ 5. Call `studio_record_control(action="toggle")` when the chapter completes and verify the saved capture on disk.
@@ -0,0 +1,14 @@
1
+ ---
2
+ description: Run Antigravity Studio end-to-end production loop without drift (/studio-run)
3
+ ---
4
+
5
+ # /studio-run
6
+
7
+ 1. Run `studio_doctor` and confirm all binaries and MCPs are green.
8
+ 2. Confirm execution mode with the user at kickoff: **Director Mode** (`director`, default — pauses after every artifact for creative review/feedback) or **Autopilot Mode** (`autopilot` — runs end-to-end without review pauses). Switch anytime via `studio_set_mode` or `agstudio mode <dir> director|autopilot`.
9
+ 3. Run `studio_status(project_dir)` and `studio_next_step(project_dir)`.
10
+ 4. Execute ONLY the exact step returned by `studio_next_step`:
11
+ - In **Director Mode**, when `action == "await_user_review"`, show the produced artifact (`rel_path` / `abs_path`) to the user, ask for approval or creative direction, and record via `studio_review_step` (`agstudio review`). When `action == "regenerate_with_feedback"`, apply the user's feedback, regenerate that asset, and record a new receipt.
12
+ - Otherwise execute the returned production stage (NotebookLM -> Pomelli -> Stitch MCP -> Flow Cast Posters -> Flow 8 Shots + Genie 4 -> Flow Music -> HyperFrames Endcard -> FFmpeg Master -> 7 Mechanical Reliability Gates).
13
+ 5. Record a SHA-256 receipt after every produced file so progress and SHA-256-bound reviews are 100% resumable.
14
+ 6. Finish only when `studio_verify_all` outputs `"overall_pass": true` and `exports/gates-sheet.jpg`.
@@ -0,0 +1,117 @@
1
+ """Shared FFmpeg helpers for v0.2 engines: bounded runs, two-pass EBU R128, and voice-presence checks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import os
8
+ import re
9
+ import subprocess
10
+ import tempfile
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from antigravity_studio.media import ENCODE_TIMEOUT_SEC, measure_loudness, probe_media
15
+ from antigravity_studio.toolpaths import ffmpeg_exe
16
+
17
+ AUDIO_ENCODE_ARGS = ("-c:a", "aac", "-ar", "48000", "-ac", "2", "-b:a", "256k")
18
+
19
+
20
+ def require_ffmpeg() -> str:
21
+ """Return the ffmpeg path or raise FileNotFoundError with an install hint."""
22
+ found = ffmpeg_exe()
23
+ if not found:
24
+ raise FileNotFoundError("ffmpeg not found (macOS: brew install ffmpeg; Ubuntu: sudo apt install ffmpeg)")
25
+ return found
26
+
27
+
28
+ def encode_timeout(duration_sec: float) -> int:
29
+ """Scale the encode timeout with media length so long films never hit a fixed 180 s wall."""
30
+ return int(max(ENCODE_TIMEOUT_SEC, duration_sec * 30.0))
31
+
32
+
33
+ def run_ffmpeg(cmd: list[str], *, timeout: int) -> tuple[bool, str]:
34
+ """Run ffmpeg with a hard timeout; return (ok, stderr tail)."""
35
+ try:
36
+ res = subprocess.run(cmd, capture_output=True, text=True, check=False, timeout=timeout)
37
+ except subprocess.TimeoutExpired:
38
+ return False, f"ffmpeg timed out after {timeout}s"
39
+ except FileNotFoundError as exc:
40
+ return False, str(exc)
41
+ return res.returncode == 0, res.stderr.strip()[-800:]
42
+
43
+
44
+ def loudnorm_two_pass(
45
+ src: Path,
46
+ dest: Path,
47
+ *,
48
+ target_lufs: float,
49
+ max_true_peak_dbtp: float = -1.0,
50
+ timeout: int = ENCODE_TIMEOUT_SEC,
51
+ ) -> dict[str, Any]:
52
+ """Two-pass loudnorm src -> dest (video stream copied), atomically, then measure the result."""
53
+ ffmpeg = require_ffmpeg()
54
+ tp = round(max_true_peak_dbtp - 0.3, 1) # AAC re-encode headroom
55
+ base = f"loudnorm=I={target_lufs:.1f}:TP={tp:.1f}:LRA=11"
56
+ try:
57
+ p1 = subprocess.run(
58
+ [ffmpeg, "-nostats", "-i", str(src), "-vn", "-af", f"{base}:print_format=json", "-f", "null", "-"],
59
+ capture_output=True,
60
+ text=True,
61
+ check=False,
62
+ timeout=timeout,
63
+ )
64
+ except subprocess.TimeoutExpired:
65
+ return {"ok": False, "error": f"loudnorm analysis timed out after {timeout}s"}
66
+ m_json = re.search(r"\{[^{}]*\"input_i\"[^{}]*\}", p1.stderr, re.DOTALL)
67
+ af = base
68
+ if m_json:
69
+ stats = json.loads(m_json.group(0))
70
+ af = (
71
+ f"{base}:linear=true:measured_I={stats['input_i']}:measured_TP={stats['input_tp']}:"
72
+ f"measured_LRA={stats['input_lra']}:measured_thresh={stats['input_thresh']}:"
73
+ f"offset={stats['target_offset']}"
74
+ )
75
+
76
+ dest.parent.mkdir(parents=True, exist_ok=True)
77
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{dest.stem}.", suffix=dest.suffix or ".mp4", dir=str(dest.parent))
78
+ os.close(fd)
79
+ tmp = Path(tmp_name)
80
+ replaced = False
81
+ try:
82
+ has_video = bool(probe_media(src).get("has_video"))
83
+ cmd = [ffmpeg, "-y", "-v", "error", "-i", str(src), "-af", f"{af},aresample=48000"]
84
+ cmd += ["-c:v", "copy"] if has_video else ["-vn"]
85
+ cmd += [*AUDIO_ENCODE_ARGS, "-movflags", "+faststart", str(tmp)]
86
+ ok, err = run_ffmpeg(cmd, timeout=timeout)
87
+ if not ok:
88
+ return {"ok": False, "error": f"loudnorm pass 2 failed: {err}"}
89
+ loud = measure_loudness(tmp)
90
+ if not loud.get("ok"):
91
+ return {"ok": False, "error": f"loudness verification failed: {loud.get('error')}"}
92
+ os.replace(tmp, dest)
93
+ replaced = True
94
+ return {"ok": True, "loudness": loud, "two_pass": bool(m_json)}
95
+ finally:
96
+ if not replaced:
97
+ with contextlib.suppress(OSError):
98
+ tmp.unlink()
99
+
100
+
101
+ def mean_volume_db(media: Path, *, start: float = 0.0, duration: float | None = None) -> float | None:
102
+ """Mean audio volume (dBFS) of a window via volumedetect; None when unmeasurable."""
103
+ ffmpeg = ffmpeg_exe()
104
+ if not ffmpeg:
105
+ return None
106
+ cmd = [ffmpeg, "-nostats", "-ss", f"{max(0.0, start):.3f}"]
107
+ if duration is not None:
108
+ cmd += ["-t", f"{max(0.05, duration):.3f}"]
109
+ cmd += ["-i", str(media), "-vn", "-af", "volumedetect", "-f", "null", "-"]
110
+ try:
111
+ res = subprocess.run(cmd, capture_output=True, text=True, check=False, timeout=ENCODE_TIMEOUT_SEC)
112
+ except subprocess.TimeoutExpired:
113
+ return None
114
+ match = re.search(r"mean_volume:\s*(-?\d+(?:\.\d+)?|-inf)\s*dB", res.stderr)
115
+ if not match or match.group(1) == "-inf":
116
+ return None
117
+ return float(match.group(1))
@@ -0,0 +1,238 @@
1
+ """SRT parsing and UI-safe burned-in caption rendering that needs no libass/freetype in ffmpeg."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import platform
8
+ import re
9
+ import subprocess
10
+ import sys
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from PIL import Image, ImageDraw, ImageFont, features
15
+
16
+ # 1080x1920 vertical safe area: platform chrome covers the top bar, the bottom caption/CTA
17
+ # stack, and the right-hand action rail on Shorts, Reels, and TikTok.
18
+ VERTICAL_SAFE_ZONE = {"left": 60, "right": 1080 - 160, "top": 240, "bottom": 1920 - 480}
19
+ MAX_CUES = 400
20
+
21
+ _TS = r"(\d{1,2}):(\d{2}):(\d{2})[,.](\d{1,3})"
22
+ _CUE_RE = re.compile(_TS + r"\s*-->\s*" + _TS)
23
+ _DEVANAGARI = re.compile(r"[\u0900-\u097F]")
24
+ # Scripts that need complex text layout (reordering/conjuncts): Indic, Arabic, Hebrew, Thai, etc.
25
+ _COMPLEX_SCRIPT = re.compile(r"[\u0590-\u08FF\u0900-\u0DFF\u0E00-\u0E7F\u1000-\u109F]")
26
+ _FRIBIDI_DIRS = ("/opt/homebrew/lib", "/usr/local/lib", "/opt/local/lib")
27
+ _LATIN_FONTS = (
28
+ "/System/Library/Fonts/Supplemental/Arial Bold.ttf",
29
+ "/System/Library/Fonts/Helvetica.ttc",
30
+ "/Library/Fonts/Arial Bold.ttf",
31
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
32
+ "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf",
33
+ "C:/Windows/Fonts/arialbd.ttf",
34
+ )
35
+ _DEVANAGARI_FONTS = (
36
+ "/System/Library/Fonts/Supplemental/Devanagari Sangam MN.ttc",
37
+ "/System/Library/Fonts/Kohinoor.ttc",
38
+ "/usr/share/fonts/truetype/noto/NotoSansDevanagari-Bold.ttf",
39
+ "/usr/share/fonts/truetype/lohit-devanagari/Lohit-Devanagari.ttf",
40
+ "C:/Windows/Fonts/Nirmala.ttf",
41
+ )
42
+
43
+
44
+ def _ts_to_sec(h: str, m: str, s: str, ms: str) -> float:
45
+ return int(h) * 3600 + int(m) * 60 + int(s) + int(ms.ljust(3, "0")) / 1000.0
46
+
47
+
48
+ def sec_to_srt_ts(value: float) -> str:
49
+ """Format seconds as an SRT timestamp (HH:MM:SS,mmm)."""
50
+ total_ms = max(0, round(value * 1000))
51
+ h, rem = divmod(total_ms, 3_600_000)
52
+ m, rem = divmod(rem, 60_000)
53
+ s, ms = divmod(rem, 1000)
54
+ return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
55
+
56
+
57
+ def parse_srt(text: str) -> list[dict[str, Any]]:
58
+ """Parse SRT text into ordered cues; raises ValueError on malformed or overlapping timing."""
59
+ cues: list[dict[str, Any]] = []
60
+ for block in re.split(r"\r?\n\s*\r?\n", text.strip().lstrip("\ufeff")):
61
+ lines = [ln.rstrip() for ln in block.splitlines() if ln.strip()]
62
+ timing_idx = next((i for i, ln in enumerate(lines) if _CUE_RE.search(ln)), None)
63
+ if timing_idx is None:
64
+ continue
65
+ match = _CUE_RE.search(lines[timing_idx])
66
+ if match is None:
67
+ continue
68
+ start = _ts_to_sec(*match.groups()[:4])
69
+ end = _ts_to_sec(*match.groups()[4:])
70
+ body = " ".join(lines[timing_idx + 1 :]).strip()
71
+ if end <= start:
72
+ raise ValueError(f"SRT cue ends before it starts at {lines[timing_idx]!r}")
73
+ if body:
74
+ cues.append({"start": round(start, 3), "end": round(end, 3), "text": body})
75
+ if len(cues) > MAX_CUES:
76
+ raise ValueError(f"SRT has {len(cues)} cues; maximum is {MAX_CUES}")
77
+ return cues
78
+
79
+
80
+ def format_srt(cues: list[dict[str, Any]]) -> str:
81
+ """Serialise cues back to SRT."""
82
+ blocks = [
83
+ f"{i}\n{sec_to_srt_ts(c['start'])} --> {sec_to_srt_ts(c['end'])}\n{c['text']}"
84
+ for i, c in enumerate(cues, start=1)
85
+ ]
86
+ return "\n\n".join(blocks) + "\n"
87
+
88
+
89
+ def _load_font(
90
+ text: str, size: int, layout: ImageFont.Layout = ImageFont.Layout.BASIC
91
+ ) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
92
+ candidates = _DEVANAGARI_FONTS + _LATIN_FONTS if _DEVANAGARI.search(text) else _LATIN_FONTS
93
+ for path in candidates:
94
+ if Path(path).is_file():
95
+ try:
96
+ return ImageFont.truetype(path, size, layout_engine=layout)
97
+ except OSError:
98
+ continue
99
+ return ImageFont.load_default(size=size)
100
+
101
+
102
+ def _wrap(draw: ImageDraw.ImageDraw, text: str, font: Any, max_width: int) -> list[str]:
103
+ words, lines, current = text.split(), [], ""
104
+ for word in words:
105
+ trial = f"{current} {word}".strip()
106
+ if draw.textlength(trial, font=font) <= max_width or not current:
107
+ current = trial
108
+ else:
109
+ lines.append(current)
110
+ current = word
111
+ if current:
112
+ lines.append(current)
113
+ return lines[:3]
114
+
115
+
116
+ def needs_complex_layout(text: str) -> bool:
117
+ """True when text uses a script whose glyphs must be reordered/shaped (e.g. Hindi)."""
118
+ return bool(_COMPLEX_SCRIPT.search(text))
119
+
120
+
121
+ def raqm_available() -> bool:
122
+ """True when Pillow can shape complex scripts in this process."""
123
+ return bool(features.check("raqm"))
124
+
125
+
126
+ def render_caption_png(
127
+ text: str,
128
+ out_path: Path,
129
+ *,
130
+ max_width: int,
131
+ font_size: int = 54,
132
+ shaped: bool | None = None,
133
+ ) -> tuple[int, int]:
134
+ """Render one caption as a transparent PNG (white bold text on a dark rounded plate)."""
135
+ use_raqm = raqm_available() if shaped is None else shaped
136
+ layout = ImageFont.Layout.RAQM if use_raqm else ImageFont.Layout.BASIC
137
+ lang = "hi" if _DEVANAGARI.search(text) and use_raqm else None
138
+ probe = ImageDraw.Draw(Image.new("RGBA", (8, 8)))
139
+ font = _load_font(text, font_size, layout)
140
+ pad_x, pad_y, gap = 28, 18, 10
141
+ lines = _wrap(probe, text, font, max_width - 2 * pad_x)
142
+ boxes = [probe.textbbox((0, 0), ln, font=font, language=lang) for ln in lines]
143
+ line_h = max((b[3] - b[1]) for b in boxes) if boxes else font_size
144
+ text_w = max((b[2] - b[0]) for b in boxes) if boxes else 0
145
+ width = min(max_width, int(text_w + 2 * pad_x))
146
+ height = int(len(lines) * line_h + (len(lines) - 1) * gap + 2 * pad_y)
147
+ img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
148
+ draw = ImageDraw.Draw(img)
149
+ draw.rounded_rectangle((0, 0, width - 1, height - 1), radius=22, fill=(10, 10, 12, 190))
150
+ y = pad_y
151
+ for ln, box in zip(lines, boxes):
152
+ lw = box[2] - box[0]
153
+ draw.text(((width - lw) / 2 - box[0], y - box[1]), ln, font=font, fill=(255, 255, 255, 255), language=lang)
154
+ y += line_h + gap
155
+ out_path.parent.mkdir(parents=True, exist_ok=True)
156
+ img.save(out_path)
157
+ return width, height
158
+
159
+
160
+ def _shaping_env() -> dict[str, str]:
161
+ env = dict(os.environ)
162
+ if platform.system() == "Darwin":
163
+ extra = [d for d in _FRIBIDI_DIRS if Path(d).is_dir()]
164
+ current = [p for p in env.get("DYLD_FALLBACK_LIBRARY_PATH", "").split(os.pathsep) if p]
165
+ env["DYLD_FALLBACK_LIBRARY_PATH"] = os.pathsep.join([*current, *extra, "/usr/lib"])
166
+ return env
167
+
168
+
169
+ def render_caption_batch(items: list[dict[str, Any]]) -> dict[str, Any]:
170
+ """Render caption PNGs; complex scripts are shaped (in a helper process if needed) or refused.
171
+
172
+ items: [{"text", "out", "max_width", "font_size"?}] -> {"ok", "sizes": [[w, h], ...], "layout"}
173
+ """
174
+ complex_needed = any(needs_complex_layout(str(it["text"])) for it in items)
175
+ if not complex_needed or raqm_available():
176
+ sizes = [
177
+ list(render_caption_png(str(it["text"]), Path(it["out"]), max_width=int(it["max_width"]),
178
+ font_size=int(it.get("font_size", 54))))
179
+ for it in items
180
+ ]
181
+ return {"ok": True, "sizes": sizes, "layout": "raqm" if raqm_available() else "basic"}
182
+ try:
183
+ res = subprocess.run(
184
+ [sys.executable, "-m", "antigravity_studio.captions"],
185
+ input=json.dumps({"items": items}),
186
+ capture_output=True,
187
+ text=True,
188
+ check=False,
189
+ timeout=120,
190
+ env=_shaping_env(),
191
+ )
192
+ payload = json.loads(res.stdout) if res.returncode == 0 and res.stdout.strip() else None
193
+ except (subprocess.TimeoutExpired, json.JSONDecodeError, OSError):
194
+ payload = None
195
+ if isinstance(payload, dict) and payload.get("ok"):
196
+ return payload
197
+ return {
198
+ "ok": False,
199
+ "error": (
200
+ "Captions contain a complex script (e.g. Hindi) but no text shaper is available, so they would "
201
+ "render with broken glyph order. Install FriBiDi (macOS: brew install fribidi; Ubuntu: "
202
+ "sudo apt install libfribidi0; Windows: add fribidi.dll next to Python) and retry."
203
+ ),
204
+ }
205
+
206
+
207
+ def _main() -> int:
208
+ """Helper-process entry: shape and render a caption batch read from stdin as JSON."""
209
+ request = json.loads(sys.stdin.read() or "{}")
210
+ if not raqm_available():
211
+ print(json.dumps({"ok": False, "error": "raqm unavailable in helper process"}))
212
+ return 0
213
+ items = request.get("items", [])
214
+ sizes = [
215
+ list(render_caption_png(str(it["text"]), Path(it["out"]), max_width=int(it["max_width"]),
216
+ font_size=int(it.get("font_size", 54)), shaped=True))
217
+ for it in items
218
+ ]
219
+ print(json.dumps({"ok": True, "sizes": sizes, "layout": "raqm"}))
220
+ return 0
221
+
222
+
223
+ def caption_position(width: int, height: int, *, anchor_bottom_y: int) -> tuple[int, int]:
224
+ """Centre a caption plate inside the vertical safe zone with its bottom edge at anchor_bottom_y."""
225
+ zone = VERTICAL_SAFE_ZONE
226
+ x = zone["left"] + max(0, (zone["right"] - zone["left"] - width) // 2)
227
+ y = min(max(zone["top"], anchor_bottom_y - height), zone["bottom"] - height)
228
+ return int(x), int(y)
229
+
230
+
231
+ def box_inside_safe_zone(x: int, y: int, width: int, height: int) -> bool:
232
+ """True when a caption plate lies fully inside the platform-UI safe zone."""
233
+ zone = VERTICAL_SAFE_ZONE
234
+ return x >= zone["left"] and y >= zone["top"] and x + width <= zone["right"] and y + height <= zone["bottom"]
235
+
236
+
237
+ if __name__ == "__main__": # pragma: no cover - exercised through render_caption_batch
238
+ raise SystemExit(_main())