Word-Pop Captions
Bold 1-3 word pop-up captions timed to every word, burned in and safe-zone checked
Before: A 30 s vertical crop of a talking-head interview.. 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 word-pop-captions skill on short.mp4. Add those bold pop-up captions for TikTok and burn them in. Just do it.
Recipe
- 1Transcribe with word times and fix misheard names
- 2Pick about one stressed word in five
- 3Group words into 1-3 word cards by phrase and measured width
- 4Lint every card, then burn in
- 5Check a contact sheet against the safe zone and the face
About
Burns short-form captions into a talking video: one to three words at a time, each card appearing on the first frame of its first word with a small pop, heavy white uppercase type with a black outline, and about one card in five stressed in an accent colour. You also get the card-by-card SRT, the styled ASS file and sentence subtitles for a platform upload.
The look comes from measuring captions frame by frame in top podcast and talking-head shorts: 2 words a card at the median, capitals about 3.4% of the frame height, the line in the lower middle. Cards are grouped by phrase (never ending on "of" or "the", never splitting a name), never flash for less than 0.3 s, and are sized from the real rendered width so they always fit inside the TikTok, Reels and Shorts safe zone, below the face. A linter checks every card before burn-in.
Limits: cards follow the transcript's pauses, so a slow speaker who pauses mid-phrase gets some awkward breaks and longer cards; the agent asks you to confirm names it could not verify, since burned-in text cannot be fixed later.
Proof footage: Open Culture Voices: Maja Drabczyk, Creative Commons, https://youtu.be/Keej4G0xlks.
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.
Word-pop captions
The caption style of fast short-form video: a card of one to three words appears on the first frame of its first word, pops in, and gives way to the next card, so the viewer reads along at the speaker's pace with the sound off. Every number below was measured on top-performing vertical clips; the measurements are in references/style.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. Same rules and values on both.
When to use
- Vertical shorts, reels and TikToks; talking heads and podcast clips; landscape videos that want the same energetic look.
- Not for long-form subtitles meant to be read as sentences (two lines, 42 characters): use a broadcast subtitle skill for those. The sentence SRT this skill writes is for platform upload, not a substitute for proper subtitles.
Inputs
- A video with speech in one language. Optional: names and terms to spell right, words to stress, a font, a position preference, the target platform.
Approval gate
Before writing files, tell the user in five lines or fewer: the video (size, length), the language, the style (font, capital height, position, accent colour), the words you plan to stress, and the files you will deliver. Wait for a yes, unless the user said "just do it" or equivalent.
Pipeline
Every step ends with its check; do not continue past a failed one.
- Probe size, frame rate and duration. Check: vertical (height > width) or landscape picks the defaults; frame rate is the file's real rate.
- Transcribe with word times. Check: read the whole transcript; fix misheard names and terms by editing word text only, never times; the language is right. List every proper noun you could not confirm and ask the user about it in your final message (a misspelled name burned into a video cannot be fixed later).
- Choose stressed words: about one card in five; the word that carries its sentence: a number, a name, a result, a contrast, or the key noun the first time it comes up. Never a filler, a pronoun, a function word or a generic noun (things, people), and never two cards in a row. Read each chosen word aloud in its sentence: if stressing it would sound odd, pick another. Check: the list has about (cards / 5) words and you can say why each one matters.
- Build cards at the final values. Check: the log names a real heavy sans (not a fallback) and capitals of 65 px on a 1920 frame (scaled for other sizes).
- Lint the cards. Check: 0 errors; every warning read and either fixed or explained.
- Burn in (or render through Zylcut). Check: same duration as the input, audio present.
- Look at frames (QA below). Then deliver the MP4, the card SRT, the ASS and the sentence SRT, and say which is which in one line each.
Final values
| Rule | Value |
|---|---|
| Words per card | 1-3 (median 2), grouped by phrase: a card ends at a clause end or a pause, never on a word that leads into the next ("OF", "THE", "AND", "WITH"); a pause of 0.6 s or more always ends a card |
| Card timing | on at its first word's start; held to the next card across gaps up to 0.5 s (no flicker), else off 0.15 s after its last word; at most 1.5 s unless its words last longer |
| Shortest card | 0.30 s on screen, never less: a flash card joins its neighbour |
| Lines | one; a card a little too wide is drawn smaller (down to 80%); two lines only when that is not enough and splitting the card would leave a flash card; two lines grow upwards from the one-line position. Never split a name across cards |
| Font | Montserrat ExtraBold, else Poppins ExtraBold (or another heavy geometric sans), uppercase |
| Size | capitals 3.4% of height on vertical (65 px at 1920), 5.5% on landscape |
| Position | one line, centred; centre at 62% of height on vertical, 80% on landscape |
| Safe zone (vertical, 1080x1920) | x 48-888 and y 288-1248, scaled to the frame; the line also stays below the face |
| Colour | white #FFFFFF; accent #FFB21E on stressed words |
| Outline and shadow | black outline 7% of the capital height (4-5 px at 65 px); hard black shadow 5% down, 60% opacity |
| Pop | scale 72% to 106% to 100% over 0.16 s on each new card; no fades, no slides |
| On-screen rate | follows speech; above about 5 words a second, check that cards are readable |
QA
Open a contact sheet of frames 0.1 s into cards across the whole video and check each tile:
- whole words only, one line, nothing cut at the frame edges;
- inside the safe box and clear of the face (eyes and mouth visible);
- stressed words coloured, at most one card in five, never fillers;
- readable over the brightest part of the picture (outline visible);
- the first card is on screen on the first spoken word, and the last card leaves within 0.15 s of the last word.
Gotchas
- An English-only model turns other languages into fluent nonsense: check the language first.
- libass sizes by line metrics, so the same size number gives different capitals in different fonts. Size by measured capital height (the build script does).
- A missing font falls back silently in libass; read the font name in the build log.
- Never edit times in an SRT by hand: fix the transcript text or punctuation and build again.
- Captions over a speaker's mouth hurt more than slightly low captions: move the line, do not shrink the type below about 55 px capitals on 1920.
- Platform SRT uploads are not styled; the look only exists in the burned-in video.
Limits
- Cards are grouped from the transcript's punctuation and pauses. A slow speaker who pauses in the middle of a phrase gets some cards that end on a small word ("UP OF") and cards held longer than the 0.55 s reference median; fixing the transcript's punctuation (a full stop or comma where the thought ends) and building again improves it.
- A card a little too wide for the safe width is drawn up to 20% smaller rather than wrapped, so card sizes can differ slightly.
- A separate judge scored the last test (a slow, pausing speaker with Polish names) 5-7 out of 10 per area, mostly for phrase breaks; legibility, placement and timing to the word passed.
Files
7 files, 71 KB. Nothing in a skill runs until your agent runs it.
1---
2name: word-pop-captions
3description: Burn short-form "word pop" captions into a video - 1 to 3 words per card timed to each spoken word, heavy white uppercase type with a black outline sized by measured capital height, a small pop on each card, one stressed word in five in an accent colour, kept inside the platform safe zone and below the face - and deliver the card SRT, a styled ASS, sentence SRT for upload and the burned-in MP4. Use when the user wants TikTok, Reels or Shorts style captions, animated captions, big bold captions, word-by-word or 1-3 word captions, captions with highlighted keywords, or says "caption this short", "add those pop-up captions" or "burn in captions". Works on vertical and landscape video. Not for broadcast or accessibility subtitles (2-line sentence subtitles).
4license: Apache-2.0
5compatibility: Generic path needs Python 3.8+, ffmpeg and ffprobe with libass, and whisper.cpp whisper-cli (or any word-timed transcript). 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---
11
12# Word-pop captions
13
14The caption style of fast short-form video: a card of one to three words appears on the first
15frame of its first word, pops in, and gives way to the next card, so the viewer reads along at
16the speaker's pace with the sound off. Every number below was measured on top-performing
17vertical clips; the measurements are in [references/style.md](references/style.md).
18
19**Which backend.** If Zylcut MCP tools are available (for example `context`,
20`media_transcribe`, `capture`, `check`), follow [references/zylcut.md](references/zylcut.md);
21otherwise follow [references/ffmpeg.md](references/ffmpeg.md). Same rules and values on both.
22
23## When to use
24
25- Vertical shorts, reels and TikToks; talking heads and podcast clips; landscape videos that
26 want the same energetic look.
27- Not for long-form subtitles meant to be read as sentences (two lines, 42 characters): use a
28 broadcast subtitle skill for those. The sentence SRT this skill writes is for platform upload,
29 not a substitute for proper subtitles.
30
31## Inputs
32
33- A video with speech in one language. Optional: names and terms to spell right, words to
34 stress, a font, a position preference, the target platform.
35
36## Approval gate
37
38Before writing files, tell the user in five lines or fewer: the video (size, length), the
39language, the style (font, capital height, position, accent colour), the words you plan to
40stress, and the files you will deliver. Wait for a yes, unless the user said "just do it" or
41equivalent.
42
43## Pipeline
44
45Every step ends with its check; do not continue past a failed one.
46
471. **Probe** size, frame rate and duration. Check: vertical (height > width) or landscape picks
48 the defaults; frame rate is the file's real rate.
492. **Transcribe with word times.** Check: read the whole transcript; fix misheard names and
50 terms by editing word text only, never times; the language is right. List every proper noun
51 you could not confirm and ask the user about it in your final message (a misspelled name
52 burned into a video cannot be fixed later).
533. **Choose stressed words**: about one card in five; the word that carries its sentence: a
54 number, a name, a result, a contrast, or the key noun the first time it comes up. Never a
55 filler, a pronoun, a function word or a generic noun (things, people), and never two cards in
56 a row. Read each chosen word aloud in its sentence: if stressing it would sound odd, pick
57 another. Check: the list has about (cards / 5) words and you can say why each one matters.
584. **Build cards** at the final values. Check: the log names a real heavy sans (not a fallback)
59 and capitals of 65 px on a 1920 frame (scaled for other sizes).
605. **Lint** the cards. Check: 0 errors; every warning read and either fixed or explained.
616. **Burn in** (or render through Zylcut). Check: same duration as the input, audio present.
627. **Look at frames** (QA below). Then deliver the MP4, the card SRT, the ASS and the sentence
63 SRT, and say which is which in one line each.
64
65## Final values
66
67| Rule | Value |
68|---|---|
69| Words per card | 1-3 (median 2), grouped by phrase: a card ends at a clause end or a pause, never on a word that leads into the next ("OF", "THE", "AND", "WITH"); a pause of 0.6 s or more always ends a card |
70| Card timing | on at its first word's start; held to the next card across gaps up to 0.5 s (no flicker), else off 0.15 s after its last word; at most 1.5 s unless its words last longer |
71| Shortest card | 0.30 s on screen, never less: a flash card joins its neighbour |
72| Lines | one; a card a little too wide is drawn smaller (down to 80%); two lines only when that is not enough and splitting the card would leave a flash card; two lines grow upwards from the one-line position. Never split a name across cards |
73| Font | Montserrat ExtraBold, else Poppins ExtraBold (or another heavy geometric sans), uppercase |
74| Size | capitals 3.4% of height on vertical (65 px at 1920), 5.5% on landscape |
75| Position | one line, centred; centre at 62% of height on vertical, 80% on landscape |
76| Safe zone (vertical, 1080x1920) | x 48-888 and y 288-1248, scaled to the frame; the line also stays below the face |
77| Colour | white `#FFFFFF`; accent `#FFB21E` on stressed words |
78| Outline and shadow | black outline 7% of the capital height (4-5 px at 65 px); hard black shadow 5% down, 60% opacity |
79| Pop | scale 72% to 106% to 100% over 0.16 s on each new card; no fades, no slides |
80| On-screen rate | follows speech; above about 5 words a second, check that cards are readable |
81
82## QA
83
84Open a contact sheet of frames 0.1 s into cards across the whole video and check each tile:
85
86- whole words only, one line, nothing cut at the frame edges;
87- inside the safe box and clear of the face (eyes and mouth visible);
88- stressed words coloured, at most one card in five, never fillers;
89- readable over the brightest part of the picture (outline visible);
90- the first card is on screen on the first spoken word, and the last card leaves within
91 0.15 s of the last word.
92
93## Gotchas
94
95- An English-only model turns other languages into fluent nonsense: check the language first.
96- libass sizes by line metrics, so the same size number gives different capitals in different
97 fonts. Size by measured capital height (the build script does).
98- A missing font falls back silently in libass; read the font name in the build log.
99- Never edit times in an SRT by hand: fix the transcript text or punctuation and build again.
100- Captions over a speaker's mouth hurt more than slightly low captions: move the line, do not
101 shrink the type below about 55 px capitals on 1920.
102- Platform SRT uploads are not styled; the look only exists in the burned-in video.
103
104## Limits
105
106- Cards are grouped from the transcript's punctuation and pauses. A slow speaker who pauses in
107 the middle of a phrase gets some cards that end on a small word ("UP OF") and cards held longer
108 than the 0.55 s reference median; fixing the transcript's punctuation (a full stop or comma
109 where the thought ends) and building again improves it.
110- A card a little too wide for the safe width is drawn up to 20% smaller rather than wrapped, so
111 card sizes can differ slightly.
112- A separate judge scored the last test (a slow, pausing speaker with Polish names) 5-7 out of 10
113 per area, mostly for phrase breaks; legibility, placement and timing to the word passed.
114
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
1# Generic path (ffmpeg and whisper-cli)
2
3Use this when no Zylcut MCP tools are available. Everything runs from the shell with
4`scripts/words.py` and `scripts/wordpop.py` (Python 3.8+, standard library only).
5
6## Steps
7
81. **Probe**: `ffprobe -v error -show_entries stream=width,height,r_frame_rate -show_entries format=duration -of json IN.mp4`.
9 Note the size (vertical or landscape) and the real frame rate.
102. **Transcribe with word times**:
11 `python3 scripts/words.py transcribe IN.mp4 -o words.json --model ~/.cache/whisper/ggml-small.en.bin`
12 (whisper.cpp `whisper-cli` must be on PATH; `--model` takes any ggml model; use a
13 multilingual model and `--language xx` for other languages). If the user already has a
14 word-timed transcript (whisper JSON, a Zylcut transcript), use
15 `python3 scripts/words.py import THEIRS.json -o words.json --audio IN.mp4`.
16 Check: `python3 scripts/words.py show words.json` and read it. Fix misheard words by editing
17 their text in `words.json`, never their times. If the speech is not English and the model is
18 English-only, the transcript is nonsense: stop and switch model.
193. **Pick the stressed words** (style.md rule 5): about one card in five, the word that carries
20 the sentence. Pass them as `--emphasis "word,word"`, or wrap one occurrence as `*word*` in
21 `words.json`.
224. **Build the cards**:
23 `python3 scripts/wordpop.py build words.json --video IN.mp4 -o captions --emphasis "..."`.
24 It writes `captions.ass` (styled, for burning), `captions.cards.srt` (one cue per card, for
25 editors that want the pop timing), `captions.srt` (sentence subtitles for an upload to
26 YouTube, TikTok or Instagram, which do not style SRT), `captions.tsx` (a Zylcut component) and
27 `captions.cards.json`. The log names the font and the capital height it measured; if it says
28 a fallback font, install Montserrat or Poppins or pass `--font` with an installed heavy sans.
295. **Check the cards**: `python3 scripts/wordpop.py check captions.cards.json`. Check: 0 errors.
30 Read every warning (a long card that might not fit, a card under 0.2 s, more than about 5
31 words a second).
326. **Burn**: `python3 scripts/wordpop.py burn IN.mp4 captions.ass OUT.mp4` (libx264 CRF 20,
33 audio copied, 4 threads). Check: the output has the input's duration and audio.
347. **Look at frames**: `python3 scripts/wordpop.py sheet OUT.mp4 captions.cards.json sheet.jpg`
35 and open the image. Check every tile: whole words, one line, inside the cyan safe box, below
36 the face (not across the mouth or eyes), accent words coloured, outline readable on the
37 brightest background. If the line covers a face, move it with `--y` (0.70 lower, 0.55 higher)
38 and rebuild.
39
40## Notes
41
42- `--from S --to S --offset S` captions a part of a long transcript for a clip cut from it.
43- Times in every output are seconds of the input video. If you trim the video afterwards, build
44 again from the trimmed file's transcript.
45- ffmpeg needs libass (`ffmpeg -filters | grep ass`). Without it, deliver the ASS and SRT files
46 and say the burn-in needs an ffmpeg build with libass.
47
1# Word-pop style bible
2
3Measured on 15 captioned vertical clips (720x1280, from 21 two-person podcast Shorts and talking
4head Shorts with 65k to 52M views), frame by frame: the caption band found by a bright-glyph mask
5with a dark edge, a card is a change of that mask, words read by OCR and cross-checked against a
6word-timed transcript of the same window. Sizes are scaled to a 1920 px tall frame.
7
8## Reference numbers (min / median / p90 / max over clips)
9
10| Metric | min | median | p90 | max | Used in the skill |
11|---|---|---|---|---|---|
12| Words per card (transcript count) | 1 | 2 | 3 | 6 | at most 3, median 2 |
13| Card duration (s) | 0.30 | 0.55 | 1.0 | 1.8 | cards follow the words; shortest about 0.35 s |
14| Caption centre y (fraction of height) | 0.50 | 0.66 | 0.72 | 0.74 | 0.62 (the median sits below the vertical safe zone's bottom edge once the line's height is added) |
15| Capital height (px at 1920) | 29 | 57 | 75 | 90 | 65 px (CAP_FRAC 0.034) |
16| Dark edge around glyphs (share of edge pixels) | 0.21 | 0.75 | 0.88 | 0.91 | black outline plus a small hard shadow |
17| Edge width (px at 1920) | 1.5 | 2.2 | 3.5 | 4.5 | 4-5 px outline (see note) |
18| Lines per card | 1 | 1 | 2 | 2 | 1 line |
19| Cards with an accent-coloured word (share) | 0 | 0.20 | 0.38 | 0.86 | about 1 card in 5 |
20| Uppercase letter share | 0.01 | 0.09 | 0.53 | 1.0 | upper by default; `--case asis` for sentence case |
21| Time with a caption on screen (share) | 0.56 | 0.83 | 0.93 | 0.94 | every spoken word is on screen |
22
23- Base colour: white in 14 clips, yellow in 1.
24- Accent colours by word count: orange 285, yellow 105, red 59, cyan 24, others under 20. The
25 default accent is an orange-yellow, `#FFB21E`.
26- Speech in these clips runs at 2.8 / 3.55 / 4.2 / 5.05 words per second (min / median / p90 /
27 max), so a 2-word card lasts about 0.55 s at the median pace. The cards follow the speaker; the
28 script never speeds them up or slows them down.
29- One talking-head reference measured fully (17.7 s, 47 words): 19 cards, about 3 words a card,
30 all uppercase, band centre at 0.52 of the height (higher, because the speaker is framed low).
31
32## Rules taken from the numbers
33
341. **1 to 3 words a card, never more**, grouped by phrase: broken at clause ends and pauses,
35 never after a word that leads into the next ("OF", "THE", "AND"), never inside a name.
362. **A card appears on its first word's first frame** and stays until the next card across gaps
37 up to 0.5 s (so cards do not flicker), else for 0.15 s after its last word (nothing on screen
38 in a long pause); at most 1.5 s unless its own words take longer.
393. **One line, centred, in the lower middle**: centre at 62% of the height on vertical, below the
40 face and above the platform's caption and button zone (vertical safe zone x 48-888 on a 1080
41 frame, y 288-1248 on 1920). Landscape: centre at 80% of the height, capitals 5.5% of height.
424. **Heavy sans, white, black outline**: Montserrat ExtraBold or Poppins ExtraBold, capitals
43 65 px on a 1920 frame (3.4% of height), outline 7% of the capital height, hard shadow 5%.
445. **Stress about one card in five** with the accent colour: the word that carries the sentence
45 (a number, a result, a contrast, a name), never a filler, and never two cards in a row.
466. **A small pop**: each new card scales 72% to 106% to 100% over 0.16 s. Words never slide or
47 fade (a fade costs reading time on a 0.5 s card).
48
49Note on edge width: the measured 2.2 px comes from 720p copies, where an outline 4 px wide at
501080p shrinks to under 2 px and blurs into the glyph; the skill uses 4-5 px so the line stays
51readable over white shirts and bright walls.
52
53## Fonts and libass sizing
54
55libass sizes a font by its line metrics, not its capitals, so the same `Fontsize` gives
56different capitals in different fonts (at size 100: Poppins ExtraBold capitals 47 px, Arial Black
5757 px, Impact 75 px). `wordpop.py build` renders a test frame of the chosen font, measures the
58capital height and works out the size from it, so `--cap 65` means 65 px capitals in any font.
59
1# Zylcut path
2
3Use this when Zylcut MCP tools are available. Zylcut draws word-pop captions natively with
4`<captions preset="bold">`: one to three words at a time from the transcript, each card popping
5in, stressed words in an accent colour. This path sets that element to the measured style and
6checks it. Read the in-app **zylcut-editor** skill first if you have not in this session.
7
8## Steps
9
101. **Open the project**, read `index.tsx`, take a `user_edits` baseline and read `notes`. Find
11 the scene and the clip the captions belong to (`<video id=...>`; a cut clip with `keep` is
12 fine).
132. **Transcribe** the clip's file with `media_transcribe` (`projectId`, `output` under
14 `assets/transcripts/`, a `glossary` for names). Read the words in the returned file; fix a
15 misheard word by adding the term to the glossary and transcribing again, never by typing new
16 times.
173. **Choose stressed words**: one per sentence at most, the word that carries it (a number, a
18 result, a contrast, a name), and no more than one every 4 s. Write them as `emphasis`, or wrap
19 a single occurrence as `*word*` in the transcript JSON's word text.
204. **Add the captions** after the clip, inside the same parent:
21
22 ```tsx
23 <captions id="word-pop" src="transcripts/<file>.json" follow="<clip id>" preset="bold"
24 fontFamily="Montserrat" fontWeight={800} fontSize={93} textCase="upper"
25 y={1040} colors={["#FFB21E"]} emphasis={["word", "word"]} punctuation="hide">
26 <stroke width={10} color="#000000" />
27 <shadow color="#000000" offsetY={3} blur={0} opacity={0.6} />
28 </captions>
29 ```
30
31 These are the 1080x1920 values: font size 93 gives capitals about 65 px (Montserrat's
32 capitals are 0.70 of its size), `y={1040}` puts the line's centre at y 1190 (the `bold` box is
33 300 px tall, so top = centre - 150), and a 10 px stroke shows 5 px outside the letters (text
34 draws its fill over the inner half). For other sizes scale all three by height / 1920. On
35 landscape, capitals about 5.5% of height and the centre at 0.80 of the height.
36 The `bold` preset shows groups of about 0.2 s of speech (usually one word, two for fast
37 short words); that is within the measured 1-3 words per card.
385. **Verify**:
39 - `context`: no `compileError`.
40 - `check` on the scene with `platform` set to the target app (`tiktok`, `reels` or
41 `shorts`): no `text-off-frame`, `low-contrast-text`, `caption-over-face` or
42 `platform-safe-area` on the captions, and `captions-no-sound` absent. `stats.pacing.captionWordsPerSecond` at most about 5.
43 - `capture` with `times` every 1-2 s: whole words, inside the safe box, below the face,
44 accent words coloured.
456. **Export** only when asked: `export` with preset `vertical-1080` (or `youtube-1080` for
46 landscape). For the sidecar files: `export` with a `.srt` path writes sentence subtitles; the
47 card-by-card SRT and ASS come from the generic script (`wordpop.py build` on the same
48 transcript converted with `words.py import`) when the user wants them.
49
50## Notes
51
52- `bold` draws its own 14 px outline and hard shadow only while the captions have no
53 `<stroke>`/`<shadow>` children; the children above replace them with the measured ones.
54- Montserrat ships with Zylcut, so captures and exports match on every machine.
55- `follow` keeps captions in sync through every cut; never place captions by scene time over a
56 cut clip.
57
1#!/usr/bin/env python3
2"""Word-pop captions: 1-3 word cards timed to each spoken word, as ASS, SRT and burned-in video.
3
4Usage:
5 wordpop.py build words.json --video IN.mp4 -o NAME [options]
6 Writes NAME.ass (styled, for burning), NAME.cards.srt (one cue per card), NAME.srt
7 (readable sentence subtitles, at most 2 lines of 42 characters, for upload), NAME.tsx (a
8 Zylcut component drawing the same cards) and NAME.cards.json (the cards, for check).
9 wordpop.py burn IN.mp4 NAME.ass OUT.mp4 [--crf 20] [--threads 4]
10 Burns the ASS file with libass and copies the audio.
11 wordpop.py check NAME.cards.json words.json
12 Prints the card measurements and exits 1 when a hard rule fails.
13 wordpop.py sheet OUT.mp4 NAME.cards.json SHEET.jpg [--n 12]
14 Contact sheet of frames 0.1 s after card starts, with the safe zone drawn.
15
16Build options (defaults are the measured style; see references/style.md):
17 --emphasis "word,word" words drawn in the accent colour (case and punctuation ignored).
18 A word written *like this* in words.json is stressed too.
19 --accent "#FFB21E" accent colour for stressed words (orange-yellow).
20 --active also colour the word being spoken (white otherwise).
21 --font NAME font family (default: the first installed heavy sans, see FONTS).
22 --cap PX capital-letter height in pixels (default: CAP_FRAC x frame height).
23 The font size is worked out from a rendered test of the chosen font.
24 --y FRAC centre of the caption line as a fraction of height (default 0.62 on
25 vertical, 0.80 on landscape).
26 --max-words 3 words per card.
27 --case upper|asis letter case (default upper).
28 --pop / --no-pop scale pop on each new card (default on).
29 --from S --to S only words in this time range of words.json (times stay as in the file
30 unless --offset is given).
31 --offset S subtract S from every time (use when the video starts at S in the file).
32
33Standard library only. Needs ffmpeg with libass for burn and sheet.
34"""
35
36import argparse
37import json
38import os
39import re
40import shutil
41import subprocess
42import sys
43
44FONTS = ["Montserrat ExtraBold", "Montserrat Black", "Anton", "Poppins ExtraBold", "Poppins Black",
45 "Archivo Black", "Figtree Black", "Inter ExtraBold", "Arial Black", "Impact", "DejaVu Sans"]
46CAP_FRAC = 0.034 # capital height / frame height on vertical (65 px on 1920)
47CAP_FRAC_LAND = 0.055 # on landscape
48OUTLINE_FRAC = 0.07 # outline width / capital height (4-5 px at 65 px capitals)
49SHADOW_FRAC = 0.05 # drop shadow offset / capital height
50GAP_JOIN = 0.50 # a word's display is held to the next word's start when the gap is this or less
51TAIL = 0.15 # otherwise it is held this long after the word ends
52MIN_CARD = 0.35 # a card shorter than this takes one more word when it can
53BREAK_GAP = 0.30 # a pause this long starts a new card
54
55
56def die(msg, code=2):
57 print("error: " + msg, file=sys.stderr)
58 sys.exit(code)
59
60
61def probe(path):
62 r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
63 "stream=width,height,r_frame_rate:format=duration", "-of", "json", path],
64 capture_output=True, text=True)
65 if r.returncode != 0:
66 die("ffprobe could not read " + path)
67 d = json.loads(r.stdout)
68 s = d["streams"][0]
69 n, m = s["r_frame_rate"].split("/")
70 return int(s["width"]), int(s["height"]), float(n) / float(m or 1), float(d["format"]["duration"])
71
72
73def pick_font(explicit):
74 if explicit:
75 return explicit
76 if shutil.which("fc-list"):
77 r = subprocess.run(["fc-list", ":", "family", "style"], capture_output=True, text=True)
78 have = r.stdout
79 for f in FONTS:
80 fam = f.rsplit(" ", 1)
81 if f in have or (len(fam) == 2 and fam[0] in have and fam[1] in have and f.split()[0] not in ("Arial",)):
82 return f
83 return "Arial Black"
84
85
86def calibrate(font):
87 """Render the font once and measure it: (cap height / font size, width per capital / cap height).
88 libass sizes a font by its line metrics, so the same size gives different letters per font."""
89 import tempfile
90 tmp = tempfile.mkdtemp(prefix="wp-")
91 text = "THE QUICK BROWN FOX JUMPS OVER MY LAZY DOG"
92 ass = os.path.join(tmp, "c.ass")
93 with open(ass, "w") as fh:
94 fh.write("[Script Info]\nPlayResX: 4000\nPlayResY: 400\nWrapStyle: 2\n[V4+ Styles]\n"
95 "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"
96 "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"
97 "[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n"
98 "Dialogue: 0,0:00:00.00,0:00:01.00,A,,0,0,0,,%s\n" % (font, text))
99 pgm = os.path.join(tmp, "c.pgm")
100 esc = ass.replace("\\", "/").replace(":", "\\:")
101 r = subprocess.run(["ffmpeg", "-v", "info", "-y", "-f", "lavfi", "-i", "color=black:s=4000x400:d=0.2",
102 "-vf", "subtitles='%s',format=gray" % esc, "-frames:v", "1", pgm], capture_output=True, text=True)
103 used = ""
104 for l in r.stderr.splitlines():
105 if "fontselect" in l:
106 used = l.split("->")[-1].strip().split(",")[0]
107 try:
108 b = open(pgm, "rb").read()
109 p = b.split(maxsplit=4)
110 w, h = int(p[1]), int(p[2])
111 px = p[4][-(w * h):]
112 x0, x1, y0, y1 = w, 0, h, 0
113 for y in range(h):
114 row = px[y * w:(y + 1) * w]
115 if max(row) > 128:
116 y0, y1 = min(y0, y), max(y1, y)
117 x0 = min(x0, next(i for i, v in enumerate(row) if v > 128))
118 x1 = max(x1, w - 1 - next(i for i, v in enumerate(reversed(row)) if v > 128))
119 cap = y1 - y0 + 1
120 res = (cap / 100.0, (x1 - x0 + 1) / len(text) / cap, used)
121 except Exception:
122 res = (0.62, 0.80, used)
123 shutil.rmtree(tmp, ignore_errors=True)
124 return res
125
126
127def norm(w):
128 return re.sub(r"[^\w']", "", w.lower().replace("*", ""))
129
130
131def is_name(w):
132 t = re.sub(r"^[\"'(\[]+", "", w.replace("*", ""))
133 return bool(t) and t[0].isupper() and t.lower() not in ("i", "i'm", "i've", "i'd", "i'll")
134
135
136def ends_clause(w):
137 return w.rstrip('"\')]*').endswith((".", "?", "!", ",", ";", ":"))
138
139
140def ends_sentence(w):
141 return w.rstrip('"\')]*').endswith((".", "?", "!"))
142
143
144def display(w, case):
145 t = w.replace("*", "")
146 t = re.sub(r"^[\"'(\[]+|[\"')\].,;:]+$", "", t) # social captions drop end punctuation; keep ? !
147 t = t.rstrip(".,;:")
148 return t.upper() if case == "upper" else t
149
150
151# words that should not end a card: the phrase continues into the next word
152NO_END = set("""a an the this that these those my your his her its our their of to in on at for with by from
153into onto over under about as than and or but nor so if because when while where who which whose whom
154i we you he she they it is are was were be been am has have had do does did will would can could
155should may might must not no very more most just really there here some any every each all both
156one two three four five six seven eight nine ten""".split())
157NO_START = set("""of 's n't""".split())
158MAX_HOLD = 1.5 # a card stays at most this long after its first word (unless its words last longer)
159HARD_GAP = 0.60 # a pause this long always starts a new card
160
161
162def measure_widths(font, size, outline, texts):
163 """Rendered pixel width of each one-line text at 100% scale, outline included, measured with
164 libass itself, so wide capitals (M, W) and kerning are counted rather than estimated."""
165 import tempfile
166 if len(texts) > 40: # keep the canvas within ffmpeg's frame size limits
167 return measure_widths(font, size, outline, texts[:40]) + measure_widths(font, size, outline, texts[40:])
168 if not texts:
169 return []
170 tmp = tempfile.mkdtemp(prefix="wp-")
171 band = int(size * 1.6)
172 Wc, Hc = 3000, band * len(texts)
173 ass = os.path.join(tmp, "m.ass")
174 with open(ass, "w", encoding="utf-8") as fh:
175 fh.write("[Script Info]\nPlayResX: %d\nPlayResY: %d\nWrapStyle: 2\n[V4+ Styles]\n"
176 "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"
177 "Style: A,%s,%d,&H00FFFFFF,&H00FFFFFF,&H00FFFFFF,&H00000000,-1,0,0,0,100,100,0,0,1,%d,0,5,0,0,0,1\n"
178 "[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n" % (Wc, Hc, font, size, outline))
179 for k, t in enumerate(texts):
180 fh.write("Dialogue: 0,0:00:00.00,0:00:01.00,A,,0,0,0,,{\\pos(%d,%d)}%s\n" % (Wc // 2, band * k + band // 2, t.replace("{", "(").replace("}", ")")))
181 pgm = os.path.join(tmp, "m.pgm")
182 esc = ass.replace("\\", "/").replace(":", "\\:")
183 subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "color=black:s=%dx%d:d=0.2" % (Wc, Hc),
184 "-vf", "subtitles='%s',format=gray" % esc, "-frames:v", "1", pgm], capture_output=True)
185 b = open(pgm, "rb").read()
186 p = b.split(maxsplit=4)
187 w, h = int(p[1]), int(p[2])
188 px = p[4][-(w * h):]
189 out = []
190 for k in range(len(texts)):
191 x0, x1 = w, -1
192 for y in range(band * k, band * (k + 1), 2):
193 row = px[y * w:(y + 1) * w]
194 if max(row) > 128:
195 x0 = min(x0, next(i for i, v in enumerate(row) if v > 128))
196 x1 = max(x1, w - 1 - next(i for i, v in enumerate(reversed(row)) if v > 128))
197 out.append(max(0, x1 - x0 + 1))
198 shutil.rmtree(tmp, ignore_errors=True)
199 return out
200
201
202SHRINK = 0.80 # a card a little too wide is drawn smaller (down to 80%) before it takes two lines
203
204
205class Fit:
206 """Measured rendered widths (libass, outline included) against the safe width."""
207
208 def __init__(self, widths, limit):
209 self.widths, self.limit = widths, limit
210
211 def w(self, text):
212 return self.widths.get(text, 10 ** 6)
213
214
215def line_break(texts, fit):
216 """None when the words fit one line (shrunk to SHRINK at most); else the index k of the best
217 2-line split; -1 if none fits."""
218 if fit.w(" ".join(texts)) * SHRINK <= fit.limit:
219 return None
220 best, bk = None, -1
221 for k in range(1, len(texts)):
222 a, b = " ".join(texts[:k]), " ".join(texts[k:])
223 if fit.w(a) <= fit.limit and fit.w(b) <= fit.limit:
224 d = abs(fit.w(a) - fit.w(b))
225 if best is None or d < best:
226 best, bk = d, k
227 return bk
228
229
230def make_cards(words, max_words, fit, case):
231 """Best grouping of words into 1..max_words cards (dynamic programming): breaks at clause
232 ends and pauses, never on a function word that leads into the next one, no flash cards."""
233 n = len(words)
234 INF = float("inf")
235 cost = [INF] * (n + 1)
236 back = [0] * (n + 1)
237 cost[0] = 0.0
238 for j in range(1, n + 1):
239 for i in range(j - 1, max(-1, j - 1 - max_words), -1):
240 ws = words[i:j]
241 texts = [display(x["w"], case) for x in ws]
242 text = " ".join(texts)
243 br = line_break(texts, fit)
244 if br == -1 and j - i > 1:
245 break
246 if any(ws[k + 1]["s"] - ws[k]["e"] >= HARD_GAP for k in range(len(ws) - 1)):
247 break
248 c = 1.0 + (3.0 if br else 0.0) # two lines only when one cannot hold the phrase
249 last = ws[-1]["w"]
250 gap_after = words[j]["s"] - ws[-1]["e"] if j < n else 9.0
251 if j == n or ends_clause(last):
252 pass
253 elif j < n and is_name(last) and is_name(words[j]["w"]):
254 c += 4.5 # "OLGA / VESOTKA": a name is never split
255 elif norm(last) in NO_END:
256 c += 1.5 if gap_after >= HARD_GAP else 4.5 # "OF" / "POLISH": the phrase is cut
257 elif gap_after >= BREAK_GAP:
258 pass
259 elif j < n and norm(words[j]["w"]) in NO_START:
260 c += 3.0
261 else:
262 c += 0.8
263 for k in range(len(ws) - 1):
264 g = ws[k + 1]["s"] - ws[k]["e"]
265 if ends_sentence(ws[k]["w"]):
266 c += 3.0 # a sentence end inside a card
267 elif ends_clause(ws[k]["w"]):
268 c += 1.2
269 if g >= BREAK_GAP:
270 c += 2.0 # a pause inside a card
271 dur = ws[-1]["e"] - ws[0]["s"]
272 nxt = words[j]["s"] if j < n else ws[-1]["e"] + 1
273 shown = min(nxt, ws[-1]["e"] + (gap_after if gap_after <= GAP_JOIN else 0.15)) - ws[0]["s"]
274 if shown < 0.30:
275 c += 6.0 # a flash card
276 elif shown < MIN_CARD:
277 c += 2.0
278 if dur > MAX_HOLD:
279 c += 2.0
280 if shown > 1.0 and j - i > 1:
281 c += (shown - 1.0) * 6.0 # reference cards last 0.55 s at the median, 1.0 s at p90
282 if j - i == 1 and len(text) <= 4 and j < n and gap_after < BREAK_GAP:
283 c += 0.8 # a lone short word when it could join its phrase
284 if j - i == 1 and norm(ws[0]["w"]) in NO_END:
285 c += 3.0 # a card of only "TO", "AND", "FROM" says nothing
286 if cost[i] + c < cost[j]:
287 cost[j] = cost[i] + c
288 back[j] = i
289 cards = []
290 j = n
291 while j > 0:
292 i = back[j]
293 cards.append(words[i:j])
294 j = i
295 return cards[::-1]
296
297
298def card_times(cards):
299 res = []
300 for k, c in enumerate(cards):
301 s = c[0]["s"]
302 e = c[-1]["e"]
303 if k + 1 < len(cards):
304 nxt = cards[k + 1][0]["s"]
305 e = nxt if nxt - e <= GAP_JOIN else min(nxt, e + TAIL)
306 else:
307 e = e + TAIL
308 e = max(min(e, s + MAX_HOLD), c[-1]["e"])
309 res.append((s, e))
310 return res
311
312
313def ass_time(t):
314 t = max(0.0, t)
315 cs = int(t * 100 + 1e-6) # floor to the centisecond so nothing shows before its word
316 h, cs = divmod(cs, 360000)
317 m, cs = divmod(cs, 6000)
318 s, cs = divmod(cs, 100)
319 return "%d:%02d:%02d.%02d" % (h, m, s, cs)
320
321
322def srt_time(t):
323 ms = int(round(max(0.0, t) * 1000))
324 h, ms = divmod(ms, 3600000)
325 m, ms = divmod(ms, 60000)
326 s, ms = divmod(ms, 1000)
327 return "%02d:%02d:%02d,%03d" % (h, m, s, ms)
328
329
330def ass_colour(hexc):
331 h = hexc.lstrip("#")
332 if len(h) != 6:
333 die("colour must be #RRGGBB: " + hexc)
334 return "&H%s%s%s" % (h[4:6], h[2:4], h[0:2])
335
336
337def sentence_srt(words, max_chars=42):
338 """Readable sentence subtitles: at most 2 lines of max_chars, 1-7 s, break at clauses."""
339 cues = []
340 cur = []
341 for i, w in enumerate(words):
342 cur.append(w)
343 text = " ".join(x["w"].replace("*", "") for x in cur)
344 nxt = words[i + 1] if i + 1 < len(words) else None
345 long_gap = nxt is not None and nxt["s"] - w["e"] >= 1.0
346 full = nxt is not None and len(text + " " + nxt["w"]) > 2 * max_chars
347 dur = w["e"] - cur[0]["s"]
348 if nxt is None or ends_sentence(w["w"]) or long_gap or full or dur > 6.0 or (ends_clause(w["w"]) and len(text) > max_chars):
349 cues.append(cur)
350 cur = []
351 out = []
352 for k, c in enumerate(cues):
353 text = " ".join(x["w"].replace("*", "") for x in c)
354 lines = [text]
355 if len(text) > max_chars:
356 best = None
357 for j in range(1, len(c)):
358 a = " ".join(x["w"].replace("*", "") for x in c[:j])
359 b = " ".join(x["w"].replace("*", "") for x in c[j:])
360 if len(a) <= max_chars and len(b) <= max_chars:
361 score = abs(len(a) - len(b)) - (8 if ends_clause(c[j - 1]["w"]) else 0)
362 if best is None or score < best[0]:
363 best = (score, [a, b])
364 if best:
365 lines = best[1]
366 s = c[0]["s"]
367 e = c[-1]["e"] + 0.3
368 if k + 1 < len(cues):
369 e = min(e, cues[k + 1][0]["s"] - 0.07)
370 e = max(e, s + 1.0) if k + 1 >= len(cues) or cues[k + 1][0]["s"] - s >= 1.07 else e
371 out.append((s, e, lines))
372 return out
373
374
375def cmd_build(a):
376 W, H, fps, dur = probe(a.video)
377 d = json.load(open(a.words))
378 words = [dict(w) for w in d["words"] if a.start <= w["s"] < a.end]
379 if not words:
380 die("no words in range")
381 for w in words:
382 w["s"] = round(w["s"] - a.offset, 3)
383 w["e"] = round(w["e"] - a.offset, 3)
384 words = [w for w in words if w["e"] > 0 and w["s"] < dur]
385 vertical = H > W
386 font = pick_font(a.font)
387 cap_px = a.cap or round(H * (CAP_FRAC if vertical else CAP_FRAC_LAND))
388 cap_ratio, wfac, used = calibrate(font)
389 size = round(cap_px / cap_ratio)
390 y = a.y if a.y is not None else (0.62 if vertical else 0.80)
391 safe_l, safe_r = (int(W * 48 / 1080), int(W * 888 / 1080)) if vertical else (int(W * 0.05), int(W * 0.95))
392 if vertical:
393 # centre on the frame; the right rail (buttons) limits the half-width
394 half = min(W / 2 - safe_l, safe_r - W / 2)
395 safe_l, safe_r = int(W / 2 - half), int(W / 2 + half)
396 safe_w = safe_r - safe_l
397 factor = wfac * cap_px * (1.0 if a.case == "upper" else 0.85)
398 max_chars = max(6, int(safe_w * 0.94 / factor)) # estimate, only for the log
399 outline = max(2, round(cap_px * OUTLINE_FRAC))
400 disp = [display(w["w"], a.case) for w in words]
401 pieces = sorted(set(" ".join(disp[i:j]) for i in range(len(disp))
402 for j in range(i + 1, min(len(disp), i + a.max_words) + 1)))
403 fit = Fit(dict(zip(pieces, measure_widths(font, size, outline, pieces))), safe_w * 0.96)
404 cards = make_cards(words, a.max_words, fit, a.case)
405 times = card_times(cards)
406 emph = set(norm(x) for x in a.emphasis.split(",") if x.strip()) if a.emphasis else set()
407 accent = ass_colour(a.accent)
408 shadow = max(1, round(cap_px * SHADOW_FRAC))
409 cx = (safe_l + safe_r) // 2
410 cy = int(H * y)
411 head = ["[Script Info]", "ScriptType: v4.00+", "PlayResX: %d" % W, "PlayResY: %d" % H, "WrapStyle: 0",
412 "ScaledBorderAndShadow: yes", "YCbCr Matrix: TV.709", "",
413 "[V4+ Styles]",
414 "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
415 "Style: Pop,%s,%d,&H00FFFFFF,&H00FFFFFF,&H00000000,&H60000000,-1,0,0,0,100,100,0,0,1,%d,%d,5,%d,%d,0,1"
416 % (font, size, outline, shadow, safe_l, W - safe_r), "",
417 "[Events]", "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"]
418 ev = []
419 rec = []
420 for c, (s, e) in zip(cards, times):
421 stressed = [norm(w["w"]) in emph or "*" in w["w"] for w in c]
422 # one event per word span inside the card, so the active word can change colour
423 spans = []
424 for k, w in enumerate(c):
425 ss = s if k == 0 else w["s"]
426 ee = c[k + 1]["s"] if k + 1 < len(c) else e
427 spans.append((ss, ee, k))
428 if not a.active:
429 spans = [(s, e, -1)]
430 texts_c = [display(w["w"], a.case) for w in c]
431 brk = line_break(texts_c, fit)
432 L1 = fit.w(" ".join(texts_c)) if not brk or brk < 0 else max(fit.w(" ".join(texts_c[:brk])), fit.w(" ".join(texts_c[brk:])))
433 k_sc = min(1.0, fit.limit / max(1, L1))
434 # two lines grow upwards: the bottom line sits where a one-line card would
435 py = cy if not brk or brk < 0 else cy - int(round(size * 0.55))
436 for j, (ss, ee, act) in enumerate(spans):
437 parts = []
438 for k, w in enumerate(c):
439 t = display(w["w"], a.case).replace("{", "(").replace("}", ")")
440 if stressed[k] or (a.active and k == act):
441 t = "{\\c%s&}%s{\\c&HFFFFFF&}" % (accent, t)
442 parts.append(t)
443 pre = "{\\pos(%d,%d)" % (cx, py)
444 sc = lambda v: int(round(v * k_sc))
445 if a.pop and j == 0:
446 pre += "\\fscx%d\\fscy%d\\t(0,90,\\fscx%d\\fscy%d)\\t(90,160,\\fscx%d\\fscy%d)" % (sc(72), sc(72), sc(106), sc(106), sc(100), sc(100))
447 elif k_sc < 1.0:
448 pre += "\\fscx%d\\fscy%d" % (sc(100), sc(100))
449 pre += "}"
450 body = " ".join(parts) if not brk or brk < 0 else " ".join(parts[:brk]) + "\\N" + " ".join(parts[brk:])
451 ev.append("Dialogue: 0,%s,%s,Pop,,0,0,0,,%s%s" % (ass_time(ss), ass_time(ee), pre, body))
452 rec.append({"s": round(s, 3), "e": round(e, 3), "words": [w["w"] for w in c], "word_starts": [w["s"] for w in c],
453 "text": " ".join(display(w["w"], a.case) for w in c),
454 "lines": 2 if brk and brk > 0 else 1, "width_px": round(L1 * k_sc), "scale": round(k_sc, 3), "stressed": [w["w"] for w, st in zip(c, stressed) if st]})
455 base = a.output
456 with open(base + ".ass", "w", encoding="utf-8") as fh:
457 fh.write("\n".join(head + ev) + "\n")
458 with open(base + ".cards.srt", "w", encoding="utf-8") as fh:
459 for k, r in enumerate(rec):
460 fh.write("%d\n%s --> %s\n%s\n\n" % (k + 1, srt_time(r["s"]), srt_time(r["e"]), r["text"]))
461 with open(base + ".srt", "w", encoding="utf-8") as fh:
462 for k, (s, e, lines) in enumerate(sentence_srt(words)):
463 fh.write("%d\n%s --> %s\n%s\n\n" % (k + 1, srt_time(s), srt_time(e), "\n".join(lines)))
464 write_tsx(base + ".tsx", rec, W, H, cap_px, cy, a.accent, a.case, a.pop)
465 meta = {"video": os.path.abspath(a.video), "w": W, "h": H, "fps": fps, "font": font, "font_file": used, "size": size, "cap_px": cap_px, "y": y,
466 "center_px": [cx, cy], "safe_x": [safe_l, safe_r], "max_chars": max_chars, "outline": outline,
467 "accent": a.accent, "active": a.active, "cards": rec}
468 json.dump(meta, open(base + ".cards.json", "w"), indent=1)
469 print("wrote %s.ass, %s.cards.srt, %s.srt, .tsx, %s.cards.json: %d cards, font %s (%s) size %d = capitals %d px, centre y %d (%.2f), safe width %d px"
470 % (base, base, base, base, len(rec), font, used or "?", size, cap_px, cy, y, safe_w))
471 if not a.font and font == "Arial Black":
472 print("note: no preferred heavy font found; using Arial Black. Pass --font to choose.")
473
474
475def write_tsx(path, rec, W, H, cap_px, cy, accent, case, pop):
476 """A Zylcut component with one <text> per card (Montserrat 800, ships with Zylcut)."""
477 fsize = round(cap_px / 0.70)
478 rows = []
479 for r in rec:
480 text = r["text"]
481 ranges = []
482 pos = 0
483 words = text.split(" ")
484 stressed_disp = set(display(w, case) for w in r["stressed"])
485 for w in words:
486 if w in stressed_disp:
487 ranges.append([pos, pos + len(w)])
488 pos += len(w) + 1
489 rows.append(" [%.3f, %.3f, %s, %s]," % (r["s"], r["e"], json.dumps(text), json.dumps(ranges)))
490 pop_track = ("""
491 <keyframeTrack property="scale">
492 <keyframe time={0} value={0.72} easing="easeOut" />
493 <keyframe time={0.09} value={1.06} easing="easeInOut" />
494 <keyframe time={0.16} value={1} />
495 </keyframeTrack>""" if pop else "")
496 tsx = """// Word-pop captions made by wordpop.py: %d cards. Times are seconds of the video file.
497// Use: import WordPop from "./wordpop"; then <WordPop offset={0} /> as the last child of the scene.
498// offset = the scene time at which the file's second 0 plays (start - sourceIn of the clip).
499import { For } from "solid-js";
500
501const W = %d, CENTRE_Y = %d, SIZE = %d, ACCENT = "%s";
502export const cards: [number, number, string, [number, number][]][] = [
503%s
504];
505
506export default function WordPop(props: { offset?: number }) {
507 const off = props.offset ?? 0;
508 return (
509 <group id="word-pop">
510 <For each={cards}>
511 {([s, e, text, accents], i) => (
512 <text id={"pop-" + (i() + 1)} start={s + off} end={e + off} x={0} width={W} textAlign="center"
513 y={CENTRE_Y - Math.round(SIZE * 0.6)} fontFamily="Montserrat" fontWeight={800} fontSize={SIZE} color="#FFFFFF">
514 {text}
515 <stroke width={%d} color="#000000" join="round" />
516 <shadow color="#000000" offsetY={%d} opacity={0.6} />
517 <For each={accents}>{([a, b]) => <textRange start={a} end={b} color={ACCENT} />}</For>%s
518 </text>
519 )}
520 </For>
521 </group>
522 );
523}
524""" % (len(rec), W, cy, fsize, accent, "\n".join(rows), max(2, round(cap_px * OUTLINE_FRAC)) * 2, max(1, round(cap_px * SHADOW_FRAC)), pop_track)
525 with open(path, "w", encoding="utf-8") as fh:
526 fh.write(tsx)
527
528
529def cmd_burn(a):
530 if not shutil.which("ffmpeg"):
531 die("ffmpeg is not on PATH")
532 ass = os.path.abspath(a.ass).replace("\\", "/").replace(":", "\\:").replace("'", "\\'")
533 cmd = ["ffmpeg", "-hide_banner", "-y", "-threads", str(a.threads), "-i", a.input, "-vf", "subtitles='%s'" % ass,
534 "-c:v", "libx264", "-preset", "medium", "-crf", str(a.crf), "-pix_fmt", "yuv420p", "-c:a", "copy",
535 "-movflags", "+faststart", a.output]
536 r = subprocess.run(cmd, capture_output=True, text=True)
537 sel = [l for l in r.stderr.splitlines() if "fontselect" in l]
538 for l in sel[:3]:
539 print(l.strip())
540 if r.returncode != 0:
541 die("ffmpeg failed: " + r.stderr.strip()[-600:])
542 print("wrote " + a.output)
543
544
545def cmd_check(a):
546 m = json.load(open(a.cards))
547 cards = m["cards"]
548 fps = m["fps"] or 30.0
549 frame = 1.0 / fps
550 errs, warns = [], []
551 n = [len(c["words"]) for c in cards]
552 durs = [c["e"] - c["s"] for c in cards]
553 dist = {k: n.count(k) for k in sorted(set(n))}
554 for k, c in enumerate(cards):
555 if len(c["words"]) > 3:
556 errs.append("card %d has %d words: %s" % (k + 1, len(c["words"]), c["text"]))
557 lag = c["s"] - c["word_starts"][0]
558 if lag > frame + 1e-6 or lag < -0.011:
559 errs.append("card %d starts %.3f s from its first word" % (k + 1, lag))
560 sw = m["safe_x"][1] - m["safe_x"][0]
561 if c.get("width_px", 0) > sw:
562 errs.append("card %d is %d px wide, wider than the safe width %d px: %s" % (k + 1, c["width_px"], sw, c["text"]))
563 if c.get("scale", 1) < SHRINK - 0.005:
564 warns.append("card %d is drawn at %d%%: %s" % (k + 1, c["scale"] * 100, c["text"]))
565 if c["e"] - c["s"] < 0.2:
566 warns.append("card %d shows only %.2f s: %s" % (k + 1, c["e"] - c["s"], c["text"]))
567 if k + 1 < len(cards) and cards[k + 1]["s"] < c["e"] - 1e-6:
568 errs.append("card %d overlaps the next" % (k + 1))
569 span = cards[-1]["e"] - cards[0]["s"] if cards else 1
570 wps = sum(n) / span if span > 0 else 0
571 if wps > 5.5:
572 warns.append("%.1f words per second on screen, above about 5" % wps)
573 h = m["h"]
574 top = m["center_px"][1] - m["cap_px"] * 0.75
575 bot = m["center_px"][1] + m["cap_px"] * 0.75
576 if m["h"] > m["w"] and (top < h * 288 / 1920 or bot > h * 1248 / 1920):
577 errs.append("caption line y %d-%d leaves the vertical safe zone (y %d-%d)" % (top, bot, h * 288 // 1920, h * 1248 // 1920))
578 stressed = sum(1 for c in cards if c["stressed"])
579 print("cards %d | words per card %s | median card %.2f s | shortest %.2f s | %.2f words/s | stressed cards %d | font %s capitals %d px at y %d"
580 % (len(cards), dist, sorted(durs)[len(durs) // 2] if durs else 0, min(durs) if durs else 0, wps, stressed, m["font"], m["cap_px"], m["center_px"][1]))
581 for w in warns:
582 print("WARNING " + w)
583 for e in errs:
584 print("ERROR " + e)
585 print("%d error(s), %d warning(s)" % (len(errs), len(warns)))
586 sys.exit(1 if errs else 0)
587
588
589def cmd_sheet(a):
590 m = json.load(open(a.cards))
591 cards = m["cards"]
592 if not cards:
593 die("no cards")
594 step = max(1, len(cards) // a.n)
595 pick = cards[::step][:a.n]
596 W, H = m["w"], m["h"]
597 tw = 270 if H > W else 480
598 th = int(tw * H / W) // 2 * 2
599 tmp = os.path.splitext(a.sheet)[0] + "_tiles"
600 os.makedirs(tmp, exist_ok=True)
601 sy0, sy1 = (int(H * 288 / 1920), int(H * 1248 / 1920)) if H > W else (int(H * 0.05), int(H * 0.95))
602 sx0, sx1 = m["safe_x"]
603 files = []
604 for k, c in enumerate(pick):
605 t = c["s"] + 0.1
606 f = os.path.join(tmp, "%02d.png" % k)
607 vf = ("drawbox=x=%d:y=%d:w=%d:h=%d:color=cyan@0.8:t=4,scale=%d:%d,drawtext=text='%.2f':x=6:y=6:fontsize=20:fontcolor=white:box=1:boxcolor=black@0.6"
608 % (sx0, sy0, sx1 - sx0, sy1 - sy0, tw, th, t))
609 subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", "%.3f" % t, "-i", a.video, "-frames:v", "1", "-vf", vf, f])
610 if os.path.exists(f):
611 files.append(f)
612 cols = min(6, len(files))
613 rows = (len(files) + cols - 1) // cols
614 inputs = []
615 for f in files:
616 inputs += ["-i", f]
617 lay = "|".join("%d_%d" % ((i % cols) * tw, (i // cols) * th) for i in range(len(files)))
618 flt = "".join("[%d:v]" % i for i in range(len(files))) + "xstack=inputs=%d:layout=%s:fill=black" % (len(files), lay) if len(files) > 1 else "null"
619 subprocess.run(["ffmpeg", "-v", "error", "-y"] + inputs + ["-filter_complex", flt, "-frames:v", "1", "-q:v", "4", a.sheet])
620 shutil.rmtree(tmp, ignore_errors=True)
621 print("wrote %s (%d frames, safe zone in cyan)" % (a.sheet, len(files)))
622
623
624def main():
625 p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
626 sub = p.add_subparsers(dest="cmd", required=True)
627 b = sub.add_parser("build")
628 b.add_argument("words")
629 b.add_argument("--video", required=True)
630 b.add_argument("-o", "--output", default="captions")
631 b.add_argument("--emphasis", default="")
632 b.add_argument("--accent", default="#FFB21E")
633 b.add_argument("--active", action="store_true")
634 b.add_argument("--font")
635 b.add_argument("--cap", type=int)
636 b.add_argument("--y", type=float)
637 b.add_argument("--max-words", type=int, default=3)
638 b.add_argument("--case", choices=["upper", "asis"], default="upper")
639 b.add_argument("--pop", dest="pop", action="store_true", default=True)
640 b.add_argument("--no-pop", dest="pop", action="store_false")
641 b.add_argument("--from", dest="start", type=float, default=0.0)
642 b.add_argument("--to", dest="end", type=float, default=1e9)
643 b.add_argument("--offset", type=float, default=0.0)
644 u = sub.add_parser("burn")
645 u.add_argument("input")
646 u.add_argument("ass")
647 u.add_argument("output")
648 u.add_argument("--crf", type=int, default=20)
649 u.add_argument("--threads", type=int, default=4)
650 c = sub.add_parser("check")
651 c.add_argument("cards")
652 c.add_argument("words", nargs="?")
653 s = sub.add_parser("sheet")
654 s.add_argument("video")
655 s.add_argument("cards")
656 s.add_argument("sheet")
657 s.add_argument("--n", type=int, default=12)
658 a = p.parse_args()
659 {"build": cmd_build, "burn": cmd_burn, "check": cmd_check, "sheet": cmd_sheet}[a.cmd](a)
660
661
662if __name__ == "__main__":
663 main()
664
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//".
14
15words.json holds {source, duration, words:[{i,w,s,e}], sentences:[{i,s,e,w0,w1,text}],
16silences:[[s,e]], floor_db, speech_db}. Times are seconds of the input file.
17Word edges are moved onto the sound: a word ends where the level drops into a silence and
18starts where it rises out of one, so a cut on a word edge never clips the word.
19
20Standard library only. Needs ffmpeg on PATH; transcribe also needs whisper-cli.
21"""
22
23import argparse
24import array
25import json
26import math
27import os
28import shutil
29import subprocess
30import sys
31import tempfile
32
33FRAME = 0.01 # level frames of 10 ms
34RATE = 16000
35
36
37def die(msg):
38 print("error: " + msg, file=sys.stderr)
39 sys.exit(2)
40
41
42def find_model(explicit):
43 if explicit:
44 if not os.path.exists(explicit):
45 die("model not found: " + explicit)
46 return explicit
47 env = os.environ.get("WHISPER_MODEL")
48 if env and os.path.exists(env):
49 return env
50 home = os.path.expanduser("~")
51 names = ["ggml-small.en.bin", "ggml-base.en.bin", "ggml-medium.en.bin", "ggml-small.bin", "ggml-base.bin"]
52 dirs = [os.path.join(home, ".cache", "whisper"), os.path.join(home, ".cache", "whisper.cpp"),
53 "models", os.path.join(home, "whisper.cpp", "models"), "/opt/homebrew/share/whisper-cpp",
54 "/usr/local/share/whisper-cpp"]
55 for d in dirs:
56 for n in names:
57 p = os.path.join(d, n)
58 if os.path.exists(p):
59 return p
60 die("no whisper model found. Pass --model /path/to/ggml-small.en.bin or set WHISPER_MODEL. "
61 "Models come from the whisper.cpp project (ggml-small.en.bin is a good default).")
62
63
64def decode_wav(inp, wav):
65 if not shutil.which("ffmpeg"):
66 die("ffmpeg is not on PATH")
67 r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", inp, "-vn", "-ac", "1", "-ar", str(RATE),
68 "-c:a", "pcm_s16le", wav], capture_output=True, text=True)
69 if r.returncode != 0:
70 die("ffmpeg could not read %s: %s" % (inp, r.stderr.strip()[-400:]))
71
72
73def levels(wav):
74 """dB level of every 10 ms frame of a 16 kHz mono s16 WAV."""
75 with open(wav, "rb") as fh:
76 data = fh.read()
77 # skip the RIFF header: find the "data" chunk
78 pos = data.find(b"data")
79 if pos < 0:
80 die("bad WAV file")
81 pcm = array.array("h")
82 pcm.frombytes(data[pos + 8:pos + 8 + ((len(data) - pos - 8) // 2) * 2])
83 if sys.byteorder == "big":
84 pcm.byteswap()
85 n = int(RATE * FRAME)
86 out = []
87 for k in range(0, len(pcm) - n + 1, n):
88 seg = pcm[k:k + n]
89 ms = sum(x * x for x in seg) / n
90 out.append(10 * math.log10(ms / (32768.0 ** 2) + 1e-12))
91 return out
92
93
94def silences_from_levels(db):
95 """Silent runs of 0.12 s or more, with the threshold set between the noise floor and the voice."""
96 if not db:
97 return [], -90.0, -20.0
98 srt = sorted(db)
99 floor = srt[int(len(srt) * 0.10)]
100 speech = srt[int(len(srt) * 0.90)]
101 thr = max(floor + 6.0, speech - 30.0)
102 thr = min(thr, speech - 12.0) if speech - floor > 18 else (floor + speech) / 2
103 out = []
104 start = None
105 for i, v in enumerate(db + [999.0]):
106 if v < thr:
107 if start is None:
108 start = i
109 else:
110 if start is not None and (i - start) * FRAME >= 0.12:
111 out.append([round(start * FRAME, 3), round(i * FRAME, 3)])
112 start = None
113 return out, round(floor, 1), round(speech, 1)
114
115
116def snap_words(words, sil):
117 """Move word edges onto the sound using the silence list."""
118 def nearest(t, edges, win):
119 best = None
120 for x in edges:
121 if abs(x - t) <= win and (best is None or abs(x - t) < abs(best - t)):
122 best = x
123 return best
124 starts = [s for s, e in sil] # where sound stops
125 ends = [e for s, e in sil] # where sound starts again
126 for w in words:
127 e = nearest(w["e"], starts, 0.30)
128 if e is not None and e > w["s"] + 0.04:
129 w["e"] = round(e + 0.03, 3)
130 s = nearest(w["s"], ends, 0.30)
131 if s is not None and s < w["e"] - 0.04:
132 w["s"] = round(max(0.0, s - 0.03), 3)
133 for a, b in zip(words, words[1:]):
134 if b["s"] < a["e"]:
135 mid = round((a["e"] + b["s"]) / 2, 3)
136 a["e"], b["s"] = mid, mid
137 return words
138
139
140def sentences(words, sil):
141 out = []
142 w0 = 0
143 for i, w in enumerate(words):
144 end = w["w"].rstrip('"\')]').endswith((".", "?", "!"))
145 gap = words[i + 1]["s"] - w["e"] if i + 1 < len(words) else 0
146 if end or gap >= 0.9 or i == len(words) - 1:
147 seg = words[w0:i + 1]
148 out.append({"i": len(out), "s": seg[0]["s"], "e": seg[-1]["e"], "w0": w0, "w1": i,
149 "text": " ".join(x["w"] for x in seg)})
150 w0 = i + 1
151 return out
152
153
154def from_whisper_cli(d):
155 words = []
156 for seg in d.get("transcription", []):
157 toks = [t for t in seg.get("tokens", []) if not t.get("text", "").startswith("[_")]
158 text = seg.get("text", "").strip()
159 if not text or text.startswith("[") or text.startswith("("):
160 continue
161 s = seg["offsets"]["from"] / 1000.0
162 e = seg["offsets"]["to"] / 1000.0
163 if toks: # the last token's end is where the word's sound ends; the segment runs on to the next word
164 e = max(s + 0.05, toks[-1]["offsets"]["to"] / 1000.0)
165 if words and not seg.get("text", "").startswith(" "):
166 words[-1]["w"] += text # a split piece such as "n't" or "%"
167 words[-1]["e"] = e
168 continue
169 words.append({"w": text, "s": s, "e": e})
170 return words
171
172
173def from_segments(d):
174 segs = d.get("segments", d if isinstance(d, list) else [])
175 words = []
176 for seg in segs:
177 for w in seg.get("words", []):
178 t = (w.get("text") or w.get("word") or "").strip()
179 if t:
180 rec = {"w": t, "s": float(w["start"]), "e": float(w["end"])}
181 spk = w.get("speaker", seg.get("speaker"))
182 if spk is not None:
183 rec["spk"] = spk
184 words.append(rec)
185 return words
186
187
188def finish(words, wav, source, out):
189 words = [w for w in words if w["e"] > w["s"]]
190 words.sort(key=lambda w: w["s"])
191 if wav:
192 db = levels(wav)
193 sil, floor, speech = silences_from_levels(db)
194 words = snap_words(words, sil)
195 duration = round(len(db) * FRAME, 2)
196 else:
197 sil, floor, speech = [], None, None
198 duration = round(words[-1]["e"], 2) if words else 0.0
199 for i, w in enumerate(words):
200 w["i"] = i
201 w["s"] = round(w["s"], 3)
202 w["e"] = round(w["e"], 3)
203 res = {"source": os.path.abspath(source) if source else None, "duration": duration,
204 "floor_db": floor, "speech_db": speech,
205 "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],
206 "sentences": sentences(words, sil), "silences": sil}
207 with open(out, "w") as fh:
208 json.dump(res, fh, indent=0)
209 print("wrote %s: %d words, %d sentences, %d silences, %.1f s" % (out, len(words), len(res["sentences"]), len(sil), res["duration"]))
210
211
212def cmd_transcribe(a):
213 if not shutil.which("whisper-cli"):
214 die("whisper-cli (whisper.cpp) is not on PATH. Install it (brew install whisper-cpp, or build "
215 "whisper.cpp) or transcribe with any word-timed tool and run 'words.py import'.")
216 model = find_model(a.model)
217 tmp = tempfile.mkdtemp(prefix="words-")
218 wav = os.path.join(tmp, "a.wav")
219 decode_wav(a.input, wav)
220 base = os.path.join(tmp, "w")
221 r = subprocess.run(["whisper-cli", "-m", model, "-f", wav, "-ojf", "-ml", "1", "-sow", "-t", str(a.threads),
222 "-of", base] + (["-l", a.language] if a.language else []), capture_output=True, text=True)
223 if r.returncode != 0 or not os.path.exists(base + ".json"):
224 die("whisper-cli failed: " + r.stderr.strip()[-400:])
225 with open(base + ".json", "rb") as fh:
226 d = json.loads(fh.read().decode("utf-8", "replace"))
227 finish(from_whisper_cli(d), wav, a.input, a.output)
228 shutil.rmtree(tmp, ignore_errors=True)
229
230
231def cmd_import(a):
232 with open(a.transcript, "rb") as fh:
233 d = json.loads(fh.read().decode("utf-8", "replace"))
234 words = from_whisper_cli(d) if isinstance(d, dict) and "transcription" in d else from_segments(d)
235 if not words:
236 die("no word timings found in " + a.transcript)
237 if not a.audio:
238 finish(words, None, None, a.output)
239 return
240 tmp = tempfile.mkdtemp(prefix="words-")
241 wav = os.path.join(tmp, "a.wav")
242 decode_wav(a.audio, wav)
243 finish(words, wav, a.audio, a.output)
244 shutil.rmtree(tmp, ignore_errors=True)
245
246
247def cmd_show(a):
248 with open(a.words) as fh:
249 d = json.load(fh)
250 W = d["words"]
251 for s in d["sentences"]:
252 if s["e"] < a.start or s["s"] > a.end:
253 continue
254 parts = []
255 for k in range(s["w0"], s["w1"] + 1):
256 parts.append(W[k]["w"])
257 if k < s["w1"] and W[k + 1]["s"] - W[k]["e"] >= 0.4:
258 parts.append("//%.1fs//" % (W[k + 1]["s"] - W[k]["e"]))
259 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)))
260
261
262def main():
263 p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
264 sub = p.add_subparsers(dest="cmd", required=True)
265 t = sub.add_parser("transcribe")
266 t.add_argument("input")
267 t.add_argument("-o", "--output", default="words.json")
268 t.add_argument("--model")
269 t.add_argument("--threads", type=int, default=4)
270 t.add_argument("--language", help="two-letter code for a multilingual model (default: the model's own)")
271 i = sub.add_parser("import")
272 i.add_argument("transcript")
273 i.add_argument("--audio")
274 i.add_argument("-o", "--output", default="words.json")
275 s = sub.add_parser("show")
276 s.add_argument("words")
277 s.add_argument("--from", dest="start", type=float, default=0.0)
278 s.add_argument("--to", dest="end", type=float, default=1e9)
279 a = p.parse_args()
280 {"transcribe": cmd_transcribe, "import": cmd_import, "show": cmd_show}[a.cmd](a)
281
282
283if __name__ == "__main__":
284 main()
285
Reviews
No reviews yet. Installed it? Tell others how it went.
Versions
- v1.0.0First version25 Nov 2026
More for captions
Broadcast Subtitles
NewTV-standard SRT, VTT and burned-in subtitles, checked line by line by a linter
Podcast, Talking headSRT or VTT, 16:9 video
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