Active-Speaker Vertical Cut
Turns a two-person 16:9 podcast into a 9:16 cut that keeps the frame on whoever talks
Before: 60 s of a two-person podcast that is already a multi-camera edit (close-ups and wide shots).. 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 active-speaker-cut skill on podcast.mp4. Make it vertical for Reels and keep the frame on whoever is talking. Just do it.
Recipe
- 1Transcribe with word times
- 2Map the source's shots and where each face sits
- 3Label every turn of speech with its speaker
- 4Plan framings: switches, listener reactions, punch-ins
- 5Render, then check a frame after every framing change and fix
About
Reframes a landscape two-person podcast or interview for Reels, TikTok and Shorts. The frame holds one face at a time and switches to the new speaker in the gap before their first word, never inside a word. The source's own camera cuts are kept, wide shots are cropped tight on the speaker, the listener gets the frame through silences in wide shots, and long holds alternate between a normal and a slightly closer crop at sentence ends. All changes are hard cuts with no pans.
The numbers come from measuring 16 two-person vertical clips of large podcast channels frame by frame: one face on screen 95% of the time, the face centred at x 0.49 and y 0.32, about 16 framing changes and 4.7 speaker switches a minute. The agent labels each turn, checks a frame after every framing change against centre guides (face centred, eyes near the upper third, headroom, mouth clear of the mic) and fixes the layout until every frame passes. The original audio is left untouched.
Limits: on the generic path speakers are labelled from the transcript and the picture, not by voice, so a listener's short interjection can stay on the speaker. Crops from 1080p wide shots are soft. Two speakers only.
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.
Active-speaker cut
A vertical cut of a two-person conversation where the frame is always on the person talking, the way large podcast channels cut their Shorts: one face, centred, hard cuts that land on the new speaker's first word, and no flicker on short replies. The measurements behind every value 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
- A landscape recording of two people: one wide camera, a multi-camera edit (wides and close-ups), or a side-by-side video call.
- Not for one person (crop once on the face) or three or more (the rules here assume two).
Inputs
- The recording (or a range of it). Optional: who is who (names), a range, captions to add after (a caption skill does that on the finished vertical video).
Approval gate
Before rendering, tell the user in five lines or fewer: the input (size, length, range), the people as you named them (left and right), how many speaker switches the plan has, and the output (1080x1920 MP4, audio untouched). 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 the file. Check: landscape, two people, the range is right.
- Transcribe with word times (with speaker labels on the Zylcut path). Check: the words read like the conversation.
- Layout: find the source's camera cuts and fill each shot's face centres, names and face height from the ruler sheet. Check: every shot filled; the same person has the same name everywhere; values are face centres, not body centres.
- Label every turn with its speaker: voice labels where you have them, then your own reading of the conversation (questions and answers, the close-up the source shows during the turn, a frame when unsure). Picture motion is a hint only. Check: read the turn table top to bottom; it matches who says what.
- Plan the crop (speaker switches, listener reactions in wide shots, punch-ins on long holds). Check: switches per minute plausible (median 4.7, up to about 12), framing changes about 10-25 a minute, no framing under 1.5 s except where the source itself cuts.
- Render (or write the Zylcut
<video>). Check: same duration as the range, audio intact. - Check and look: 0 switches inside a word; a frame after every framing change shows one whole face on the centre line, eyes near the one-third line, nobody cut off by the edge, the mouth not behind the mic, headroom above the hair, no stray object at an edge. Fix the layout and re-plan until every frame passes; never ship an off-centre face.
Final values
| Rule | Value |
|---|---|
| Output | 1080x1920, H.264, source audio untouched (no re-mix, no cuts in time) |
| Framing | one face; centre x at the frame's centre; face centre at about 0.32 of the height in wide shots |
| Close-up in the source | frame the person in it (the source already chose the speaker) |
| Wide shot in the source | crop on the speaker's face, 2.2x tighter than full height |
| Listener reactions | in a wide shot, a silence of 1.2 s or more shows the listener; during a long monologue the listener gets about 2 s at a sentence end, at most once every 8 s |
| Punch-ins | a framing held over 4.5 s alternates 1.0x and 1.2x every 3-4.5 s, at a sentence end, else a clause end, else the longest pause (hard cuts) |
| Switch point | in the gap before the new speaker's first word; never inside a word |
| Shortest framing | 1.5 s, except framings that both start and end on source camera cuts; a shorter one joins its neighbour |
| Close-up in the source (size) | cropped 1.15x so the face is larger, as in the references |
| Short replies | 2 words or fewer ("yeah", "right") keep the current framing |
| Motion | none inside a framing: hard cuts only, no pans, no slow zooms |
Gotchas
- Face, not body: a crop on the body centre cuts the head off when the person leans; read the face on the ruler.
- In a wide two-shot the person on the right of the source is often turned toward the left: put the centre on the face itself, not on the space the head faces.
- Voice labels are per call and can swap; confirm who is A with a frame before planning.
- Laughs, coughs and cross-talk get labelled as speech: a turn of laughter is a short reply, not a switch.
- Whisper can mishear a name; it does not matter for framing, but fix it before captioning.
- Never move a switch into a word to "land on the beat": a cut inside a word is the first thing a viewer notices.
Limits
- No face detector in the scripts: face positions come from the ruler sheet, read by eye.
- Two speakers only; overlapping speech keeps whoever held the frame.
- Listener reactions need a wide shot with both people in it; in a source made only of close-ups, the source's own choice of close-up stands.
- A 2.2x crop of a 1080p wide shot is soft (about 490 px of source height fills 1920); lower it
with
--wide-zoom 1.8when sharpness matters more than face size. - On the generic path speakers are labelled from the transcript and the picture, not by voice, so short interjections from the listener ("Oh, Jesus", "Thank you") can be given to the speaker. Where the source shows a close-up, the frame follows it anyway; the Zylcut path labels turns by voice.
- Close-ups are cropped 1.15x, so faces reach about 0.20 of the frame height against 0.28 in the references; tighter crops of a 1080p source turn soft. Punch-ins are a gentle 1.2x.
Files
7 files, 67 KB. Nothing in a skill runs until your agent runs it.
1---
2name: active-speaker-cut
3description: Turn a landscape two-person podcast or interview into a vertical 9:16 video that always frames whoever is talking - one face filling the frame, hard cuts in the gap before the new speaker's first word (never inside a word), each framing held at least 1.5 s, one- and two-word replies ignored so the picture never jitters, wide shots cropped tight on the speaker, the source audio untouched. Use when the user wants a podcast, interview or two-camera conversation reframed for TikTok, Reels or Shorts, says "make it vertical and follow the speaker", "crop to whoever is talking", "active speaker", "auto reframe my podcast", or has a 16:9 conversation that needs a 9:16 version. Not for one-person talking heads (a single face crop) or for picking which clips to post.
4license: Apache-2.0
5compatibility: Generic path needs Python 3.8+, ffmpeg and ffprobe, and whisper.cpp whisper-cli (or any word-timed transcript). Zylcut path uses the Zylcut MCP tools. Scripts are standard library only; there is no face detector, so face positions are read off a ruler sheet.
6metadata:
7 version: "1.0.0"
8 author: Zylcut
9 outcome: podcast-clips
10---
11
12# Active-speaker cut
13
14A vertical cut of a two-person conversation where the frame is always on the person talking,
15the way large podcast channels cut their Shorts: one face, centred, hard cuts that land on the
16new speaker's first word, and no flicker on short replies. The measurements behind every value
17are 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- A landscape recording of two people: one wide camera, a multi-camera edit (wides and
26 close-ups), or a side-by-side video call.
27- Not for one person (crop once on the face) or three or more (the rules here assume two).
28
29## Inputs
30
31- The recording (or a range of it). Optional: who is who (names), a range, captions to add after
32 (a caption skill does that on the finished vertical video).
33
34## Approval gate
35
36Before rendering, tell the user in five lines or fewer: the input (size, length, range), the
37people as you named them (left and right), how many speaker switches the plan has, and the
38output (1080x1920 MP4, audio untouched). Wait for a yes, unless the user said "just do it" or
39equivalent.
40
41## Pipeline
42
43Every step ends with its check; do not continue past a failed one.
44
451. **Probe** the file. Check: landscape, two people, the range is right.
462. **Transcribe with word times** (with speaker labels on the Zylcut path). Check: the words read
47 like the conversation.
483. **Layout**: find the source's camera cuts and fill each shot's face centres, names and face
49 height from the ruler sheet. Check: every shot filled; the same person has the same name
50 everywhere; values are face centres, not body centres.
514. **Label every turn** with its speaker: voice labels where you have them, then your own reading
52 of the conversation (questions and answers, the close-up the source shows during the turn, a
53 frame when unsure). Picture motion is a hint only. Check: read the turn table top to bottom;
54 it matches who says what.
555. **Plan** the crop (speaker switches, listener reactions in wide shots, punch-ins on long
56 holds). Check: switches per minute plausible (median 4.7, up to about 12), framing changes
57 about 10-25 a minute, no framing under 1.5 s except where the source itself cuts.
586. **Render** (or write the Zylcut `<video>`). Check: same duration as the range, audio intact.
597. **Check and look**: 0 switches inside a word; a frame after every framing change shows one
60 whole face on the centre line, eyes near the one-third line, nobody cut off by the edge, the
61 mouth not behind the mic, headroom above the hair, no stray object at an edge. Fix the layout and re-plan until every frame passes; never ship
62 an off-centre face.
63
64## Final values
65
66| Rule | Value |
67|---|---|
68| Output | 1080x1920, H.264, source audio untouched (no re-mix, no cuts in time) |
69| Framing | one face; centre x at the frame's centre; face centre at about 0.32 of the height in wide shots |
70| Close-up in the source | frame the person in it (the source already chose the speaker) |
71| Wide shot in the source | crop on the speaker's face, 2.2x tighter than full height |
72| Listener reactions | in a wide shot, a silence of 1.2 s or more shows the listener; during a long monologue the listener gets about 2 s at a sentence end, at most once every 8 s |
73| Punch-ins | a framing held over 4.5 s alternates 1.0x and 1.2x every 3-4.5 s, at a sentence end, else a clause end, else the longest pause (hard cuts) |
74| Switch point | in the gap before the new speaker's first word; never inside a word |
75| Shortest framing | 1.5 s, except framings that both start and end on source camera cuts; a shorter one joins its neighbour |
76| Close-up in the source (size) | cropped 1.15x so the face is larger, as in the references |
77| Short replies | 2 words or fewer ("yeah", "right") keep the current framing |
78| Motion | none inside a framing: hard cuts only, no pans, no slow zooms |
79
80## Gotchas
81
82- Face, not body: a crop on the body centre cuts the head off when the person leans; read the
83 face on the ruler.
84- In a wide two-shot the person on the right of the source is often turned toward the left: put
85 the centre on the face itself, not on the space the head faces.
86- Voice labels are per call and can swap; confirm who is A with a frame before planning.
87- Laughs, coughs and cross-talk get labelled as speech: a turn of laughter is a short reply, not a
88 switch.
89- Whisper can mishear a name; it does not matter for framing, but fix it before captioning.
90- Never move a switch into a word to "land on the beat": a cut inside a word is the first thing a
91 viewer notices.
92
93## Limits
94
95- No face detector in the scripts: face positions come from the ruler sheet, read by eye.
96- Two speakers only; overlapping speech keeps whoever held the frame.
97- Listener reactions need a wide shot with both people in it; in a source made only of
98 close-ups, the source's own choice of close-up stands.
99- A 2.2x crop of a 1080p wide shot is soft (about 490 px of source height fills 1920); lower it
100 with `--wide-zoom 1.8` when sharpness matters more than face size.
101- On the generic path speakers are labelled from the transcript and the picture, not by voice,
102 so short interjections from the listener ("Oh, Jesus", "Thank you") can be given to the
103 speaker. Where the source shows a close-up, the frame follows it anyway; the Zylcut path
104 labels turns by voice.
105- Close-ups are cropped 1.15x, so faces reach about 0.20 of the frame height against 0.28 in
106 the references; tighter crops of a 1080p source turn soft. Punch-ins are a gentle 1.2x.
107
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. Scripts: `scripts/words.py` and
4`scripts/speakercut.py` (Python 3.8+, standard library only, ffmpeg and ffprobe on PATH).
5
6## Steps
7
81. **Probe** the file (`ffprobe`): size, frame rate, duration. Check: it is landscape and has
9 two people. For a part of a long recording, pass `--from S --to S` to `layout` and cut the
10 same range everywhere.
112. **Transcribe**: `python3 scripts/words.py transcribe IN.mp4 -o words.json` (whisper.cpp
12 `whisper-cli` on PATH; `--model` for another ggml model, `--language xx` with a multilingual
13 one). Check: `python3 scripts/words.py show words.json` reads like the conversation.
143. **Layout**: `python3 scripts/speakercut.py layout IN.mp4 -o layout.json`. It finds the source's
15 own camera cuts and writes `layout.jpg`: one frame per shot with a width ruler (yellow, 0-100)
16 and a height ruler (cyan). Open the image and edit `layout.json`, one entry per shot:
17 - `people`: the horizontal centre of each visible **face** (not the body), 0-1, left to right,
18 read off the ruler to the nearest 0.01. One number for a close-up, two for a two-shot.
19 - `names`: one stable name per person, the same in every shot ("A" = the person on the left
20 of the wide shot, "B" = the right).
21 - `face_y` (optional, recommended for wide shots): the face centre's height, 0-1, one number
22 per person or one for all. Without it a wide shot is cropped from the upper part.
23 - `zoom` (optional): crop tightness for that shot; defaults are 1.0 for one person and 2.2
24 for two or more.
25 Check: every shot has people and names; the same person has the same name everywhere.
264. **Who speaks, turn by turn**: `python3 scripts/speakercut.py activity IN.mp4 layout.json -o act.json`
27 then `python3 scripts/speakercut.py plan words.json layout.json --activity act.json -o plan.json`.
28 It prints numbered turns with a guess from picture motion (`src motion`, `conf` above about 2
29 is a strong guess). The guess is a hint, not the answer. Decide each turn yourself:
30 - from the words: who asks and who answers, who tells the story, who says "you" to whom;
31 - from the source: in an edited multi-camera recording the close-up on screen during a turn
32 is nearly always the speaker (check `layout.jpg` for the shot covering it);
33 - from a frame when still unsure: `ffmpeg -ss T -i IN.mp4 -frames:v 1 f.jpg` at the turn's
34 middle and look at whose mouth is open.
35 Then re-run `plan` with every turn set: `--set '{"0":"A","1":"B",...}'` (turn numbers as
36 printed). Check: the printed table matches the conversation; the speaker switches per minute
37 are plausible (references: median 4.7, up to about 12).
385. **Render**: `python3 scripts/speakercut.py render IN.mp4 plan.json -o OUT.mp4` (1080x1920,
39 H.264, the source audio untouched).
406. **Check**: `python3 scripts/speakercut.py check plan.json words.json --video OUT.mp4 --sheet sheet.jpg`.
41 Check: 0 errors (no switch of ours inside a word; a source camera cut that falls inside a
42 word is reported and cannot move). Open `sheet.jpg` (one frame per framing, cyan lines at the
43 centre and at one third of the height) and fix every framing where:
44 - the face centre is more than about a tenth of the frame width off the vertical line: change
45 that shot's `people` value for that person by the same amount (source width = crop width x
46 2.2 in wide shots, x 1.15 in close-ups, so a miss of 0.2 of the vertical frame is about
47 0.03 of the source width in a wide shot and 0.05 in a close-up);
48 - the eyes are far from the horizontal line: set or change that shot's `face_y`;
49 - the mic or a hand covers the mouth in a wide-shot crop: move the centre a little toward the
50 uncovered side;
51 - the hair touches the top edge (lower the eyes with a larger `face_y`), or a stray object
52 pokes in at a side edge (shift the centre away from it).
53 Then repeat 4-6 (re-run `plan` with the same `--set`). Two rounds are usually enough.
54
55## Notes
56
57- A source with camera cuts keeps them: the crop changes on the source's cuts as well as on
58 speaker switches, and a close-up always frames the person in it.
59- A single static wide shot (one camera on two people) is the case where speaker choice matters
60 most: every framing comes from the turn labels, so label every turn.
61- `--min-hold 1.5` (seconds a framing stays at least) and `--short 2` (replies of this many words
62 or fewer never take the frame) are the measured defaults. `--react-every 8` (listener
63 reactions in wide shots, 0 = off), `--punch 1.2 --max-hold 4.5` (punch-ins on long holds, 1 =
64 off) and `--wide-zoom 2.2` set the rest.
65
1# Active-speaker framing: reference measurements
2
3Measured on 16 two-person vertical podcast clips (720x1280, from 21 clips of large podcast
4channels, 65k to 6.4M views; 5 clips with 3+ people left out), at full frame rate: cuts by two
5detectors (colour histogram plus pixel change, and ffmpeg's scene score), faces by a YuNet face
6detector, identity by face embeddings, and speakers by a per-clip voice model trained on long
7single-person shots (held-out accuracy 0.89-1.00 in the 6 clips used for timing).
8
9## Numbers (min / median / p90 / max over clips)
10
11| Metric | min | median | p90 | max |
12|---|---|---|---|---|
13| Framing changes per minute | 4.0 | 16.3 | 26.8 | 28.0 |
14| Speaker switches per minute | 0 | 4.7 | 11.8 | 14.4 |
15| Shortest face shot per clip (s) | 0.08 | 0.85 | 1.43 | 8.3 |
16| Median face shot (s) | 1.2 | 2.6 | 6.9 | 9.3 |
17| Time on a single face (share) | 0.65 | 0.95 | 1.0 | 1.0 |
18| Two-shot time (share) | 0 | 0 | 0 | 0.04 |
19| Face centre x (fraction of width) | 0.42 | 0.49 | 0.52 | 0.62 |
20| Face centre y (fraction of height) | 0.24 | 0.32 | 0.34 | 0.34 |
21| Face height (fraction of height) | 0.15 | 0.28 | 0.35 | 0.36 |
22| Zoom inside a shot (last / first face height) | 0.97 | 1.00 | 1.05 | 1.16 |
23| On-screen person is the one speaking (share, 6 clips) | 0.85 | 0.99 | 0.99 | 1.0 |
24| Switch time vs the new speaker's first word (frames, pooled, + = late) | -14 | +0.15 | +11 | +42 |
25
26Cut types over 521 cuts: reframe of the same person 34%, speaker switch 29%, to or from B-roll
2723%, same-framing jump cut 11%, layout change 4%.
28
29## What the numbers mean for the skill
30
311. **One face fills the frame**: single-face hard cuts, almost never a two-shot. The face sits
32 centred (x 0.49), its centre at about 0.32 of the height, its height about 0.28 of the frame.
332. **The picture follows the voice**: 99% of the time the person on screen is the one talking.
34 The switch lands on the new speaker's first word (median within one frame); the skill cuts in
35 the gap just before it, never inside a word.
363. **Holds**: a median face shot of 2.6 s, rarely under 0.85 s. The skill holds each framing at
37 least 1.5 s and does not cut away for a reply of one or two words ("yeah", "right").
384. **No moving crop**: there is no pan between speakers; the crop is still inside a shot and
39 changes by a hard cut. The small motion seen inside shots comes from the source cameras.
405. **Wide shots get cropped tighter** on the speaker's face (2.2x), so a face in a wide
41 two-shot gets closer to the close-up size.
426. **Listeners and reframes are part of the cut**: up to about half the speaker-switch cuts in
43 some clips go to a listener with no new speaker within 2 s, and 34% of all cuts reframe the
44 same person. The skill shows the listener through silences and once every 8 s or so of a long
45 monologue in wide shots, and alternates 1.0x and 1.2x on any framing held over 5 s.
46
47Not copied from the references: B-roll inserts, which are editing choices beyond a reframe.
48
1# Zylcut path
2
3Use this when Zylcut MCP tools are available. Zylcut labels speakers while it transcribes, and
4the crop becomes a `<video>` with stepped keyframes in the project, so the user can adjust any
5framing in the editor. Read the in-app **zylcut-editor** skill first if you have not this session.
6
7## Steps
8
91. **Open the project** (`open` with the project folder; for a loose file, make a project folder
10 under the user's chosen place), read `index.tsx`, take a `user_edits` baseline and read
11 `notes`. `media_probe` the recording.
122. **Transcribe with speakers**: `media_transcribe` with `speakers: 2` and `output` under the
13 project's `assets/transcripts/`. Convert: `python3 scripts/words.py import <that file> -o words.json`
14 (the `speaker` labels are kept as `spk`). The labels A and B are in the order first heard;
15 find out who is who with `media_grab` at a turn of each label.
163. **Layout**: `python3 scripts/speakercut.py layout <recording> -o layout.json` and fill it from
17 `layout.jpg` as in [ffmpeg.md](ffmpeg.md) step 3 (face centres, names, `face_y`). Name the
18 people with the same letters the transcript uses once you know who is who, or map them with
19 `--map '{"A":"B","B":"A"}'` in the next step.
204. **Plan**: `python3 scripts/speakercut.py plan words.json layout.json -o plan.json` (add
21 `--map` if needed). Read the printed turns: `src labels` turns come from the voice labels.
22 Fix any wrong turn with `--set` as in ffmpeg.md step 4 (a cough or a laugh can carry the wrong
23 label).
245. **Write the edit**: `python3 scripts/speakercut.py jsx plan.json --width 1080 --height 1920`
25 prints a `<video>` with stepped `x`, `y`, `width` and `height` keyframes (times in source
26 seconds). Put it in a 1080x1920 `<scene>`; set `src` to the recording's library path; keep the
27 generated keyframes as they are.
286. **Verify**: `context` (no `compileError`); `check` on the scene (no `cut-in-word`, no
29 `one-frame-pop`, and `caption-over-face` absent if captions exist); `capture` with `times`
30 just after each keyframe: one face, whole, centred, eyes in the upper third.
317. **Export** only when asked: `export` with preset `vertical-1080`.
32
33## Notes
34
35- `media_track` follows one face; it does not choose between two speakers, so it is not used for
36 the switching. It can still help read a face's x for a shot: run it on that shot's range and
37 convert its `x` back to a fraction of the source width.
38
1#!/usr/bin/env python3
2"""Active-speaker 9:16 cut of a two-person recording: a crop that frames whoever is talking.
3
4Usage:
5 speakercut.py layout VIDEO -o layout.json [--from S --to S]
6 Finds shot changes and the picture area (black bars excluded), writes layout.json with one
7 entry per shot and an empty "people" list, and a sheet layout.jpg: one frame per shot,
8 numbered, with a 0-100 ruler. Fill each shot's "people" with the horizontal centre of each
9 visible face as a fraction of the width, left to right (one number for a close-up, two for
10 a two-shot), and give each a stable name ("A" left person, "B" right person).
11 speakercut.py activity VIDEO layout.json -o activity.json
12 Measures picture motion around each face (head and mouth area), 10 times a second.
13 speakercut.py plan words.json layout.json -o plan.json [--activity activity.json] [options]
14 Labels each turn of speech with its speaker (from word "spk" labels when the transcript
15 has them, else from the motion), then plans the crop: one framing per turn, switches only
16 in a gap between words, each framing held at least --min-hold seconds, short replies
17 (--short words or fewer) never switch. Prints the plan as a table.
18 speakercut.py render VIDEO plan.json -o OUT.mp4 [--crf 20] [--threads 4]
19 Renders 1080x1920 with the planned crops; the audio is the source's, untouched.
20 speakercut.py check plan.json words.json [--video OUT.mp4 --sheet sheet.jpg]
21 Switch count, shortest hold, switches per minute, any switch inside a word; a sheet of
22 frames just after each switch.
23 speakercut.py jsx plan.json --width W --height H
24 Prints a Zylcut <video> element with stepped x keyframes for a 1080x1920 scene.
25
26plan options: --min-hold 1.5 --short 2 --lead 0.0 (seconds the picture leads the voice at a
27switch; 0 cuts in the gap before the new speaker's first word) --zoom 1.0 (tighter crop).
28
29Standard library only. Needs ffmpeg and ffprobe.
30"""
31
32import argparse
33import array
34import json
35import os
36import re
37import shutil
38import subprocess
39import sys
40
41FPS_A = 10 # activity samples per second
42
43
44def die(msg, code=2):
45 print("error: " + msg, file=sys.stderr)
46 sys.exit(code)
47
48
49def run(cmd, **kw):
50 return subprocess.run(cmd, capture_output=True, **kw)
51
52
53def probe(path):
54 r = run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
55 "stream=width,height,r_frame_rate:format=duration", "-of", "json", path], text=True)
56 if r.returncode != 0:
57 die("ffprobe could not read " + path)
58 d = json.loads(r.stdout)
59 s = d["streams"][0]
60 n, m = s["r_frame_rate"].split("/")
61 return int(s["width"]), int(s["height"]), float(n) / float(m or 1), float(d["format"]["duration"])
62
63
64def cmd_layout(a):
65 W, H, fps, dur = probe(a.video)
66 t0, t1 = a.start, min(a.end, dur)
67 ss = ["-ss", "%.3f" % t0, "-t", "%.3f" % (t1 - t0)]
68 r = run(["ffmpeg", "-hide_banner", "-threads", "4"] + ss + ["-i", a.video, "-vf",
69 "scale=320:-2,scdet=t=12:s=1", "-an", "-f", "null", "-"], text=True)
70 cuts = [round(t0 + float(x), 3) for x in re.findall(r"lavfi\.scd\.time:\s*([\d.]+)", r.stderr)]
71 bounds = [t0] + [c for c in cuts if t0 < c < t1] + [t1]
72 shots = []
73 for i in range(len(bounds) - 1):
74 a0, a1 = bounds[i], bounds[i + 1]
75 if a1 - a0 < 0.4 and shots:
76 shots[-1]["to"] = round(a1, 3)
77 continue
78 shots.append({"i": len(shots), "from": round(a0, 3), "to": round(a1, 3), "people": [], "names": []})
79 if len(shots) > 1 and shots[0]["to"] - shots[0]["from"] < 0.4:
80 shots[1]["from"] = shots[0]["from"]
81 shots.pop(0)
82 for i, s in enumerate(shots):
83 s["i"] = i
84 # picture area (black bars) from cropdetect over the span
85 r = run(["ffmpeg", "-hide_banner", "-threads", "4"] + ss + ["-i", a.video, "-vf", "fps=2,cropdetect=limit=24:round=2:reset=0",
86 "-an", "-f", "null", "-"], text=True)
87 m = re.findall(r"crop=(\d+):(\d+):(\d+):(\d+)", r.stderr)
88 box = [int(x) for x in m[-1]] if m else [W, H, 0, 0]
89 out = {"video": os.path.abspath(a.video), "w": W, "h": H, "fps": fps, "from": t0, "to": t1,
90 "picture": {"w": box[0], "h": box[1], "x": box[2], "y": box[3]}, "shots": shots}
91 json.dump(out, open(a.output, "w"), indent=1)
92 sheet = os.path.splitext(a.output)[0] + ".jpg"
93 make_sheet(a.video, [(s["i"], (s["from"] + s["to"]) / 2) for s in shots], W, H, sheet)
94 print("wrote %s: %d shots, picture area %dx%d at %d,%d; sheet %s" % (a.output, len(shots), box[0], box[1], box[2], box[3], sheet))
95 print("next: look at the sheet and fill each shot's people (face centres, 0-1, left to right) and names")
96
97
98def make_sheet(video, items, W, H, path, label="shot"):
99 tw = 640 if label == "shot" else 400
100 th = int(tw * H / W) // 2 * 2
101 tmp = path + "_tiles"
102 os.makedirs(tmp, exist_ok=True)
103 ticks = ",".join("drawbox=x=%d:y=0:w=%d:h=%d:color=yellow@0.9:t=fill,drawtext=text='%d':x=%d:y=%d:fontsize=%d:fontcolor=yellow:box=1:boxcolor=black@0.7"
104 % (W * k // 10, max(2, W // 640), H // 12, k * 10, W * k // 10 + 4, H // 12, max(14, H // 22)) for k in range(1, 10))
105 if label == "shot": # a height ruler too, for face_y
106 ticks += "," + ",".join("drawbox=x=0:y=%d:w=%d:h=%d:color=cyan@0.9:t=fill,drawtext=text='%d':x=%d:y=%d:fontsize=%d:fontcolor=cyan:box=1:boxcolor=black@0.7"
107 % (H * k // 10, W // 30, max(2, H // 360), k * 10, W // 30 + 4, H * k // 10 - H // 50, max(14, H // 22)) for k in range(1, 10))
108 files = []
109 for i, (n, t) in enumerate(items):
110 f = os.path.join(tmp, "%03d.png" % i)
111 txt = "%s %s %.1fs" % (label, n, t) if label else "%.1fs" % t
112 guide = "drawbox=x=iw/2-1:y=0:w=2:h=ih:color=cyan@0.6:t=fill,drawbox=x=0:y=ih/3-1:w=iw:h=2:color=cyan@0.6:t=fill,"
113 vf = (ticks + "," if label == "shot" else guide) + "drawtext=text='%s':x=8:y=h-th-8:fontsize=%d:fontcolor=white:box=1:boxcolor=black@0.7,scale=%d:%d" % (txt, max(18, H // 18), tw, th)
114 run(["ffmpeg", "-v", "error", "-y", "-ss", "%.3f" % t, "-i", video, "-frames:v", "1", "-vf", vf, f])
115 if os.path.exists(f):
116 files.append(f)
117 if not files:
118 return
119 cols = min(2 if label == "shot" else 4, len(files))
120 lay = "|".join("%d_%d" % ((i % cols) * tw, (i // cols) * th) for i in range(len(files)))
121 ins = []
122 for f in files:
123 ins += ["-i", f]
124 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"
125 run(["ffmpeg", "-v", "error", "-y"] + ins + ["-filter_complex", flt, "-frames:v", "1", "-q:v", "4", path])
126 shutil.rmtree(tmp, ignore_errors=True)
127
128
129def cmd_activity(a):
130 L = json.load(open(a.layout))
131 W, H = L["w"], L["h"]
132 pw, ph = 160, max(2, int(160 * H / W) // 2 * 2)
133 t0, t1 = L["from"], L["to"]
134 p = subprocess.Popen(["ffmpeg", "-v", "error", "-threads", "4", "-ss", "%.3f" % t0, "-t", "%.3f" % (t1 - t0), "-i", L["video"],
135 "-vf", "fps=%d,scale=%d:%d,format=gray" % (FPS_A, pw, ph), "-f", "rawvideo", "-"], stdout=subprocess.PIPE)
136 n = pw * ph
137 pic = L["picture"]
138 py0 = int(pic["y"] / H * ph)
139 py1 = int((pic["y"] + pic["h"]) / H * ph)
140 prev = None
141 series = {}
142 k = 0
143 while True:
144 buf = p.stdout.read(n)
145 if len(buf) < n:
146 break
147 t = t0 + k / FPS_A
148 k += 1
149 cur = buf
150 if prev is not None:
151 shot = next((s for s in L["shots"] if s["from"] <= t < s["to"]), None)
152 if shot and shot["people"]:
153 for name, cx in zip(shot.get("names") or [], shot["people"]):
154 half = 0.10 if len(shot["people"]) > 1 else 0.18
155 x0 = max(0, int((cx - half) * pw))
156 x1 = min(pw, int((cx + half) * pw))
157 # head and shoulders: the top 70% of the picture area
158 y0, y1 = py0, py0 + int((py1 - py0) * 0.70)
159 tot = 0
160 for y in range(y0, y1):
161 row = y * pw
162 for x in range(x0, x1):
163 d = cur[row + x] - prev[row + x]
164 tot += d if d > 0 else -d
165 area = max(1, (x1 - x0) * (y1 - y0))
166 series.setdefault(name, []).append([round(t, 2), round(tot / area, 3), len(shot["people"])])
167 prev = cur
168 p.wait()
169 json.dump({"fps": FPS_A, "series": series}, open(a.output, "w"))
170 print("wrote %s: %s" % (a.output, ", ".join("%s %d samples" % (k2, len(v)) for k2, v in series.items())))
171
172
173def turns_from_words(words, gap=0.35):
174 out = []
175 cur = []
176 for w in words:
177 if cur and (w["s"] - cur[-1]["e"] >= gap or ("spk" in w and w.get("spk") != cur[-1].get("spk")) or
178 cur[-1]["w"].rstrip('"\')').endswith((".", "?", "!"))):
179 out.append(cur)
180 cur = []
181 cur.append(w)
182 if cur:
183 out.append(cur)
184 return out
185
186
187def shot_at(L, t):
188 for s in L["shots"]:
189 if s["from"] <= t < s["to"]:
190 return s
191 return L["shots"][-1]
192
193
194def cmd_plan(a):
195 L = json.load(open(a.layout))
196 words = [w for w in json.load(open(a.words))["words"] if L["from"] <= w["s"] < L["to"]]
197 if not words:
198 die("no words inside the layout's span")
199 for s in L["shots"]:
200 if not s["people"]:
201 die("shot %d (%.1f-%.1f s) has no people; fill layout.json from the sheet first" % (s["i"], s["from"], s["to"]))
202 if len(s.get("names") or []) != len(s["people"]):
203 die("shot %d: give one name per person" % s["i"])
204 act = json.load(open(a.activity))["series"] if a.activity else {}
205 # per-person median activity, so a restless listener is not mistaken for the talker
206 med = {}
207 for k, v in act.items():
208 xs = sorted(x[1] for x in v if x[2] > 1) or sorted(x[1] for x in v)
209 med[k] = xs[len(xs) // 2] if xs else 1.0
210 turns = turns_from_words(words)
211 labelled = []
212 names_all = sorted(set(n for s in L["shots"] for n in s["names"]))
213 for tw in turns:
214 s0, e0 = tw[0]["s"], tw[-1]["e"]
215 spk_votes = {}
216 for w in tw:
217 if "spk" in w:
218 spk_votes[w["spk"]] = spk_votes.get(w["spk"], 0) + 1
219 src = "labels"
220 who = None
221 conf = 1.0
222 if spk_votes:
223 who = max(spk_votes, key=spk_votes.get)
224 who = (a.map or {}).get(who, who) if isinstance(a.map, dict) else who
225 else:
226 src = "motion"
227 score = {}
228 for k, v in act.items():
229 xs = [x[1] for x in v if s0 - 0.1 <= x[0] <= e0 + 0.1]
230 if xs:
231 score[k] = (sum(xs) / len(xs)) / max(0.05, med.get(k, 1.0))
232 if score:
233 ranked = sorted(score.items(), key=lambda kv: -kv[1])
234 who = ranked[0][0]
235 conf = ranked[0][1] / max(0.01, ranked[1][1]) if len(ranked) > 1 else 2.0
236 labelled.append({"s": s0, "e": e0, "n": len(tw), "who": who, "conf": round(conf, 2), "src": src,
237 "text": " ".join(w["w"] for w in tw)})
238 # the agent's (or user's) own labels win: --set '{"3": "B"}' (turn numbers as printed)
239 for k, who in (a.set or {}).items():
240 if 0 <= int(k) < len(labelled):
241 labelled[int(k)].update({"who": who, "src": "set", "conf": 9.0})
242 # smoothing: short replies and low-confidence turns keep the current speaker
243 cur = None
244 for t in labelled:
245 if t["src"] == "set":
246 cur = t["who"]
247 continue
248 if t["who"] is None:
249 t["who"] = cur
250 elif cur is not None and t["who"] != cur and (t["n"] <= a.short or (t["src"] == "motion" and t["conf"] < 1.15)):
251 t["kept"] = t["who"]
252 t["who"] = cur
253 cur = t["who"] or cur
254 # first turns with no speaker take the first known one
255 first = next((t["who"] for t in labelled if t["who"]), names_all[0] if names_all else "A")
256 for t in labelled:
257 if t["who"] is None:
258 t["who"] = first
259 # switch points: in the gap before the first word of a turn whose speaker differs
260 events = [] # (time, who)
261 last_switch = L["from"] - 99
262 cur = labelled[0]["who"]
263 events.append([L["from"], cur])
264 for i, t in enumerate(labelled[1:], 1):
265 if t["who"] == cur:
266 continue
267 prev_end = labelled[i - 1]["e"]
268 sw = max(prev_end, t["s"] - a.lead - 0.04)
269 sw = min(sw, t["s"])
270 if sw - last_switch < a.min_hold or sw - L["from"] < a.min_hold:
271 # too soon: hold the current framing; the next differing turn tries again
272 continue
273 events.append([round(sw, 3), t["who"]])
274 last_switch = sw
275 cur = t["who"]
276 # drop a final framing shorter than min-hold
277 if len(events) > 1 and L["to"] - events[-1][0] < a.min_hold:
278 events.pop()
279 # crop segments: split at speaker switches and at source shot changes
280 W, H = L["w"], L["h"]
281 pic = L["picture"]
282 ch = int(round(pic["h"] / a.zoom)) // 2 * 2
283 cw = int(round(ch * 9 / 16)) // 2 * 2
284 if cw > pic["w"]:
285 cw = pic["w"] // 2 * 2
286 ch = int(round(cw * 16 / 9)) // 2 * 2
287 def crop_for(sh, who, extra=1.0):
288 if who in sh["names"]:
289 cx = sh["people"][sh["names"].index(who)]
290 elif len(sh["people"]) == 1:
291 cx = sh["people"][0] # a close-up of someone: frame them
292 else:
293 cx = sum(sh["people"]) / len(sh["people"])
294 # a wide shot (2+ people) is cropped tighter on the chosen face, as the references frame
295 # a single face: face centre at about 0.32 of the height
296 zoom = (sh.get("zoom") or (a.wide_zoom if len(sh["people"]) > 1 else a.close_zoom)) * a.zoom * extra
297 sh_ = int(round(pic["h"] / zoom)) // 2 * 2
298 sw_ = int(round(sh_ * 9 / 16)) // 2 * 2
299 if sw_ > pic["w"]:
300 sw_ = pic["w"] // 2 * 2
301 sh_ = int(round(sw_ * 16 / 9)) // 2 * 2
302 fy = sh.get("face_y")
303 if isinstance(fy, list):
304 fy = fy[sh["names"].index(who)] if who in sh["names"] else fy[0]
305 x = int(round(cx * W - sw_ / 2))
306 x = max(pic["x"], min(pic["x"] + pic["w"] - sw_, x))
307 if fy is None:
308 y = pic["y"] + max(0, (pic["h"] - sh_) // 2) if zoom <= 1.0 else pic["y"] + int((pic["h"] - sh_) * 0.25)
309 else:
310 y = int(round(pic["y"] + fy * pic["h"] - 0.32 * sh_))
311 y = max(pic["y"], min(pic["y"] + pic["h"] - sh_, y))
312 return x, y, sw_, sh_
313
314 # gaps between words where a framing may change: (time, after a sentence end)
315 gaps = []
316 for w0, w1 in zip(words, words[1:]):
317 if w1["s"] - w0["e"] >= 0.06: # a real gap: a switch between abutting words can clip a sound
318 gaps.append(((w0["e"] + w1["s"]) / 2, w0["w"].rstrip('"\')').endswith((".", "?", "!", ","))))
319
320 # gaps with their strength (2 sentence end, 1 clause end, 0 other) and length, for punch-ins
321 gaps3 = []
322 for w0, w1 in zip(words, words[1:]):
323 gl = w1["s"] - w0["e"]
324 if gl >= 0.06:
325 t0 = w0["w"].rstrip('"\')')
326 gaps3.append(((w0["e"] + w1["s"]) / 2, 2 if t0.endswith((".", "?", "!")) else 1 if t0.endswith((",", ";", ":")) else 0, gl))
327
328 cuts = sorted(set([e[0] for e in events] + [s["from"] for s in L["shots"]] + [L["to"]]))
329 blocks = [] # (start, end, who, shot, extra zoom, kind)
330 for x0, x1 in zip(cuts, cuts[1:]):
331 if x1 - x0 < 1e-3:
332 continue
333 who = [e[1] for e in events if e[0] <= x0 + 1e-6][-1]
334 sh = shot_at(L, (x0 + x1) / 2)
335 blocks.append([x0, x1, who, sh, 1.0, "speaker"])
336
337 # reactions: in a wide shot, while one person talks on, show the listener for about 1.5-2.5 s
338 # at a sentence end, at most once every --react-every seconds (references: listener shots
339 # are part of the cut; the speaker keeps the frame for the rest)
340 if a.react_every > 0:
341 out = []
342 for b in blocks:
343 x0, x1, who, sh, ex, kind = b
344 others = [n for n in sh["names"] if n != who]
345 if len(sh["people"]) < 2 or not others or x1 - x0 < 4.0:
346 out.append(b)
347 continue
348 t = x0
349 last = x0 - a.react_every
350 # a long silence in a wide shot: the listener holds the frame through it
351 for w0, w1 in zip(words, words[1:]):
352 g0, g1 = max(x0, w0["e"] + 0.15), min(x1, w1["s"] - 0.1)
353 if g1 - g0 >= 1.2 and g0 >= t:
354 if g0 - t > 0.05:
355 out.append([t, g0, who, sh, ex, kind])
356 out.append([g0, g1, others[0], sh, ex, "reaction"])
357 t = last = g1
358 cand = [g for g, end in gaps if max(t, x0 + 2.0) <= g <= x1 - 2.5 and end]
359 for g in cand:
360 if g - last < a.react_every or g < t:
361 continue
362 g2 = next((h for h, _ in gaps if 1.5 <= h - g <= 2.5), None)
363 if g2 is None or g2 > x1 - 1.5:
364 continue
365 out.append([t, g, who, sh, ex, kind])
366 out.append([g, g2, others[0], sh, ex, "reaction"])
367 t = last = g2
368 out.append([t, x1, who, sh, ex, kind])
369 blocks = out
370
371 # punch-ins: a framing held longer than --max-hold is split at sentence-end gaps every 3-5 s,
372 # alternating 1.0x and --punch (references: 34% of cuts reframe the same person)
373 if a.punch and a.punch > 1.0:
374 out = []
375 for b in blocks:
376 x0, x1, who, sh, ex, kind = b
377 if x1 - x0 <= a.max_hold or kind == "reaction":
378 out.append(b)
379 continue
380 t, k = x0, 0
381 while True:
382 # the best gap 3-4.5 s after the last change: a sentence end, else a clause end,
383 # else the longest pause; if none, the first gap after 4.5 s
384 win = [(g, end, gl) for g, end, gl in gaps3 if 3.0 <= g - t <= 4.5 and g <= x1 - 2.0]
385 if win:
386 g = max(win, key=lambda c: (c[1] == 2, c[1] == 1, c[2]))[0]
387 else:
388 later = [g for g, end, gl in gaps3 if g - t > 4.5 and g <= x1 - 2.0]
389 if not later:
390 break
391 g = later[0]
392 out.append([t, g, who, sh, a.punch if k % 2 else 1.0, kind])
393 t, k = g, k + 1
394 out.append([t, x1, who, sh, a.punch if k % 2 else 1.0, kind])
395 blocks = out
396
397 # no flashes: a framing shorter than --min-hold that a source cut does not force joins the
398 # neighbour in the same shot (the previous one first)
399 src = set(round(sh_["from"], 3) for sh_ in L["shots"][1:])
400 changed = True
401 while changed:
402 changed = False
403 for k, b in enumerate(blocks):
404 d = b[1] - b[0]
405 forced = round(b[0], 3) in src and (round(b[1], 3) in src or k == len(blocks) - 1)
406 if d >= a.min_hold or forced or len(blocks) == 1:
407 continue
408 prev = blocks[k - 1] if k > 0 and blocks[k - 1][3] is b[3] else None
409 nxt = blocks[k + 1] if k + 1 < len(blocks) and blocks[k + 1][3] is b[3] else None
410 if prev is not None:
411 prev[1] = b[1]
412 elif nxt is not None:
413 nxt[0] = b[0]
414 else:
415 continue
416 del blocks[k]
417 changed = True
418 break
419
420 segs = []
421 for x0, x1, who, sh, ex, kind in blocks:
422 if x1 - x0 < 0.05:
423 continue
424 x, y, sw_, sh_ = crop_for(sh, who, ex)
425 if segs and segs[-1]["x"] == x and segs[-1]["y"] == y and segs[-1]["cw"] == sw_ and abs(segs[-1]["e"] - x0) < 1e-3:
426 segs[-1]["e"] = round(x1, 3)
427 continue
428 shown = who if who in sh["names"] else sh["names"][0] # the face actually on screen
429 segs.append({"s": round(x0, 3), "e": round(x1, 3), "x": x, "y": y, "cw": sw_, "ch": sh_, "who": shown,
430 "shot": sh["i"], "kind": kind, "zoom": ex})
431 plan = {"video": L["video"], "w": W, "h": H, "fps": L["fps"], "from": L["from"], "to": L["to"], "crop": [cw, ch],
432 "events": events, "segments": segs, "turns": labelled,
433 "shot_changes": [sh["from"] for sh in L["shots"][1:]]}
434 json.dump(plan, open(a.output, "w"), indent=1)
435 print("%-4s %-8s %-8s %-4s %-6s %-6s %s" % ("turn", "start", "end", "who", "conf", "src", "text"))
436 for ti, t in enumerate(labelled):
437 note = " (kept %s: %s)" % (t.get("kept"), "short reply" if t["n"] <= a.short else "unsure") if t.get("kept") else ""
438 print("%4d %8.2f %8.2f %-4s %-6s %-6s %s%s" % (ti, t["s"], t["e"], t["who"], t["conf"], t["src"], t["text"][:70], note))
439 print("wrote %s: %d framings, %d speaker switches, %d reactions, %d punch-ins, crop %dx%d" % (
440 a.output, len(segs), len(events) - 1, sum(1 for g in segs if g["kind"] == "reaction"),
441 sum(1 for g in segs if g["zoom"] > 1.0), cw, ch))
442
443
444def cmd_render(a):
445 P = json.load(open(a.plan))
446 cw, ch = P["crop"]
447 fps = round(P["fps"], 3)
448 parts = []
449 for k, g in enumerate(P["segments"]):
450 parts.append("[0:v]trim=start=%.3f:end=%.3f,setpts=PTS-STARTPTS,crop=%d:%d:%d:%d,scale=1080:1920:flags=lanczos,setsar=1,fps=%g[v%d];"
451 % (g["s"], g["e"], g.get("cw", cw), g.get("ch", ch), g["x"], g["y"], fps, k))
452 flt = "".join(parts) + "".join("[v%d]" % k for k in range(len(P["segments"]))) + "concat=n=%d:v=1:a=0[v];[0:a]atrim=start=%.3f:end=%.3f,asetpts=PTS-STARTPTS[a]" % (
453 len(P["segments"]), P["from"], P["to"])
454 script = a.output + ".filter.txt"
455 open(script, "w").write(flt)
456 r = run(["ffmpeg", "-hide_banner", "-y", "-threads", str(a.threads), "-i", P["video"], "-filter_complex_script", script,
457 "-map", "[v]", "-map", "[a]", "-c:v", "libx264", "-preset", "medium", "-crf", str(a.crf), "-pix_fmt", "yuv420p",
458 "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", a.output], text=True)
459 os.remove(script)
460 if r.returncode != 0:
461 die("render failed: " + r.stderr[-600:])
462 print("wrote %s (%.1f s, %d framings)" % (a.output, P["to"] - P["from"], len(P["segments"])))
463
464
465def cmd_check(a):
466 P = json.load(open(a.plan))
467 words = [w for w in json.load(open(a.words))["words"] if P["from"] <= w["s"] < P["to"]]
468 segs = P["segments"]
469 holds = [g["e"] - g["s"] for g in segs]
470 switches = [g["s"] for g in segs[1:]]
471 errs, warns = [], []
472 src_cuts = P.get("shot_changes", [])
473 ours = [t for t in switches if not any(abs(t - x) < 1e-3 for x in src_cuts)]
474 src_in_word = [t for t in src_cuts if any(w["s"] + 0.02 < t < w["e"] - 0.02 for w in words)]
475 for t in ours:
476 for w in words:
477 if w["s"] + 0.02 < t < w["e"] - 0.02:
478 errs.append("framing changes at %.2f s inside the word %r (%.2f-%.2f)" % (t, w["w"], w["s"], w["e"]))
479 for g, h in zip(segs, holds):
480 ends_on_src = any(abs(g["e"] - x) < 1e-3 for x in src_cuts) or g is segs[-1]
481 starts_on_src = any(abs(g["s"] - x) < 1e-3 for x in src_cuts) or g is segs[0]
482 if h < 1.0 and not (ends_on_src and starts_on_src):
483 warns.append("framing %.2f-%.2f s lasts %.2f s" % (g["s"], g["e"], h))
484 span = P["to"] - P["from"]
485 spk_sw = len(P["events"]) - 1
486 print("length %.1f s | framings %d | speaker switches %d (%.1f per minute) | source cuts kept %d | shortest framing %.2f s | median %.2f s"
487 % (span, len(segs), spk_sw, spk_sw / span * 60, len(src_cuts), min(holds), sorted(holds)[len(holds) // 2]))
488 kinds = {}
489 for g in segs[1:]:
490 kinds[g.get("kind", "speaker")] = kinds.get(g.get("kind", "speaker"), 0) + 1
491 print("framing changes by kind: %s (source cuts %d, of which %d fall inside a word in the source itself and cannot move)"
492 % (", ".join("%s %d" % kv for kv in sorted(kinds.items())), len(src_cuts), len(src_in_word)))
493 for w in warns:
494 print("WARNING " + w + " (a source camera cut, or a switch too close to one)")
495 for e in errs:
496 print("ERROR " + e)
497 if a.video and a.sheet:
498 W, H, fps, dur = probe(a.video)
499 items = [(i, min(dur - 0.05, g["s"] - P["from"] + 0.15)) for i, g in enumerate(segs)][:24]
500 make_sheet(a.video, items, W, H, a.sheet, label="framing")
501 print("wrote " + a.sheet)
502 print("%d error(s), %d warning(s)" % (len(errs), len(warns)))
503 sys.exit(1 if errs else 0)
504
505
506def cmd_jsx(a):
507 """A Zylcut <video> for a WxH scene: stepped keyframes for x, y, width and height, one step per framing."""
508 P = json.load(open(a.plan))
509 cw0, ch0 = P["crop"]
510 rows = []
511 # a crop change on a source camera cut steps half a frame early: Zylcut shows the new
512 # camera's first frame before a keyframe at the same time takes effect
513 src = P.get("shot_changes", [])
514 half = 0.5 / float(P.get("fps") or 25)
515 for g in P["segments"]:
516 sc = a.height / g.get("ch", ch0)
517 t = g["s"] - half if any(abs(g["s"] - x) < 1e-3 for x in src) else g["s"]
518 rows.append((round(t, 3), round(-g["x"] * sc), round(-g["y"] * sc), round(P["w"] * sc), round(P["h"] * sc)))
519
520 def track(prop, k):
521 return (' <keyframeTrack property="%s">\n' % prop + "\n".join(
522 ' <keyframe time={%.3f} value={%d} easing="steps(1)" />' % (r[0], r[k]) for r in rows) + "\n </keyframeTrack>")
523 print("""{/* keyframe times are source seconds of the file; place the clip with start = the scene time of sourceIn */}
524<video id="speaker-cut" src="%s" sourceIn={%.3f} sourceOut={%.3f} x={%d} y={%d} width={%d} height={%d}>
525%s
526%s
527%s
528%s
529</video>""" % (os.path.basename(P["video"]), P["from"], P["to"], rows[0][1], rows[0][2], rows[0][3], rows[0][4],
530 track("x", 1), track("y", 2), track("width", 3), track("height", 4)))
531
532
533def main():
534 p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
535 sub = p.add_subparsers(dest="cmd", required=True)
536 l = sub.add_parser("layout")
537 l.add_argument("video")
538 l.add_argument("-o", "--output", default="layout.json")
539 l.add_argument("--from", dest="start", type=float, default=0.0)
540 l.add_argument("--to", dest="end", type=float, default=1e9)
541 c = sub.add_parser("activity")
542 c.add_argument("video")
543 c.add_argument("layout")
544 c.add_argument("-o", "--output", default="activity.json")
545 q = sub.add_parser("plan")
546 q.add_argument("words")
547 q.add_argument("layout")
548 q.add_argument("-o", "--output", default="plan.json")
549 q.add_argument("--activity")
550 q.add_argument("--min-hold", type=float, default=1.5)
551 q.add_argument("--short", type=int, default=2)
552 q.add_argument("--lead", type=float, default=0.0)
553 q.add_argument("--zoom", type=float, default=1.0)
554 q.add_argument("--close-zoom", type=float, default=1.15, help="zoom on a source close-up (default 1.15)")
555 q.add_argument("--wide-zoom", type=float, default=2.2, help="extra zoom in shots with 2+ people (default 2.2)")
556 q.add_argument("--react-every", type=float, default=8.0, help="seconds between listener reactions in wide shots (0 = none)")
557 q.add_argument("--punch", type=float, default=1.2, help="punch-in zoom for long holds (1 = none)")
558 q.add_argument("--max-hold", type=float, default=4.5, help="a framing longer than this gets punch-ins")
559 q.add_argument("--set", type=json.loads, default=None, help='JSON of turn number to speaker name, e.g. {"3":"B","7":"A"}')
560 q.add_argument("--map", type=json.loads, default=None, help='JSON map of transcript speaker labels to layout names, e.g. {"A":"L","B":"R"}')
561 r = sub.add_parser("render")
562 r.add_argument("video")
563 r.add_argument("plan")
564 r.add_argument("-o", "--output", default="speaker-cut.mp4")
565 r.add_argument("--crf", type=int, default=20)
566 r.add_argument("--threads", type=int, default=4)
567 k = sub.add_parser("check")
568 k.add_argument("plan")
569 k.add_argument("words")
570 k.add_argument("--video")
571 k.add_argument("--sheet")
572 j = sub.add_parser("jsx")
573 j.add_argument("plan")
574 j.add_argument("--width", type=int, default=1080)
575 j.add_argument("--height", type=int, default=1920)
576 a = p.parse_args()
577 {"layout": cmd_layout, "activity": cmd_activity, "plan": cmd_plan, "render": cmd_render, "check": cmd_check, "jsx": cmd_jsx}[a.cmd](a)
578
579
580if __name__ == "__main__":
581 main()
582
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 podcast clips
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