remotion-ffmpeg-skill 0.0.0-stage → 0.2.0

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 (32) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +112 -2
  3. package/SKILL.md +66 -0
  4. package/bin/remotion-ffmpeg-skill.js +100 -0
  5. package/mcp/server.py +150 -0
  6. package/package.json +12 -4
  7. package/references/timeline.md +93 -0
  8. package/scripts/_captions.py +79 -0
  9. package/scripts/_common.py +538 -0
  10. package/scripts/_contract.py +202 -0
  11. package/scripts/analyze.py +240 -0
  12. package/scripts/deliver.py +79 -0
  13. package/scripts/doctor.py +83 -0
  14. package/scripts/init.py +62 -0
  15. package/scripts/pipeline.py +122 -0
  16. package/scripts/render.py +215 -0
  17. package/scripts/still.py +84 -0
  18. package/templates/remotion-project/package.json +20 -0
  19. package/templates/remotion-project/public/.gitkeep +0 -0
  20. package/templates/remotion-project/remotion.config.ts +6 -0
  21. package/templates/remotion-project/src/Root.tsx +32 -0
  22. package/templates/remotion-project/src/compositions/BeatMontage.tsx +60 -0
  23. package/templates/remotion-project/src/compositions/Captioned.tsx +95 -0
  24. package/templates/remotion-project/src/compositions/Highlights.tsx +98 -0
  25. package/templates/remotion-project/src/compositions/Jumpcut.tsx +52 -0
  26. package/templates/remotion-project/src/compositions/PeakPulse.tsx +73 -0
  27. package/templates/remotion-project/src/compositions/Titled.tsx +138 -0
  28. package/templates/remotion-project/src/index.ts +4 -0
  29. package/templates/remotion-project/src/lib/SourceVideo.tsx +84 -0
  30. package/templates/remotion-project/src/lib/useStagedFont.ts +25 -0
  31. package/templates/remotion-project/src/timeline.ts +214 -0
  32. package/templates/remotion-project/tsconfig.json +15 -0
@@ -0,0 +1,202 @@
1
+ #!/usr/bin/env python3
2
+ """Machine-readable execution contract for remotion-ffmpeg-skill (internal module, not a tool).
3
+
4
+ python3 scripts/_contract.py --json # every public tool: role, writes, verification, input schema
5
+ python3 scripts/_contract.py doctor --json # same as doctor.py --json
6
+
7
+ Input schemas are generated from each script's own build_parser(), so the CLI stays the single
8
+ source of truth; the facts a parser cannot express (role, what it writes, how it verifies,
9
+ which ffmpeg-skill scripts it calls) live in TOOL_META and are checked by tests/test_contract.py.
10
+ The MCP server (mcp/server.py) is built from this contract and nothing else.
11
+ """
12
+ import argparse
13
+ import importlib
14
+ import json
15
+ import subprocess
16
+ import sys
17
+ from pathlib import Path
18
+ from typing import Any, Dict, List
19
+
20
+ HERE = Path(__file__).resolve().parent
21
+ sys.path.insert(0, str(HERE))
22
+ from _common import SKILL_ID, TIMELINE_SCHEMA, version # noqa: E402
23
+
24
+ CONTRACT_VERSION = "1.0"
25
+
26
+ ROLES = {
27
+ "analysis": "measures media and writes a data file (no media)",
28
+ "execution": "writes a new media artifact; inputs are never modified",
29
+ "verification": "checks an artifact or the environment; writes no media",
30
+ "setup": "creates a project folder",
31
+ "orchestration": "runs other tools in order, each verified before the next",
32
+ }
33
+
34
+ # Tool order = workflow order (also the MCP tools/list order).
35
+ TOOL_META: Dict[str, Dict[str, Any]] = {
36
+ "analyze": {
37
+ "role": "analysis",
38
+ "summary": "Measure a source with ffmpeg-skill and write timeline.json (+ captions from a file).",
39
+ "writes": "timeline.json",
40
+ "verification": "every number comes from ffmpeg-skill probe/scenes/silence; warnings for VFR/HDR/rotation",
41
+ "ffmpeg_skill": ["probe", "scenes", "silence"],
42
+ "dry_run": True,
43
+ },
44
+ "init": {
45
+ "role": "setup",
46
+ "summary": "Create a Remotion project with the built-in compositions (optionally npm install).",
47
+ "writes": "project folder",
48
+ "verification": "refuses a non-empty folder; npm install exit status",
49
+ "ffmpeg_skill": [],
50
+ "dry_run": True,
51
+ },
52
+ "still": {
53
+ "role": "execution",
54
+ "summary": "Render single frames as PNG to check the look before a full render.",
55
+ "writes": "PNG files",
56
+ "verification": "frames must lie inside the composition; view the PNGs",
57
+ "ffmpeg_skill": ["_contract doctor (CJK font lookup)"],
58
+ "dry_run": True,
59
+ },
60
+ "render": {
61
+ "role": "execution",
62
+ "summary": "Render a composition from a timeline, verify it (frames, fps, size, audio) and write a contact sheet.",
63
+ "writes": "video file (+ contact sheet PNG)",
64
+ "verification": "exact frame count / fps / size / audio against the timeline; non-zero exit on mismatch",
65
+ "ffmpeg_skill": ["probe", "look", "overlay (--overlay)", "_contract doctor (CJK font lookup)"],
66
+ "dry_run": True,
67
+ },
68
+ "deliver": {
69
+ "role": "execution",
70
+ "summary": "Run an ffmpeg-skill delivery template (YouTube, Reels, ...) and its compliance check.",
71
+ "writes": "deliverable video",
72
+ "verification": "ffmpeg-skill check.py table; non-zero exit on any FAIL row",
73
+ "ffmpeg_skill": ["render --template", "check"],
74
+ "dry_run": True,
75
+ },
76
+ "pipeline": {
77
+ "role": "orchestration",
78
+ "summary": "analyze -> render -> deliver in one call, stopping at the first failed step.",
79
+ "writes": "timeline.json, render, deliverable",
80
+ "verification": "each step's own verification",
81
+ "ffmpeg_skill": ["probe", "scenes", "silence", "look", "render --template", "check"],
82
+ "dry_run": True,
83
+ },
84
+ "doctor": {
85
+ "role": "verification",
86
+ "summary": "What this machine can do: Python, Node/npm, ffmpeg-skill, ffmpeg, a project's Remotion install.",
87
+ "writes": None,
88
+ "verification": "reports only",
89
+ "ffmpeg_skill": ["_contract doctor"],
90
+ "dry_run": False,
91
+ },
92
+ }
93
+
94
+ # Flags every tool takes; the MCP server adds --json itself.
95
+ SHARED = {"json", "dry_run", "overwrite", "timeout", "help"}
96
+
97
+
98
+ def public_tools() -> List[str]:
99
+ return sorted(p.stem for p in HERE.glob("*.py") if not p.stem.startswith("_"))
100
+
101
+
102
+ def _json_type(action: argparse.Action) -> Dict[str, Any]:
103
+ if isinstance(action, (argparse._StoreTrueAction, argparse._StoreFalseAction)):
104
+ return {"type": "boolean"}
105
+ t: Dict[str, Any]
106
+ if action.type is int:
107
+ t = {"type": "integer"}
108
+ elif action.type is float:
109
+ t = {"type": "number"}
110
+ else:
111
+ t = {"type": "string"}
112
+ if action.choices:
113
+ t["enum"] = list(action.choices)
114
+ if isinstance(action, argparse._AppendAction):
115
+ t = {"type": "array", "items": t}
116
+ return t
117
+
118
+
119
+ def input_schema(parser: argparse.ArgumentParser) -> Dict[str, Any]:
120
+ props: Dict[str, Any] = {}
121
+ required: List[str] = []
122
+ positional: List[str] = []
123
+ for a in parser._actions:
124
+ if a.dest in SHARED or isinstance(a, argparse._HelpAction):
125
+ continue
126
+ schema = _json_type(a)
127
+ if a.help and a.help is not argparse.SUPPRESS:
128
+ schema["description"] = a.help.replace("%%", "%")
129
+ if a.default not in (None, False, argparse.SUPPRESS) and not isinstance(a, argparse._AppendAction):
130
+ schema["default"] = a.default
131
+ props[a.dest] = schema
132
+ if not a.option_strings:
133
+ positional.append(a.dest)
134
+ required.append(a.dest)
135
+ elif a.required:
136
+ required.append(a.dest)
137
+ props["dry_run"] = {"type": "boolean", "description": "plan only: return the commands, write nothing"}
138
+ props["overwrite"] = {"type": "boolean", "description": "allow replacing an existing output file"}
139
+ props["timeout"] = {"type": "number", "description": "wall-clock limit per external step in seconds (default 1800)"}
140
+ return {"type": "object", "properties": props, "required": required, "x-positional": positional,
141
+ "additionalProperties": False}
142
+
143
+
144
+ def flag_for(parser: argparse.ArgumentParser) -> Dict[str, str]:
145
+ """dest -> the long option string the CLI accepts (for building argv from structured arguments)."""
146
+ out: Dict[str, str] = {}
147
+ for a in parser._actions:
148
+ longs = [o for o in a.option_strings if o.startswith("--")]
149
+ if longs:
150
+ out[a.dest] = longs[0]
151
+ return out
152
+
153
+
154
+ def tool_spec(name: str) -> Dict[str, Any]:
155
+ mod = importlib.import_module(name)
156
+ parser = mod.build_parser()
157
+ meta = TOOL_META[name]
158
+ doc = (mod.__doc__ or "").strip()
159
+ return {
160
+ "name": name,
161
+ "script": f"scripts/{name}.py",
162
+ "role": meta["role"],
163
+ "summary": meta["summary"],
164
+ "description": doc.split("\n\n")[0].replace("\n", " "),
165
+ "writes": meta["writes"],
166
+ "verification": meta["verification"],
167
+ "ffmpeg_skill": meta["ffmpeg_skill"],
168
+ "dry_run": meta["dry_run"],
169
+ "inputSchema": input_schema(parser),
170
+ "flags": flag_for(parser),
171
+ }
172
+
173
+
174
+ def build() -> Dict[str, Any]:
175
+ return {
176
+ "skill": SKILL_ID,
177
+ "version": version(),
178
+ "contract_version": CONTRACT_VERSION,
179
+ "timeline_schema": TIMELINE_SCHEMA,
180
+ "depends_on": {"ffmpeg-skill": "https://github.com/kajisho5/ffmpeg-skill", "node": ">=18",
181
+ "python": ">=3.10"},
182
+ "roles": ROLES,
183
+ "conventions": {
184
+ "output": "one JSON object on stdout with --json; human lines on stderr",
185
+ "errors": {"input": 2, "missing_tool": 3, "timeout": 4, "failed": 1},
186
+ "originals": "inputs are never modified; an existing output is refused without --overwrite",
187
+ },
188
+ "tools": [tool_spec(n) for n in TOOL_META],
189
+ }
190
+
191
+
192
+ def main() -> None:
193
+ if len(sys.argv) > 1 and sys.argv[1] == "doctor":
194
+ sys.exit(subprocess.call([sys.executable, str(HERE / "doctor.py"), *sys.argv[2:]]))
195
+ p = argparse.ArgumentParser(description="remotion-ffmpeg-skill execution contract")
196
+ p.add_argument("--json", action="store_true", help="print the contract as JSON (the default output)")
197
+ p.parse_args()
198
+ print(json.dumps(build(), ensure_ascii=False, indent=2))
199
+
200
+
201
+ if __name__ == "__main__":
202
+ main()
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env python3
2
+ """Measure a source video with ffmpeg-skill and write a timeline.json that the Remotion
3
+ compositions read as props: real duration/fps/size, scene cuts, silences and the speech
4
+ ranges between them, audio peaks, an optional beat grid, and captions from a file.
5
+
6
+ Every number comes from a measurement (ffmpeg-skill's probe.py / scenes.py / silence.py);
7
+ nothing is guessed. Warnings flag sources Remotion handles badly (variable frame rate, HDR).
8
+ Several inputs are joined first with ffmpeg-skill join.py (size, fps and audio normalised to the
9
+ first clip) and measured as one source; the clip boundaries are kept in the timeline.
10
+
11
+ Examples:
12
+ python3 analyze.py talk.mp4 # -> talk.timeline.json
13
+ python3 analyze.py talk.mp4 --captions talk.srt -o tl.json
14
+ python3 analyze.py music.mp4 --beats # also measure the beat grid
15
+ python3 analyze.py talk.mp4 --threshold -42 --min-silence 0.8 # quiet room
16
+ python3 analyze.py intro.mp4 talk.mov outro.mp4 --captions all.srt # joined, then measured
17
+ """
18
+ import argparse
19
+ import sys
20
+ from pathlib import Path
21
+ from typing import Any, Dict, List
22
+
23
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
24
+ from _common import (STATE, TIMELINE_SCHEMA, SKILL_ID, add_common, apply_common, default_output, die,
25
+ emit, ffmpeg_skill_version, ffskill, ffskill_cmd, info, refuse_existing,
26
+ require_ffmpeg_skill, shell_join, version)
27
+ from _captions import CaptionError, read_captions
28
+
29
+
30
+ def build_parser() -> argparse.ArgumentParser:
31
+ p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
32
+ formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__)
33
+ p.add_argument("input", nargs="+", help="source video (or audio) file; several are joined in order first")
34
+ p.add_argument("--joined", help="with several inputs: where the joined source goes (default: <first>_joined.mp4)")
35
+ p.add_argument("--join-transition", default="none",
36
+ help="with several inputs: ffmpeg-skill join.py --transition (default none = straight cuts)")
37
+ p.add_argument("--join-duration", type=float, default=0.5, help="transition length in seconds (default 0.5)")
38
+ p.add_argument("-o", "--output", help="timeline file (default: <name>.timeline.json)")
39
+ p.add_argument("--captions", help="SRT, WebVTT or JSON cue list to carry into the timeline (text kept as written)")
40
+ p.add_argument("--beats", action="store_true", help="also measure the beat grid (scenes.py --beats)")
41
+ p.add_argument("--highlights", type=int, metavar="N",
42
+ help="also rank N highlight ranges (scenes.py --highlights; audio energy) for the Highlights composition")
43
+ p.add_argument("--target", type=float, metavar="SECONDS", help="with --highlights: total length the picks add up to")
44
+ p.add_argument("--no-scenes", action="store_true", help="skip scene-cut detection")
45
+ p.add_argument("--no-silence", action="store_true", help="skip silence detection (speech = whole file)")
46
+ p.add_argument("--threshold", type=float, help="silence level in dBFS for silence.py (default -35)")
47
+ p.add_argument("--min-silence", type=float, help="shortest gap in seconds that counts as silence (default 0.6)")
48
+ p.add_argument("--margin", type=float, help="seconds of silence kept around speech (default 0.15)")
49
+ p.add_argument("--scene-threshold", type=float, help="scenes.py --threshold (default 8)")
50
+ add_common(p)
51
+ return p
52
+
53
+
54
+ def silence_args(a: argparse.Namespace) -> List[str]:
55
+ out: List[str] = ["--list"]
56
+ for flag, val in (("--threshold", a.threshold), ("--min-silence", a.min_silence), ("--margin", a.margin)):
57
+ if val is not None:
58
+ out += [flag, str(val)]
59
+ return out
60
+
61
+
62
+ def scene_args(a: argparse.Namespace) -> List[str]:
63
+ out: List[str] = []
64
+ if a.scene_threshold is not None:
65
+ out += ["--threshold", str(a.scene_threshold)]
66
+ if a.beats:
67
+ out.append("--beats")
68
+ if getattr(a, "highlights", None):
69
+ out += ["--highlights", str(a.highlights)]
70
+ if a.target:
71
+ out += ["--target", str(a.target)]
72
+ return out
73
+
74
+
75
+ def warnings_for(probe: Dict[str, Any]) -> List[str]:
76
+ w: List[str] = []
77
+ v = probe.get("video") or {}
78
+ if v.get("variable_frame_rate_suspected"):
79
+ w.append("variable frame rate suspected: Remotion renders on a fixed frame grid, so cuts and captions "
80
+ "can drift. Make a constant-frame-rate copy first (ffmpeg-skill export.py / fit.py --fps).")
81
+ if v.get("hdr") or v.get("hdr_signal") or v.get("bt2020_or_hdr"):
82
+ w.append("HDR / BT.2020 source: Remotion composites in the browser's SDR colour space, so the picture "
83
+ "will look washed out. Convert first: ffmpeg-skill color.py --to-sdr.")
84
+ if v.get("rotation"):
85
+ w.append(f"source is rotated {v.get('rotation')} degrees by metadata; check the first still.py frame.")
86
+ fps = v.get("fps")
87
+ if fps and abs(fps - round(fps)) > 1e-3 and abs(fps * 1001 / 1000 - round(fps * 1001 / 1000)) > 1e-3:
88
+ w.append(f"unusual frame rate {fps}: the compositions use it as-is.")
89
+ return w
90
+
91
+
92
+ def main() -> None:
93
+ a = build_parser().parse_args()
94
+ apply_common(a)
95
+ inputs = [Path(i).expanduser() for i in a.input]
96
+ missing = [str(i) for i in inputs if not i.is_file()]
97
+ if missing:
98
+ die(f"input not found: {', '.join(missing)}", "input")
99
+ src = inputs[0]
100
+ joined: Path = Path(a.joined).expanduser() if a.joined else default_output(src, "_joined", ".mp4")
101
+ out = Path(a.output) if a.output else default_output(joined if len(inputs) > 1 else src, ".timeline", ".json")
102
+ refuse_existing(out)
103
+ skill = require_ffmpeg_skill()
104
+
105
+ captions: List[Dict[str, Any]] = []
106
+ if a.captions:
107
+ cpath = Path(a.captions).expanduser()
108
+ if not cpath.is_file():
109
+ die(f"captions file not found: {cpath}", "input")
110
+ try:
111
+ captions = read_captions(cpath)
112
+ except (CaptionError, ValueError) as e:
113
+ die(f"cannot read {cpath}: {e}", "input")
114
+
115
+ join_args = [*map(str, inputs), "-o", str(joined), "--transition", a.join_transition,
116
+ "--duration", str(a.join_duration)] + (["--overwrite"] if STATE.overwrite else [])
117
+ plan = ([shell_join(ffskill_cmd("join", join_args))] if len(inputs) > 1 else []) + \
118
+ [shell_join(ffskill_cmd("probe", [str(joined if len(inputs) > 1 else src)]))]
119
+ if STATE.dry_run:
120
+ target = str(joined if len(inputs) > 1 else src)
121
+ if not a.no_scenes:
122
+ plan.append(shell_join(ffskill_cmd("scenes", [target, *scene_args(a)])))
123
+ if not a.no_silence:
124
+ plan.append(shell_join(ffskill_cmd("silence", [target, *silence_args(a)])))
125
+ emit({"output": str(out), "commands": plan}, f"would write {out} after {len(plan)} ffmpeg-skill steps")
126
+ return
127
+
128
+ clips: List[Dict[str, Any]] = []
129
+ pre_commands: List[str] = []
130
+ if len(inputs) > 1:
131
+ refuse_existing(joined)
132
+ durations = []
133
+ for f in inputs:
134
+ pr = ffskill("probe", [str(f)])
135
+ # The picture's own length: a stream-copied clip's audio can run a few ms past it.
136
+ durations.append(float((pr.get("video") or {}).get("duration") or pr.get("duration") or 0))
137
+ pre_commands.append(pr["_command"])
138
+ info(f"joining {len(inputs)} clips with ffmpeg-skill join.py -> {joined}")
139
+ jn = ffskill("join", join_args)
140
+ pre_commands.append(jn["_command"])
141
+ overlap = a.join_duration if a.join_transition != "none" else 0.0
142
+ t = 0.0
143
+ for i, (f, d) in enumerate(zip(inputs, durations)):
144
+ start = max(0.0, t - (overlap if i > 0 else 0.0))
145
+ clips.append({"name": f.name, "path": str(f.resolve()), "start": round(start, 3), "end": round(start + d, 3)})
146
+ t = start + d
147
+ src = joined
148
+
149
+ probe = ffskill("probe", [str(src)])
150
+ video, audio = probe.get("video"), probe.get("audio")
151
+ duration = float(probe.get("duration") or (video or {}).get("duration") or (audio or {}).get("duration") or 0)
152
+ if duration <= 0:
153
+ die(f"{src} has no measurable duration", "input")
154
+ commands = pre_commands + [probe["_command"]]
155
+ if clips:
156
+ # The last boundary is the measured joined duration (encoders can round the tail by a frame).
157
+ clips[-1]["end"] = round(duration, 3)
158
+
159
+ scenes: List[Dict[str, float]] = [{"start": 0.0, "end": round(duration, 3)}]
160
+ peaks: List[Dict[str, float]] = []
161
+ beats: Any = None
162
+ highlights: List[Dict[str, float]] = []
163
+ if a.highlights and (a.no_scenes or not video):
164
+ die("--highlights needs scene detection on a video source", "input")
165
+ if video and not a.no_scenes:
166
+ sc = ffskill("scenes", [str(src), *scene_args(a)])
167
+ commands.append(sc["_command"])
168
+ scenes = [{"start": round(float(s["start"]), 3), "end": round(float(s["end"]), 3)}
169
+ for s in sc.get("scenes", [])] or scenes
170
+ peaks = [{"time": round(float(p["time"]), 3), "rms": float(p.get("rms", 0))}
171
+ for p in sc.get("audio_peaks", [])]
172
+ if a.beats:
173
+ grid = sc.get("beat_grid") or {}
174
+ beats = {"times": [round(float(b), 3) for b in (sc.get("beats") or [])],
175
+ "tempo_bpm": grid.get("tempo_bpm"), "confidence": grid.get("confidence"),
176
+ "usable": bool(grid.get("usable")) and bool(sc.get("beats"))}
177
+ # Chronological order: the composition plays them as they happen in the source.
178
+ highlights = sorted(({"start": round(float(h["start"]), 3), "end": round(float(h["end"]), 3)}
179
+ for h in (sc.get("highlights") or []) if float(h["end"]) > float(h["start"])),
180
+ key=lambda h: h["start"])
181
+
182
+ silences: List[List[float]] = []
183
+ speech: List[List[float]] = [[0.0, round(duration, 3)]]
184
+ if audio and not a.no_silence:
185
+ si = ffskill("silence", [str(src), *silence_args(a)])
186
+ commands.append(si["_command"])
187
+ silences = [[round(float(s), 3), round(float(e), 3)] for s, e in si.get("silences", [])]
188
+ keep = [[round(float(s), 3), round(float(e), 3)] for s, e in si.get("keep", []) if float(e) > float(s)]
189
+ speech = keep or speech
190
+
191
+ v = video or {}
192
+ timeline: Dict[str, Any] = {
193
+ "schema": TIMELINE_SCHEMA,
194
+ "generator": {"name": SKILL_ID, "version": version(),
195
+ "ffmpeg_skill": ffmpeg_skill_version(skill)},
196
+ "source": {
197
+ "path": str(src.resolve()),
198
+ "name": src.name,
199
+ "duration": round(duration, 3),
200
+ "fps": float(v.get("fps") or 30.0),
201
+ "width": int(v.get("width") or 1920),
202
+ "height": int(v.get("height") or 1080),
203
+ "has_video": bool(video),
204
+ "has_audio": bool(audio),
205
+ },
206
+ "scenes": scenes,
207
+ "silences": silences,
208
+ "speech": speech,
209
+ "peaks": peaks,
210
+ "beats": beats,
211
+ "highlights": highlights,
212
+ "clips": clips,
213
+ "captions": captions,
214
+ "warnings": warnings_for(probe),
215
+ }
216
+ if not video:
217
+ timeline["warnings"].append("audio-only source: width/height/fps default to 1920x1080 at 30 fps; "
218
+ "render with --aspect / --width to choose the frame.")
219
+ for w in timeline["warnings"]:
220
+ info(f"warning: {w}")
221
+
222
+ out.parent.mkdir(parents=True, exist_ok=True)
223
+ import json
224
+ out.write_text(json.dumps(timeline, ensure_ascii=False, indent=2), encoding="utf-8")
225
+ speech_total = sum(e - s for s, e in speech)
226
+ emit({"output": str(out), "commands": commands, "verified": True,
227
+ "summary": {"duration": timeline["source"]["duration"], "fps": timeline["source"]["fps"],
228
+ "size": f"{timeline['source']['width']}x{timeline['source']['height']}",
229
+ "scenes": len(scenes), "silences": len(silences),
230
+ "speech_seconds": round(speech_total, 3), "peaks": len(peaks),
231
+ "captions": len(captions), "beats": bool(beats and beats.get("usable")),
232
+ "tempo_bpm": (beats or {}).get("tempo_bpm"), "highlights": len(highlights),
233
+ "clips": len(clips) or 1},
234
+ "warnings": timeline["warnings"]},
235
+ f"wrote {out}: {timeline['source']['duration']}s, {len(scenes)} scenes, {len(silences)} silences "
236
+ f"(speech {speech_total:.2f}s), {len(peaks)} peaks, {len(captions)} captions")
237
+
238
+
239
+ if __name__ == "__main__":
240
+ main()
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env python3
2
+ """Turn a Remotion render into a platform deliverable with ffmpeg-skill: its delivery
3
+ template (frame, loudness, codec for YouTube, Reels, TikTok, ...) and then check.py's
4
+ compliance table. Without --platform it only checks the file as it is.
5
+
6
+ Examples:
7
+ python3 deliver.py captioned.mp4 --platform youtube # -> captioned_youtube.mp4 + check
8
+ python3 deliver.py jumpcut.mp4 --platform reels -o reel.mp4
9
+ python3 deliver.py master.mov --check-only --platform x # measure, change nothing
10
+ """
11
+ import argparse
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
16
+ from _common import (STATE, add_common, apply_common, default_output, die, emit, ffskill, ffskill_cmd,
17
+ refuse_existing, require_ffmpeg_skill, shell_join)
18
+
19
+ # ffmpeg-skill's templates/*.json names (render.py --list-templates).
20
+ PLATFORMS = ["youtube", "youtube-shorts", "shorts", "reels", "tiktok", "x", "facebook", "linkedin", "podcast", "audiogram"]
21
+
22
+
23
+ def build_parser() -> argparse.ArgumentParser:
24
+ p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
25
+ formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__)
26
+ p.add_argument("input", help="rendered video")
27
+ p.add_argument("--platform", choices=PLATFORMS, help="ffmpeg-skill delivery template to run")
28
+ p.add_argument("-o", "--output", help="deliverable path (default: <name>_<platform>.mp4)")
29
+ p.add_argument("--check-only", action="store_true", help="run check.py only, write nothing")
30
+ add_common(p)
31
+ return p
32
+
33
+
34
+ def main() -> None:
35
+ a = build_parser().parse_args()
36
+ apply_common(a)
37
+ src = Path(a.input).expanduser()
38
+ if not src.is_file():
39
+ die(f"input not found: {src}", "input")
40
+ require_ffmpeg_skill()
41
+ commands = []
42
+
43
+ target = src
44
+ if a.platform and not a.check_only:
45
+ out = Path(a.output).expanduser() if a.output else default_output(src, f"_{a.platform}", ".mp4")
46
+ refuse_existing(out)
47
+ args = ["--template", a.platform, str(src), "-o", str(out)]
48
+ if STATE.overwrite:
49
+ args.append("--overwrite")
50
+ if STATE.dry_run:
51
+ commands.append(shell_join(ffskill_cmd("render", args)))
52
+ commands.append(shell_join(ffskill_cmd("check", [str(out), "--platform", a.platform])))
53
+ emit({"output": str(out), "commands": commands}, f"would deliver {out}")
54
+ return
55
+ r = ffskill("render", args)
56
+ commands.append(r["_command"])
57
+ target = out
58
+
59
+ check_args = [str(target)] + (["--platform", a.platform] if a.platform else [])
60
+ if STATE.dry_run:
61
+ emit({"output": None, "commands": [shell_join(ffskill_cmd("check", check_args))]}, "would check")
62
+ return
63
+ ck = ffskill("check", check_args, allow_fail=True)
64
+ commands.append(ck.get("_command", shell_join(ffskill_cmd("check", check_args))))
65
+ checks = ck.get("checks", [])
66
+ failed = [c for c in checks if c.get("status") == "FAIL"]
67
+ warns = [c for c in checks if c.get("status") == "WARN"]
68
+ ok = bool(checks) and not failed
69
+ lines = [f"{c['status']:4} {c['check']}: {c.get('value')} (expected {c.get('expected')})" for c in checks]
70
+ emit({"status": "completed" if ok else "failed", "output": str(target) if target != src else None,
71
+ "checked": str(target), "platform": a.platform, "verified": ok, "checks": checks,
72
+ "failed": [c["check"] for c in failed], "warnings": [c["check"] for c in warns], "commands": commands},
73
+ "\n".join([f"{target.name}: {'PASS' if ok else 'FAIL'} ({len(failed)} fail, {len(warns)} warn)"] + lines))
74
+ if not ok:
75
+ sys.exit(1)
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env python3
2
+ """Report what this machine can do: Python, Node/npm, ffmpeg-skill (and its own doctor),
3
+ and -- with --project -- whether that Remotion project is installed and its version.
4
+
5
+ Run it after a failure, not before every job.
6
+
7
+ Examples:
8
+ python3 doctor.py
9
+ python3 doctor.py --project ./motion --json
10
+ """
11
+ import argparse
12
+ import json
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
19
+ from _common import add_common, apply_common, emit, ffmpeg_skill_version, find_ffmpeg_skill, remotion_bin, version
20
+
21
+
22
+ def _version(cmd):
23
+ try:
24
+ out = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
25
+ return (out.stdout or out.stderr).strip().splitlines()[0] if out.returncode == 0 else None
26
+ except (OSError, subprocess.TimeoutExpired, IndexError):
27
+ return None
28
+
29
+
30
+ def build_parser() -> argparse.ArgumentParser:
31
+ p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
32
+ formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__)
33
+ p.add_argument("--project", help="Remotion project folder to inspect")
34
+ add_common(p)
35
+ return p
36
+
37
+
38
+ def main() -> None:
39
+ a = build_parser().parse_args()
40
+ apply_common(a)
41
+
42
+ rows = []
43
+
44
+ def row(name, ok, value, fix=""):
45
+ rows.append({"check": name, "ok": bool(ok), "value": value, "fix": "" if ok else fix})
46
+
47
+ row("python", sys.version_info >= (3, 10), sys.version.split()[0], "use Python 3.10 or newer")
48
+ node = shutil.which("node")
49
+ row("node", node, _version([node, "--version"]) if node else None, "install Node.js from https://nodejs.org")
50
+ npm = shutil.which("npm")
51
+ row("npm", npm, _version([npm, "--version"]) if npm else None, "npm ships with Node.js")
52
+ skill = find_ffmpeg_skill()
53
+ row("ffmpeg-skill", skill, f"{skill} ({ffmpeg_skill_version(skill)})" if skill else None,
54
+ "npx ffmpeg-skill (or set FFMPEG_SKILL_DIR)")
55
+ ff = None
56
+ if skill:
57
+ try:
58
+ out = subprocess.run([sys.executable, str(skill / "scripts" / "_contract.py"), "doctor", "--json"],
59
+ capture_output=True, text=True, timeout=60)
60
+ ff = json.loads(out.stdout)
61
+ row("ffmpeg", ff.get("ok", False), ff.get("ffmpeg") or None,
62
+ "missing: " + ", ".join(map(str, ff.get("missing") or [])) + " (python3 <ffmpeg-skill>/scripts/_contract.py doctor)")
63
+ except (OSError, ValueError, subprocess.TimeoutExpired):
64
+ row("ffmpeg", False, None, "ffmpeg-skill doctor could not run")
65
+ if a.project:
66
+ proj = Path(a.project).expanduser().resolve()
67
+ rb = remotion_bin(proj)
68
+ rv = None
69
+ pkg = proj / "node_modules" / "remotion" / "package.json"
70
+ if pkg.is_file():
71
+ rv = json.loads(pkg.read_text(encoding="utf-8")).get("version")
72
+ row("remotion project", rb.exists(), f"{proj} (remotion {rv})" if rv else str(proj),
73
+ f"cd {proj} && npm install")
74
+
75
+ ok = all(r["ok"] for r in rows)
76
+ lines = [f"{'ok ' if r['ok'] else 'NO '} {r['check']}: {r['value']}" + (f" -> {r['fix']}" if r["fix"] else "")
77
+ for r in rows]
78
+ emit({"status": "completed", "ok": ok, "version": version(), "checks": rows, "ffmpeg_skill_doctor": ff},
79
+ "\n".join([f"remotion-ffmpeg-skill {version()}: {'ready' if ok else 'not ready'}"] + lines))
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env python3
2
+ """Create a Remotion project wired for measured timelines: the three built-in compositions
3
+ (Captioned, Jumpcut, PeakPulse), the timeline types, and pinned Remotion versions.
4
+
5
+ Examples:
6
+ python3 init.py ./motion # copy the template (then: cd motion && npm install)
7
+ python3 init.py ./motion --install # copy and run npm install
8
+ """
9
+ import argparse
10
+ import shutil
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
15
+ from _common import ROOT, STATE, add_common, apply_common, die, emit, info, run, shell_join
16
+
17
+ TEMPLATE = ROOT / "templates" / "remotion-project"
18
+
19
+
20
+ def build_parser() -> argparse.ArgumentParser:
21
+ p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
22
+ formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__)
23
+ p.add_argument("directory", help="new project folder (must not exist, or be empty)")
24
+ p.add_argument("--install", action="store_true", help="run npm install after copying")
25
+ add_common(p)
26
+ return p
27
+
28
+
29
+ def main() -> None:
30
+ a = build_parser().parse_args()
31
+ apply_common(a)
32
+ dst = Path(a.directory).expanduser().resolve()
33
+ if dst.exists() and any(dst.iterdir()) and not STATE.overwrite:
34
+ die(f"{dst} exists and is not empty; pick a new folder (or --overwrite to copy over it)", "input")
35
+ if not (TEMPLATE / "package.json").is_file():
36
+ die(f"template missing: {TEMPLATE}", "failed")
37
+ npm = shutil.which("npm") or shutil.which("npm.cmd")
38
+ commands = [f"copy {TEMPLATE} -> {dst}"]
39
+ if a.install:
40
+ if not npm:
41
+ die("npm not found: install Node.js (https://nodejs.org) to render with Remotion", "missing_tool")
42
+ commands.append(shell_join([npm, "install", "--no-audit", "--no-fund"]))
43
+ if STATE.dry_run:
44
+ emit({"output": str(dst), "commands": commands}, f"would create {dst}")
45
+ return
46
+
47
+ shutil.copytree(TEMPLATE, dst, dirs_exist_ok=True,
48
+ ignore=shutil.ignore_patterns("node_modules", ".rfs", "out"))
49
+ installed = False
50
+ if a.install:
51
+ info("npm install (Remotion, React) ...")
52
+ proc = run([npm, "install", "--no-audit", "--no-fund"], cwd=dst)
53
+ if proc.returncode != 0:
54
+ die("npm install failed:\n" + "\n".join((proc.stderr or "").strip().splitlines()[-20:]), "failed")
55
+ installed = True
56
+ emit({"output": str(dst), "commands": commands, "installed": installed, "entry": "src/index.ts",
57
+ "compositions": ["Captioned", "Jumpcut", "PeakPulse"]},
58
+ f"created {dst}" + ("" if installed else f"\nnext: cd {dst} && npm install"))
59
+
60
+
61
+ if __name__ == "__main__":
62
+ main()