Broadcast Subtitles
TV-standard SRT, VTT and burned-in subtitles, checked line by line by a linter
Before: A 60 s cut of a two-person podcast (10:50-11:50 of the episode).. After: the result made by the skill from that input. The prompt and the steps the skill follows are written out below the player.
Use the broadcast-subtitles skill on interview.mp4. I need proper TV-style subtitles: an SRT I can upload and a burned-in copy. Just do it.
Recipe
- 1Transcribe with word times and fix misheard names
- 2Label who speaks when there are two or more people
- 3Find camera cuts and segment the words into timed subtitles
- 4Lint every subtitle against the broadcast rules
- 5Burn in with a plate or outline and check frames
About
Turns a video's speech into sentence subtitles that follow the rules streaming services and broadcasters give their subtitlers, then checks every subtitle with a linter before delivery. You get an SRT to upload, a VTT, and a burned-in copy.
The rules are numbers, not taste: at most 2 lines of 42 characters, 20 characters per second (up to 22 on at most 1 subtitle in 10 to keep a clause whole), 5/6 s to 7 s on screen, 2-frame gaps, in and out times snapped to camera cuts, and line breaks that never strand "the" or "of". Two speakers get Netflix-style dashes with aligned lines. Text is sized to the BBC's 7% line height, and a dark plate is used automatically when the background behind the text is bright. The targets were checked against 3,820 professional subtitles from 17 talks.
Limits: on very fast speech (over about 200 words a minute) verbatim subtitles still split a few clauses and run fuller than a human subtitler's. Speaker turns and misheard names should be checked by you; the agent lists the ones it could not confirm.
Proof footage: We Wrote Letters to Our Younger Selves, Episode 6 by Two Peas In A Pod, CC BY, https://youtu.be/eproyMMv5QI.
Generic and Zylcut edition
One install. With Zylcut connected to your agent, the same skill uses Zylcut's tools instead of rendering files.
Instructions
The SKILL.md your agent reads, exactly as reviewed.
Broadcast subtitles
Sentence subtitles that a viewer reads without effort: the rules streaming services and broadcasters give their subtitlers, applied by a script and then checked by a linter, so the result passes a timed-text review. The numbers are in "Final values" and the reasons and sources in references/standard.md.
Which backend. If Zylcut MCP tools are available (for example context,
media_transcribe, capture, check), follow references/zylcut.md;
otherwise follow references/ffmpeg.md. Both use the same scripts and the
same rules; only transcription, preview and burn-in differ.
When to use
- Long-form, interviews, talks, tutorials, documentaries, client deliveries, accessibility.
- Any request for an SRT or VTT file, or for subtitles that look like TV or streaming.
- Not for 1-3 word "pop" captions on a fast short: that is a different style with different numbers (a word-pop caption skill).
Inputs
- A video (landscape or vertical). Its speech should be in one language the transcriber reads.
- Optional: a transcript or script (spellings of names), the speakers' names, the target (YouTube upload only, burned-in, or both), a font or a plate preference.
Approval gate
Before writing files, tell the user in five lines or fewer: the video and its size and frame rate, the language, what you will deliver (SRT, VTT, burned-in MP4), the style (white text with a thin outline, or a dark plate), the position, and any names you will spell a special way. Wait for a yes. Skip the wait only when the user said "just do it" or equivalent.
Pipeline
Every step ends with its check. Do not go on with a failed check.
- Probe. Size, frame rate and duration (
ffprobeormedia_probe). Check: the frame rate is the file's real rate (29.97 is not 30); every frame-based rule uses it. - Transcribe with word times (
scripts/words.py transcribe, ormedia_transcribethenscripts/words.py import). Check: read the transcript (words.py show). Fix misheard names and terms inwords.jsonby editing the word text only, never the times. Never invent words: subtitles say what was said, minus fillers (um, uh) which the script drops if you remove them fromwords.json. - Label speakers when two or more people talk (an interview, a podcast). Read
words.py show: a question and its answer, "yeah", "no, no" and a change of topic mark the turns. For each turn you are unsure of, grab a frame a moment after it (ffmpeg -ss T -i VIDEO -frames:v 1 t.jpg) and see whose mouth moves. Thenscripts/words.py label words.json 0=A 21=B 57=A(word numbers fromshow). Check:showprints<B w21>at each turn, and no turn sits inside a sentence unless someone really interrupts. A single speaker needs no labels. - Find shot changes (
scripts/subtitles.py shots VIDEO -o shots.json). Check: the count is plausible for the footage (a single-camera talk can have 0). - Make the subtitles (
scripts/subtitles.py make words.json --video VIDEO --shots shots.json -o subs). It segments at sentence and clause ends, balances the lines, times every subtitle by the rules and writessubs.srt,subs.vtt,subs.assandsubs.tsx. For vertical video it sets the line length from the safe width (about 32 characters). - Lint (
scripts/subtitles.py check subs.srt --fps FPS --shots shots.json --max-chars N). Check: 0 errors. Read every warning; fix the ones the text can fix (a line break, a cue that should split) by editingwords.jsonpunctuation and re-running step 5, never by hand-editing times in the SRT. - Read it as a viewer. Read the SRT top to bottom. Fix punctuation the transcriber got
wrong in
words.json(a line said as a question ends in "?", a run-on gets its full stop). Each subtitle is a whole phrase, lines do not end on "the", "of", "to", "and" or a first name, and nothing is missing. Fix and repeat steps 5-6. - Burn in if asked (
scripts/subtitles.py burn VIDEO subs.ass OUT.mp4, or the Zylcut component). Check: the font line in the log names the font you chose, not a fallback. Ifmakeprinted "the subtitle band is bright", remake with--platebefore burning. - Look at frames (see QA). Then deliver.
Final values
| Rule | Value |
|---|---|
| Lines per subtitle | 2 at most (1 when it fits) |
| Characters per line | 42 landscape; vertical: what fits the safe width at the chosen size (about 32) |
| Reading speed | at most 20 characters per second (spaces and punctuation count); aim for 17. Up to 22 on at most 1 subtitle in 10, only to keep a clause whole (7.7% of the measured professional subtitles go over 20) |
| Duration | at least 5/6 s (20 frames at 24 fps), at most 7 s |
| Gap between subtitles | 2 frames, or 12 frames and more; gaps of 3-11 frames are closed to 2 |
| Lead-out | up to 0.5 s after the last word, if nothing follows sooner |
| Shot change, in-time | moved back onto a shot change up to 12 frames before the first word (forward at most 4 frames) |
| Shot change, out-time | within 12 frames of a shot change after speech ends: 2 frames before the change. Never 1-11 frames over a new shot: when speech runs up to 6 frames past a cut the subtitle ends 2 frames before it (the next one comes in on the cut), otherwise it stays 12 frames or more into the new shot |
| Line breaks | after punctuation; never after an article, preposition, conjunction or first name; balanced, bottom-heavy when equal |
| Speakers | at most one change of speaker per subtitle, at its line break; each line starts with "-" and no space (Netflix English); each speaker's line is a whole sentence; the two lines start at one x so the dashes align |
| Text | sentence case as spoken, with punctuation; numbers as the transcript has them |
| Look | off-white #F2F2F2, semibold sans (Arial class), dark outline about 12% of the capital height plus a soft shadow; or a 75% black plate |
| Size | BBC line height 7% of frame height on landscape, 4% on vertical: capitals 4.3% (46 px at 1080) and 2.5% (48 px on 1920) |
| Position | bottom centre; landscape 7.5% of height above the bottom edge, inside 90% title safe; vertical above the bottom 420 px of 1920 and inside x 60-900 |
Measured on 17 professionally subtitled talks (3,820 subtitles): longest line 42 characters, 0% three-line subtitles, 46% two-line, durations 1.17-5.38 s (2nd-98th percentile), never under 5/6 s or over 7 s, reading speed median 14.4 and 98th percentile 20.8 characters per second.
QA before delivery
checkshows 0 errors on the final SRT.- Light walls, skies or tables behind the text:
makesays "the subtitle band is bright" (more than 10% near-white pixels) and the plate is then the default look; remake with--plate. - Frames: grab the first subtitle, the longest two-line subtitle, and one over the busiest
background (
ffmpeg -ss T -i OUT.mp4 -frames:v 1 f.jpg, orcapturein Zylcut). Text is whole, inside the safe area, readable at phone size, and never sits on burned-in text or a lower third (move it to the top for that stretch if it does: add{\an8}to those cues in the ASS). - Duration: the burned-in file's duration equals the source's, and the audio is untouched.
- Deliver the SRT (and VTT) even when the user only asked for burned-in video, unless they said not to: platforms use it for accessibility and search.
Gotchas
- Transcribers drop punctuation on slow or unscripted speech. Segmentation leans on full
stops and commas. If
words.py showprints one huge sentence, add the missing full stops and commas to the word text inwords.json(where the speaker clearly ends a thought), then remake. - Wrong language gives fluent nonsense. An English-only model on a Welsh or Spanish passage
writes confident English garbage. Read the transcript before anything else; use a multilingual
model or the Zylcut
languageoption for other languages. - Frame rate. Gaps and shot snapping are counted in frames of the video's real rate. Pass
--fps 29.97, not 30, tocheckfor NTSC footage. - ffmpeg sizes SRT styles on a 288-line grid. Burn the ASS file the script writes (its
PlayResX/PlayResY equal the video, so sizes are pixels), not the SRT with
force_style. - Fonts fail silently. libass picks a fallback without an error; the burn step prints the font it used. Fonts also differ in how big a "size" looks, so the script sizes by capital height, measured from a rendered test of the chosen font.
- A plate with inline colour. Do not add colour tags to plate cues; the plate is its own layer for that reason (see references/ffmpeg.md).
- Fast speech forces a few mid-clause splits. Above about 180 words a minute, some phrases
cannot fit one subtitle even at the 22 cps tolerance, so the script ends a subtitle at the
least bad word (often at a short pause). Accept it, name it in the report, and offer condensed
subtitles; do not raise
--max-cps, and do not drop or reword words unless the user asks for condensed subtitles. - Do not patch the scripts. If a rule seems wrong for this video, say so in the report; the scripts are shared by every run of this skill.
- Shot-change snapping cuts at most 6 frames of a word's tail. A subtitle over a cut in mid-sentence stays, as broadcast practice allows; one that would hang 1-11 frames over a new shot is trimmed to the cut or held 12 frames past it. A remaining linter warning means neither fit (the subtitle would go under 5/6 s); leave it and mention it.
Limits
Tested cold on a fast two-person interview (about 185 words a minute, 230 at its fastest). A separate judge scored the last run 7-9 out of 10 per area, not 8 everywhere:
- Very fast speech, verbatim. Some subtitles still split mid-clause or start a new sentence partway through a line, and about 3 in 4 subtitles use two lines (professional talks: under half). Condensed subtitles fix this, but only when the user asks for them.
- Who speaks comes from reading the transcript and frames. On a wide shot with both people in view, a short reply can go to the wrong person. Ask the user to check dialogue subtitles.
- Words the transcriber mishears (names, places) stay as heard unless the user gives the spelling. The report lists the ones to check.
Credit
Adapted from the caption-styling skill in the vidmoat/skills repository by Vidmoat Skills contributors (text CC-BY-4.0, scripts Apache-2.0); see NOTICE. Changed by Zylcut: broadcast values (20 cps, 42 characters, 5/6-7 s, frame gaps, shot changes), automatic segmentation and timing, a Zylcut path, and measured references.
Files
9 files, 101 KB. Nothing in a skill runs until your agent runs it.
1---
2name: broadcast-subtitles
3description: Make broadcast-standard sentence subtitles for a video from its speech - at most 2 lines of 42 characters, at most 20 characters per second, 5/6 s to 7 s per subtitle, 2-frame gaps, in and out times snapped to shot changes, balanced line breaks - delivered as SRT, VTT and a burned-in copy, and checked by a linter. Use when the user wants subtitles or closed captions that read like TV or streaming subtitles, accessibility-grade captions, an SRT for YouTube or a client, captions that pass a reading-speed or line-length review, or says "subtitle this", "add subtitles", "make an SRT", "proper subtitles, not TikTok captions", or "my captions flash by too fast". Works on landscape and vertical video. Not for word-by-word pop captions on shorts.
4license: Apache-2.0
5compatibility: Generic path needs Python 3.8+, ffmpeg and ffprobe (with libass for burn-in) and a word-timed transcriber (whisper.cpp whisper-cli, or any that writes word times). Zylcut path uses the Zylcut MCP tools. Scripts are standard library only.
6metadata:
7 version: "1.0.0"
8 author: Zylcut
9 outcome: captions
10 adapted-from: caption-styling by Vidmoat Skills contributors (vidmoat/skills, CC-BY-4.0 text, Apache-2.0 scripts)
11---
12
13# Broadcast subtitles
14
15Sentence subtitles that a viewer reads without effort: the rules streaming services and
16broadcasters give their subtitlers, applied by a script and then checked by a linter, so the
17result passes a timed-text review. The numbers are in "Final values" and the reasons and sources
18in [references/standard.md](references/standard.md).
19
20**Which backend.** If Zylcut MCP tools are available (for example `context`,
21`media_transcribe`, `capture`, `check`), follow [references/zylcut.md](references/zylcut.md);
22otherwise follow [references/ffmpeg.md](references/ffmpeg.md). Both use the same scripts and the
23same rules; only transcription, preview and burn-in differ.
24
25## When to use
26
27- Long-form, interviews, talks, tutorials, documentaries, client deliveries, accessibility.
28- Any request for an SRT or VTT file, or for subtitles that look like TV or streaming.
29- Not for 1-3 word "pop" captions on a fast short: that is a different style with different
30 numbers (a word-pop caption skill).
31
32## Inputs
33
34- A video (landscape or vertical). Its speech should be in one language the transcriber reads.
35- Optional: a transcript or script (spellings of names), the speakers' names, the target
36 (YouTube upload only, burned-in, or both), a font or a plate preference.
37
38## Approval gate
39
40Before writing files, tell the user in five lines or fewer: the video and its size and frame
41rate, the language, what you will deliver (SRT, VTT, burned-in MP4), the style (white text with a
42thin outline, or a dark plate), the position, and any names you will spell a special way. Wait for
43a yes. Skip the wait only when the user said "just do it" or equivalent.
44
45## Pipeline
46
47Every step ends with its check. Do not go on with a failed check.
48
491. **Probe.** Size, frame rate and duration (`ffprobe` or `media_probe`). Check: the frame rate
50 is the file's real rate (29.97 is not 30); every frame-based rule uses it.
512. **Transcribe with word times** (`scripts/words.py transcribe`, or `media_transcribe` then
52 `scripts/words.py import`). Check: read the transcript (`words.py show`). Fix misheard names
53 and terms in `words.json` by editing the word text only, never the times. Never invent words:
54 subtitles say what was said, minus fillers (um, uh) which the script drops if you remove them
55 from `words.json`.
563. **Label speakers** when two or more people talk (an interview, a podcast). Read `words.py
57 show`: a question and its answer, "yeah", "no, no" and a change of topic mark the turns. For
58 each turn you are unsure of, grab a frame a moment after it (`ffmpeg -ss T -i VIDEO -frames:v 1
59 t.jpg`) and see whose mouth moves. Then `scripts/words.py label words.json 0=A 21=B 57=A`
60 (word numbers from `show`). Check: `show` prints `<B w21>` at each turn, and no turn sits
61 inside a sentence unless someone really interrupts. A single speaker needs no labels.
624. **Find shot changes** (`scripts/subtitles.py shots VIDEO -o shots.json`). Check: the count is
63 plausible for the footage (a single-camera talk can have 0).
645. **Make the subtitles** (`scripts/subtitles.py make words.json --video VIDEO --shots
65 shots.json -o subs`). It segments at sentence and clause ends, balances the lines, times every
66 subtitle by the rules and writes `subs.srt`, `subs.vtt`, `subs.ass` and `subs.tsx`.
67 For vertical video it sets the line length from the safe width (about 32 characters).
686. **Lint** (`scripts/subtitles.py check subs.srt --fps FPS --shots shots.json --max-chars N`).
69 Check: 0 errors. Read every warning; fix the ones the text can fix (a line break, a cue that
70 should split) by editing `words.json` punctuation and re-running step 5, never by hand-editing
71 times in the SRT.
727. **Read it as a viewer.** Read the SRT top to bottom. Fix punctuation the transcriber got
73 wrong in `words.json` (a line said as a question ends in "?", a run-on gets its full stop). Each subtitle is a whole phrase, lines
74 do not end on "the", "of", "to", "and" or a first name, and nothing is missing. Fix and repeat
75 steps 5-6.
768. **Burn in** if asked (`scripts/subtitles.py burn VIDEO subs.ass OUT.mp4`, or the Zylcut
77 component). Check: the font line in the log names the font you chose, not a fallback.
78 If `make` printed "the subtitle band is bright", remake with `--plate` before burning.
799. **Look at frames** (see QA). Then deliver.
80
81## Final values
82
83| Rule | Value |
84|---|---|
85| Lines per subtitle | 2 at most (1 when it fits) |
86| Characters per line | 42 landscape; vertical: what fits the safe width at the chosen size (about 32) |
87| Reading speed | at most 20 characters per second (spaces and punctuation count); aim for 17. Up to 22 on at most 1 subtitle in 10, only to keep a clause whole (7.7% of the measured professional subtitles go over 20) |
88| Duration | at least 5/6 s (20 frames at 24 fps), at most 7 s |
89| Gap between subtitles | 2 frames, or 12 frames and more; gaps of 3-11 frames are closed to 2 |
90| Lead-out | up to 0.5 s after the last word, if nothing follows sooner |
91| Shot change, in-time | moved back onto a shot change up to 12 frames before the first word (forward at most 4 frames) |
92| Shot change, out-time | within 12 frames of a shot change after speech ends: 2 frames before the change. Never 1-11 frames over a new shot: when speech runs up to 6 frames past a cut the subtitle ends 2 frames before it (the next one comes in on the cut), otherwise it stays 12 frames or more into the new shot |
93| Line breaks | after punctuation; never after an article, preposition, conjunction or first name; balanced, bottom-heavy when equal |
94| Speakers | at most one change of speaker per subtitle, at its line break; each line starts with "-" and no space (Netflix English); each speaker's line is a whole sentence; the two lines start at one x so the dashes align |
95| Text | sentence case as spoken, with punctuation; numbers as the transcript has them |
96| Look | off-white #F2F2F2, semibold sans (Arial class), dark outline about 12% of the capital height plus a soft shadow; or a 75% black plate |
97| Size | BBC line height 7% of frame height on landscape, 4% on vertical: capitals 4.3% (46 px at 1080) and 2.5% (48 px on 1920) |
98| Position | bottom centre; landscape 7.5% of height above the bottom edge, inside 90% title safe; vertical above the bottom 420 px of 1920 and inside x 60-900 |
99
100Measured on 17 professionally subtitled talks (3,820 subtitles): longest line 42 characters,
1010% three-line subtitles, 46% two-line, durations 1.17-5.38 s (2nd-98th percentile), never under
1025/6 s or over 7 s, reading speed median 14.4 and 98th percentile 20.8 characters per second.
103
104## QA before delivery
105
106- `check` shows 0 errors on the final SRT.
107- Light walls, skies or tables behind the text: `make` says "the subtitle band is bright" (more
108 than 10% near-white pixels) and the plate is then the default look; remake with `--plate`.
109- Frames: grab the first subtitle, the longest two-line subtitle, and one over the busiest
110 background (`ffmpeg -ss T -i OUT.mp4 -frames:v 1 f.jpg`, or `capture` in Zylcut). Text is whole,
111 inside the safe area, readable at phone size, and never sits on burned-in text or a lower third
112 (move it to the top for that stretch if it does: add `{\an8}` to those cues in the ASS).
113- Duration: the burned-in file's duration equals the source's, and the audio is untouched.
114- Deliver the SRT (and VTT) even when the user only asked for burned-in video, unless they said
115 not to: platforms use it for accessibility and search.
116
117## Gotchas
118
119- **Transcribers drop punctuation on slow or unscripted speech.** Segmentation leans on full
120 stops and commas. If `words.py show` prints one huge sentence, add the missing full stops and
121 commas to the word text in `words.json` (where the speaker clearly ends a thought), then remake.
122- **Wrong language gives fluent nonsense.** An English-only model on a Welsh or Spanish passage
123 writes confident English garbage. Read the transcript before anything else; use a multilingual
124 model or the Zylcut `language` option for other languages.
125- **Frame rate.** Gaps and shot snapping are counted in frames of the video's real rate. Pass
126 `--fps 29.97`, not 30, to `check` for NTSC footage.
127- **ffmpeg sizes SRT styles on a 288-line grid.** Burn the ASS file the script writes (its
128 PlayResX/PlayResY equal the video, so sizes are pixels), not the SRT with `force_style`.
129- **Fonts fail silently.** libass picks a fallback without an error; the burn step prints the
130 font it used. Fonts also differ in how big a "size" looks, so the script sizes by capital
131 height, measured from a rendered test of the chosen font.
132- **A plate with inline colour.** Do not add colour tags to plate cues; the plate is its own
133 layer for that reason (see references/ffmpeg.md).
134- **Fast speech forces a few mid-clause splits.** Above about 180 words a minute, some phrases
135 cannot fit one subtitle even at the 22 cps tolerance, so the script ends a subtitle at the
136 least bad word (often at a short pause). Accept it, name it in the report, and offer condensed
137 subtitles; do not raise `--max-cps`, and do not drop or reword words unless the user asks for
138 condensed subtitles.
139- **Do not patch the scripts.** If a rule seems wrong for this video, say so in the report;
140 the scripts are shared by every run of this skill.
141- **Shot-change snapping cuts at most 6 frames of a word's tail.** A subtitle over a cut in
142 mid-sentence stays, as broadcast practice allows; one that would hang 1-11 frames over a new
143 shot is trimmed to the cut or held 12 frames past it. A remaining linter warning means
144 neither fit (the subtitle would go under 5/6 s); leave it and mention it.
145
146## Limits
147
148Tested cold on a fast two-person interview (about 185 words a minute, 230 at its fastest). A
149separate judge scored the last run 7-9 out of 10 per area, not 8 everywhere:
150- **Very fast speech, verbatim.** Some subtitles still split mid-clause or start a new sentence
151 partway through a line, and about 3 in 4 subtitles use two lines (professional talks: under
152 half). Condensed subtitles fix this, but only when the user asks for them.
153- **Who speaks** comes from reading the transcript and frames. On a wide shot with both people
154 in view, a short reply can go to the wrong person. Ask the user to check dialogue subtitles.
155- **Words the transcriber mishears** (names, places) stay as heard unless the user gives the
156 spelling. The report lists the ones to check.
157
158## Credit
159
160Adapted from the caption-styling skill in the vidmoat/skills repository by Vidmoat Skills
161contributors (text CC-BY-4.0, scripts Apache-2.0); see NOTICE. Changed by Zylcut: broadcast
162values (20 cps, 42 characters, 5/6-7 s, frame gaps, shot changes), automatic segmentation and
163timing, a Zylcut path, and measured references.
164
1Copyright 2026 Zylcut
2
3
4 Apache License
5 Version 2.0, January 2004
6 http://www.apache.org/licenses/
7
8 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
9
10 1. Definitions.
11
12 "License" shall mean the terms and conditions for use, reproduction,
13 and distribution as defined by Sections 1 through 9 of this document.
14
15 "Licensor" shall mean the copyright owner or entity authorized by
16 the copyright owner that is granting the License.
17
18 "Legal Entity" shall mean the union of the acting entity and all
19 other entities that control, are controlled by, or are under common
20 control with that entity. For the purposes of this definition,
21 "control" means (i) the power, direct or indirect, to cause the
22 direction or management of such entity, whether by contract or
23 otherwise, or (ii) ownership of fifty percent (50%) or more of the
24 outstanding shares, or (iii) beneficial ownership of such entity.
25
26 "You" (or "Your") shall mean an individual or Legal Entity
27 exercising permissions granted by this License.
28
29 "Source" form shall mean the preferred form for making modifications,
30 including but not limited to software source code, documentation
31 source, and configuration files.
32
33 "Object" form shall mean any form resulting from mechanical
34 transformation or translation of a Source form, including but
35 not limited to compiled object code, generated documentation,
36 and conversions to other media types.
37
38 "Work" shall mean the work of authorship, whether in Source or
39 Object form, made available under the License, as indicated by a
40 copyright notice that is included in or attached to the work
41 (an example is provided in the Appendix below).
42
43 "Derivative Works" shall mean any work, whether in Source or Object
44 form, that is based on (or derived from) the Work and for which the
45 editorial revisions, annotations, elaborations, or other modifications
46 represent, as a whole, an original work of authorship. For the purposes
47 of this License, Derivative Works shall not include works that remain
48 separable from, or merely link (or bind by name) to the interfaces of,
49 the Work and Derivative Works thereof.
50
51 "Contribution" shall mean any work of authorship, including
52 the original version of the Work and any modifications or additions
53 to that Work or Derivative Works thereof, that is intentionally
54 submitted to Licensor for inclusion in the Work by the copyright owner
55 or by an individual or Legal Entity authorized to submit on behalf of
56 the copyright owner. For the purposes of this definition, "submitted"
57 means any form of electronic, verbal, or written communication sent
58 to the Licensor or its representatives, including but not limited to
59 communication on electronic mailing lists, source code control systems,
60 and issue tracking systems that are managed by, or on behalf of, the
61 Licensor for the purpose of discussing and improving the Work, but
62 excluding communication that is conspicuously marked or otherwise
63 designated in writing by the copyright owner as "Not a Contribution."
64
65 "Contributor" shall mean Licensor and any individual or Legal Entity
66 on behalf of whom a Contribution has been received by Licensor and
67 subsequently incorporated within the Work.
68
69 2. Grant of Copyright License. Subject to the terms and conditions of
70 this License, each Contributor hereby grants to You a perpetual,
71 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
72 copyright license to reproduce, prepare Derivative Works of,
73 publicly display, publicly perform, sublicense, and distribute the
74 Work and such Derivative Works in Source or Object form.
75
76 3. Grant of Patent License. Subject to the terms and conditions of
77 this License, each Contributor hereby grants to You a perpetual,
78 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79 (except as stated in this section) patent license to make, have made,
80 use, offer to sell, sell, import, and otherwise transfer the Work,
81 where such license applies only to those patent claims licensable
82 by such Contributor that are necessarily infringed by their
83 Contribution(s) alone or by combination of their Contribution(s)
84 with the Work to which such Contribution(s) was submitted. If You
85 institute patent litigation against any entity (including a
86 cross-claim or counterclaim in a lawsuit) alleging that the Work
87 or a Contribution incorporated within the Work constitutes direct
88 or contributory patent infringement, then any patent licenses
89 granted to You under this License for that Work shall terminate
90 as of the date such litigation is filed.
91
92 4. Redistribution. You may reproduce and distribute copies of the
93 Work or Derivative Works thereof in any medium, with or without
94 modifications, and in Source or Object form, provided that You
95 meet the following conditions:
96
97 (a) You must give any other recipients of the Work or
98 Derivative Works a copy of this License; and
99
100 (b) You must cause any modified files to carry prominent notices
101 stating that You changed the files; and
102
103 (c) You must retain, in the Source form of any Derivative Works
104 that You distribute, all copyright, patent, trademark, and
105 attribution notices from the Source form of the Work,
106 excluding those notices that do not pertain to any part of
107 the Derivative Works; and
108
109 (d) If the Work includes a "NOTICE" text file as part of its
110 distribution, then any Derivative Works that You distribute must
111 include a readable copy of the attribution notices contained
112 within such NOTICE file, excluding those notices that do not
113 pertain to any part of the Derivative Works, in at least one
114 of the following places: within a NOTICE text file distributed
115 as part of the Derivative Works; within the Source form or
116 documentation, if provided along with the Derivative Works; or,
117 within a display generated by the Derivative Works, if and
118 wherever such third-party notices normally appear. The contents
119 of the NOTICE file are for informational purposes only and
120 do not modify the License. You may add Your own attribution
121 notices within Derivative Works that You distribute, alongside
122 or as an addendum to the NOTICE text from the Work, provided
123 that such additional attribution notices cannot be construed
124 as modifying the License.
125
126 You may add Your own copyright statement to Your modifications and
127 may provide additional or different license terms and conditions
128 for use, reproduction, or distribution of Your modifications, or
129 for any such Derivative Works as a whole, provided Your use,
130 reproduction, and distribution of the Work otherwise complies with
131 the conditions stated in this License.
132
133 5. Submission of Contributions. Unless You explicitly state otherwise,
134 any Contribution intentionally submitted for inclusion in the Work
135 by You to the Licensor shall be under the terms and conditions of
136 this License, without any additional terms or conditions.
137 Notwithstanding the above, nothing herein shall supersede or modify
138 the terms of any separate license agreement you may have executed
139 with Licensor regarding such Contributions.
140
141 6. Trademarks. This License does not grant permission to use the trade
142 names, trademarks, service marks, or product names of the Licensor,
143 except as required for reasonable and customary use in describing the
144 origin of the Work and reproducing the content of the NOTICE file.
145
146 7. Disclaimer of Warranty. Unless required by applicable law or
147 agreed to in writing, Licensor provides the Work (and each
148 Contributor provides its Contributions) on an "AS IS" BASIS,
149 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
150 implied, including, without limitation, any warranties or conditions
151 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
152 PARTICULAR PURPOSE. You are solely responsible for determining the
153 appropriateness of using or redistributing the Work and assume any
154 risks associated with Your exercise of permissions under this License.
155
156 8. Limitation of Liability. In no event and under no legal theory,
157 whether in tort (including negligence), contract, or otherwise,
158 unless required by applicable law (such as deliberate and grossly
159 negligent acts) or agreed to in writing, shall any Contributor be
160 liable to You for damages, including any direct, indirect, special,
161 incidental, or consequential damages of any character arising as a
162 result of this License or out of the use or inability to use the
163 Work (including but not limited to damages for loss of goodwill,
164 work stoppage, computer failure or malfunction, or any and all
165 other commercial damages or losses), even if such Contributor
166 has been advised of the possibility of such damages.
167
168 9. Accepting Warranty or Additional Liability. While redistributing
169 the Work or Derivative Works thereof, You may choose to offer,
170 and charge a fee for, acceptance of support, warranty, indemnity,
171 or other liability obligations and/or rights consistent with this
172 License. However, in accepting such obligations, You may act only
173 on Your own behalf and on Your sole responsibility, not on behalf
174 of any other Contributor, and only if You agree to indemnify,
175 defend, and hold each Contributor harmless for any liability
176 incurred by, or claims asserted against, such Contributor by reason
177 of your accepting any such warranty or additional liability.
178
179 END OF TERMS AND CONDITIONS
180
181 APPENDIX: How to apply the Apache License to your work.
182
183 To apply the Apache License to your work, attach the following
184 boilerplate notice, with the fields enclosed by brackets "[]"
185 replaced with your own identifying information. (Don't include
186 the brackets!) The text should be enclosed in the appropriate
187 comment syntax for the file format. We also recommend that a
188 file or class name and description of purpose be included on the
189 same "printed page" as the copyright notice for easier
190 identification within third-party archives.
191
192 Copyright [yyyy] [name of copyright owner]
193
194 Licensed under the Apache License, Version 2.0 (the "License");
195 you may not use this file except in compliance with the License.
196 You may obtain a copy of the License at
197
198 http://www.apache.org/licenses/LICENSE-2.0
199
200 Unless required by applicable law or agreed to in writing, software
201 distributed under the License is distributed on an "AS IS" BASIS,
202 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203 See the License for the specific language governing permissions and
204 limitations under the License.
205
1Attribution 4.0 International
2
3=======================================================================
4
5Creative Commons Corporation ("Creative Commons") is not a law firm and
6does not provide legal services or legal advice. Distribution of
7Creative Commons public licenses does not create a lawyer-client or
8other relationship. Creative Commons makes its licenses and related
9information available on an "as-is" basis. Creative Commons gives no
10warranties regarding its licenses, any material licensed under their
11terms and conditions, or any related information. Creative Commons
12disclaims all liability for damages resulting from their use to the
13fullest extent possible.
14
15Using Creative Commons Public Licenses
16
17Creative Commons public licenses provide a standard set of terms and
18conditions that creators and other rights holders may use to share
19original works of authorship and other material subject to copyright
20and certain other rights specified in the public license below. The
21following considerations are for informational purposes only, are not
22exhaustive, and do not form part of our licenses.
23
24 Considerations for licensors: Our public licenses are
25 intended for use by those authorized to give the public
26 permission to use material in ways otherwise restricted by
27 copyright and certain other rights. Our licenses are
28 irrevocable. Licensors should read and understand the terms
29 and conditions of the license they choose before applying it.
30 Licensors should also secure all rights necessary before
31 applying our licenses so that the public can reuse the
32 material as expected. Licensors should clearly mark any
33 material not subject to the license. This includes other CC-
34 licensed material, or material used under an exception or
35 limitation to copyright. More considerations for licensors:
36 wiki.creativecommons.org/Considerations_for_licensors
37
38 Considerations for the public: By using one of our public
39 licenses, a licensor grants the public permission to use the
40 licensed material under specified terms and conditions. If
41 the licensor's permission is not necessary for any reason--for
42 example, because of any applicable exception or limitation to
43 copyright--then that use is not regulated by the license. Our
44 licenses grant only permissions under copyright and certain
45 other rights that a licensor has authority to grant. Use of
46 the licensed material may still be restricted for other
47 reasons, including because others have copyright or other
48 rights in the material. A licensor may make special requests,
49 such as asking that all changes be marked or described.
50 Although not required by our licenses, you are encouraged to
51 respect those requests where reasonable. More_considerations
52 for the public:
53 wiki.creativecommons.org/Considerations_for_licensees
54
55=======================================================================
56
57Creative Commons Attribution 4.0 International Public License
58
59By exercising the Licensed Rights (defined below), You accept and agree
60to be bound by the terms and conditions of this Creative Commons
61Attribution 4.0 International Public License ("Public License"). To the
62extent this Public License may be interpreted as a contract, You are
63granted the Licensed Rights in consideration of Your acceptance of
64these terms and conditions, and the Licensor grants You such rights in
65consideration of benefits the Licensor receives from making the
66Licensed Material available under these terms and conditions.
67
68
69Section 1 -- Definitions.
70
71 a. Adapted Material means material subject to Copyright and Similar
72 Rights that is derived from or based upon the Licensed Material
73 and in which the Licensed Material is translated, altered,
74 arranged, transformed, or otherwise modified in a manner requiring
75 permission under the Copyright and Similar Rights held by the
76 Licensor. For purposes of this Public License, where the Licensed
77 Material is a musical work, performance, or sound recording,
78 Adapted Material is always produced where the Licensed Material is
79 synched in timed relation with a moving image.
80
81 b. Adapter's License means the license You apply to Your Copyright
82 and Similar Rights in Your contributions to Adapted Material in
83 accordance with the terms and conditions of this Public License.
84
85 c. Copyright and Similar Rights means copyright and/or similar rights
86 closely related to copyright including, without limitation,
87 performance, broadcast, sound recording, and Sui Generis Database
88 Rights, without regard to how the rights are labeled or
89 categorized. For purposes of this Public License, the rights
90 specified in Section 2(b)(1)-(2) are not Copyright and Similar
91 Rights.
92
93 d. Effective Technological Measures means those measures that, in the
94 absence of proper authority, may not be circumvented under laws
95 fulfilling obligations under Article 11 of the WIPO Copyright
96 Treaty adopted on December 20, 1996, and/or similar international
97 agreements.
98
99 e. Exceptions and Limitations means fair use, fair dealing, and/or
100 any other exception or limitation to Copyright and Similar Rights
101 that applies to Your use of the Licensed Material.
102
103 f. Licensed Material means the artistic or literary work, database,
104 or other material to which the Licensor applied this Public
105 License.
106
107 g. Licensed Rights means the rights granted to You subject to the
108 terms and conditions of this Public License, which are limited to
109 all Copyright and Similar Rights that apply to Your use of the
110 Licensed Material and that the Licensor has authority to license.
111
112 h. Licensor means the individual(s) or entity(ies) granting rights
113 under this Public License.
114
115 i. Share means to provide material to the public by any means or
116 process that requires permission under the Licensed Rights, such
117 as reproduction, public display, public performance, distribution,
118 dissemination, communication, or importation, and to make material
119 available to the public including in ways that members of the
120 public may access the material from a place and at a time
121 individually chosen by them.
122
123 j. Sui Generis Database Rights means rights other than copyright
124 resulting from Directive 96/9/EC of the European Parliament and of
125 the Council of 11 March 1996 on the legal protection of databases,
126 as amended and/or succeeded, as well as other essentially
127 equivalent rights anywhere in the world.
128
129 k. You means the individual or entity exercising the Licensed Rights
130 under this Public License. Your has a corresponding meaning.
131
132
133Section 2 -- Scope.
134
135 a. License grant.
136
137 1. Subject to the terms and conditions of this Public License,
138 the Licensor hereby grants You a worldwide, royalty-free,
139 non-sublicensable, non-exclusive, irrevocable license to
140 exercise the Licensed Rights in the Licensed Material to:
141
142 a. reproduce and Share the Licensed Material, in whole or
143 in part; and
144
145 b. produce, reproduce, and Share Adapted Material.
146
147 2. Exceptions and Limitations. For the avoidance of doubt, where
148 Exceptions and Limitations apply to Your use, this Public
149 License does not apply, and You do not need to comply with
150 its terms and conditions.
151
152 3. Term. The term of this Public License is specified in Section
153 6(a).
154
155 4. Media and formats; technical modifications allowed. The
156 Licensor authorizes You to exercise the Licensed Rights in
157 all media and formats whether now known or hereafter created,
158 and to make technical modifications necessary to do so. The
159 Licensor waives and/or agrees not to assert any right or
160 authority to forbid You from making technical modifications
161 necessary to exercise the Licensed Rights, including
162 technical modifications necessary to circumvent Effective
163 Technological Measures. For purposes of this Public License,
164 simply making modifications authorized by this Section 2(a)
165 (4) never produces Adapted Material.
166
167 5. Downstream recipients.
168
169 a. Offer from the Licensor -- Licensed Material. Every
170 recipient of the Licensed Material automatically
171 receives an offer from the Licensor to exercise the
172 Licensed Rights under the terms and conditions of this
173 Public License.
174
175 b. No downstream restrictions. You may not offer or impose
176 any additional or different terms or conditions on, or
177 apply any Effective Technological Measures to, the
178 Licensed Material if doing so restricts exercise of the
179 Licensed Rights by any recipient of the Licensed
180 Material.
181
182 6. No endorsement. Nothing in this Public License constitutes or
183 may be construed as permission to assert or imply that You
184 are, or that Your use of the Licensed Material is, connected
185 with, or sponsored, endorsed, or granted official status by,
186 the Licensor or others designated to receive attribution as
187 provided in Section 3(a)(1)(A)(i).
188
189 b. Other rights.
190
191 1. Moral rights, such as the right of integrity, are not
192 licensed under this Public License, nor are publicity,
193 privacy, and/or other similar personality rights; however, to
194 the extent possible, the Licensor waives and/or agrees not to
195 assert any such rights held by the Licensor to the limited
196 extent necessary to allow You to exercise the Licensed
197 Rights, but not otherwise.
198
199 2. Patent and trademark rights are not licensed under this
200 Public License.
201
202 3. To the extent possible, the Licensor waives any right to
203 collect royalties from You for the exercise of the Licensed
204 Rights, whether directly or through a collecting society
205 under any voluntary or waivable statutory or compulsory
206 licensing scheme. In all other cases the Licensor expressly
207 reserves any right to collect such royalties.
208
209
210Section 3 -- License Conditions.
211
212Your exercise of the Licensed Rights is expressly made subject to the
213following conditions.
214
215 a. Attribution.
216
217 1. If You Share the Licensed Material (including in modified
218 form), You must:
219
220 a. retain the following if it is supplied by the Licensor
221 with the Licensed Material:
222
223 i. identification of the creator(s) of the Licensed
224 Material and any others designated to receive
225 attribution, in any reasonable manner requested by
226 the Licensor (including by pseudonym if
227 designated);
228
229 ii. a copyright notice;
230
231 iii. a notice that refers to this Public License;
232
233 iv. a notice that refers to the disclaimer of
234 warranties;
235
236 v. a URI or hyperlink to the Licensed Material to the
237 extent reasonably practicable;
238
239 b. indicate if You modified the Licensed Material and
240 retain an indication of any previous modifications; and
241
242 c. indicate the Licensed Material is licensed under this
243 Public License, and include the text of, or the URI or
244 hyperlink to, this Public License.
245
246 2. You may satisfy the conditions in Section 3(a)(1) in any
247 reasonable manner based on the medium, means, and context in
248 which You Share the Licensed Material. For example, it may be
249 reasonable to satisfy the conditions by providing a URI or
250 hyperlink to a resource that includes the required
251 information.
252
253 3. If requested by the Licensor, You must remove any of the
254 information required by Section 3(a)(1)(A) to the extent
255 reasonably practicable.
256
257 4. If You Share Adapted Material You produce, the Adapter's
258 License You apply must not prevent recipients of the Adapted
259 Material from complying with this Public License.
260
261
262Section 4 -- Sui Generis Database Rights.
263
264Where the Licensed Rights include Sui Generis Database Rights that
265apply to Your use of the Licensed Material:
266
267 a. for the avoidance of doubt, Section 2(a)(1) grants You the right
268 to extract, reuse, reproduce, and Share all or a substantial
269 portion of the contents of the database;
270
271 b. if You include all or a substantial portion of the database
272 contents in a database in which You have Sui Generis Database
273 Rights, then the database in which You have Sui Generis Database
274 Rights (but not its individual contents) is Adapted Material; and
275
276 c. You must comply with the conditions in Section 3(a) if You Share
277 all or a substantial portion of the contents of the database.
278
279For the avoidance of doubt, this Section 4 supplements and does not
280replace Your obligations under this Public License where the Licensed
281Rights include other Copyright and Similar Rights.
282
283
284Section 5 -- Disclaimer of Warranties and Limitation of Liability.
285
286 a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
287 EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
288 AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
289 ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
290 IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
291 WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
292 PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
293 ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
294 KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
295 ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
296
297 b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
298 TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
299 NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
300 INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
301 COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
302 USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
303 ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
304 DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
305 IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
306
307 c. The disclaimer of warranties and limitation of liability provided
308 above shall be interpreted in a manner that, to the extent
309 possible, most closely approximates an absolute disclaimer and
310 waiver of all liability.
311
312
313Section 6 -- Term and Termination.
314
315 a. This Public License applies for the term of the Copyright and
316 Similar Rights licensed here. However, if You fail to comply with
317 this Public License, then Your rights under this Public License
318 terminate automatically.
319
320 b. Where Your right to use the Licensed Material has terminated under
321 Section 6(a), it reinstates:
322
323 1. automatically as of the date the violation is cured, provided
324 it is cured within 30 days of Your discovery of the
325 violation; or
326
327 2. upon express reinstatement by the Licensor.
328
329 For the avoidance of doubt, this Section 6(b) does not affect any
330 right the Licensor may have to seek remedies for Your violations
331 of this Public License.
332
333 c. For the avoidance of doubt, the Licensor may also offer the
334 Licensed Material under separate terms or conditions or stop
335 distributing the Licensed Material at any time; however, doing so
336 will not terminate this Public License.
337
338 d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
339 License.
340
341
342Section 7 -- Other Terms and Conditions.
343
344 a. The Licensor shall not be bound by any additional or different
345 terms or conditions communicated by You unless expressly agreed.
346
347 b. Any arrangements, understandings, or agreements regarding the
348 Licensed Material not stated herein are separate from and
349 independent of the terms and conditions of this Public License.
350
351
352Section 8 -- Interpretation.
353
354 a. For the avoidance of doubt, this Public License does not, and
355 shall not be interpreted to, reduce, limit, restrict, or impose
356 conditions on any use of the Licensed Material that could lawfully
357 be made without permission under this Public License.
358
359 b. To the extent possible, if any provision of this Public License is
360 deemed unenforceable, it shall be automatically reformed to the
361 minimum extent necessary to make it enforceable. If the provision
362 cannot be reformed, it shall be severed from this Public License
363 without affecting the enforceability of the remaining terms and
364 conditions.
365
366 c. No term or condition of this Public License will be waived and no
367 failure to comply consented to unless expressly agreed to by the
368 Licensor.
369
370 d. Nothing in this Public License constitutes or may be interpreted
371 as a limitation upon, or waiver of, any privileges and immunities
372 that apply to the Licensor or You, including from the legal
373 processes of any jurisdiction or authority.
374
375
376=======================================================================
377
378Creative Commons is not a party to its public
379licenses. Notwithstanding, Creative Commons may elect to apply one of
380its public licenses to material it publishes and in those instances
381will be considered the “Licensor.” The text of the Creative Commons
382public licenses is dedicated to the public domain under the CC0 Public
383Domain Dedication. Except for the limited purpose of indicating that
384material is shared under a Creative Commons public license or as
385otherwise permitted by the Creative Commons policies published at
386creativecommons.org/policies, Creative Commons does not authorize the
387use of the trademark "Creative Commons" or any other trademark or logo
388of Creative Commons without its prior written consent including,
389without limitation, in connection with any unauthorized modifications
390to any of its public licenses or any other arrangements,
391understandings, or agreements concerning use of licensed material. For
392the avoidance of doubt, this paragraph does not form part of the
393public licenses.
394
395Creative Commons may be contacted at creativecommons.org.
396
1broadcast-subtitles
2Copyright 2026 Zylcut
3
4This skill adapts the caption-styling skill from the vidmoat/skills repository
5(Copyright 2026 Buzz Innovations Ltd and Vidmoat Skills contributors):
6 - its prose (CC-BY-4.0, full text in LICENSE-CONTENT) was rewritten and extended
7 for broadcast subtitle rules, shot-change timing and a second editing backend;
8 - its check_captions.py (Apache-2.0, full text in LICENSE) was extended into
9 scripts/subtitles.py (frame-based gaps, shot changes, line breaks, segmentation,
10 timing, ASS, VTT and Zylcut output).
11Changes by Zylcut. The original authors do not endorse this adaptation, and no
12trademark of theirs is licensed here.
13
1# Generic path: ffmpeg, ffprobe and a local transcriber
2
3Use this when no Zylcut tools are available. Everything runs in the user's project folder; the
4scripts write only the files named on their command line.
5
6## Tools
7
8- `ffmpeg` and `ffprobe` on PATH, with libass (`ffmpeg -filters` lists `subtitles`).
9- A word-timed transcriber. `scripts/words.py transcribe` runs whisper.cpp's `whisper-cli` and
10 finds a model in `~/.cache/whisper/` or `$WHISPER_MODEL` (`ggml-small.en.bin` for English). For
11 another language use a multilingual model (`ggml-small.bin`) with `--model`. Any other tool that
12 writes word times as JSON works through `words.py import`.
13- Python 3.8 or newer. No packages to install.
14
15## Commands, in order
16
17```bash
18S=path/to/this/skill/scripts
19ffprobe -v error -select_streams v:0 -show_entries stream=width,height,r_frame_rate -of csv=p=0 input.mp4
20python3 $S/words.py transcribe input.mp4 -o words.json # 16 kHz WAV + whisper-cli
21python3 $S/words.py show words.json # read it; fix names in words.json
22python3 $S/words.py label words.json 0=A 21=B 57=A # two or more speakers only
23python3 $S/subtitles.py shots input.mp4 -o shots.json
24python3 $S/subtitles.py make words.json --video input.mp4 --shots shots.json -o subs
25python3 $S/subtitles.py check subs.srt --fps 25 --shots shots.json --max-chars 42
26python3 $S/subtitles.py burn input.mp4 subs.ass input.subtitled.mp4
27```
28
29- Use the real frame rate from ffprobe in `check` (`30000/1001` is 29.97).
30- On vertical video pass `--max-chars` with the number `make` printed (it fits the safe width).
31- Dialogue subtitles (two speakers) carry `{\an1\pos(x,y)}` so both dashed lines start at one x
32 while the block stays centred.
33- `make --plate` gives the dark-plate look (use it when `make` says the band is bright); the default is an outline and soft shadow.
34- Long recordings: `words.py transcribe` handles a whole file; it takes about a tenth of real
35 time on a recent laptop with the small model.
36- A clip cut from a longer recording: either transcribe the clip itself, or transcribe the source
37 once and pass `make --from START --to END --offset START`.
38
39## The ASS file the script writes
40
41`PlayResX`/`PlayResY` equal the video size, so sizes and margins are pixels. `WrapStyle: 2`
42turns off automatic wrapping: the script's line breaks are the only ones. Colours are
43`&HAABBGGRR` (alpha `00` opaque).
44
45- **Outline style** (default): one layer, `BorderStyle` 1, an outline about 12% of the capital
46 height and a half-transparent shadow.
47- **Plate style** (`--plate`): two layers per subtitle. Layer 0 is invisible text with
48 `BorderStyle` 3, which draws a box per line in `OutlineColour` `&H40000000` (black at 75%);
49 layer 1 carries the visible text. Keep colour tags off layer 0, or the box splits into one box
50 per colour run with dark seams.
51- To lift one subtitle to the top (a lower third or burned-in text sits at the bottom), add
52 `{\an8}` at the start of that cue's text on both layers.
53
54## Checking the burn
55
56```bash
57ffmpeg -v error -ss 12.5 -i input.subtitled.mp4 -frames:v 1 check.jpg
58ffprobe -v error -show_entries format=duration -of csv=p=0 input.subtitled.mp4
59```
60
61Look at the first subtitle, the longest two-line subtitle and the busiest background. The
62`fontselect:` line the burn step prints must name the font you meant.
63
1# The standard, with reasons and sources
2
3Each rule below names where it comes from and what we measured on real professional subtitles.
4Use it to explain a choice to the user, and to decide when a rule may bend.
5
6## Sources
7
8- Netflix, English (USA) Timed Text Style Guide, and Timed Text Style Guide: Subtitle Timing
9 Guidelines (Netflix Partner Help Center): 42 characters per line, 2 lines, 20 characters per
10 second for adult programmes (17 for children's), minimum 5/6 s, maximum 7 s, 2 frames between
11 subtitles, gaps of 3-11 frames closed to 2, shot-change timing.
12- BBC Subtitle Guidelines (bbc.co.uk accessibility): 160-180 words per minute, line breaks at
13 natural linguistic points, white text on black, size and position by frame height.
14- Vertical practice (caption-styling, vidmoat/skills): text clear of the bottom 420 px on
15 1080x1920, 64-72 px type, about 28-32 characters per line.
16
17## Measured references
18
19Human-made English subtitles downloaded as text only and measured with a script (no video kept):
20
21| Measure | 17 talks, 3,820 subtitles | 12 popular explainers and trailers, 1,718 subtitles |
22|---|---|---|
23| Longest line, 95th percentile / max | 41 / 42 | 55 / 62 |
24| Lines over 42 characters | 0% | 48% |
25| Two-line subtitles | 46% | 70% |
26| Three or more lines | 0% | 0% |
27| Duration 2nd / median / 98th percentile | 1.17 / 2.71 / 5.38 s | 1.12 / 4.00 / 6.72 s |
28| Under 5/6 s, over 7 s | 0%, 0% | 0.7%, 1.1% |
29| Reading speed median / 90th / 98th percentile | 14.4 / 19.5 / 20.8 cps | 16.7 / 21.3 / 24.7 cps |
30| Over 20 cps | 7.7% | 17.8% |
31| Gaps of 0 / 1-2 / 3-11 / 12+ frames (at 24) | 24% / 46% / 6% / 25% | 78% / 3% / 1% / 18% |
32| Speech rate (median per file) | 152 wpm | 163 wpm |
33
34The talks follow the broadcast rules almost exactly; the creator subtitles break the line length
35half the time and read faster. This skill holds to the first column. On 2 talks with camera cuts
36(24 and 62 shot changes), 23 of 34 subtitles that ended within 0.5 s of a cut ended 0-3 frames
37before it, which is the out-time rule below.
38
39## Why each rule
40
41| Rule | Why | When it may bend |
42|---|---|---|
43| 2 lines | A third line covers the picture and is not read in time. | Never in this skill. |
44| 42 characters (landscape) | Longer lines make the eye travel too far; it is the streaming limit. | Vertical uses the safe width instead (about 32). |
45| 20 cps, 17 aim, 22 tolerated on 1 in 10 | Adults read 20 cps with some effort; 17 leaves time to watch. 98% of the measured talks stay under 20.8 and 7.7% go over 20, so professionals accept a brief overrun to keep a clause whole. | Never over 22, and never to save a split that could fall at a clause end. |
46| 5/6 s minimum | Shorter subtitles flash and are missed. | Never. |
47| 7 s maximum | Longer ones are re-read. | Never. |
48| 2-frame gap, close 3-11 | A gap of a few frames reads as a flicker; 2 frames lets the eye see a change. | Never. |
49| In-time onto a shot change | A subtitle that appears a few frames before a cut, then the cut, reads as two events. | Only back up to 12 frames, so it never shows before speech by more than 0.5 s. |
50| Out-time 2 frames before a shot change | A subtitle that lingers over a new shot for a few frames looks late. | Only when speech has ended before the cut. |
51| Line breaks at phrase ends | Each line should be a unit of meaning; a line ending on "the" makes the reader wait. | When no break fits the length, the least bad break wins (the script scores them). |
52| Two speakers: "-" per line, no space, one change per subtitle | Netflix English style; a viewer must see who says which line, and a change mid-line cannot be shown. | A rapid exchange of one-word replies may share a subtitle; never three speakers. |
53| Bottom-heavy when equal | The shorter top line leaves the picture clearer and reads naturally. | Balance wins over bottom-heavy. |
54| Off-white, outline or plate | Pure white blooms after compression; contrast cannot be checked frame by frame, so an outline or plate guarantees it. | A plate on busy or bright footage; an outline elsewhere. |
55
56## Segmentation, as the script does it
57
58The script tries every split of the words into subtitles and keeps the cheapest, where cost adds:
59ending away from a sentence or clause end, ending on an article, preposition, conjunction or
60auxiliary, splitting before "of", a long pause inside a subtitle, reading speed over 17 (and much
61more over 20), time on screen under 5/6 s, a needlessly tiny subtitle, and an unbalanced line
62break. The reading speed uses the time a subtitle can really stay up: from its first word to the
63next subtitle (less 2 frames), at most 0.5 s past its last word and at most 7 s.
64
1# Zylcut path
2
3Use this when Zylcut MCP tools are available. The edit is the project's `index.tsx`; the
4subtitles go in as a component file the script writes, so every subtitle keeps the exact timing
5and line breaks the rules produced. Read the in-app **zylcut-editor** skill first if you have not
6in this session (structure, timing, `check`, `capture`, `export`).
7
8## Steps
9
101. **Open the project** (`open` with the folder, or `projects`), read `index.tsx`, take a
11 `user_edits` baseline and read `notes`.
122. **Probe** the video with `media_probe`: width, height, frame rate (`averagePacketRate` of the
13 video track) and duration of what the scene plays.
143. **Transcribe** with `media_transcribe` (`projectId`, `output` under the project's
15 `assets/transcripts/`, a `glossary` for names). Add `speakers: 2` (or the count) for an
16 interview so speaker changes get dashes. Then convert:
17 `python3 scripts/words.py import assets/transcripts/<file>.json -o words.json`
18 (aligned English times need no `--audio`; pass `--audio` for estimated times).
19 Read it with `words.py show` and fix misheard names in the word text.
20 The automatic speaker labels can split two people into more voices: check the turns in
21 `show` against frames (`media_grab`) and relabel with `words.py label words.json 0=A 21=B ...`.
224. **Shot changes**: `python3 scripts/subtitles.py shots <video> -o shots.json` when ffmpeg is on
23 PATH. Without it, skip shot snapping (say so in the report) or list the cuts yourself from a
24 `media_grab` with `auto: true` and write `{"shots": [seconds, ...]}`.
255. **Make**: `python3 scripts/subtitles.py make words.json --video <video> --shots shots.json -o
26 subtitles` (or `--size WxH --fps F --duration S` instead of `--video`). If the scene plays a
27 trimmed part of the file, pass `--from IN --to OUT --offset IN` so times are scene seconds.
28 If the scene is a cut clip (`keep`), make the subtitles from a transcript of the exported cut
29 instead: export the scene's audio (`export` with a `.wav` path), transcribe that file, and use
30 its times.
316. **Lint**: `python3 scripts/subtitles.py check subtitles.srt --fps F --shots shots.json`.
32 0 errors before going on.
337. **Place**: copy `subtitles.tsx` into the project folder, then in `index.tsx`:
34 `import Subtitles from "./subtitles";` and `<Subtitles />` as the last child of the scene, so
35 it draws on top. It renders one `<text>` per subtitle (Inter 600, off-white, outline and
36 shadow, bottom-centred, `start`/`end` from the SRT). Do not also add `<captions>`.
378. **Verify**: `context` shows no `compileError`; `check` on the scene (no `text-off-frame`, no
38 `low-contrast-text`; with `platform: "youtube"` for landscape or the target app for vertical);
39 `capture` at the first subtitle, the longest two-line one and the busiest background.
409. **Deliver**: the linted `subtitles.srt` and `.vtt` from step 5 are the sidecar files. Export
41 the video only when the user asks (`export`, preset `youtube-1080` or `vertical-1080`).
42
43## Notes
44
45- Zylcut snaps `start`/`end` to its 30 fps frame grid; at 25 or 29.97 fps a subtitle can move by
46 under one frame. The SRT keeps the exact times.
47- To restyle, edit the constants at the top of `subtitles.tsx` (size, bottom margin) or the
48 `<text>` props; keep the timing rows as generated.
49- Zylcut's own `export` to `.srt` re-segments captions with its own rules; deliver the SRT from
50 this script instead, since it is the one that passed the linter.
51
1#!/usr/bin/env python3
2"""Broadcast-standard subtitles from a word-timed transcript: segment, time, snap, check, burn.
3
4Usage:
5 subtitles.py shots VIDEO -o shots.json [--threshold 12]
6 Finds shot changes (ffmpeg scdet) and writes their times.
7 subtitles.py make words.json (--video VIDEO | --size WxH --fps FPS --duration S) -o NAME [--shots shots.json] [options]
8 Writes NAME.srt, NAME.vtt, NAME.ass (styled for burning) and NAME.tsx (a Zylcut component).
9 subtitles.py check NAME.srt --fps FPS [--shots shots.json] [--max-chars 42] [--max-cps 20]
10 Lints the file against the rules below; exits 1 on any error. Works on any SRT or VTT.
11 subtitles.py burn VIDEO NAME.ass OUT.mp4 [--crf 20] [--threads 4]
12
13Rules (Netflix English timed-text guide unless noted; see references/standard.md):
14 2 lines at most; 42 characters per line on landscape (vertical: what fits the safe width,
15 about 32); reading speed at most 20 characters per second, aim for 17 or less; a cue lasts
16 5/6 s to 7 s; cues are 2 frames apart or chained; gaps of 3-11 frames are closed to 2 frames;
17 an in-time moves back onto a shot change up to 12 frames before it; an out-time within 12
18 frames of a shot change moves to 2 frames before it; a line never ends on an article,
19 preposition, conjunction, auxiliary or a first name; two lines are balanced, bottom-heavy when
20 it can be chosen.
21
22make options:
23 --max-chars N characters per line (default 42 landscape, or the safe width on vertical)
24 --max-cps 20 hard reading-speed limit; --target-cps 17 is what segmentation aims for
25 --lead-out 0.5 seconds a cue may stay after its last word, if nothing follows
26 --font NAME burn-in font (default: first installed of Arial, Helvetica, DejaVu Sans)
27 --plate draw a 75% black plate behind the text instead of an outline
28 --offset S subtract S from every word time (video starts S into the transcript)
29 --from S --to S only words in this range (before --offset)
30 --speakers FILE optional JSON [[start,end,"A"],...]: a speaker change inside a cue starts
31 each line with "-" (no space, Netflix English)
32
33Standard library only. Needs ffmpeg/ffprobe for shots, make (frame rate, size) and burn.
34The checker extends check_captions.py from the caption-styling skill in the vidmoat/skills
35repository by Vidmoat Skills contributors (Apache-2.0); modified by Zylcut.
36"""
37
38import argparse
39import json
40import os
41import re
42import shutil
43import subprocess
44import sys
45
46NO_END = set("""a an the this these those my your his her its our their of to in on at for with by from
47into onto about over under than as and but or nor so if because while when where which who whom whose
48not mr mrs ms dr very""".split())
49# weaker: often a main verb or a subject that can end a line
50SOFT_END = set("""is are was were be been being am has have had do does did will would can could shall should
51may might must i i'm i've i'd i'll we you he she it they that isn't aren't wasn't weren't don't doesn't
52didn't won't wouldn't can't couldn't shouldn't haven't hasn't hadn't that's it's there's here's what's
53who's we're you're they're we've you've they'll we'll you'll he's she's""".split())
54NO_START = set("of 's n't".split())
55# a line that starts with an auxiliary or modal splits a subject from its verb ("my mom / wouldn't")
56AUX_START = set("""is are was were am be been has have had do does did will would can could shall should may
57might must isn't aren't wasn't weren't don't doesn't didn't won't wouldn't can't couldn't shouldn't
58haven't hasn't hadn't""".split())
59
60
61def die(msg, code=2):
62 print("error: " + msg, file=sys.stderr)
63 sys.exit(code)
64
65
66def probe(path):
67 r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
68 "stream=width,height,r_frame_rate:format=duration", "-of", "json", path],
69 capture_output=True, text=True)
70 if r.returncode != 0:
71 die("ffprobe could not read " + path)
72 d = json.loads(r.stdout)
73 s = d["streams"][0]
74 n, m = s["r_frame_rate"].split("/")
75 return int(s["width"]), int(s["height"]), float(n) / float(m or 1), float(d["format"]["duration"])
76
77
78# ---------- shots ----------
79
80def cmd_shots(a):
81 r = subprocess.run(["ffmpeg", "-hide_banner", "-threads", "4", "-i", a.video, "-vf",
82 "scale=320:-2,scdet=t=%g:s=1" % a.threshold, "-an", "-f", "null", "-"],
83 capture_output=True, text=True)
84 t = [round(float(x), 3) for x in re.findall(r"lavfi\.scd\.time:\s*([\d.]+)", r.stderr)]
85 json.dump({"video": os.path.abspath(a.video), "threshold": a.threshold, "shots": t}, open(a.output, "w"), indent=1)
86 print("wrote %s: %d shot changes" % (a.output, len(t)))
87
88
89# ---------- segmentation ----------
90
91def clean(w):
92 return w.replace("*", "")
93
94
95def endword(w):
96 return re.sub(r"[^\w']", "", w.lower())
97
98
99def ends_sentence(w):
100 return w.rstrip('"\')]').endswith((".", "?", "!"))
101
102
103def ends_clause(w):
104 return w.rstrip('"\')]').endswith((",", ";", ":", "--"))
105
106
107def is_name(w):
108 return w[:1].isupper() and endword(w) not in NO_END and len(w) > 1
109
110
111TWO_LINE_COST = 2.2 # tuned so about half the subtitles are one line, as in the reference files
112
113
114def best_break(ws, max_chars):
115 """Best way to show words ws as 1 or 2 lines: (cost, [lines]) or None if it cannot fit."""
116 text = " ".join(clean(x["w"]) for x in ws)
117 if len(text) <= max_chars:
118 # one line; a long single line is fine, but very long one-liners read better split
119 mid = sum(1 for x in ws[:-1] if ends_sentence(x["w"]))
120 return (0.0 if len(text) <= max_chars * 0.8 else 0.5) + 0.8 * mid, [text]
121 best = None
122 for j in range(1, len(ws)):
123 a = " ".join(clean(x["w"]) for x in ws[:j])
124 b = " ".join(clean(x["w"]) for x in ws[j:])
125 if len(a) > max_chars or len(b) > max_chars:
126 continue
127 last = ws[j - 1]["w"]
128 cost = abs(len(a) - len(b)) / max_chars * 4
129 if len(a) > len(b):
130 cost += 0.6 # bottom-heavy preferred
131 if ends_sentence(last) or ends_clause(last):
132 cost -= 1.0
133 elif endword(last) in NO_END:
134 cost += 6.0
135 elif endword(last) in SOFT_END:
136 cost += 2.5
137 elif endword(ws[j]["w"]) in NO_START:
138 cost += 3.0
139 elif endword(ws[j]["w"]) in AUX_START:
140 cost += 2.0
141 elif is_name(last) and is_name(ws[j]["w"]):
142 cost += 5.0 # first name + surname
143 elif re.match(r"^\d", last) and not re.match(r"^\d", ws[j]["w"]):
144 cost += 3.0 # number + unit
145 # a sentence that ends inside a line (not at its end) reads as two thoughts on one line
146 for part in (ws[:j - 1], ws[j:-1]):
147 if any(ends_sentence(x["w"]) for x in part):
148 cost += 3.0
149 cost += TWO_LINE_COST # one line is preferred when the speech allows it
150 if best is None or cost < best[0]:
151 best = (cost, [a, b])
152 return best
153
154
155OVER = 2.0 # cps a subtitle may go over the limit to keep a clause whole (at most 1 in 10)
156
157
158def segment(words, fps, max_chars, max_cps, target_cps, lead_out):
159 n = len(words)
160 frame = 1.0 / fps
161 INF = float("inf")
162 cost = [INF] * (n + 1)
163 back = [None] * (n + 1)
164 cost[0] = 0.0
165 for j in range(1, n + 1):
166 for i in range(j - 1, -1, -1):
167 ws = words[i:j]
168 text_len = len(" ".join(clean(x["w"]) for x in ws))
169 if text_len > 2 * max_chars + 1:
170 break
171 span = ws[-1]["e"] - ws[0]["s"]
172 if span > 7.0 and j - i > 1:
173 break
174 turns = [k for k in range(1, len(ws)) if ws[k].get("spk") != ws[k - 1].get("spk")]
175 if len(turns) > 1:
176 continue # at most one speaker change per cue
177 if turns:
178 # the change must be the line break; each line carries a "-" dash
179 a_ = " ".join(clean(x["w"]) for x in ws[:turns[0]])
180 b_ = " ".join(clean(x["w"]) for x in ws[turns[0]:])
181 if len(a_) + 1 > max_chars or len(b_) + 1 > max_chars:
182 continue
183 br = (0.0, [a_, b_])
184 # a dialogue subtitle holds whole sentences: the first speaker's part starts one,
185 # the second speaker's part ends one
186 if i > 0 and not ends_sentence(words[i - 1]["w"]) and words[i - 1].get("spk") == ws[0].get("spk"):
187 br = (br[0] + 10, br[1])
188 if j < n and not ends_sentence(ws[-1]["w"]) and words[j].get("spk") == ws[-1].get("spk"):
189 br = (br[0] + 10, br[1])
190 else:
191 br = best_break(ws, max_chars)
192 if br is None:
193 continue
194 nxt = words[j]["s"] if j < n else ws[-1]["e"] + lead_out + 1
195 avail = min(ws[-1]["e"] + lead_out, nxt - 2 * frame) - ws[0]["s"]
196 avail = max(avail, span)
197 avail = min(avail, 7.0)
198 cps = text_len / max(avail, 0.05)
199 c = 1.0 + br[0]
200 last = ws[-1]["w"]
201 gap_after = (words[j]["s"] - ws[-1]["e"]) if j < n else 9
202 if j < n and words[j].get("spk") != ws[-1].get("spk"):
203 c += 0
204 elif ends_sentence(last) or j == n:
205 c += 0
206 elif ends_clause(last) or gap_after >= 0.5:
207 c += 1.5
208 elif endword(last) in NO_END:
209 c += 9.0
210 elif j < n and endword(words[j]["w"]) in NO_START:
211 c += 7.0
212 elif endword(last) in SOFT_END:
213 c += 5.5
214 else:
215 c += 4.0
216 whole = ends_sentence(last) or ends_clause(last) or j == n
217 if cps > max_cps + OVER or (cps > max_cps and not whole):
218 c += 40 + (cps - max_cps) * 10
219 elif cps > max_cps:
220 # professionals go a little over 20 cps (7.7% of measured subtitles) rather than
221 # break a clause; the linter allows it on at most 1 subtitle in 10
222 c += 10 + (cps - max_cps) * 4
223 elif cps > target_cps:
224 c += (cps - target_cps) * 1.5
225 if avail < 5.0 / 6.0:
226 c += 12
227 elif avail < 1.3:
228 c += 3 # a flash: legal, but merge it when the speech allows
229 if text_len < 12 and not (ends_sentence(last) or j == n):
230 c += 2
231 # a short fragment of a sentence stranded at either end of a cue reads badly:
232 # "...we were / so young. So neither" or "...like this. Yeah,"
233 ends = [k for k in range(i, j - 1) if ends_sentence(words[k]["w"])]
234 if ends:
235 head = len(" ".join(clean(x["w"]) for x in words[i:ends[0] + 1]))
236 if i > 0 and not ends_sentence(words[i - 1]["w"]) and head < 20:
237 c += 8
238 tail = len(" ".join(clean(x["w"]) for x in words[ends[-1] + 1:j]))
239 if not (ends_sentence(last) or j == n) and tail < 20:
240 c += 8
241 # a cue that runs over a long pause inside it reads badly
242 for k in range(i, j - 1):
243 g = words[k + 1]["s"] - words[k]["e"]
244 if g >= 1.5:
245 c += 15
246 if cost[i] + c < cost[j]:
247 cost[j] = cost[i] + c
248 back[j] = (i, br[1])
249 cues = []
250 j = n
251 while j > 0:
252 i, lines = back[j]
253 cues.append({"i": i, "j": j, "lines": lines})
254 j = i
255 cues.reverse()
256 return cues
257
258
259def timing(cues, words, fps, shots, lead_out, duration):
260 frame = 1.0 / fps
261 snap = 12 * frame
262 fr = lambda t: round(round(t * fps) / fps, 3)
263 for c in cues:
264 c["s"] = words[c["i"]]["s"]
265 c["e"] = words[c["j"] - 1]["e"]
266 c["speech_end"] = c["e"]
267 # in-times: back onto a shot change up to 12 frames before the first word; forward only 4 frames
268 for k, c in enumerate(cues):
269 prev_end = cues[k - 1]["speech_end"] if k else -1
270 for x in shots:
271 if 0 <= c["s"] - x <= snap and x >= prev_end:
272 c["s"] = x
273 c["snapped_in"] = True
274 break
275 if 0 < x - c["s"] <= 4 * frame:
276 c["s"] = x
277 c["snapped_in"] = True
278 break
279 # out-times: lead-out, chaining, minimum duration, shot changes
280 for k, c in enumerate(cues):
281 nxt = cues[k + 1]["s"] if k + 1 < len(cues) else duration
282 e = min(c["speech_end"] + lead_out, nxt - 2 * frame)
283 e = max(e, c["speech_end"]) if nxt - 2 * frame >= c["speech_end"] else nxt - 2 * frame
284 if e - c["s"] < 5.0 / 6.0:
285 e = min(c["s"] + 5.0 / 6.0, nxt - 2 * frame)
286 if 2.5 * frame < nxt - e < 11.5 * frame:
287 e = nxt - 2 * frame # close 3-11 frame gaps to 2 frames
288 for x in shots:
289 if c["speech_end"] <= x and abs(x - e) <= snap and x - 2 * frame >= c["s"] + 5.0 / 6.0:
290 e = min(x - 2 * frame, nxt - 2 * frame)
291 c["snapped_out"] = True
292 break
293 if 0 < e - x < 12 * frame and x < c["speech_end"]:
294 # speech runs a little past a cut: never hang 1-11 frames over the new shot
295 next_close = k + 1 < len(cues) and cues[k + 1]["s"] - x <= 12 * frame
296 if (c["speech_end"] - x <= 6 * frame or next_close) and x - 2 * frame >= c["s"] + 5.0 / 6.0:
297 e = x - 2 * frame # trim the last few frames of the word's tail
298 if k + 1 < len(cues) and 0 < cues[k + 1]["s"] - x <= 12 * frame:
299 cues[k + 1]["s"] = x # and the next subtitle comes in on the cut
300 cues[k + 1]["snapped_in"] = True
301 elif x + 12 * frame <= nxt - 2 * frame:
302 e = x + 12 * frame # or stay at least 12 frames into the new shot
303 c["snapped_out"] = True
304 break
305 e = min(e, c["s"] + 7.0)
306 c["e"] = e
307 for c in cues:
308 c["s"], c["e"] = fr(c["s"]), fr(c["e"])
309 for k in range(len(cues) - 1):
310 gap = cues[k + 1]["s"] - cues[k]["e"]
311 if gap < 2 * frame - 1e-6 or 2.5 * frame < gap < 11.5 * frame:
312 cues[k]["e"] = fr(cues[k + 1]["s"] - 2 * frame) # 2 frames apart after rounding too
313 return cues
314
315
316def apply_speakers(cues, words, spk):
317 if not spk:
318 return cues
319
320 def who(t):
321 for s, e, w in spk:
322 if s <= t <= e:
323 return w
324 return None
325 for c in cues:
326 ws = words[c["i"]:c["j"]]
327 ids = [who((w["s"] + w["e"]) / 2) for w in ws]
328 if len(set(x for x in ids if x)) == 2:
329 k = next(i for i in range(1, len(ids)) if ids[i] and ids[i] != ids[0])
330 a = " ".join(clean(x["w"]) for x in ws[:k])
331 b = " ".join(clean(x["w"]) for x in ws[k:])
332 c["lines"] = ["-" + a, "-" + b]
333 c["dialogue"] = True
334 return cues
335
336
337# ---------- writers ----------
338
339def srt_t(t, sep=","):
340 ms = int(round(max(0, t) * 1000))
341 h, ms = divmod(ms, 3600000)
342 m, ms = divmod(ms, 60000)
343 s, ms = divmod(ms, 1000)
344 return "%02d:%02d:%02d%s%03d" % (h, m, s, sep, ms)
345
346
347def ass_t(t):
348 cs = int(round(max(0, t) * 100))
349 h, cs = divmod(cs, 360000)
350 m, cs = divmod(cs, 6000)
351 s, cs = divmod(cs, 100)
352 return "%d:%02d:%02d.%02d" % (h, m, s, cs)
353
354
355def pick_font(explicit):
356 if explicit:
357 return explicit
358 if shutil.which("fc-list"):
359 have = subprocess.run(["fc-list", ":", "family"], capture_output=True, text=True).stdout
360 for f in ["Arial", "Helvetica Neue", "Helvetica", "Liberation Sans", "DejaVu Sans", "Noto Sans"]:
361 if re.search(r"(^|,)%s(,|$)" % re.escape(f), have, re.M):
362 return f
363 return "Arial"
364
365
366def calibrate(font):
367 """(cap height / font size, mixed-case width per character / cap height) from one rendered frame."""
368 import tempfile
369 if not shutil.which("ffmpeg"):
370 return (0.70, 0.75)
371 tmp = tempfile.mkdtemp(prefix="bs-")
372 text = "The quick brown fox jumps over the lazy dog, then it rests."
373 ass = os.path.join(tmp, "c.ass")
374 with open(ass, "w") as fh:
375 fh.write("[Script Info]\nPlayResX: 4000\nPlayResY: 400\nWrapStyle: 2\n[V4+ Styles]\n"
376 "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n"
377 "Style: A,%s,100,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,-1,0,0,0,100,100,0,0,1,0,0,5,0,0,0,1\n"
378 "[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n"
379 "Dialogue: 0,0:00:00.00,0:00:01.00,A,,0,0,0,,%s\nDialogue: 0,0:00:00.00,0:00:01.00,A,,0,0,0,,{\\pos(2000,330)}HHHH\n" % (font, text))
380 pgm = os.path.join(tmp, "c.pgm")
381 esc = ass.replace("\\", "/").replace(":", "\\:")
382 subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "color=black:s=4000x400:d=0.2",
383 "-vf", "subtitles='%s',format=gray" % esc, "-frames:v", "1", pgm], capture_output=True)
384 try:
385 b = open(pgm, "rb").read()
386 p = b.split(maxsplit=4)
387 w, h = int(p[1]), int(p[2])
388 px = p[4][-(w * h):]
389 rows = [y for y in range(h) if max(px[y * w:(y + 1) * w]) > 128]
390 # the HHHH line sits low: its rows are the cap height
391 hrows = [y for y in rows if y > 280]
392 cap = max(hrows) - min(hrows) + 1
393 trows = [y for y in rows if y < 280]
394 x0, x1 = w, 0
395 for y in trows:
396 row = px[y * w:(y + 1) * w]
397 x0 = min(x0, next(i for i, v in enumerate(row) if v > 128))
398 x1 = max(x1, w - 1 - next(i for i, v in enumerate(reversed(row)) if v > 128))
399 res = (cap / 100.0, (x1 - x0 + 1) / len(text) / cap)
400 except Exception:
401 res = (0.70, 0.75)
402 shutil.rmtree(tmp, ignore_errors=True)
403 return res
404
405
406WFAC = 0.75 # mixed-case width per character / cap height; set from calibrate() in make
407
408
409def write_all(base, cues, W, H, fps, font, plate, cap_px, size, margin_v, safe_l, safe_r):
410 with open(base + ".srt", "w", encoding="utf-8") as fh:
411 for k, c in enumerate(cues):
412 fh.write("%d\n%s --> %s\n%s\n\n" % (k + 1, srt_t(c["s"]), srt_t(c["e"]), "\n".join(c["lines"])))
413 with open(base + ".vtt", "w", encoding="utf-8") as fh:
414 fh.write("WEBVTT\n\n")
415 for k, c in enumerate(cues):
416 fh.write("%s --> %s line:-2\n%s\n\n" % (srt_t(c["s"], "."), srt_t(c["e"], "."), "\n".join(c["lines"])))
417 outline = max(2, round(cap_px * 0.12))
418 head = ["[Script Info]", "ScriptType: v4.00+", "PlayResX: %d" % W, "PlayResY: %d" % H, "WrapStyle: 2",
419 "ScaledBorderAndShadow: yes", "YCbCr Matrix: TV.709", "", "[V4+ Styles]",
420 "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding"]
421 if plate:
422 pad = max(4, round(cap_px * 0.35))
423 head.append("Style: Plate,%s,%d,&HFF000000,&HFF000000,&H40000000,&H00000000,-1,0,0,0,100,100,0,0,3,%d,0,2,%d,%d,%d,1" % (font, size, pad, safe_l, W - safe_r, margin_v))
424 head.append("Style: Sub,%s,%d,&H00F2F2F2,&H00F2F2F2,&H00000000,&H00000000,-1,0,0,0,100,100,0,0,1,0,0,2,%d,%d,%d,1" % (font, size, safe_l, W - safe_r, margin_v))
425 else:
426 head.append("Style: Sub,%s,%d,&H00F2F2F2,&H00F2F2F2,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,%d,%d,2,%d,%d,%d,1" % (font, size, outline, max(1, outline // 2), safe_l, W - safe_r, margin_v))
427 head += ["", "[Events]", "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"]
428 ev = []
429 for c in cues:
430 t = "\\N".join(l.replace("{", "(").replace("}", ")") for l in c["lines"])
431 if c.get("dialogue") or all(l.startswith("-") for l in c["lines"]) and len(c["lines"]) == 2:
432 # dialogue: the block is centred but its lines start at one x, so the dashes align
433 wpx = max(len(l) for l in c["lines"]) * cap_px * WFAC
434 t = "{\\an1\\pos(%d,%d)}" % (round((W - wpx) / 2), H - margin_v) + t
435 if plate:
436 ev.append("Dialogue: 0,%s,%s,Plate,,0,0,0,,%s" % (ass_t(c["s"]), ass_t(c["e"]), t))
437 ev.append("Dialogue: 1,%s,%s,Sub,,0,0,0,,%s" % (ass_t(c["s"]), ass_t(c["e"]), t))
438 with open(base + ".ass", "w", encoding="utf-8") as fh:
439 fh.write("\n".join(head + ev) + "\n")
440 # Zylcut component: one <text> per cue, bottom-centred, same timing
441 fsize = round(cap_px / 0.70) # Inter's capitals are about 0.70 of its font size in Zylcut
442 line_h = round(fsize * 1.2)
443 rows = []
444 for c in cues:
445 left = "null"
446 if c.get("dialogue"):
447 wpx = max(len(l) for l in c["lines"]) * cap_px * WFAC * 1.05
448 left = str(round((W - wpx) / 2))
449 rows.append(" [%.3f, %.3f, %s, %s]," % (c["s"], c["e"], json.dumps("\n".join(c["lines"])), left))
450 tsx = """// Subtitles made by subtitles.py: %d cues. Times are seconds of the scene.
451// Use: import Subtitles from "./subtitles"; then <Subtitles /> as the last child of the scene.
452import { For } from "solid-js";
453
454const W = %d, H = %d, BOTTOM = %d, SIZE = %d, LINE = %d;
455// The 4th value is the left edge of a two-speaker subtitle (lines left-aligned so the dashes line up).
456export const cues: [number, number, string, number | null][] = [
457%s
458];
459
460export default function Subtitles() {
461 return (
462 <group id="subtitles">
463 <For each={cues}>
464 {([start, end, text, left], i) => {
465 const lines = text.split("\\n").length;
466 return (
467 <text id={"sub-" + (i() + 1)} start={start} end={end} x={left ?? 0} width={left === null ? W : W - left}
468 textAlign={left === null ? "center" : "left"}
469 y={H - BOTTOM - lines * LINE} fontFamily="Inter" fontWeight={600} fontSize={SIZE} leading={1.2}
470 color="#F2F2F2"%s>
471 {text}
472 </text>
473 );
474 }}
475 </For>
476 </group>
477 );
478}
479""" % (len(cues), W, H, margin_v, fsize, line_h, "\n".join(rows),
480 ' background="#000000" backgroundOpacity={0.75} backgroundPadding={%d}' % max(6, round(cap_px * 0.35)) if plate
481 else '>\n <stroke width={%d} color="#000000" />\n <shadow blur={4} offsetY={2} color="#000000" opacity={0.6} /' % (outline * 2))
482 with open(base + ".tsx", "w", encoding="utf-8") as fh:
483 fh.write(tsx)
484
485
486def cmd_make(a):
487 if a.video:
488 W, H, fps, dur = probe(a.video)
489 elif a.size and a.fps and a.duration:
490 W, H = (int(x) for x in a.size.lower().split("x"))
491 fps, dur = a.fps, a.duration
492 else:
493 die("give --video, or --size WxH --fps FPS --duration S")
494 d = json.load(open(a.words))
495 words = [dict(w) for w in d["words"] if a.start <= w["s"] < a.end]
496 for w in words:
497 w["s"] = round(w["s"] - a.offset, 3)
498 w["e"] = round(w["e"] - a.offset, 3)
499 words = [w for w in words if w["e"] > 0 and w["s"] < dur and clean(w["w"]).strip()]
500 if not words:
501 die("no words in range")
502 shots = []
503 if a.shots:
504 shots = [t - a.offset for t in json.load(open(a.shots))["shots"]]
505 shots = [t for t in shots if 0 < t < dur]
506 vertical = H > W
507 font = pick_font(a.font)
508 global WFAC
509 cap_ratio, wfac = calibrate(font)
510 WFAC = wfac
511 # BBC: line height 7-8% of frame height on 16:9, 3.9-4.5% on 9:16 (we take the low end);
512 # a line is about 1.6 capital heights, so capitals are 4.3% / 2.5% of the height
513 cap_px = a.cap or round(H * (0.025 if vertical else 0.043))
514 size = round(cap_px / cap_ratio)
515 if vertical:
516 safe_l, safe_r = round(W * 60 / 1080), round(W * 900 / 1080)
517 margin_v = round(H * 420 / 1920)
518 else:
519 safe_l, safe_r = round(W * 0.10), round(W * 0.90)
520 margin_v = round(H * 0.075)
521 fit = int((safe_r - safe_l) * 0.96 / (wfac * cap_px))
522 max_chars = a.max_chars or min(42, fit)
523 if max_chars > fit:
524 print("note: %d characters may not fit the safe width at this size (about %d fit)" % (max_chars, fit))
525 cues = segment(words, fps, max_chars, a.max_cps, a.target_cps, a.lead_out)
526 cues = timing(cues, words, fps, sorted(shots), a.lead_out, dur)
527 spk = json.load(open(a.speakers)) if a.speakers else None
528 if spk is None and any("spk" in w for w in words):
529 spk = [[w["s"], w["e"], w["spk"]] for w in words if "spk" in w]
530 cues = apply_speakers(cues, words, spk)
531 write_all(a.output, cues, W, H, fps, font, a.plate, cap_px, size, margin_v, safe_l, safe_r)
532 json.dump({"video": os.path.abspath(a.video) if a.video else None, "w": W, "h": H, "fps": fps, "font": font, "size": size, "cap_px": cap_px,
533 "max_chars": max_chars, "margin_v": margin_v, "cues": [{k: c[k] for k in ("s", "e", "lines")} for c in cues]},
534 open(a.output + ".json", "w"), indent=1)
535 if a.video and not a.plate:
536 lines_h = 2 * cap_px * 1.45
537 bright = band_brightness(a.video, dur, max(0.0, (H - margin_v - lines_h) / H), (H - margin_v + cap_px * 0.4) / H)
538 if bright > 0.10:
539 print("note: the subtitle band is bright (%d%% of its pixels are near white): remake with --plate" % round(bright * 100))
540 sn_i = sum(1 for c in cues if c.get("snapped_in"))
541 sn_o = sum(1 for c in cues if c.get("snapped_out"))
542 print("wrote %s.srt/.vtt/.ass/.tsx: %d cues, %d chars/line max, font %s size %d (capitals %d px), %d in-times and %d out-times snapped to %d shot changes"
543 % (a.output, len(cues), max_chars, font, size, cap_px, sn_i, sn_o, len(shots)))
544
545
546def band_brightness(video, dur, top, bottom):
547 """Share of bright pixels (luma > 200) in the subtitle band, over 12 frames across the video."""
548 vals = []
549 for k in range(12):
550 t = dur * (k + 0.5) / 12
551 r = subprocess.run(["ffmpeg", "-v", "error", "-ss", "%.2f" % t, "-i", video, "-frames:v", "1", "-vf",
552 "crop=iw*0.6:ih*%.4f:iw*0.2:ih*%.4f,scale=96:-2,format=gray" % (bottom - top, top),
553 "-f", "rawvideo", "-"], capture_output=True)
554 if r.returncode == 0 and r.stdout:
555 b = r.stdout
556 vals.append(sum(1 for x in b if x > 200) / len(b))
557 return sorted(vals)[len(vals) // 2] if vals else 0.0
558
559
560# ---------- checker ----------
561
562TIME_RE = re.compile(r"(?:(\d+):)?(\d{1,2}):(\d{2})[,.](\d{1,3})\s*-->\s*(?:(\d+):)?(\d{1,2}):(\d{2})[,.](\d{1,3})")
563TAG_RE = re.compile(r"<[^>]*>|\{[^}]*\}")
564
565
566def to_s(h, m, s, ms):
567 return int(h or 0) * 3600 + int(m) * 60 + int(s) + int((ms or "0").ljust(3, "0")) / 1000.0
568
569
570def parse(text):
571 text = text.replace("\r\n", "\n").replace("\r", "\n").lstrip("")
572 cues = []
573 line_no = 1
574 for block in re.split(r"\n\s*\n", text.strip()):
575 raw = block.split("\n")
576 start_line = line_no
577 line_no += len(raw) + 1
578 if not raw or raw[0].startswith(("WEBVTT", "NOTE", "STYLE", "REGION")):
579 continue
580 k = next((i for i, l in enumerate(raw) if "-->" in l), None)
581 if k is None:
582 raise ValueError("line %d: block has no timing line" % start_line)
583 m = TIME_RE.search(raw[k])
584 if not m:
585 raise ValueError("line %d: cannot parse timing %r" % (start_line + k, raw[k]))
586 g = m.groups()
587 lines = [TAG_RE.sub("", l).strip() for l in raw[k + 1:]]
588 cues.append({"index": len(cues) + 1, "start": to_s(*g[0:4]), "end": to_s(*g[4:8]),
589 "lines": [l for l in lines if l], "line_no": start_line})
590 return cues
591
592
593def check(cues, fps, max_chars, max_lines, max_cps, target_cps, min_dur, max_dur, shots):
594 out = []
595 frame = 1.0 / fps
596 eps = 1e-6
597
598 def add(c, level, rule, msg):
599 out.append({"cue": c["index"], "line": c["line_no"], "level": level, "rule": rule, "message": msg})
600 for i, c in enumerate(cues):
601 dur = c["end"] - c["start"]
602 chars = sum(len(l) for l in c["lines"])
603 if not c["lines"]:
604 add(c, "error", "empty", "cue has no text")
605 if dur <= 0:
606 add(c, "error", "timing", "end is not after start")
607 continue
608 if len(c["lines"]) > max_lines:
609 add(c, "error", "lines", "%d lines (max %d)" % (len(c["lines"]), max_lines))
610 for l in c["lines"]:
611 if len(l) > max_chars:
612 add(c, "error", "line-length", "%d characters in %r (max %d)" % (len(l), l[:50], max_chars))
613 if len(c["lines"]) == 2:
614 first_end = endword(c["lines"][0].split()[-1]) if c["lines"][0].split() else ""
615 if first_end in NO_END and not c["lines"][0].rstrip().endswith((",", ".", "?", "!", ";", ":")):
616 add(c, "warning", "line-break", "line 1 ends on %r; break after a clause or before the phrase" % first_end)
617 if len(c["lines"][0]) + len(c["lines"][1]) <= max_chars and not c["lines"][1].startswith("-"):
618 add(c, "warning", "needless-break", "both lines fit on one line of %d" % max_chars)
619 cps = chars / dur
620 if cps > max_cps + OVER + eps:
621 add(c, "error", "reading-speed", "%.1f characters/second (max %.0f); split, extend or condense" % (cps, max_cps))
622 elif cps > max_cps + eps:
623 add(c, "warning", "reading-speed", "%.1f characters/second: over %.0f, tolerated up to %.0f on at most 1 subtitle in 10 to keep a clause whole" % (cps, max_cps, max_cps + OVER))
624 elif cps > target_cps + eps:
625 add(c, "info", "reading-speed", "%.1f characters/second (aim for %.0f or less)" % (cps, target_cps))
626 if dur < min_dur - eps:
627 add(c, "error", "too-short", "on screen %.3f s (min %.3f s)" % (dur, min_dur))
628 if dur > max_dur + eps:
629 add(c, "error", "too-long", "on screen %.2f s (max %.1f s)" % (dur, max_dur))
630 if i + 1 < len(cues):
631 gap = cues[i + 1]["start"] - c["end"]
632 if gap < -eps:
633 add(c, "error", "overlap", "overlaps the next cue by %.3f s" % -gap)
634 elif eps < gap < 2 * frame - frame / 2:
635 add(c, "error", "gap", "gap of %.3f s (%d frame) to the next cue; make it 2 frames" % (gap, round(gap * fps)))
636 elif 2.5 * frame < gap < 11.5 * frame:
637 add(c, "warning", "gap", "gap of %d frames to the next cue; close it to 2 frames" % round(gap * fps))
638 for x in shots:
639 if c["start"] < x < c["end"]:
640 if x - c["start"] < 12 * frame - eps and x - c["start"] > frame:
641 add(c, "warning", "shot-change", "starts %d frames before a shot change at %.2f s; start on the change" % (round((x - c["start"]) * fps), x))
642 elif c["end"] - x < 12 * frame - eps and c["end"] - x > frame:
643 add(c, "warning", "shot-change", "ends %d frames after a shot change at %.2f s; end 2 frames before it" % (round((c["end"] - x) * fps), x))
644 over = [c for c in cues if c["end"] > c["start"] and sum(len(l) for l in c["lines"]) / (c["end"] - c["start"]) > max_cps + eps]
645 if len(over) > max(1, len(cues) // 10):
646 add(over[0], "error", "reading-speed", "%d of %d subtitles are over %.0f characters/second (at most 1 in 10)" % (len(over), len(cues), max_cps))
647 return out
648
649
650def cmd_check(a):
651 try:
652 cues = parse(open(a.path, encoding="utf-8-sig").read())
653 except (OSError, UnicodeDecodeError, ValueError) as e:
654 print("cannot read %s: %s" % (a.path, e), file=sys.stderr)
655 return 2
656 shots = json.load(open(a.shots))["shots"] if a.shots else []
657 f = check(cues, a.fps, a.max_chars, a.max_lines, a.max_cps, a.target_cps, a.min_dur, a.max_dur, shots)
658 errors = [x for x in f if x["level"] == "error"]
659 warns = [x for x in f if x["level"] == "warning"]
660 infos = [x for x in f if x["level"] == "info"]
661 cps = sorted(sum(len(l) for l in c["lines"]) / (c["end"] - c["start"]) for c in cues if c["end"] > c["start"])
662 durs = sorted(c["end"] - c["start"] for c in cues)
663 if a.json:
664 print(json.dumps({"cues": len(cues), "errors": len(errors), "warnings": len(warns), "findings": f}, indent=1))
665 else:
666 for x in f:
667 if x["level"] != "info" or a.verbose:
668 print("%-7s cue %-4d (line %d) %-14s %s" % (x["level"].upper(), x["cue"], x["line"], x["rule"], x["message"]))
669 if cues:
670 print("cues %d | lines: one %d two %d | longest line %d | cps median %.1f p95 %.1f max %.1f | over %g cps: %d | duration median %.2f min %.2f max %.2f"
671 % (len(cues), sum(1 for c in cues if len(c["lines"]) == 1), sum(1 for c in cues if len(c["lines"]) == 2),
672 max(len(l) for c in cues for l in c["lines"]), cps[len(cps) // 2], cps[int(len(cps) * 0.95)], cps[-1],
673 a.target_cps, len(infos), durs[len(durs) // 2], durs[0], durs[-1]))
674 print("%d cue(s), %d error(s), %d warning(s)" % (len(cues), len(errors), len(warns)))
675 return 1 if errors else 0
676
677
678def cmd_burn(a):
679 ass = os.path.abspath(a.ass).replace("\\", "/").replace(":", "\\:").replace("'", "\\'")
680 r = subprocess.run(["ffmpeg", "-hide_banner", "-y", "-threads", str(a.threads), "-i", a.video, "-vf", "subtitles='%s'" % ass,
681 "-c:v", "libx264", "-preset", "medium", "-crf", str(a.crf), "-pix_fmt", "yuv420p", "-c:a", "copy",
682 "-movflags", "+faststart", a.output], capture_output=True, text=True)
683 for l in r.stderr.splitlines():
684 if "fontselect" in l:
685 print(l.strip())
686 break
687 if r.returncode != 0:
688 die("ffmpeg failed: " + r.stderr.strip()[-600:])
689 print("wrote " + a.output)
690
691
692def main():
693 p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
694 sub = p.add_subparsers(dest="cmd", required=True)
695 s = sub.add_parser("shots")
696 s.add_argument("video")
697 s.add_argument("-o", "--output", default="shots.json")
698 s.add_argument("--threshold", type=float, default=12)
699 m = sub.add_parser("make")
700 m.add_argument("words")
701 m.add_argument("--video")
702 m.add_argument("--size")
703 m.add_argument("--fps", type=float)
704 m.add_argument("--duration", type=float)
705 m.add_argument("-o", "--output", default="subtitles")
706 m.add_argument("--shots")
707 m.add_argument("--max-chars", type=int)
708 m.add_argument("--max-cps", type=float, default=20)
709 m.add_argument("--target-cps", type=float, default=17)
710 m.add_argument("--lead-out", type=float, default=0.5)
711 m.add_argument("--font")
712 m.add_argument("--cap", type=int, help="capital height in pixels")
713 m.add_argument("--plate", action="store_true")
714 m.add_argument("--offset", type=float, default=0.0)
715 m.add_argument("--from", dest="start", type=float, default=0.0)
716 m.add_argument("--to", dest="end", type=float, default=1e9)
717 m.add_argument("--speakers")
718 c = sub.add_parser("check")
719 c.add_argument("path")
720 c.add_argument("--fps", type=float, default=25.0)
721 c.add_argument("--shots")
722 c.add_argument("--max-chars", type=int, default=42)
723 c.add_argument("--max-lines", type=int, default=2)
724 c.add_argument("--max-cps", type=float, default=20)
725 c.add_argument("--target-cps", type=float, default=17)
726 c.add_argument("--min-dur", type=float, default=5.0 / 6.0)
727 c.add_argument("--max-dur", type=float, default=7.0)
728 c.add_argument("--json", action="store_true")
729 c.add_argument("--verbose", action="store_true")
730 b = sub.add_parser("burn")
731 b.add_argument("video")
732 b.add_argument("ass")
733 b.add_argument("output")
734 b.add_argument("--crf", type=int, default=20)
735 b.add_argument("--threads", type=int, default=4)
736 a = p.parse_args()
737 r = {"shots": cmd_shots, "make": cmd_make, "check": cmd_check, "burn": cmd_burn}[a.cmd](a)
738 sys.exit(r or 0)
739
740
741if __name__ == "__main__":
742 main()
743
1#!/usr/bin/env python3
2"""Word-timed transcript in one normal form, with word edges checked against the sound.
3
4Usage:
5 words.py transcribe INPUT [-o words.json] [--model PATH] [--language xx] [--threads 4]
6 Runs ffmpeg (16 kHz mono) and whisper.cpp's whisper-cli, then writes words.json.
7 words.py import TRANSCRIPT.json [--audio INPUT] [-o words.json]
8 Reads another word-timed transcript (Zylcut media_transcribe JSON, whisper-cli -ojf JSON,
9 or any {"segments":[{"words":[{"text","start","end"}]}]}) and writes words.json. A word's
10 "speaker" label is kept. Without --audio the times are kept as given (no snapping).
11 words.py show words.json [--from S] [--to S]
12 Prints numbered sentences: [sentence] start-end (length) [first word#-last word#] text,
13 with pauses of 0.4 s or more marked as "//0.6s//", and each word's speaker when labelled.
14 words.py label words.json TURN [TURN ...]
15 Labels who speaks: each TURN is WORD#=NAME (for example 0=A 21=B 57=A); a label runs
16 from that word to the next turn. Writes "spk" on every word, in place.
17
18words.json holds {source, duration, words:[{i,w,s,e}], sentences:[{i,s,e,w0,w1,text}],
19silences:[[s,e]], floor_db, speech_db}. Times are seconds of the input file.
20Word edges are moved onto the sound: a word ends where the level drops into a silence and
21starts where it rises out of one, so a cut on a word edge never clips the word.
22
23Standard library only. Needs ffmpeg on PATH; transcribe also needs whisper-cli.
24"""
25
26import argparse
27import array
28import json
29import math
30import os
31import shutil
32import subprocess
33import sys
34import tempfile
35
36FRAME = 0.01 # level frames of 10 ms
37RATE = 16000
38
39
40def die(msg):
41 print("error: " + msg, file=sys.stderr)
42 sys.exit(2)
43
44
45def find_model(explicit):
46 if explicit:
47 if not os.path.exists(explicit):
48 die("model not found: " + explicit)
49 return explicit
50 env = os.environ.get("WHISPER_MODEL")
51 if env and os.path.exists(env):
52 return env
53 home = os.path.expanduser("~")
54 names = ["ggml-small.en.bin", "ggml-base.en.bin", "ggml-medium.en.bin", "ggml-small.bin", "ggml-base.bin"]
55 dirs = [os.path.join(home, ".cache", "whisper"), os.path.join(home, ".cache", "whisper.cpp"),
56 "models", os.path.join(home, "whisper.cpp", "models"), "/opt/homebrew/share/whisper-cpp",
57 "/usr/local/share/whisper-cpp"]
58 for d in dirs:
59 for n in names:
60 p = os.path.join(d, n)
61 if os.path.exists(p):
62 return p
63 die("no whisper model found. Pass --model /path/to/ggml-small.en.bin or set WHISPER_MODEL. "
64 "Models come from the whisper.cpp project (ggml-small.en.bin is a good default).")
65
66
67def decode_wav(inp, wav):
68 if not shutil.which("ffmpeg"):
69 die("ffmpeg is not on PATH")
70 r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", inp, "-vn", "-ac", "1", "-ar", str(RATE),
71 "-c:a", "pcm_s16le", wav], capture_output=True, text=True)
72 if r.returncode != 0:
73 die("ffmpeg could not read %s: %s" % (inp, r.stderr.strip()[-400:]))
74
75
76def levels(wav):
77 """dB level of every 10 ms frame of a 16 kHz mono s16 WAV."""
78 with open(wav, "rb") as fh:
79 data = fh.read()
80 # skip the RIFF header: find the "data" chunk
81 pos = data.find(b"data")
82 if pos < 0:
83 die("bad WAV file")
84 pcm = array.array("h")
85 pcm.frombytes(data[pos + 8:pos + 8 + ((len(data) - pos - 8) // 2) * 2])
86 if sys.byteorder == "big":
87 pcm.byteswap()
88 n = int(RATE * FRAME)
89 out = []
90 for k in range(0, len(pcm) - n + 1, n):
91 seg = pcm[k:k + n]
92 ms = sum(x * x for x in seg) / n
93 out.append(10 * math.log10(ms / (32768.0 ** 2) + 1e-12))
94 return out
95
96
97def silences_from_levels(db):
98 """Silent runs of 0.12 s or more, with the threshold set between the noise floor and the voice."""
99 if not db:
100 return [], -90.0, -20.0
101 srt = sorted(db)
102 floor = srt[int(len(srt) * 0.10)]
103 speech = srt[int(len(srt) * 0.90)]
104 thr = max(floor + 6.0, speech - 30.0)
105 thr = min(thr, speech - 12.0) if speech - floor > 18 else (floor + speech) / 2
106 out = []
107 start = None
108 for i, v in enumerate(db + [999.0]):
109 if v < thr:
110 if start is None:
111 start = i
112 else:
113 if start is not None and (i - start) * FRAME >= 0.12:
114 out.append([round(start * FRAME, 3), round(i * FRAME, 3)])
115 start = None
116 return out, round(floor, 1), round(speech, 1)
117
118
119def snap_words(words, sil):
120 """Move word edges onto the sound using the silence list."""
121 def nearest(t, edges, win):
122 best = None
123 for x in edges:
124 if abs(x - t) <= win and (best is None or abs(x - t) < abs(best - t)):
125 best = x
126 return best
127 starts = [s for s, e in sil] # where sound stops
128 ends = [e for s, e in sil] # where sound starts again
129 for w in words:
130 e = nearest(w["e"], starts, 0.30)
131 if e is not None and e > w["s"] + 0.04:
132 w["e"] = round(e + 0.03, 3)
133 s = nearest(w["s"], ends, 0.30)
134 if s is not None and s < w["e"] - 0.04:
135 w["s"] = round(max(0.0, s - 0.03), 3)
136 for a, b in zip(words, words[1:]):
137 if b["s"] < a["e"]:
138 mid = round((a["e"] + b["s"]) / 2, 3)
139 a["e"], b["s"] = mid, mid
140 return words
141
142
143def sentences(words, sil):
144 out = []
145 w0 = 0
146 for i, w in enumerate(words):
147 end = w["w"].rstrip('"\')]').endswith((".", "?", "!"))
148 gap = words[i + 1]["s"] - w["e"] if i + 1 < len(words) else 0
149 if end or gap >= 0.9 or i == len(words) - 1:
150 seg = words[w0:i + 1]
151 out.append({"i": len(out), "s": seg[0]["s"], "e": seg[-1]["e"], "w0": w0, "w1": i,
152 "text": " ".join(x["w"] for x in seg)})
153 w0 = i + 1
154 return out
155
156
157def from_whisper_cli(d):
158 words = []
159 for seg in d.get("transcription", []):
160 toks = [t for t in seg.get("tokens", []) if not t.get("text", "").startswith("[_")]
161 text = seg.get("text", "").strip()
162 if not text or text.startswith("[") or text.startswith("("):
163 continue
164 s = seg["offsets"]["from"] / 1000.0
165 e = seg["offsets"]["to"] / 1000.0
166 if toks: # the last token's end is where the word's sound ends; the segment runs on to the next word
167 e = max(s + 0.05, toks[-1]["offsets"]["to"] / 1000.0)
168 if words and not seg.get("text", "").startswith(" "):
169 words[-1]["w"] += text # a split piece such as "n't" or "%"
170 words[-1]["e"] = e
171 continue
172 words.append({"w": text, "s": s, "e": e})
173 return words
174
175
176def from_segments(d):
177 segs = d.get("segments", d if isinstance(d, list) else [])
178 words = []
179 for seg in segs:
180 for w in seg.get("words", []):
181 t = (w.get("text") or w.get("word") or "").strip()
182 if t:
183 rec = {"w": t, "s": float(w["start"]), "e": float(w["end"])}
184 spk = w.get("speaker", seg.get("speaker"))
185 if spk is not None:
186 rec["spk"] = spk
187 words.append(rec)
188 return words
189
190
191def finish(words, wav, source, out):
192 for w in words:
193 # whisper marks a guessed change of speaker with a leading "-"; it is not a word
194 w["w"] = w["w"].lstrip("-\u2013\u2014 ").strip() if w["w"][:1] in "-\u2013\u2014" else w["w"]
195 words = [w for w in words if w["e"] > w["s"] and w["w"]]
196 words.sort(key=lambda w: w["s"])
197 if wav:
198 db = levels(wav)
199 sil, floor, speech = silences_from_levels(db)
200 words = snap_words(words, sil)
201 duration = round(len(db) * FRAME, 2)
202 else:
203 sil, floor, speech = [], None, None
204 duration = round(words[-1]["e"], 2) if words else 0.0
205 for i, w in enumerate(words):
206 w["i"] = i
207 w["s"] = round(w["s"], 3)
208 w["e"] = round(w["e"], 3)
209 res = {"source": os.path.abspath(source) if source else None, "duration": duration,
210 "floor_db": floor, "speech_db": speech,
211 "words": [dict({"i": w["i"], "w": w["w"], "s": w["s"], "e": w["e"]}, **({"spk": w["spk"]} if "spk" in w else {})) for w in words],
212 "sentences": sentences(words, sil), "silences": sil}
213 with open(out, "w") as fh:
214 json.dump(res, fh, indent=0)
215 print("wrote %s: %d words, %d sentences, %d silences, %.1f s" % (out, len(words), len(res["sentences"]), len(sil), res["duration"]))
216
217
218def cmd_transcribe(a):
219 if not shutil.which("whisper-cli"):
220 die("whisper-cli (whisper.cpp) is not on PATH. Install it (brew install whisper-cpp, or build "
221 "whisper.cpp) or transcribe with any word-timed tool and run 'words.py import'.")
222 model = find_model(a.model)
223 tmp = tempfile.mkdtemp(prefix="words-")
224 wav = os.path.join(tmp, "a.wav")
225 decode_wav(a.input, wav)
226 base = os.path.join(tmp, "w")
227 r = subprocess.run(["whisper-cli", "-m", model, "-f", wav, "-ojf", "-ml", "1", "-sow", "-t", str(a.threads),
228 "-of", base] + (["-l", a.language] if a.language else []), capture_output=True, text=True)
229 if r.returncode != 0 or not os.path.exists(base + ".json"):
230 die("whisper-cli failed: " + r.stderr.strip()[-400:])
231 with open(base + ".json", "rb") as fh:
232 d = json.loads(fh.read().decode("utf-8", "replace"))
233 finish(from_whisper_cli(d), wav, a.input, a.output)
234 shutil.rmtree(tmp, ignore_errors=True)
235
236
237def cmd_import(a):
238 with open(a.transcript, "rb") as fh:
239 d = json.loads(fh.read().decode("utf-8", "replace"))
240 words = from_whisper_cli(d) if isinstance(d, dict) and "transcription" in d else from_segments(d)
241 if not words:
242 die("no word timings found in " + a.transcript)
243 if not a.audio:
244 finish(words, None, None, a.output)
245 return
246 tmp = tempfile.mkdtemp(prefix="words-")
247 wav = os.path.join(tmp, "a.wav")
248 decode_wav(a.audio, wav)
249 finish(words, wav, a.audio, a.output)
250 shutil.rmtree(tmp, ignore_errors=True)
251
252
253def cmd_show(a):
254 with open(a.words) as fh:
255 d = json.load(fh)
256 W = d["words"]
257 for s in d["sentences"]:
258 if s["e"] < a.start or s["s"] > a.end:
259 continue
260 parts = []
261 for k in range(s["w0"], s["w1"] + 1):
262 if "spk" in W[k] and (k == 0 or W[k - 1].get("spk") != W[k]["spk"]):
263 parts.append("<%s w%d>" % (W[k]["spk"], k))
264 parts.append(W[k]["w"])
265 if k < s["w1"] and W[k + 1]["s"] - W[k]["e"] >= 0.4:
266 parts.append("//%.1fs//" % (W[k + 1]["s"] - W[k]["e"]))
267 print("[%d] %.2f-%.2f (%.1fs) [w%d-w%d] %s" % (s["i"], s["s"], s["e"], s["e"] - s["s"], s["w0"], s["w1"], " ".join(parts)))
268
269
270def cmd_label(a):
271 with open(a.words) as fh:
272 d = json.load(fh)
273 W = d["words"]
274 turns = []
275 for t in a.turns:
276 k, _, name = t.partition("=")
277 if not k.isdigit() or not name:
278 die("a turn is WORD#=NAME, for example 21=B")
279 turns.append((int(k), name))
280 turns.sort()
281 if not turns or turns[0][0] != 0:
282 die("the first turn must start at word 0")
283 for n, (k, name) in enumerate(turns):
284 end = turns[n + 1][0] if n + 1 < len(turns) else len(W)
285 for w in W[k:end]:
286 w["spk"] = name
287 with open(a.words, "w") as fh:
288 json.dump(d, fh, indent=1)
289 for k, name in turns:
290 print("w%d %.2fs %s: %s" % (k, W[k]["s"], name, " ".join(x["w"] for x in W[k:k + 8])))
291
292
293def main():
294 p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
295 sub = p.add_subparsers(dest="cmd", required=True)
296 t = sub.add_parser("transcribe")
297 t.add_argument("input")
298 t.add_argument("-o", "--output", default="words.json")
299 t.add_argument("--model")
300 t.add_argument("--threads", type=int, default=4)
301 t.add_argument("--language", help="two-letter code for a multilingual model (default: the model's own)")
302 i = sub.add_parser("import")
303 i.add_argument("transcript")
304 i.add_argument("--audio")
305 i.add_argument("-o", "--output", default="words.json")
306 s = sub.add_parser("show")
307 s.add_argument("words")
308 s.add_argument("--from", dest="start", type=float, default=0.0)
309 s.add_argument("--to", dest="end", type=float, default=1e9)
310 lb = sub.add_parser("label")
311 lb.add_argument("words")
312 lb.add_argument("turns", nargs="+")
313 a = p.parse_args()
314 {"transcribe": cmd_transcribe, "import": cmd_import, "show": cmd_show, "label": cmd_label}[a.cmd](a)
315
316
317if __name__ == "__main__":
318 main()
319
Reviews
No reviews yet. Installed it? Tell others how it went.
Versions
- v1.0.0First version25 Nov 2026
More for captions
Word-Pop Captions
NewBold 1-3 word pop-up captions timed to every word, burned in and safe-zone checked
Talking head, Podcast9:16 video, SRT or VTT
Stickman Video Director
NewTurn a topic, article or script into a narrated stickman video, in 17 styles.
Script16:9 video, 9:16 video, SRT or VTT
VideoAnimated story shorts
New55-70 s vertical cartoon story shorts: flat 2D characters in a painted 3D world.
Script9:16 video