remotion-ffmpeg-skill 0.10.1 → 0.11.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.
package/README.md CHANGED
@@ -58,6 +58,7 @@ npx remotion-ffmpeg-skill # this skill, next to it in ~/.claude/skills
58
58
  - "Cut the silences out of this recording, jump-cut style, and keep the subtitles in sync."
59
59
  - "Make graphics that hit on the loud moments of `clip.mp4`, as a Reel."
60
60
  - "Here are my chapters (`0:00 Intro` …): put them on screen and make it a YouTube upload." — a card at each chapter start, chapter markers in the file, and the description block to paste.
61
+ - "Caption `talk.mp4` from the transcript transcription-skill made, words lighting up as they're spoken." — `analyze.py --words talk.transcript.json`; the transcript's schema version is checked and its times are used exactly as written.
61
62
  - "Japanese captions, vertical, for TikTok." — renders 9:16 with a blurred fill, stages a CJK font automatically, breaks lines between phrases.
62
63
 
63
64
  ## Under the hood
package/SKILL.md CHANGED
@@ -48,6 +48,7 @@ Changing the shape alone is not a reason: ffmpeg-skill's Reels / TikTok / Shorts
48
48
  | "cut the silences / jump cut / tighten this talk" (with motion) | `analyze.py` → `render.py --comp Jumpcut` (captions re-timed if given) |
49
49
  | "graphics that react to the audio / hit on the beat / on cuts" | `analyze.py [--beats]` → `render.py --comp PeakPulse` (pulses on beats when the grid was measured) |
50
50
  | "karaoke captions / words light up as they're spoken" | `analyze.py --words WORDS.json [--captions F.srt]` → `render.py --comp Karaoke` (word timings from a local speech engine, whisper JSON; without an SRT the cues are grouped from the words) |
51
+ | "captions from the transcript" (transcription-skill output) | `analyze.py --words talk.transcript.json` → `render.py --comp Captioned` or `Karaoke`. Only schema `transcription-skill/transcript/0.1` is read, checked against its contract; another version, a broken document or one whose duration differs from the source by more than 0.5 s is refused (`kind: input`) — ask for a fresh transcript, never patch its times. Segments without word timings become one plain cue each (named in the warnings) |
51
52
  | "lower thirds / name titles / scene titles" | `render.py --comp Titled --options` with `lowerThirds` / `sceneTitles` — the text comes from the user; ask for it, never invent names |
52
53
  | "chapters" / a YouTube chapter list (`0:00 Intro` per line) | `analyze.py --chapters chapters.txt` (or `--chapters source` for markers the file already has) → `render.py --comp Titled` (a card at each chapter start, `chapterSeconds`) → `deliver.py --platform youtube --chapters chapters.txt` (markers in the file + `<name>_description.txt` to paste). Titles as written; a line without one is refused. Not with Jumpcut / Highlights: their cuts move every chapter |
53
54
  | "highlight reel / best moments" | `analyze.py --highlights N [--target S]` → `render.py --comp Highlights` (audio-energy ranking: candidates, say so) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "remotion-ffmpeg-skill",
3
- "version": "0.10.1",
3
+ "version": "0.11.0",
4
4
  "description": "Agent Skill: ffmpeg-skill measures the footage, Remotion draws the motion graphics from those measurements, ffmpeg-skill checks and delivers the result. Timeline-driven captions, silence jump cuts and audio-peak motion with probe-first / verify-last rendering. Local, no API keys.",
5
5
  "keywords": [
6
6
  "remotion",
@@ -24,7 +24,7 @@ Measure a source with ffmpeg-skill and write timeline.json (+ captions from a fi
24
24
  | `--join-duration` | number | `0.5` | transition length in seconds (default 0.5) |
25
25
  | `--output` | string | | timeline file (default: <name>.timeline.json) |
26
26
  | `--captions` | string | | SRT, WebVTT or JSON cue list to carry into the timeline (text kept as written) |
27
- | `--words` | string | | word timings from a speech engine (whisper JSON with word timestamps) for the Karaoke composition; without --captions the cues are grouped from these words |
27
+ | `--words` | string | | word timings for the Karaoke and Captioned compositions: a transcription-skill transcript (schema transcription-skill/transcript/0.1, validated strictly) or whisper JSON with word timestamps; without --captions the cues are grouped from these words |
28
28
  | `--chapters` | string | | chapter list, one `TIME TITLE` per line (YouTube's format, the same file ffmpeg-skill metadata.py --chapters writes into the container), or `source` for the chapters already in the input file; titles are kept as written |
29
29
  | `--pip` | string | | a second recording (camera) for the Pip composition: picture-in-picture over the source. The offset between the two is measured from their audio with ffmpeg-skill sync.py |
30
30
  | `--pip-offset` | number | | with --pip: the camera starts this many seconds after the source (negative: before), instead of measuring it -- for a camera without usable audio |
@@ -95,6 +95,9 @@ Example:
95
95
  - **SRT** and **WebVTT**: timing lines `00:00:01,000 --> 00:00:03,500` (comma or dot), multi-line cue text kept; simple formatting tags (`<i>`, `<b>`, `<c>`, `<v ...>`) are stripped.
96
96
  - **JSON**: `[{"start": 1.0, "end": 3.5, "text": "..."}]` or `{"cues": [...]}`.
97
97
  - **Word timings** (`--words`): whisper / faster-whisper JSON made with word timestamps (`segments[].words[]` with `word`, `start`, `end`), `{"words": [...]}` or a plain list. With no `--captions`, cues are grouped mechanically: a new cue after a pause over 0.7 s, past 32 characters or 4 s. Words are never added, dropped or reworded.
98
+ - **transcription-skill transcript** (`--words`): a JSON document with a `schema` key is read as a [transcription-skill](https://github.com/kajisho5/transcription-skill) Transcript and must be `transcription-skill/transcript/0.1`; any other schema id or version is refused. The document is checked against that contract (required fields, finite numbers, `0 ≤ start < end`, segments ordered and not overlapping, words ordered and inside their segment within 0.01 s, ends within the duration + 0.5 s, confidences in [0, 1], `duration` = `source.media_duration`) and refused on the first violation; a transcript whose `duration` differs from the measured source by more than 0.5 s is refused too (it is of another file). Times are used exactly as written — not rounded, snapped or interpolated.
99
+ - Words are trimmed in a transcript, so each word's leading space is read back from the segment's verbatim `raw_text` (one space where `raw_text` has whitespace before the word; none between Japanese tokens). Words that do not spell `raw_text` in order are not trusted: that segment becomes one plain cue, with a warning.
100
+ - Without `--captions`, cues are grouped from the words with the rule above **inside each segment** — a cue never spans two segments. A segment whose `words` is `null` becomes one cue with the segment's own `start`, `end` and `text`; it gets no `words`, so Karaoke shows it plain. The transcript's own `warnings` are carried into the timeline's `warnings` (prefixed `transcript:`), and so is a note when `source.fingerprint` is not the source's sha256.
98
101
 
99
102
  ## Adding your own composition
100
103
 
@@ -1,13 +1,15 @@
1
1
  #!/usr/bin/env python3
2
- """Caption file readers (internal module): SRT, WebVTT and a plain JSON cue list.
2
+ """Caption file readers (internal module): SRT, WebVTT, a plain JSON cue list, whisper word timings and
3
+ transcription-skill transcripts.
3
4
 
4
5
  Cue text is kept exactly as written (line breaks included): this skill never rewrites,
5
6
  shortens or paraphrases caption words -- the same rule as ffmpeg-skill.
6
7
  """
7
8
  import json
8
9
  import re
10
+ import unicodedata
9
11
  from pathlib import Path
10
- from typing import Any, Dict, List
12
+ from typing import Any, Dict, List, Optional
11
13
 
12
14
  _TS = re.compile(r"(?:(\d+):)?(\d{1,2}):(\d{2})[.,](\d{1,3})")
13
15
  _ARROW = re.compile(r"^\s*(\S+)\s+-->\s+(\S+)")
@@ -114,10 +116,6 @@ def parse_words(text: str) -> List[Dict]:
114
116
  return sorted(words, key=lambda w: w["start"])
115
117
 
116
118
 
117
- def read_words(path: Path) -> List[Dict]:
118
- return parse_words(path.read_text(encoding="utf-8-sig"))
119
-
120
-
121
119
  def cues_from_words(words: List[Dict], max_chars: int = 32, max_gap: float = 0.7, max_len: float = 4.0) -> List[Dict]:
122
120
  """Group timed words into caption cues mechanically: a new cue after a pause longer than max_gap,
123
121
  when the cue would pass max_chars characters, or last longer than max_len seconds. The words and
@@ -141,6 +139,212 @@ def _cue(ws: List[Dict]) -> Dict:
141
139
  return {"start": ws[0]["start"], "end": ws[-1]["end"], "text": "".join(w["text"] for w in ws).strip()}
142
140
 
143
141
 
142
+ # ---------------------------------------------------------------- transcription-skill transcripts
143
+
144
+ TRANSCRIPT_SCHEMA = "transcription-skill/transcript/0.1"
145
+ _TRANSCRIPT_END_TOLERANCE = 0.5 # transcription-skill validate.py END_TOLERANCE
146
+ _TRANSCRIPT_CONTAINMENT = 0.01 # transcription-skill validate.py CONTAINMENT_TOLERANCE
147
+ _TRANSCRIPT_REQUIRED = ("schema", "id", "asset_id", "language", "language_source", "language_confidence", "duration",
148
+ "segments", "source", "engine", "engine_version", "created_at", "provenance", "warnings")
149
+ _SEGMENT_REQUIRED = ("id", "start", "end", "text", "raw_text", "confidence", "words", "speaker_id")
150
+ _WORD_REQUIRED = ("start", "end", "text", "confidence")
151
+ _SOURCE_REQUIRED = ("filename", "fingerprint", "size_bytes", "media_duration")
152
+ _PROVENANCE_REQUIRED = ("engine", "engine_version", "execution_mode", "model", "model_version", "parameters",
153
+ "parameters_hash", "cache_key", "created_at", "processing_seconds", "skill_version", "skill", "tool")
154
+ _FINGERPRINT = re.compile(r"sha256:[0-9a-f]{64}")
155
+ _SPACE = re.compile(r"[\s  ]+")
156
+
157
+
158
+ def is_transcript(data: Any) -> bool:
159
+ """A document that names a schema is read as a transcript (and refused if it is not one we know)."""
160
+ return isinstance(data, dict) and "schema" in data
161
+
162
+
163
+ def _num(v: Any) -> bool:
164
+ return isinstance(v, (int, float)) and not isinstance(v, bool) and v == v and v not in (float("inf"), float("-inf"))
165
+
166
+
167
+ def _conf_ok(v: Any) -> bool:
168
+ return v is None or (_num(v) and 0.0 <= v <= 1.0)
169
+
170
+
171
+ def validate_transcript(doc: Any) -> List[str]:
172
+ """Errors against transcription-skill's Transcript contract (schemas/transcript.schema.json and the
173
+ timing rules of its validate.py). Empty list = valid. An unknown schema version is an error: its
174
+ fields could mean something else."""
175
+ if not isinstance(doc, dict):
176
+ return ["a transcript must be a JSON object"]
177
+ if doc.get("schema") != TRANSCRIPT_SCHEMA:
178
+ return [f"unsupported transcript schema {doc.get('schema')!r}: this version reads {TRANSCRIPT_SCHEMA} only"]
179
+ errs = [f"missing required field: {k}" for k in _TRANSCRIPT_REQUIRED if k not in doc]
180
+ if errs:
181
+ return errs
182
+ for k in ("id", "asset_id", "engine", "engine_version", "created_at"):
183
+ if not isinstance(doc[k], str) or not doc[k]:
184
+ errs.append(f"{k} must be a non-empty string")
185
+ if not isinstance(doc["language"], str) or not re.fullmatch(r"[a-z]{2,3}|unknown", doc["language"]):
186
+ errs.append(f"language must be an ISO 639 code or 'unknown', got {doc['language']!r}")
187
+ if doc["language_source"] not in ("requested", "detected", "unknown"):
188
+ errs.append(f"language_source must be requested, detected or unknown, got {doc['language_source']!r}")
189
+ if not _conf_ok(doc["language_confidence"]):
190
+ errs.append("language_confidence must be null or a number in [0, 1]")
191
+ if not isinstance(doc["warnings"], list) or not all(isinstance(w, str) for w in doc["warnings"]):
192
+ errs.append("warnings must be a list of strings")
193
+ dur = doc["duration"]
194
+ if not _num(dur) or dur <= 0:
195
+ errs.append(f"duration must be a positive number, got {dur!r}")
196
+ dur = None
197
+ src = doc["source"]
198
+ if not isinstance(src, dict):
199
+ errs.append("source must be an object")
200
+ else:
201
+ errs += [f"source.{k} is required" for k in _SOURCE_REQUIRED if k not in src]
202
+ if not isinstance(src.get("fingerprint"), str) or not _FINGERPRINT.fullmatch(src["fingerprint"]):
203
+ errs.append("source.fingerprint must be 'sha256:<64 hex>'")
204
+ if not isinstance(src.get("filename"), str) or not src["filename"]:
205
+ errs.append("source.filename must be a non-empty string")
206
+ md = src.get("media_duration")
207
+ if "media_duration" in src and (not _num(md) or md <= 0):
208
+ errs.append("source.media_duration must be a positive number")
209
+ elif dur is not None and _num(md) and abs(md - dur) > 1e-6:
210
+ errs.append("duration must equal source.media_duration")
211
+ prov = doc["provenance"]
212
+ if not isinstance(prov, dict):
213
+ errs.append("provenance must be an object")
214
+ else:
215
+ errs += [f"provenance.{k} is required" for k in _PROVENANCE_REQUIRED if k not in prov]
216
+ if prov.get("skill", "transcription-skill") != "transcription-skill":
217
+ errs.append(f"provenance.skill must be transcription-skill, got {prov.get('skill')!r}")
218
+ if not str(prov.get("tool", "transcription/")).startswith("transcription/"):
219
+ errs.append("provenance.tool must be a transcription/* tool name")
220
+ segs = doc["segments"]
221
+ if not isinstance(segs, list):
222
+ return errs + ["segments must be a list"]
223
+ ids = set()
224
+ prev: Optional[Dict[str, Any]] = None
225
+ for i, seg in enumerate(segs):
226
+ where = f"segments[{i}]"
227
+ if not isinstance(seg, dict):
228
+ errs.append(f"{where}: must be an object")
229
+ continue
230
+ missing = [k for k in _SEGMENT_REQUIRED if k not in seg]
231
+ if missing:
232
+ errs.append(f"{where}: missing {missing}")
233
+ continue
234
+ if not isinstance(seg["id"], str) or not seg["id"] or seg["id"] in ids:
235
+ errs.append(f"{where}: id must be a unique non-empty string")
236
+ ids.add(seg["id"])
237
+ s, e = seg["start"], seg["end"]
238
+ if not _num(s) or not _num(e):
239
+ errs.append(f"{where}: start/end must be numbers")
240
+ continue
241
+ if s < 0 or e <= s:
242
+ errs.append(f"{where}: needs 0 <= start < end, got [{s}, {e}]")
243
+ if dur is not None and e > dur + _TRANSCRIPT_END_TOLERANCE:
244
+ errs.append(f"{where}: end {e} is past the media duration {dur}")
245
+ if prev is not None and (s < prev["start"] or s < prev["end"] - _TRANSCRIPT_CONTAINMENT):
246
+ errs.append(f"{where}: starts before the previous segment ends (not ordered / overlapping)")
247
+ prev = seg
248
+ if not isinstance(seg["text"], str) or not isinstance(seg["raw_text"], str):
249
+ errs.append(f"{where}: text and raw_text must be strings")
250
+ if not _conf_ok(seg["confidence"]):
251
+ errs.append(f"{where}: confidence must be null or a number in [0, 1]")
252
+ words = seg["words"]
253
+ if words is None:
254
+ continue
255
+ if not isinstance(words, list):
256
+ errs.append(f"{where}: words must be null or a list")
257
+ continue
258
+ wprev = None
259
+ for j, w in enumerate(words):
260
+ ww = f"{where}.words[{j}]"
261
+ if not isinstance(w, dict) or any(k not in w for k in _WORD_REQUIRED):
262
+ errs.append(f"{ww}: must have {list(_WORD_REQUIRED)}")
263
+ continue
264
+ ws, we = w["start"], w["end"]
265
+ if not _num(ws) or not _num(we):
266
+ errs.append(f"{ww}: start/end must be numbers")
267
+ continue
268
+ if ws < 0 or we <= ws:
269
+ errs.append(f"{ww}: needs 0 <= start < end, got [{ws}, {we}]")
270
+ if ws < s - _TRANSCRIPT_CONTAINMENT or we > e + _TRANSCRIPT_CONTAINMENT:
271
+ errs.append(f"{ww}: [{ws}, {we}] is outside its segment [{s}, {e}]")
272
+ if wprev is not None and ws < wprev - _TRANSCRIPT_CONTAINMENT:
273
+ errs.append(f"{ww}: words not in time order")
274
+ wprev = we
275
+ if not isinstance(w["text"], str) or not w["text"].strip():
276
+ errs.append(f"{ww}: text must be a non-empty string")
277
+ if not _conf_ok(w["confidence"]):
278
+ errs.append(f"{ww}: confidence must be null or a number in [0, 1]")
279
+ return errs
280
+
281
+
282
+ def _spaced_words(seg: Dict[str, Any]) -> Optional[List[Dict[str, Any]]]:
283
+ """The segment's words with the engine's own spacing put back in front of each (`" world"`, `"字幕"`).
284
+
285
+ transcription-skill trims each word, so the spacing is read from the segment's verbatim `raw_text`:
286
+ a word gets one leading space when whitespace precedes it there (whitespace runs collapse to one, as
287
+ in the transcript's own `text`). None when the words do not spell `raw_text` in order -- then the
288
+ segment's word timings cannot be trusted to belong to its text."""
289
+ raw = "".join(ch for ch in seg["raw_text"] if unicodedata.category(ch) not in ("Cc", "Cf") or ch in "\t\n\r")
290
+ pos, out = 0, []
291
+ for w in seg["words"]:
292
+ m = _SPACE.match(raw, pos)
293
+ lead = " " if m else ""
294
+ pos = m.end() if m else pos
295
+ token = _SPACE.sub(" ", w["text"]).strip()
296
+ if not raw.startswith(token, pos):
297
+ return None
298
+ pos += len(token)
299
+ out.append({"start": w["start"], "end": w["end"], "text": lead + token})
300
+ return out if not raw[pos:].strip() else None
301
+
302
+
303
+ def parse_transcript(doc: Any) -> Dict[str, Any]:
304
+ """A validated transcription-skill Transcript -> {words, cues, warnings, duration, fingerprint, filename}.
305
+
306
+ Every time comes from the transcript as written (not rounded, shifted or stretched). Cues are grouped
307
+ from the words inside each segment (cues_from_words) and never cross a segment boundary; a segment
308
+ without usable word timings becomes one cue with the segment's own times and text, and its words
309
+ are left out of `words` (Karaoke shows that cue plain) -- no word time is ever interpolated."""
310
+ errs = validate_transcript(doc)
311
+ if errs:
312
+ more = f" (+{len(errs) - 5} more)" if len(errs) > 5 else ""
313
+ raise CaptionError("not a valid transcription-skill transcript: " + "; ".join(errs[:5]) + more)
314
+ words: List[Dict[str, Any]] = []
315
+ cues: List[Dict[str, Any]] = []
316
+ warnings = [f"transcript: {w}" for w in doc["warnings"]]
317
+ plain: List[str] = []
318
+ for seg in doc["segments"]:
319
+ sw = _spaced_words(seg) if seg["words"] else None
320
+ if sw:
321
+ words += sw
322
+ cues += cues_from_words(sw)
323
+ elif seg["text"].strip():
324
+ if seg["words"]:
325
+ warnings.append(f"transcript {seg['id']}: its words do not spell its text; shown as one plain cue")
326
+ else:
327
+ plain.append(seg["id"])
328
+ cues.append({"start": seg["start"], "end": seg["end"], "text": seg["text"].strip()})
329
+ if plain:
330
+ warnings.append("transcript has no word timings for " + ", ".join(plain)
331
+ + " (shown as plain cues; transcribe with word timestamps for Karaoke)")
332
+ if not cues:
333
+ raise CaptionError("the transcript has no speech segments")
334
+ return {"words": words, "cues": cues, "warnings": warnings, "duration": float(doc["duration"]),
335
+ "fingerprint": doc["source"]["fingerprint"], "filename": doc["source"]["filename"]}
336
+
337
+
338
+ def read_word_timings(path: Path) -> Dict[str, Any]:
339
+ """`--words`: a transcription-skill transcript (validated strictly) or whisper-style word JSON.
340
+ Returns {words, cues (None for whisper JSON: grouped later only without --captions), warnings, ...}."""
341
+ text = path.read_text(encoding="utf-8-sig")
342
+ data = json.loads(text)
343
+ if is_transcript(data):
344
+ return parse_transcript(data)
345
+ return {"words": parse_words(text), "cues": None, "warnings": []}
346
+
347
+
144
348
  # ---------------------------------------------------------------- chapters
145
349
 
146
350
  def _chapter_time(tok: str) -> float:
@@ -332,7 +332,8 @@ def _stage(project: Path, src: Path, folder: str) -> str:
332
332
  os.link(src, dst)
333
333
  except OSError:
334
334
  info(f"copying {src.name} into the project (hard link not possible across drives) ...")
335
- shutil.copy2(src, dst)
335
+ # Bytes only: copying a macOS system font's file flags (copy2 -> chflags) is not permitted.
336
+ shutil.copyfile(src, dst)
336
337
  return rel
337
338
 
338
339
 
@@ -236,11 +236,31 @@ def tool_spec(name: str) -> Dict[str, Any]:
236
236
  }
237
237
 
238
238
 
239
+ # The AI Video Production OS registry's keys (skill_id, provides[], dependencies[]): one capability
240
+ # per public tool except doctor, all EXPERIMENTAL; ffmpeg-skill is the only Skill this one calls.
241
+ PROVIDES_EXCLUDE = {"doctor"}
242
+ FFMPEG_SKILL_RANGE = ">=2.0.0 <3.0.0"
243
+
244
+
245
+ def provides() -> List[Dict[str, str]]:
246
+ return [{"id": f"remotion.{n}", "lifecycle": "EXPERIMENTAL", "tool_id": f"{SKILL_ID}/{n}"}
247
+ for n in TOOL_META if n not in PROVIDES_EXCLUDE]
248
+
249
+
250
+ def dependencies() -> List[Dict[str, Any]]:
251
+ used = sorted({s.split()[0] for m in TOOL_META.values() for s in m["ffmpeg_skill"]})
252
+ return [{"skill_id": "ffmpeg-skill", "version_range": FFMPEG_SKILL_RANGE, "required": True,
253
+ "url": "https://github.com/kajisho5/ffmpeg-skill", "scripts": used}]
254
+
255
+
239
256
  def build() -> Dict[str, Any]:
240
257
  return {
241
- "skill": SKILL_ID,
258
+ "skill_id": SKILL_ID,
259
+ "skill": {"id": SKILL_ID, "version": version()},
242
260
  "version": version(),
243
261
  "contract_version": CONTRACT_VERSION,
262
+ "provides": provides(),
263
+ "dependencies": dependencies(),
244
264
  "timeline_schema": TIMELINE_SCHEMA,
245
265
  "depends_on": {"ffmpeg-skill": "https://github.com/kajisho5/ffmpeg-skill", "node": ">=18",
246
266
  "python": ">=3.10"},
@@ -14,8 +14,10 @@ Examples:
14
14
  python3 analyze.py music.mp4 --beats # also measure the beat grid
15
15
  python3 analyze.py talk.mp4 --threshold -42 --min-silence 0.8 # quiet room
16
16
  python3 analyze.py intro.mp4 talk.mov outro.mp4 --captions all.srt # joined, then measured
17
+ python3 analyze.py talk.mp4 --words talk.transcript.json # captions from a transcription-skill transcript
17
18
  """
18
19
  import argparse
20
+ import hashlib
19
21
  import sys
20
22
  from pathlib import Path
21
23
  from typing import Any, Dict, List, Optional
@@ -24,7 +26,20 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
24
26
  from _common import (STATE, TIMELINE_SCHEMA, SKILL_ID, add_common, apply_common, default_output, die,
25
27
  emit, ffmpeg_skill_version, ffskill, ffskill_cmd, info, refuse_existing,
26
28
  require_ffmpeg_skill, shell_join, version)
27
- from _captions import CaptionError, cues_from_words, parse_chapters, read_captions, read_words, youtube_chapter_warnings
29
+ from _captions import (CaptionError, cues_from_words, parse_chapters, read_captions, read_word_timings,
30
+ youtube_chapter_warnings)
31
+
32
+ # seconds a transcript's duration may differ from the measured source (transcription-skill's own END_TOLERANCE)
33
+ TRANSCRIPT_DURATION_TOLERANCE = 0.5
34
+
35
+
36
+ def file_fingerprint(path: Path) -> str:
37
+ """`sha256:<hex>` of the file bytes -- the identity transcription-skill writes to source.fingerprint."""
38
+ h = hashlib.sha256()
39
+ with open(path, "rb") as f:
40
+ for chunk in iter(lambda: f.read(1 << 20), b""):
41
+ h.update(chunk)
42
+ return "sha256:" + h.hexdigest()
28
43
 
29
44
 
30
45
  def build_parser() -> argparse.ArgumentParser:
@@ -37,8 +52,9 @@ def build_parser() -> argparse.ArgumentParser:
37
52
  p.add_argument("--join-duration", type=float, default=0.5, help="transition length in seconds (default 0.5)")
38
53
  p.add_argument("-o", "--output", help="timeline file (default: <name>.timeline.json)")
39
54
  p.add_argument("--captions", help="SRT, WebVTT or JSON cue list to carry into the timeline (text kept as written)")
40
- p.add_argument("--words", help="word timings from a speech engine (whisper JSON with word timestamps) for the "
41
- "Karaoke composition; without --captions the cues are grouped from these words")
55
+ p.add_argument("--words", help="word timings for the Karaoke and Captioned compositions: a transcription-skill "
56
+ "transcript (schema transcription-skill/transcript/0.1, validated strictly) or whisper "
57
+ "JSON with word timestamps; without --captions the cues are grouped from these words")
42
58
  p.add_argument("--chapters", metavar="FILE|source",
43
59
  help="chapter list, one `TIME TITLE` per line (YouTube's format, the same file ffmpeg-skill "
44
60
  "metadata.py --chapters writes into the container), or `source` for the chapters already "
@@ -127,16 +143,20 @@ def main() -> None:
127
143
  die(f"cannot read {cpath}: {e}", "input")
128
144
 
129
145
  words: List[Dict[str, Any]] = []
146
+ transcript: Optional[Dict[str, Any]] = None
130
147
  if a.words:
131
148
  wpath = Path(a.words).expanduser()
132
149
  if not wpath.is_file():
133
150
  die(f"word timings file not found: {wpath}", "input")
134
151
  try:
135
- words = read_words(wpath)
152
+ timed = read_word_timings(wpath)
136
153
  except (CaptionError, ValueError) as e:
137
154
  die(f"cannot read {wpath}: {e}", "input")
155
+ words = timed["words"]
156
+ if timed["cues"] is not None:
157
+ transcript = timed
138
158
  if not captions:
139
- captions = cues_from_words(words)
159
+ captions = timed["cues"] if transcript else cues_from_words(words)
140
160
 
141
161
  join_args = [*map(str, inputs), "-o", str(joined), "--transition", a.join_transition,
142
162
  "--duration", str(a.join_duration)] + (["--overwrite"] if STATE.overwrite else [])
@@ -182,6 +202,19 @@ def main() -> None:
182
202
  # The last boundary is the measured joined duration (encoders can round the tail by a frame).
183
203
  clips[-1]["end"] = round(duration, 3)
184
204
 
205
+ transcript_warnings: List[str] = []
206
+ if transcript:
207
+ # The transcript's times are seconds on the file it was made from: a different length means a
208
+ # different file, and its words would land in the wrong places.
209
+ if abs(transcript["duration"] - duration) > TRANSCRIPT_DURATION_TOLERANCE:
210
+ die(f"--words: the transcript is of a {transcript['duration']:.3f} s file ({transcript['filename']}), "
211
+ f"the source measures {duration:.3f} s; transcribe this source (or the joined file)", "input")
212
+ if transcript["fingerprint"] != file_fingerprint(src):
213
+ transcript_warnings.append(
214
+ f"--words: the transcript was made from {transcript['filename']}, not these exact bytes "
215
+ f"(same length, so its times are used as written)")
216
+ transcript_warnings += transcript["warnings"]
217
+
185
218
  scenes: List[Dict[str, float]] = [{"start": 0.0, "end": round(duration, 3)}]
186
219
  peaks: List[Dict[str, float]] = []
187
220
  beats: Any = None
@@ -285,7 +318,7 @@ def main() -> None:
285
318
  "words": words,
286
319
  "chapters": chapters,
287
320
  "pip": pip,
288
- "warnings": warnings_for(probe) + youtube_chapter_warnings(chapters) if chapters else warnings_for(probe),
321
+ "warnings": warnings_for(probe) + (youtube_chapter_warnings(chapters) if chapters else []) + transcript_warnings,
289
322
  }
290
323
  if pip and pip["measured"] and (pip["confidence"] or 0) < 0.3:
291
324
  timeline["warnings"].append(f"pip: the measured offset ({pip['offset']:g} s) has low confidence "