Tight clean cut
A rambling talking-head take in, the tightest clean jump cut out, words never clipped
Before: the input footage. 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 tight-clean-cut skill on take.mp4 and give me the tight cut. No need to check with me first.
Recipe
- 1Transcribe with word times placed on the sound
- 2Read the whole take and mark retakes, false starts, self-corrections and fillers
- 3Plan every cut inside real silence, with breaths cut from pauses
- 4Render a preview, re-transcribe it and fix what it hears
- 5Match the frames at each join, then render at -14 LUFS
About
Give it one take of someone talking and it returns the tightest edit that still sounds like them: retakes and false starts removed (the better take kept), self-corrections resolved to the second wording, fillers and dead air gone, breaths taken out of pauses, and every cut placed in real silence so no word is clipped. It re-transcribes its own preview to prove every kept word survived and to catch the fillers the first transcript missed, then levels the result to -14 LUFS.
The pacing comes from 13 measured talking-head videos: about 0.1 s of silence at a join inside a sentence, a 0.3 s beat after a sentence, no pause or breath over 0.3 s. On our 56 s test take it cut 41% (56.1 s to 33.4 s), left no silent gap or breath-filled pause over 0.3 s, and kept audio and video within 0.01 s. Joins slide to the frames where the pose matches best.
Limits: it is a plain jump cut at the source framing, so a speaker who gestures between phrases still shows a few visible jumps; words that run together with no pause cannot be separated; and which wording of a repeated line to keep is a judgement call it reports for you to check.
Proof footage: Open Culture Voices: Maja Drabczyk by Creative Commons, CC BY, https://youtu.be/Keej4G0xlks (0:53-1:49).
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.
Tight clean cut
Turn one long take of someone talking into the tightest edit that still sounds like them: every word whole, the speaker's meaning intact, every restart and dead second gone. The picture stays a plain jump cut at the source framing; this skill adds no zooms, graphics, music or captions unless the user asks.
Pick the backend
If Zylcut MCP tools are available (for example context, media_transcribe, capture, check),
follow references/zylcut.md for the mechanics. Otherwise follow
references/ffmpeg.md, which uses the scripts in scripts/ (Python 3
standard library, ffmpeg, ffprobe and whisper-cli). The editorial rules below apply to both.
Inputs
- One recording with one main speaker (any size or frame rate). Several files: cut each, then join.
- Optional: the script they read, a target length, words or sections the user wants kept.
Final values
These come from 13 high-performing talking-head videos measured frame by frame (see references/style.md). Hard limits are marked; the rest are targets.
| What | Value | Why |
|---|---|---|
| Silence kept at a join inside a sentence | 0.08-0.16 s (lead 0.04 s before the next word, tail 0.08 s after the last) | References' median gap between speech bursts is 0.11 s; less sounds chopped, more sounds slow |
| Beat after a sentence ends / after a comma | 0.30 s / 0.18 s, where the source has that much silence | References' 90th percentile gap is 0.32 s; cutting every phrase end to 0.1 s sounds breathless |
| Breaths | out, unless a beat needs one: no breath-filled pause over 0.30 s | A pause with an inhale in it is still a pause to the viewer |
| Longest pause anywhere (hard) | 0.30 s, except a deliberate beat before a punchline | References keep 1-3 pauses over 0.5 s per minute, all on purpose |
| Pauses inside a kept sentence | over 0.30 s tightened to 0.12 s | Same feel as a join |
| Cut edges (hard) | in real silence, never inside a word | Clipped word ends are the first thing viewers notice |
| Audio fade at every join | 20 ms out and in | Stops clicks; edges are already in silence |
| Shortest kept piece | 0.4 s of picture (hard); under 1.0 s only if the pose matches on both sides | A short piece between two big pose jumps reads as a flash cut |
| Picture jump at a join | under 3 (mean grey change, 0-255) or 2.5x the edit's median | Above that the head or hands leap; nudge the edge or recut |
| Loudness (hard) | -14 LUFS integrated, -1 dBTP | What YouTube, TikTok, Reels and Shorts play at |
| Framing | source framing, no zoom, hard cuts | A plain jump cut; punch-ins are a different style |
| Typical result | 15-35% shorter than the source | Measured on our tests; restarts and pauses are most of it |
Approval gate
Before cutting, write the plan in 5-10 lines and read it back to the user: what you will remove (by kind and roughly how much), any take choices that depend on delivery, the target length if any, and the output path. Wait for a yes unless the user said "just do it" or similar. Then work through the pipeline without further questions.
Pipeline
Verify each stage before the next. The backend files give the exact commands.
- Probe and transcribe. Get duration, size, frame rate and audio streams. Make a word-timed transcript that keeps disfluencies (prompt the transcriber with fillers and stutters, as the backend file shows). Check: word count is plausible for the length (about 2-3 words a second while talking); no long stretch of speech has no words.
- Read the whole transcript before deciding anything. Follow the argument from start to end.
Mark, by word number:
- Retakes. The same line said again, or the same idea re-worded. Keep the best complete take: full grammar, no stumble, a clean ending. The last take usually wins, but not always. Words alone find only some retakes; read for meaning.
- False starts and stutters ("So the, so the main thing", "this, I think this").
- Self-corrections: "based or built around", "your team, your whole company", "on Monday, no, Tuesday". The second wording replaces the first: keep the second, cut the first and its "or", "no", "I mean". A clause restarted with the same opener ("that the plan, that the budget should") is a false start too: keep the later one.
- Fillers: um, uh, er, hmm. "Like", "you know", "I mean", "sort of" only where they carry nothing; they are often real language.
- Off-script talk: to the crew, "let me start again", counting in, the clap.
- Dead air before the first word and after the last.
- Pointers to what is no longer there: "as I said", "like I mentioned", "I said I'm from X" when what they point back to is not in the cut. Cut the pointer, keep the fact. Keep: setups, qualifications and transitions the argument needs, repetition used for emphasis or rhythm, and a beat before a punchline. Never create a claim the speaker did not make, including by joining halves of different sentences. A pickup that restarts mid-sentence may be joined to the first half only if grammar, meaning and delivery all survive the join.
- Write the edit list of kept word ranges in source order, each with its words as a comment. Re-read the kept text from top to bottom as a viewer would hear it; fix repeated ideas, dropped references and joins that read oddly. Every sentence must stand on its own: when you cut one half of a parallel pair ("otherwise than A, otherwise than B"), the other half must still attach to something, or go too. Mark where sentences end even when the transcript has no full stop there, so each gets its beat.
- Place the edges on the sound, not on transcript times (they can be 0.1-0.5 s off). Each range starts in the silence before its first word and ends in the silence after its last word, with the lead and tail above; long pauses inside ranges are tightened. Check: no edge was placed without silence beside it; where one was, extend the removal to a pause or keep the words. A join inside a sentence must still sound like one sentence: keep it tight (no beat) and never let a list or clause break across a sentence-length pause.
- Render a fast preview and verify it: re-transcribe the output and compare with the edit list. Fix, in this order: kept words that went missing at a join (move that edge out to the next pause), fillers the first transcript missed (cut them now), retakes still audible, pauses over 0.30 s (silent or holding a breath), joins that fall on loud sound, A/V drift over one frame. Repeat until clean; two or three rounds are normal.
- QA before the final render. Look at a contact sheet of frames either side of 6-10 joins: no frame that flashes past, no mid-blink freeze, no hand or head caught blurred mid-move on either side (move that edge a few frames within its silence). Measure the jump at every join (the backend files show how): for each hard jump, first slide the edge 2-6 frames within its silence to the frame where the pose matches best; if a piece under 1.0 s sits between two hard jumps, drop that phrase or keep one continuous stretch of the source through it. If a jump still stands out, move the join to the next word boundary that has a pause (one word earlier or later, cutting or keeping that word) and compare: a slightly looser join that matches beats a tight one that leaps. Jump cuts always show some movement; the aim is no leap that pulls the eye, not a frozen speaker. Read the final kept text once more. Check loudness and that audio and video end together.
- Final render at the source size and frame rate, H.264 + AAC, -14 LUFS. Report: source length, result length, how many retakes, false starts, fillers and pauses were removed, any take choice that depended on delivery, anything flagged that the user should listen to, and the output path. State only what the last verify measured: if breath-filled pauses over 0.30 s remain, say how many and where, rather than "no pause over 0.30 s".
Gotchas
- Transcribers tidy speech: they drop "uh", merge stutters and miss restarts. That is why step 5 re-transcribes the output; expect it to find fillers the first pass missed.
- Word times decide where a cut goes, so they must sit on the sound. Plain whisper.cpp times were a median 0.6 s off on our test; the generic path anchors them with DTW and snaps them to the silences (references/ffmpeg.md). Never cut on raw whisper times.
- A voiced stretch with no word in the transcript is a breath, an "uh" or a dropped word. Cut it only once you know which (the verify pass usually names it).
- A one-word removal between two words with no pause ("with the the war") can be cut only where the sound dips 12 dB or more between the words (the backend shows how to find the dips). With a shallower dip, remove the whole phrase up to a pause, or keep it and say so.
- Do not add a fixed pre-roll or post-roll "for safety". Edges go into silence; that is the safety.
- Do not speed speech up or cut inside a breath that leads into a word; a breath at the very start of a sentence can go with the pause before it.
- Music or room noise under the voice raises the silence level; the scripts measure the floor per file, but check flagged edges by ear-equivalent: re-transcribe them.
- A cut never moves a take earlier. If the user wants a section moved, do it as a separate edit.
- If the speaker repeats something on purpose (a list, a refrain), keep it and say so in the report.
Limits (from four judged test rounds)
- Pose jumps. Plain jump cuts on a speaker who gestures or leans between phrases still show 2-4 visible jumps a minute after the frame matching; a judge scored framing 5-6/10 on such a take. When that matters, hide the jumps with punch-ins or b-roll (a different style).
- Take choices are judgement calls. On the same take, separate runs chose different keepers for a reworded line ("of high importance" or "of relevance"), and a judge disagreed with some. The report names every such choice so the user can swap it back in seconds.
- No pause, no cut. A word that runs straight into the next ("I said I'm") cannot be removed cleanly; it stays and the report says so.
- Rhythm follows punctuation. Sentence and clause beats are placed after words the transcript punctuates (or that you mark). A speaker who talks in one long run gets a dense, fast result: the 90th percentile pause was 0.15-0.18 s on our test take, below the references' 0.25-0.47 s.
- Transcribers miss fillers. whisper.cpp found 2 of about 8 "uh"s on the first pass; the verify loop found the rest. Expect two or three verify rounds.
Files
10 files, 88 KB. Nothing in a skill runs until your agent runs it.
1---
2name: tight-clean-cut
3description: Cuts a talking-head, interview or monologue recording into the tightest clean edit - every word whole, retakes and false starts removed (the best complete take kept), fillers and dead air out, no pause over 0.3 s, levelled to -14 LUFS. Use when the user asks for a tight cut, clean cut, jump-cut edit, "remove the pauses", "cut out the ums", "remove retakes / bad takes / mistakes", "tighten this up" or "edit my talking head", for one speaker on camera. Works with ffmpeg and a local transcriber, or with Zylcut.
4license: Apache-2.0
5compatibility: Generic path needs ffmpeg, ffprobe, Python 3 and a local word-timed transcriber (whisper.cpp whisper-cli or similar). Zylcut path needs the Zylcut app's MCP tools. No network.
6metadata:
7 version: "1.0.0"
8 outcome: talking-head
9 author: Zylcut
10---
11
12# Tight clean cut
13
14Turn one long take of someone talking into the tightest edit that still sounds like them: every
15word whole, the speaker's meaning intact, every restart and dead second gone. The picture stays a
16plain jump cut at the source framing; this skill adds no zooms, graphics, music or captions unless
17the user asks.
18
19## Pick the backend
20
21If Zylcut MCP tools are available (for example `context`, `media_transcribe`, `capture`, `check`),
22follow [references/zylcut.md](references/zylcut.md) for the mechanics. Otherwise follow
23[references/ffmpeg.md](references/ffmpeg.md), which uses the scripts in `scripts/` (Python 3
24standard library, ffmpeg, ffprobe and whisper-cli). The editorial rules below apply to both.
25
26## Inputs
27
28- One recording with one main speaker (any size or frame rate). Several files: cut each, then join.
29- Optional: the script they read, a target length, words or sections the user wants kept.
30
31## Final values
32
33These come from 13 high-performing talking-head videos measured frame by frame
34(see [references/style.md](references/style.md)). Hard limits are marked; the rest are targets.
35
36| What | Value | Why |
37|---|---|---|
38| Silence kept at a join inside a sentence | 0.08-0.16 s (lead 0.04 s before the next word, tail 0.08 s after the last) | References' median gap between speech bursts is 0.11 s; less sounds chopped, more sounds slow |
39| Beat after a sentence ends / after a comma | 0.30 s / 0.18 s, where the source has that much silence | References' 90th percentile gap is 0.32 s; cutting every phrase end to 0.1 s sounds breathless |
40| Breaths | out, unless a beat needs one: no breath-filled pause over 0.30 s | A pause with an inhale in it is still a pause to the viewer |
41| Longest pause anywhere (hard) | 0.30 s, except a deliberate beat before a punchline | References keep 1-3 pauses over 0.5 s per minute, all on purpose |
42| Pauses inside a kept sentence | over 0.30 s tightened to 0.12 s | Same feel as a join |
43| Cut edges (hard) | in real silence, never inside a word | Clipped word ends are the first thing viewers notice |
44| Audio fade at every join | 20 ms out and in | Stops clicks; edges are already in silence |
45| Shortest kept piece | 0.4 s of picture (hard); under 1.0 s only if the pose matches on both sides | A short piece between two big pose jumps reads as a flash cut |
46| Picture jump at a join | under 3 (mean grey change, 0-255) or 2.5x the edit's median | Above that the head or hands leap; nudge the edge or recut |
47| Loudness (hard) | -14 LUFS integrated, -1 dBTP | What YouTube, TikTok, Reels and Shorts play at |
48| Framing | source framing, no zoom, hard cuts | A plain jump cut; punch-ins are a different style |
49| Typical result | 15-35% shorter than the source | Measured on our tests; restarts and pauses are most of it |
50
51## Approval gate
52
53Before cutting, write the plan in 5-10 lines and read it back to the user: what you will remove
54(by kind and roughly how much), any take choices that depend on delivery, the target length if
55any, and the output path. Wait for a yes unless the user said "just do it" or similar. Then work
56through the pipeline without further questions.
57
58## Pipeline
59
60Verify each stage before the next. The backend files give the exact commands.
61
621. **Probe and transcribe.** Get duration, size, frame rate and audio streams. Make a word-timed
63 transcript that keeps disfluencies (prompt the transcriber with fillers and stutters, as the
64 backend file shows). Check: word count is plausible for the length (about 2-3 words a second
65 while talking); no long stretch of speech has no words.
662. **Read the whole transcript before deciding anything.** Follow the argument from start to end.
67 Mark, by word number:
68 - **Retakes.** The same line said again, or the same idea re-worded. Keep the best complete
69 take: full grammar, no stumble, a clean ending. The last take usually wins, but not always.
70 Words alone find only some retakes; read for meaning.
71 - **False starts and stutters** ("So the, so the main thing", "this, I think this").
72 - **Self-corrections**: "based or built around", "your team, your whole company", "on
73 Monday, no, Tuesday". The second wording replaces the first: keep the second, cut the
74 first and its "or", "no", "I mean". A clause restarted with the same opener ("that the
75 plan, that the budget should") is a false start too: keep the later one.
76 - **Fillers**: um, uh, er, hmm. "Like", "you know", "I mean", "sort of" only where they carry
77 nothing; they are often real language.
78 - **Off-script talk**: to the crew, "let me start again", counting in, the clap.
79 - **Dead air** before the first word and after the last.
80 - **Pointers to what is no longer there**: "as I said", "like I mentioned", "I said I'm
81 from X" when what they point back to is not in the cut. Cut the pointer, keep the fact.
82 Keep: setups, qualifications and transitions the argument needs, repetition used for emphasis
83 or rhythm, and a beat before a punchline. Never create a claim the speaker did not make,
84 including by joining halves of different sentences. A pickup that restarts mid-sentence may be
85 joined to the first half only if grammar, meaning and delivery all survive the join.
863. **Write the edit list** of kept word ranges in source order, each with its words as a comment.
87 Re-read the kept text from top to bottom as a viewer would hear it; fix repeated ideas, dropped
88 references and joins that read oddly. Every sentence must stand on its own: when you cut one
89 half of a parallel pair ("otherwise than A, otherwise than B"), the other half must still
90 attach to something, or go too. Mark where sentences end even when the transcript has no full
91 stop there, so each gets its beat.
924. **Place the edges on the sound**, not on transcript times (they can be 0.1-0.5 s off). Each
93 range starts in the silence before its first word and ends in the silence after its last word,
94 with the lead and tail above; long pauses inside ranges are tightened. Check: no edge was
95 placed without silence beside it; where one was, extend the removal to a pause or keep the
96 words. A join inside a sentence must still sound like one sentence: keep it tight (no beat)
97 and never let a list or clause break across a sentence-length pause.
985. **Render a fast preview** and **verify it**: re-transcribe the output and compare with the edit
99 list. Fix, in this order: kept words that went missing at a join (move that edge out to the
100 next pause), fillers the first transcript missed (cut them now), retakes still audible, pauses
101 over 0.30 s (silent or holding a breath), joins that fall on loud sound, A/V drift over one
102 frame. Repeat until clean; two or three rounds are normal.
1036. **QA before the final render.** Look at a contact sheet of frames either side of 6-10 joins:
104 no frame that flashes past, no mid-blink freeze, no hand or head caught blurred mid-move on
105 either side (move that edge a few frames within its silence). Measure the jump at every join
106 (the backend files show how): for each hard jump, first slide the edge 2-6 frames within its
107 silence to the frame where the pose matches best; if a piece under 1.0 s sits between two
108 hard jumps, drop that phrase or keep one continuous stretch of the source through it. If a
109 jump still stands out, move the join to the next word boundary that has a pause (one word
110 earlier or later, cutting or keeping that word) and compare: a slightly looser join that
111 matches beats a tight one that leaps. Jump cuts always show some movement; the aim is no
112 leap that pulls the eye, not a frozen speaker. Read the final kept text once
113 more. Check loudness and that audio and video end together.
1147. **Final render** at the source size and frame rate, H.264 + AAC, -14 LUFS. Report: source
115 length, result length, how many retakes, false starts, fillers and pauses were removed, any take
116 choice that depended on delivery, anything flagged that the user should listen to, and the
117 output path. State only what the last verify measured: if breath-filled pauses over 0.30 s
118 remain, say how many and where, rather than "no pause over 0.30 s".
119
120## Gotchas
121
122- Transcribers tidy speech: they drop "uh", merge stutters and miss restarts. That is why step 5
123 re-transcribes the output; expect it to find fillers the first pass missed.
124- Word times decide where a cut goes, so they must sit on the sound. Plain whisper.cpp times were
125 a median 0.6 s off on our test; the generic path anchors them with DTW and snaps them to the
126 silences (references/ffmpeg.md). Never cut on raw whisper times.
127- A voiced stretch with no word in the transcript is a breath, an "uh" or a dropped word. Cut it
128 only once you know which (the verify pass usually names it).
129- A one-word removal between two words with no pause ("with the the war") can be cut only where
130 the sound dips 12 dB or more between the words (the backend shows how to find the dips). With
131 a shallower dip, remove the whole phrase up to a pause, or keep it and say so.
132- Do not add a fixed pre-roll or post-roll "for safety". Edges go into silence; that is the safety.
133- Do not speed speech up or cut inside a breath that leads into a word; a breath at the very start
134 of a sentence can go with the pause before it.
135- Music or room noise under the voice raises the silence level; the scripts measure the floor per
136 file, but check flagged edges by ear-equivalent: re-transcribe them.
137- A cut never moves a take earlier. If the user wants a section moved, do it as a separate edit.
138- If the speaker repeats something on purpose (a list, a refrain), keep it and say so in the report.
139
140## Limits (from four judged test rounds)
141
142- **Pose jumps.** Plain jump cuts on a speaker who gestures or leans between phrases still show
143 2-4 visible jumps a minute after the frame matching; a judge scored framing 5-6/10 on such a
144 take. When that matters, hide the jumps with punch-ins or b-roll (a different style).
145- **Take choices are judgement calls.** On the same take, separate runs chose different keepers
146 for a reworded line ("of high importance" or "of relevance"), and a judge disagreed with some.
147 The report names every such choice so the user can swap it back in seconds.
148- **No pause, no cut.** A word that runs straight into the next ("I said I'm") cannot be removed
149 cleanly; it stays and the report says so.
150- **Rhythm follows punctuation.** Sentence and clause beats are placed after words the transcript
151 punctuates (or that you mark). A speaker who talks in one long run gets a dense, fast result:
152 the 90th percentile pause was 0.15-0.18 s on our test take, below the references' 0.25-0.47 s.
153- **Transcribers miss fillers.** whisper.cpp found 2 of about 8 "uh"s on the first pass; the
154 verify loop found the rest. Expect two or three verify rounds.
155
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, ffprobe and a local transcriber
2
3Everything runs locally. The scripts are in this skill's `scripts/` folder (Python 3 standard
4library only); call them by their path. Work in a folder next to the input, for example
5`<input name>-cut/`, and keep every intermediate file there.
6
7```
8S=<path to this skill>/scripts
9IN=talk.mp4
10mkdir -p talk-cut && cd talk-cut
11```
12
13## 1. Probe
14
15```
16ffprobe -v error -show_entries format=duration:stream=codec_type,width,height,r_frame_rate -of json ../$IN
17```
18
19No audio stream: stop and tell the user. Two or more audio streams: ask which is the voice.
20
21## 2. Transcribe with word times, keeping disfluencies
22
23whisper.cpp (`whisper-cli`) with an English model such as `ggml-small.en.bin` or
24`ggml-base.en.bin`. Find the model the user has (`~/.cache/whisper/`, `~/models/`, the
25whisper.cpp `models/` folder); ask if there is none. The prompt makes the model write fillers and
26stutters instead of tidying them away.
27
28```
29ffmpeg -v error -y -i ../$IN -vn -ac 1 -ar 16000 audio16k.wav
30whisper-cli -m <model.bin> -f audio16k.wav -ojf -of transcript -t 4 \
31 --dtw <model name> -nfa \
32 --prompt "Umm, so, I I mean, like, uh, you know, the the thing is, hmm."
33python3 $S/words.py transcript.json --media audio16k.wav -o words.json > transcript.txt
34```
35
36`<model name>` is the file's name without `ggml-` and `.bin` (`small.en`, `base.en`, `medium`;
37`python3 -c "import sys; sys.path.insert(0,'$S'); from words import model_name; print(model_name('<model.bin>'))"`
38prints it). `--dtw` with `-nfa` (flash attention off) gives each token an anchor near the end of
39its sound; without them whisper.cpp's word times were a median 0.6 s off on our test clip, enough
40to cut the wrong word. `words.py --media` then moves every word boundary into the silence nearest
41its anchor: measured against a forced aligner on 56 s of speech, the median error fell from 0.62 s
42to 0.06 s. It also writes `sounds.json`: voiced stretches no word covers (breaths, an "uh" the
43transcriber dropped), shown in the text as `<sound 0.4s>`. If words.py prints "no DTW anchors",
44the transcript was made without `--dtw`; run it again.
45
46Other languages: use a multilingual model and drop the English prompt (write one in the
47language). Any transcriber that writes word times works: `words.py` also reads openai-whisper /
48faster-whisper JSON with `segments[].words`, and a plain `{"words": [...]}` list.
49
50`transcript.txt` has one sentence per line: `[first-last] start-end text`, with pauses of 0.3 s or
51more shown as `/0.8s/`. Read all of it.
52
53## 3. Proposals and the edit list
54
55```
56python3 $S/cutplan.py propose ../$IN words.json -o edl.json
57```
58
59This writes a starting `edl.json` that keeps every word except fillers, immediate repeats and an
60earlier take of a sentence repeated with the same ending, and prints each proposal with its
61context. It finds only word-for-word repeats. From `sounds.json` it puts quiet untranscribed
62sounds (breaths, 8 dB or more under the voice) into `cutTimes`, and lists loud ones as `check`:
63they are often an "uh", but can be a word the transcriber dropped, so cut one only after verify
64hears it as a filler. Then edit `edl.json` yourself:
65
66```json
67{
68 "keep": [
69 [6, 16, "I think the first thing to say is, of course, copyright."],
70 [18, 36, "I want to focus on something else ..."]
71 ],
72 "cutTimes": []
73}
74```
75
76- `keep`: word ranges `[first, last]` (both included) in source order. Split a range to drop
77 words inside it. Undo a proposal you disagree with by merging the ranges around it.
78- `cutTimes`: source time spans `[start, end]` to take out of the kept ranges; used in step 6 for
79 fillers the transcript missed.
80- `beats`: word numbers that end a sentence where the transcript shows no full stop; the join or
81 pause after each keeps the 0.30 s sentence beat.
82
83## 4. Plan the edges
84
85```
86python3 $S/cutplan.py plan ../$IN words.json edl.json -o ranges.json
87```
88
89Defaults are this skill's values: `--lead 0.04 --tail 0.08 --max-pause 0.30 --keep-gap 0.12`.
90Edges look for silence within 0.15 s of the word times, which assumes `words.py --media`; with
91any other transcript pass `--loose` (0.6 s), and check the joins harder. It
92reads the sound's 10 ms levels, moves words the transcript placed in a pause back onto speech,
93puts each edge in the nearest real pause, tightens long pauses, snaps edges to the source's frame
94grid and lists `check:` lines:
95
96- `no silence before/after this word`: the edge went to the quietest point between words. Prefer
97 moving the cut to a phrase boundary with a pause.
98- `the removal before word N is too short to cut cleanly, so it stays`: widen the removal to a
99 pause, or accept that those words stay.
100- A doubled word with no pause ("the the"): `python3 $S/cutplan.py dips ../$IN <start> <end>`
101 over the two words lists the quietest points and how deep each dips. At 12 dB or more, put a
102 `cutTimes` span from the dip before the first word to the dip between them; less, leave it.
103
104Sentence ends keep a 0.30 s beat (`--sentence-gap`), commas 0.18 s (`--clause-gap`), other joins 0.12 s. Breaths
105count as pause: the voice band (80-1000 Hz) is near silent through an inhale, so the planner cuts
106them with the pauses.
107
108Then let the joins pick their best frames (edges only slide through silence they already sit in):
109
110```
111python3 $S/cutplan.py match ranges.json
112```
113
114Run `match` again after every `plan`, since `plan` writes `ranges.json` afresh. To move one edge
115by hand (a pose that still jumps), edit that number in `ranges.json` directly, keep it inside
116its silence, and render again; note it, because the next `plan` overwrites it.
117
118## 5. Preview and verify
119
120```
121python3 $S/render.py ranges.json preview.mp4 --preview
122python3 $S/verify.py preview.mp4 words.json edl.json ranges.json --model <model.bin>
123```
124
125`verify.py` re-transcribes the output and prints JSON. Fix in this order:
126
127| Field | Meaning | Fix |
128|---|---|---|
129| `words.missingAtJoins` | a kept word at a range edge was not heard: clipped | widen that range's edge (keep one more word, or end at the next pause) and plan again |
130| `words.extraFillers` | um/uh heard that the first transcript missed, with `source` times | add each `source` span to `cutTimes` and plan again |
131| `words.extra` | other words heard but not meant | usually transcription noise; if it is a repeated word at a join, the removal was too short |
132| `retakes` | neighbouring sentences in the output that still share most words | decide which take to keep |
133| `pauses.overLimit` | silences over 0.30 s | usually a pause between two ranges; check the edges there |
134| `pauses.breathGapsOver0.3` | pauses that hold a breath, over 0.30 s (`breathGapsLongest`: output time, seconds) | map the time to the source (running sum of `ranges`) and add a `cutTimes` span over the breath, leaving 0.12 s (0.30 s at a sentence end) |
135| `joins.loudJoins` | a join on loud sound | move that edge to a pause |
136| `joins.hardJumps` | joins where the picture leaps (pose change), with `source` time | `match` first; then slide that edge by hand inside its silence, or drop a piece under 1.0 s that sits between two hard jumps (`joins.shortPieces`) |
137| `av.diff` | video and audio length differ | must be under one frame; re-plan if not |
138
139Words that differ only in spelling (recognising / recognizing) are not errors. Re-run plan, render
140and verify until clean. Two rounds are normal.
141
142## 6. QA frames
143
144```
145ffmpeg -v error -i preview.mp4 -vf "fps=1/4,scale=320:-2,tile=6x3" -frames:v 1 sheet.jpg
146```
147
148Look at the sheet. Then grab frames either side of a few joins (join times are the running sum of
149range lengths in `ranges.json`). Look for a piece that flashes past or a cut that lands mid-blink.
150
151## 7. Final render
152
153```
154python3 $S/render.py ranges.json ../talk-tight.mp4
155python3 $S/verify.py ../talk-tight.mp4 words.json edl.json ranges.json --model <model.bin>
156```
157
158Source size and frame rate, H.264 CRF 20, AAC 192 kb/s, loudness measured in a first pass and set
159to -14 LUFS / -1 dBTP with one linear gain. Pass `--lufs -16` for podcasts or `--lufs -23` for
160broadcast if the user names one. `--threads` (default 4) keeps the machine responsive.
161
162## Measuring
163
164`scripts/measure.py audio FILE` gives the pause statistics this skill's numbers come from (median
165gap, p90, pauses over 0.3/0.5/1.0 s) and loudness; `measure.py cuts FILE` gives cut times and shot
166lengths. Use them to compare the result with the source or with a reference the user supplies.
167
1# Measured style: tight talking-head cuts
2
313 talking-head videos from channels known for tight jump-cut delivery (education, finance, tech
4and productivity, 0.4M to 6.7M views each, measured on 2026-11-25). For each, 2 minutes from 0:20
5to 2:20 were downloaded at 360p, measured with `scripts/measure.py all`, and deleted. Numbers are
6per video, then the median and range across the 13.
7
8How to read the audio columns: a "gap" is a stretch where the sound falls to the silence level
9(set per file between the noise floor and the voice) for 60 ms or more inside speech. Music beds
10in a few references raise the silence level, so their gaps read slightly short.
11
12| Measure | Median | Range | Used as |
13|---|---|---|---|
14| Median gap between speech bursts | 0.11 s | 0.09-0.15 s | silence kept at a join: lead 0.04 s + tail 0.08 s |
15| 90th percentile gap | 0.32 s | 0.25-0.47 s | the 0.30 s pause limit |
16| Gaps over 0.5 s per 2 minutes | 3 | 0-6 | allowed only as deliberate beats |
17| Gaps per minute | 56 | 41-101 | the speech stays dense: no breathing room added |
18| Share of speech time that is silence | 17% | 12-22% | check: a tight result lands near 15% |
19| Integrated loudness | -16.1 LUFS | -20.5 to -9.5 | we master to -14 LUFS (what platforms play at) |
20| Cuts per minute (all kinds) | 9.2 | 4.2-24.0 | context: includes b-roll and graphics |
21| Median shot length | 4.1 s | 1.3-11.6 s | context |
22| 10th percentile shot | 1.3 s | 0.36-5.2 s | the 0.4 s shortest piece |
23| Share of cuts that change scale | 7% | 0-17% | plain jump cuts dominate; zooms are a separate style |
24| Punch-in step when used | 1.16x | 1.08-1.23x | context for punch-in-jump-cut |
25
26Two numbers were checked a second way: the 0.11 s median gap matches the gaps left by our planner
27(lead + tail = 0.12 s), and the 0.30 s limit sits at the references' 90th percentile.
28
29The per-video table (links and numbers) is kept with the study notes, not in this package; the
30skill describes a common way of cutting, not any one creator's style.
31
1# Zylcut path
2
3Use this when the Zylcut MCP tools are connected. The edit is the project's `index.tsx`: you
4change it with ordinary file tools, and the tools give media facts, word-level cutting, checks,
5frames and the export. The live tool descriptions are the truth if this page and they differ. For
6the house mechanics see the in-app skills `zylcut-editor` and `zylcut-clean-edit`.
7
8## 1. Project and media
9
101. `projects` gives `rootDir`. If the user is inside a project folder (it holds `index.tsx`),
11 `open` that folder. Otherwise `open` a new folder next to the input file, such as
12 `<input folder>/<name>-tight`, and keep its `id` as `projectId`.
132. Link the recording into the library instead of copying it:
14 `mkdir -p <project>/assets/footage && ln -s <abs input> <project>/assets/footage/<name>.mp4`.
153. `media_probe` the file for duration, size, frame rate and audio.
164. `media_transcribe` with `path` and `output` = `<project>/assets/transcripts/<name>.mp4.json`
17 (absolute). English gives `timing: "aligned"`, safe to cut on. Read its `warnings`.
18
19## 2. The spine
20
21Write `index.tsx` with one scene at the source size and one cut clip covering the whole file:
22
23```tsx
24export default function Project() {
25 return (
26 <stage>
27 <scene id="main" name="Tight cut" width={1280} height={720} fill="#000" active>
28 <video id="talk" name="A-roll" src="footage/talk.mp4" width={1280} height={720}
29 keep={[[0, 504.6]]} />
30 </scene>
31 </stage>
32 );
33}
34```
35
36Use the probed size and duration. Call `context`: `compileError` must be `null`. Take a
37`user_edits` baseline.
38
39## 3. Decide with transcript_cut
40
41Read first, with the pace that matches this skill:
42
43```
44transcript_cut { projectId, clip: "talk", transcript: "transcripts/talk.mp4.json", pace: "tight" }
45```
46
47It returns numbered `words`, the `kept` runs and `proposals` (`retake` groups with a scored
48keeper, `filler`, `pause`). Apply the editorial rules from SKILL.md:
49
50- Read every word line. Mark differently worded retakes, restarts and off-script talk the
51 proposals missed, as word ranges.
52- Check each retake keeper against "best complete take". Leave out of `apply` any retake that is
53 emphasis and any "like / you know" that is real language.
54
55Then write it in one call (same `pace`):
56
57```
58transcript_cut { projectId, clip: "talk", pace: "tight",
59 apply: ["r12-15", "f40", ...], remove: [[230, 236], ...], fillers: true, pausesOver: 0.3 }
60```
61
62`tight` cuts to the aligned word edges, which already hold about 40 ms before a word and 100 ms
63after it, so a join keeps roughly 0.14 s of silence: this skill's value. Each new edge is placed
64in the silence beside its kept word, on the 30 fps grid. Read `warnings`: every `no-silence` join
65is a place to look at again with `media_waveform { path, start: t - 1, end: t + 1, threshold: -32,
66minSilence: 0.08 }`; move the edge to a pause or keep the words.
67
68Sentence ends: `tight` leaves the same ~0.14 s everywhere, but this skill keeps a 0.30 s beat
69after a sentence ends. For each keep range that ends on a sentence's last word, move its end
70about 0.15 s later so 0.25-0.3 s separates the sentences, even when part of that is the start of
71a quiet breath; never past the next word's start and never more than 0.3 s in all.
72
73Read again without edits and re-read the kept text as a viewer would hear it. Fix repeated ideas
74and odd joins with `keep` or `remove`.
75
76## 4. Verify
77
781. `context`: `compileError: null`.
792. `check { projectId, id: "main", limits: { pause: 0.3 } }`. Fix every `cut-in-word`,
80 `audio-abrupt-edge` (move that range edge to a quieter frame) and `long-pause` over 0.3 s
81 that is not a deliberate beat. `check` reads the transcript through captions with `follow`; if it reports the speech codes as
82 skipped, add `<captions id="subs" src="transcripts/talk.mp4.json" follow="talk" preset="classic" />`
83 while checking, then remove it unless the user asked for captions.
843. To prove words survive a join, `media_transcribe` the source with `start`/`end` around it and
85 compare with the words you meant to keep.
864. `capture { projectId, id: "main", times: [...] }` with 8-12 times: joins at +-0.2 s, the first
87 and last frame. Look for pieces that flash past (under 0.4 s) and mid-blink freezes.
885. After the export, if `python3` is available, measure what `check` does not:
89 `python3 <skill>/scripts/measure.py joins <export.mp4> --keep '<the keep list as JSON>'`
90 lists the picture jump at every join (`hardJumps`, `shortPieces`), and
91 `python3 <skill>/scripts/measure.py audio <export.mp4>` gives `breathGapsOver0.3`, pauses that
92 hold a breath (check's `long-pause` reads only silence). Fix each hard jump by sliding that
93 range edge 2-6 frames inside its silence, or by recutting a short piece out (SKILL.md, QA);
94 cut breaths over 0.3 s with `remove` or by moving the range edge; then export again.
95
96## 5. Export
97
98When the user wants a file (or asked for "the cut"), `export { projectId, id: "main" }`. It levels
99to -14 LUFS with a -1 dBTP limiter by default; pass `loudness: -16` for a podcast. Report the
100returned `path`, the removals by kind, every `no-silence` warning you accepted, and any take
101choice that depended on delivery.
102
1#!/usr/bin/env python3
2"""Plan a tight cut from word ranges, with every edge placed in real silence.
3
4Python 3 standard library only; needs ffmpeg.
5
6 cutplan.py propose MEDIA words.json [-o edl.json]
7 Writes a starting edit list: every word kept except fillers, stutters and earlier takes
8 of a repeated sentence. Each removal is listed in "proposals" with its reason so you can
9 read it in context and undo it.
10
11 cutplan.py plan MEDIA words.json edl.json [-o ranges.json] [--lead 0.04] [--tail 0.08]
12 [--max-pause 0.30] [--keep-gap 0.12] [--sentence-gap 0.30] [--clause-gap 0.18]
13 [--fps 30] [--loose]
14 Turns the edit list into source time ranges. Each range starts in the silence just before
15 its first word and ends in the silence just after its last word, found from the sound's
16 10 ms levels (the transcript's word times are only a guide). Pauses inside a range longer
17 than --max-pause are tightened to --keep-gap (--sentence-gap after a word that ends a
18 sentence, --clause-gap after a comma; both also set the beat at a join after one). Breaths count as pause: the voice
19 band (80-1000 Hz) is near silent through an inhale. Edges land on the frame grid.
20
21 cutplan.py match ranges.json [-o ranges.json]
22 For every join, slides the outgoing end earlier and the incoming start later, each only
23 through silence (at most 0.2 s), to the pair of frames whose picture matches best, so the
24 head and hands jump less. Words are never touched: an edge only moves inside the silence
25 it already sits in. Prints each join's picture jump before and after.
26
27 cutplan.py dips MEDIA START END
28 Lists the quietest points between START and END (source seconds) with how far each dips
29 under the louder side, for cutting between two words that have no pause ("the the"): a dip
30 of 12 dB or more is a clean place for a cutTimes edge; less, and the cut will be heard.
31
32edl.json: {"keep": [[first_word, last_word, "comment"], ...], "cutTimes": [[start, end], ...]}
33"keep" holds word numbers from words.json, both included, in source order (a cut never moves a
34take earlier).
35"beats" (optional) lists word numbers that end a sentence where the transcript has no full stop
36("...is of relevance and how" when "and how" starts a new sentence): the join or pause after
37each gets the sentence beat.
38"cutTimes" (optional) holds source time spans to take out of the kept ranges, such as fillers the
39transcript missed that verify.py heard; each is widened to the silence either side of it.
40"""
41import json, math, re, sys, os
42sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
43from measure import levels, pct, probe, breath_runs
44
45FILLERS = {"um", "uh", "uhm", "umm", "erm", "er", "ah", "hmm", "mm", "eh"}
46HOP = 0.01
47
48def norm(w): return re.sub(r"[^a-z0-9']", "", w.lower())
49
50def sentences(words):
51 out, first = [], 0
52 for k, w in enumerate(words):
53 if re.search(r"[.?!]$", w["w"]) or k == len(words) - 1:
54 out.append((first, k)); first = k + 1
55 return out
56
57def propose(words):
58 cut, why = set(), {}
59 n = [norm(w["w"]) for w in words]
60 for k, t in enumerate(n):
61 if t in FILLERS: cut.add(k); why[k] = "filler"
62 # stutters and restarts inside a line: "the the", "this attitude, this, I think this"
63 for size in (3, 2, 1):
64 for k in range(len(n) - 2 * size + 1):
65 a, b = n[k:k + size], n[k + size:k + 2 * size]
66 if a == b and all(a) and not any(i in cut for i in range(k, k + size)):
67 for i in range(k, k + size): cut.add(i); why[i] = f"repeat of the next {size} word(s)"
68 # earlier take of a repeated sentence: shares >= 60% of its words with the next sentence
69 ss = sentences(words)
70 for (a0, a1), (b0, b1) in zip(ss, ss[1:]):
71 A = [x for x in n[a0:a1 + 1] if x]; Bl = [x for x in n[b0:b1 + 1] if x]; B = set(Bl)
72 # two finished sentences that end differently are parallel statements, not takes
73 same_end = A and Bl and A[-1] == Bl[-1]
74 prefix = len(A) <= len(Bl) and A[:3] == Bl[:3] and A[-1] not in Bl[len(A) - 1:]
75 if len(A) >= 3 and sum(x in B for x in A) / len(A) >= 0.6 and (same_end or prefix):
76 for i in range(a0, a1 + 1): cut.add(i); why[i] = f"earlier take of sentence {b0}-{b1}"
77 keep, run = [], None
78 for k in range(len(words)):
79 if k in cut:
80 if run: keep.append(run); run = None
81 else:
82 run = [run[0], k] if run else [k, k]
83 if run: keep.append(run)
84 keep = [[a, b, " ".join(w["w"] for w in words[a:b + 1])[:80]] for a, b in keep]
85 props, cur = [], None
86 for k in sorted(cut):
87 if cur and k == cur["to"] + 1 and why[k] == cur["reason"]: cur["to"] = k
88 else:
89 cur = {"from": k, "to": k, "reason": why[k]}; props.append(cur)
90 for p in props:
91 lo, hi = max(0, p["from"] - 5), min(len(words), p["to"] + 6)
92 p["context"] = " ".join(("[" if i == p["from"] else "") + words[i]["w"] + ("]" if i == p["to"] else "") for i in range(lo, hi))
93 return {"keep": keep, "proposals": props}
94
95def silences(lv, thr, min_len=0.05):
96 out, i = [], 0
97 while i < len(lv):
98 if lv[i] <= thr:
99 j = i
100 while j < len(lv) and lv[j] <= thr: j += 1
101 if (j - i) * HOP >= min_len: out.append((i * HOP, j * HOP))
102 i = j
103 else: i += 1
104 return out
105
106def quietest(lv, a, b):
107 ia, ib = max(0, int(a / HOP)), min(len(lv), int(b / HOP) + 1)
108 if ib <= ia: return a
109 k = min(range(ia, ib), key=lambda i: lv[i])
110 return k * HOP
111
112WIN = [0.15, 0.10] # how far before/after a word time an edge may look for silence (words.py --media)
113
114def start_edge(t, sil, lv, lead):
115 """Edge before a word the transcript says starts at t: the latest real pause (>= 0.12 s) ending
116 between t - WIN[0] and t + WIN[1], else the latest short gap, else the quietest point. Short gaps
117 can be a plosive inside a word, so they come second. Without words placed on the sound
118 (--loose) the window is 0.6 s before and 0.15 s after."""
119 for lo in (0.12, 0.05):
120 c = [(s, e) for s, e in sil if t - WIN[0] <= e <= t + WIN[1] and e - s >= lo]
121 if c:
122 s, e = max(c, key=lambda x: x[1])
123 return max(s, e - lead), True
124 return quietest(lv, t - 0.15, t + 0.05), False
125
126def end_edge(t, sil, lv, tail):
127 """Edge after a word the transcript says ends at t: the first real pause starting between
128 t - WIN[1] and t + WIN[0], else the first short gap, else the quietest point."""
129 for lo in (0.12, 0.05):
130 c = [(s, e) for s, e in sil if t - WIN[1] <= s <= t + WIN[0] and e - s >= lo]
131 if c:
132 s, e = min(c, key=lambda x: x[0])
133 return min(e, s + tail), True
134 return quietest(lv, t - 0.05, t + 0.15), False
135
136def subtract(ranges, cuts):
137 """Take source time spans out of the ranges."""
138 out = []
139 for a, b in ranges:
140 segs = [[a, b]]
141 for cs, ce in cuts:
142 nxt = []
143 for x, y in segs:
144 if ce <= x or cs >= y: nxt.append([x, y]); continue
145 if cs > x: nxt.append([x, cs])
146 if ce < y: nxt.append([ce, y])
147 segs = nxt
148 out += segs
149 return out
150
151def realign(words, lv, thr):
152 """Whisper can place a word in a pause next to it. A word whose span is mostly silent moves to
153 the nearest speech within 0.6 s (later first), keeping its length and the word order."""
154 out = [dict(w) for w in words]
155 def voiced(a, b):
156 ia, ib = int(a / HOP), max(int(a / HOP) + 1, int(b / HOP))
157 seg = lv[ia:ib]
158 return sum(x > thr for x in seg) / len(seg) if seg else 0
159 for k, w in enumerate(out):
160 if voiced(w["start"], w["end"]) >= 0.3: continue
161 d = w["end"] - w["start"]
162 lo = out[k - 1]["end"] if k else 0
163 for shift in [x * 0.02 for x in range(1, 31)]:
164 for t in (w["start"] + shift, w["start"] - shift):
165 if t >= lo and voiced(t, t + d) >= 0.5:
166 w["start"], w["end"] = round(t, 3), round(t + d, 3); break
167 else: continue
168 break
169 return out
170
171def ends_sentence(w): return bool(re.search(r"[.?!][\"')]*$", w["w"]))
172def ends_clause(w): return bool(re.search(r"[,;:][\"')]*$", w["w"]))
173
174def plan(media, words, edl, lead=0.04, tail=0.08, max_pause=0.30, keep_gap=0.12, fps=None, sentence_gap=0.30, clause_gap=0.18):
175 info = probe(media); fps = fps or info["fps"] or 30
176 beats = set(int(x) for x in edl.get("beats", []))
177 ends = lambda w: ends_sentence(w) or w["i"] in beats
178 lv = levels(media, {})
179 floor, voice = pct(lv, 10), pct(lv, 90)
180 thr = max(floor + 6, voice - 25) if voice - floor > 12 else floor + (voice - floor) * 0.5
181 sil = silences(lv, thr)
182 # a click or breath shorter than 0.1 s between two silences does not end a pause
183 merged = []
184 for x in sil:
185 if merged and x[0] - merged[-1][1] < 0.1: merged[-1] = (merged[-1][0], x[1])
186 else: merged.append(tuple(x))
187 sil = merged
188 words = realign(words, lv, thr)
189 # breaths: the full-band level stays up through an inhale, so add the stretches where the
190 # voice band is quiet (measure.breath_runs) as pause material for edges and tightening
191 allq = sorted([tuple(x) for x in sil] + breath_runs(media))
192 sil = []
193 for x in allq:
194 if sil and x[0] <= sil[-1][1] + 0.02: sil[-1] = (sil[-1][0], max(sil[-1][1], x[1]))
195 else: sil.append(x)
196 flags, raw = [], []
197 for item in edl["keep"]:
198 a, b = int(item[0]), int(item[1])
199 s, ok1 = start_edge(words[a]["start"], sil, lv, lead)
200 # a sentence ends on a short beat (0.25 s with the next lead), as in the references;
201 # inside a sentence the join stays tight so the line carries on
202 e, ok2 = end_edge(words[b]["end"], sil, lv, sentence_gap - lead if ends(words[b]) else (clause_gap - lead if ends_clause(words[b]) else tail))
203 if not ok1: flags.append({"word": a, "text": words[a]["w"], "edge": "start", "note": "no silence before this word; cut at the quietest point"})
204 if not ok2: flags.append({"word": b, "text": words[b]["w"], "edge": "end", "note": "no silence after this word; cut at the quietest point"})
205 if e <= s: e = s + 0.1
206 if raw and s < raw[-1][0]:
207 sys.exit(f"keep item {item} starts before the item above it; ranges must play in source order")
208 if raw and s - raw[-1][1] <= 0.02:
209 # neighbours in the source join up; an overlap means the words cut between them had no room
210 if s < raw[-1][1] - 0.02:
211 flags.append({"word": a, "text": words[a]["w"], "note": f"the removal before word {a} is too short to cut cleanly, so it stays; remove a longer phrase or keep it"})
212 raw[-1][1] = max(raw[-1][1], e)
213 else: raw.append([s, e])
214 cuts = []
215 for cs, ce in edl.get("cutTimes", []):
216 # a span to remove (a filler found by verify): widen it to the silences around it
217 # times heard in the preview are only near the sound: look 0.15 s inside the span too
218 before = [x for x in sil if cs - 0.4 <= x[1] <= cs + 0.15]
219 after = [x for x in sil if ce - 0.15 <= x[0] <= ce + 0.4]
220 a0 = min(before[-1][0] + tail, before[-1][1]) if before else cs
221 b0 = max(after[0][1] - lead, after[0][0]) if after else ce
222 if not before or not after: flags.append({"cut": [cs, ce], "note": "no silence beside this removal; listen to the join"})
223 cuts.append((a0, b0))
224 ranges = []
225 for s, e in raw:
226 parts, cur = [], s
227 for ps, pe in sil: # tighten long pauses inside the range
228 if ps > cur and pe < e and pe - ps > max_pause:
229 before = [w for w in words if ps - 0.2 <= w["end"] <= ps + 0.15]
230 g = sentence_gap if before and ends(before[-1]) else (clause_gap if before and ends_clause(before[-1]) else keep_gap)
231 parts.append([cur, ps + g - lead]); cur = pe - lead
232 parts.append([cur, e])
233 for p in subtract(parts, cuts):
234 p0 = round(math.floor(p[0] * fps + 1e-6) / fps, 4) # onto the source's own frame grid
235 p1 = round(math.ceil(p[1] * fps - 1e-6) / fps, 4)
236 if p1 - p0 >= 1 / fps: ranges.append([p0, p1])
237 total = sum(b - a for a, b in ranges)
238 return {"media": os.path.abspath(media), "fps": round(fps, 5), "thresholdDb": round(thr, 1), "ranges": ranges, "seconds": round(total, 2),
239 "sourceSeconds": round(info["duration"], 2), "flags": flags}
240
241def main():
242 a = sys.argv[1:]
243 if len(a) < (2 if a and a[0] == "match" else 3): print(__doc__); sys.exit(1)
244 opt = lambda k, d: float(a[a.index(k) + 1]) if k in a else d
245 out = a[a.index("-o") + 1] if "-o" in a else None
246 if "--loose" in a: WIN[0], WIN[1] = 0.6, 0.15
247 if a[0] == "match":
248 r = json.load(open(a[1])); out = out or a[1]
249 from measure import gray_frames
250 media, fps = r["media"], r["fps"]; lv = levels(media, {}); thr = r["thresholdDb"]
251 quiet = lambda t0, t1: all(x <= thr + 6 for x in lv[int(t0 / HOP):max(int(t0 / HOP) + 1, int(t1 / HOP))])
252 R = r["ranges"]
253 def diff(x, y): return sum(abs(p - q) for p, q in zip(x, y)) / len(x) if x and y else 99
254 for k in range(len(R) - 1):
255 e, s0 = R[k][1], R[k + 1][0]
256 if s0 - e < 0.5 / fps and abs(s0 - e) < 1e-3: continue # neighbours in the source: no join
257 outs = [e] + [e - i / fps for i in range(1, 7) if e - i / fps > R[k][0] + 0.4 and quiet(e - i / fps, e)]
258 ins = [s0] + [s0 + i / fps for i in range(1, 7) if s0 + i / fps < R[k + 1][1] - 0.4 and quiet(s0, s0 + i / fps)]
259 fo = dict(zip(outs, gray_frames(media, {}, 64, 36, times=[t - 1 / fps for t in outs])))
260 fi = dict(zip(ins, gray_frames(media, {}, 64, 36, times=ins)))
261 before = diff(fo.get(e), fi.get(s0))
262 best = min(((diff(fo[o], fi[i]), o, i) for o in outs for i in ins), default=(before, e, s0))
263 if best[0] < before - 0.3:
264 R[k][1], R[k + 1][0] = round(best[1], 4), round(best[2], 4)
265 print(f" join {k + 1}: jump {before:.1f} -> {min(before, best[0]):.1f}")
266 r["seconds"] = round(sum(b - a for a, b in R), 2)
267 json.dump(r, open(out, "w"), indent=1); print(f"{out}: {r['seconds']} s")
268 return
269 if a[0] == "dips":
270 lv = levels(a[1], {}); t0, t1 = float(a[2]), float(a[3])
271 i0, i1 = int(t0 / HOP), min(len(lv) - 1, int(t1 / HOP))
272 rows = []
273 for i in range(i0 + 1, i1):
274 if lv[i] <= lv[i - 1] and lv[i] <= lv[i + 1]:
275 left = max(lv[max(i0, i - 15):i] or [lv[i]]); right = max(lv[i + 1:i + 16] or [lv[i]])
276 rows.append((round(i * HOP, 2), round(lv[i], 1), round(min(left, right) - lv[i], 1)))
277 for r in sorted(rows, key=lambda r: -r[2])[:8]: print(f" {r[0]:.2f} s level {r[1]} dB dip {r[2]} dB")
278 return
279 words = json.load(open(a[2]))
280 if a[0] == "propose":
281 r = propose(words); out = out or "edl.json"
282 sp = os.path.join(os.path.dirname(os.path.abspath(a[2])), "sounds.json")
283 if os.path.exists(sp):
284 # voiced stretches no word covers (words.py --media): quiet ones are breaths and go;
285 # loud ones may be an "uh" or a word the transcriber dropped, so they are only listed
286 r["cutTimes"] = []
287 for x in json.load(open(sp)):
288 if x["seconds"] > 1.5: continue
289 if x["underVoiceDb"] >= 8:
290 r["cutTimes"].append([x["start"], x["end"]])
291 r["proposals"].append({"cutTime": [x["start"], x["end"]], "reason": f"breath or noise ({x['seconds']} s, {x['underVoiceDb']} dB under the voice)", "context": ""})
292 else:
293 r["proposals"].append({"check": [x["start"], x["end"]], "reason": f"untranscribed voiced sound ({x['seconds']} s): an uh, a laugh or a dropped word; add to cutTimes only if verify shows it is not a word", "context": ""})
294 json.dump(r, open(out, "w"), indent=1)
295 print(f"{len(r['keep'])} kept runs, {len(r['proposals'])} proposals -> {out}")
296 for p in r["proposals"]:
297 where = f"{p['from']}-{p['to']}" if "from" in p else str(p.get("cutTime") or p.get("check"))
298 print(f" {where} {p['reason']}: {p['context']}")
299 elif a[0] == "plan":
300 edl = json.load(open(a[3])); out = out or "ranges.json"
301 r = plan(a[1], words, edl, opt("--lead", 0.04), opt("--tail", 0.08), opt("--max-pause", 0.30), opt("--keep-gap", 0.12),
302 float(opt("--fps", 0)) or None, opt("--sentence-gap", 0.30), opt("--clause-gap", 0.18))
303 json.dump(r, open(out, "w"), indent=1)
304 print(f"{len(r['ranges'])} ranges, {r['seconds']} s of {r['sourceSeconds']} s -> {out}")
305 for f in r["flags"]: print(" check:", f)
306 else: print(__doc__); sys.exit(1)
307
308if __name__ == "__main__":
309 main()
310
1#!/usr/bin/env python3
2"""Measure a video the same way for references and for our output.
3
4Python 3 standard library only; needs ffmpeg and ffprobe on PATH.
5
6 measure.py audio FILE speech pauses (gaps between speech bursts) and loudness
7 measure.py cuts FILE cut times, cuts per minute, shot lengths
8 measure.py zoom FILE cuts plus the scale change across each cut (punch-ins)
9 measure.py loop FILE how well the last frame and sound lead back into the first
10 measure.py motion FILE how long the picture holds still (screen recordings)
11 measure.py joins FILE --keep '[[in,out],...]' picture jump at each join of a cut (source keep list)
12 measure.py all FILE audio + cuts + zoom, one JSON
13
14Add --start S --dur D to measure only part of a file.
15"""
16import array, json, math, re, statistics, subprocess, sys
17
18def run(cmd):
19 return subprocess.run(cmd, capture_output=True, text=True)
20
21def probe(path):
22 r = run(["ffprobe", "-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height,r_frame_rate",
23 "-of", "json", path])
24 d = json.loads(r.stdout)
25 v = next((s for s in d["streams"] if s["codec_type"] == "video"), {})
26 n, _, den = v.get("r_frame_rate", "30/1").partition("/")
27 return {"duration": float(d["format"]["duration"]), "width": v.get("width"), "height": v.get("height"),
28 "fps": float(n) / float(den or 1)}
29
30def window(args):
31 w = []
32 if args.get("start"): w += ["-ss", str(args["start"])]
33 if args.get("dur"): w += ["-t", str(args["dur"])]
34 return w
35
36def pct(xs, p):
37 if not xs: return None
38 xs = sorted(xs); k = (len(xs) - 1) * p / 100
39 f = math.floor(k); c = min(f + 1, len(xs) - 1)
40 return round(xs[f] + (xs[c] - xs[f]) * (k - f), 3)
41
42# ---------- audio ----------
43def levels(path, args, rate=16000, hop=0.01, af=None):
44 """10 ms RMS levels in dBFS of the mono mix (af: an ffmpeg audio filter applied first)."""
45 r = subprocess.run(["ffmpeg", "-v", "error", *window(args), "-i", path, "-vn", "-ac", "1", "-ar", str(rate),
46 *(["-af", af] if af else []), "-f", "s16le", "-"], capture_output=True)
47 a = array.array("h"); a.frombytes(r.stdout[: len(r.stdout) // 2 * 2])
48 n = int(rate * hop); out = []
49 for i in range(0, len(a) - n + 1, n):
50 s = 0
51 for x in a[i:i + n]: s += x * x
52 out.append(10 * math.log10(s / n / 1073741824 + 1e-12))
53 return out
54
55VOICE_BAND = "highpass=f=80,lowpass=f=1000"
56
57def breath_runs(path, args=None, below=25, min_len=0.25, soft=14):
58 """Stretches of 0.25 s or more where the voice band (80-1000 Hz) is 25 dB or more under its
59 usual level and the full band is at least 14 dB under the voice: pauses, and breaths, which
60 carry little energy under 1 kHz. Full-band silence misses a breath; this does not. Each run is
61 trimmed at both ends to where the full band is that quiet, so the hiss of an "s" or "f" at the
62 end of a word stays with the word."""
63 low = levels(path, args or {}, af=VOICE_BAND)
64 full = levels(path, args or {})
65 n = min(len(low), len(full))
66 if not n: return []
67 lthr, fthr = pct(low, 90) - below, pct(full, 90) - soft
68 out, i = [], 0
69 while i < n:
70 if low[i] <= lthr:
71 j = i
72 while j < n and low[j] <= lthr: j += 1
73 a, b = i, j
74 while a < b and full[a] > fthr: a += 1
75 while b > a and full[b - 1] > fthr: b -= 1
76 if (b - a) * 0.01 >= min_len: out.append((round(a * 0.01, 3), round(b * 0.01, 3)))
77 i = j
78 else: i += 1
79 return out
80
81def speech_gaps(lv, hop=0.01, min_gap=0.06):
82 """Silence threshold sits between the noise floor and the voice. Returns threshold and gaps inside speech."""
83 if not lv: return None, [], 0
84 floor, voice = pct(lv, 10), pct(lv, 90)
85 thr = max(floor + 6, voice - 25) if voice - floor > 12 else floor + (voice - floor) * 0.5
86 sp = [x > thr for x in lv]
87 # speech runs shorter than 40 ms are clicks; fill them
88 gaps, i, n = [], 0, len(sp)
89 first = next((k for k, s in enumerate(sp) if s), None)
90 last = n - 1 - next((k for k, s in enumerate(reversed(sp)) if s), 0)
91 if first is None: return thr, [], 0
92 i = first
93 while i <= last:
94 if not sp[i]:
95 j = i
96 while j <= last and not sp[j]: j += 1
97 g = (j - i) * hop
98 if g >= min_gap: gaps.append((round(i * hop, 2), round(g, 3)))
99 i = j
100 else: i += 1
101 return thr, gaps, (last - first) * hop
102
103def loudness(path, args):
104 r = run(["ffmpeg", "-nostats", "-v", "info", *window(args), "-i", path, "-vn", "-af", "ebur128=peak=true", "-f", "null", "-"])
105 t = r.stderr[r.stderr.rfind("Summary:"):]
106 g = lambda k: (lambda m: float(m.group(1)) if m else None)(re.search(k + r":\s+(-?[\d.]+|-inf)", t))
107 return {"lufs": g("I"), "lra": g("LRA"), "truePeak": g("Peak")}
108
109def audio(path, args):
110 """Pause statistics and loudness. breathGaps* count voice-band quiet runs (pauses with or
111 without a breath in them) over 0.3 s inside the speech."""
112 lv = levels(path, args)
113 thr, gaps, span = speech_gaps(lv)
114 g = [x for _, x in gaps if x <= 3.0]
115 res = {"thresholdDb": round(thr, 1) if thr is not None else None, "speechSpanS": round(span, 1),
116 "gaps": len(g), "gapsPerMin": round(len(g) / span * 60, 1) if span else None,
117 "gapMedianS": pct(g, 50), "gapP75S": pct(g, 75), "gapP90S": pct(g, 90), "gapMaxS": max(g) if g else None,
118 "over0.3": sum(x > 0.3 for x in g), "over0.5": sum(x > 0.5 for x in g), "over1.0": sum(x > 1.0 for x in g),
119 "silenceShare": round(sum(g) / span, 3) if span else None,
120 "longest": sorted(gaps, key=lambda x: -x[1])[:5]}
121 br = [(a, b) for a, b in breath_runs(path, args) if a > 0.05 and b < len(lv) * 0.01 - 0.05]
122 res["breathGapsOver0.3"] = sum(b - a > 0.3 for a, b in br)
123 res["breathGapsLongest"] = sorted([[a, round(b - a, 2)] for a, b in br], key=lambda x: -x[1])[:5]
124 res.update(loudness(path, args))
125 return res
126
127# ---------- picture ----------
128def gray_frames(path, args, w, h, fps=None, times=None):
129 """Grey frames as bytes. Either every frame at fps, or one frame per time."""
130 if times is not None:
131 out = []
132 for t in times:
133 r = subprocess.run(["ffmpeg", "-v", "error", "-ss", f"{max(t, 0):.3f}", "-i", path, "-frames:v", "1",
134 "-vf", f"scale={w}:{h}:flags=area,format=gray", "-f", "rawvideo", "-"], capture_output=True)
135 out.append(r.stdout if len(r.stdout) == w * h else None)
136 return out
137 vf = (f"fps={fps}," if fps else "") + f"scale={w}:{h}:flags=area,format=gray"
138 r = subprocess.run(["ffmpeg", "-v", "error", *window(args), "-i", path, "-vf", vf, "-f", "rawvideo", "-"], capture_output=True)
139 b = r.stdout; n = w * h
140 return [b[i:i + n] for i in range(0, len(b) - n + 1, n)]
141
142def cuts(path, args, w=64, h=36):
143 """A cut is a frame whose mean absolute change is far above the local motion (robust to camera moves)."""
144 info = probe(path)
145 fr = gray_frames(path, args, w, h)
146 d = [0.0]
147 for a, b in zip(fr, fr[1:]):
148 d.append(sum(abs(x - y) for x, y in zip(a, b)) / (w * h))
149 fps = info["fps"]; c = []
150 for i in range(1, len(d)):
151 lo, hi = max(1, i - 6), min(len(d), i + 7)
152 around = sorted(d[k] for k in range(lo, hi) if k != i)
153 base = around[len(around) // 2] if around else 0
154 if d[i] > 9 and d[i] > 3.5 * base + 4 and (not c or i - c[-1] > fps * 0.25):
155 c.append(i)
156 off = float(args.get("start") or 0)
157 times = [round(off + i / fps, 3) for i in c]
158 dur = len(fr) / fps if fr else 0
159 edges = [off] + times + [off + dur]
160 shots = [round(b - a, 3) for a, b in zip(edges, edges[1:])]
161 inner = shots[1:-1] if len(shots) > 2 else shots
162 return {"duration": round(dur, 2), "cuts": len(times), "cutsPerMin": round(len(times) / dur * 60, 2) if dur else None,
163 "shotMedianS": pct(inner, 50), "shotP10S": pct(inner, 10), "shotP90S": pct(inner, 90),
164 "firstCutS": round(times[0] - off, 2) if times else None, "cutTimes": times}
165
166def best_scale(a, b, w, h):
167 """Scale s so that b looks like a zoomed by s about some centre (s > 1 is a punch-in). Normalised correlation."""
168 def norm(img):
169 m = sum(img) / len(img); v = math.sqrt(sum((x - m) ** 2 for x in img)) or 1
170 return [(x - m) / v for x in img]
171 A = list(a); best = (-2, 1.0, 0, 0)
172 sub = [(x, y) for y in range(4, h - 4, 3) for x in range(4, w - 4, 3)]
173 Bs = norm([b[y * w + x] for x, y in sub])
174 for s in [0.72, 0.76, 0.8, 0.84, 0.88, 0.92, 0.96, 1.0, 1.04, 1.08, 1.12, 1.16, 1.2, 1.25, 1.3, 1.35, 1.4]:
175 for dx in range(-4, 5, 2):
176 for dy in range(-2, 3, 2):
177 vals = []
178 for x, y in sub:
179 sx = (x - w / 2) / s + w / 2 + dx; sy = (y - h / 2) / s + h / 2 + dy
180 ix, iy = int(sx), int(sy)
181 if 0 <= ix < w and 0 <= iy < h: vals.append(A[iy * w + ix])
182 else: vals.append(None)
183 if None in vals: continue
184 Av = norm(vals)
185 c = sum(p * q for p, q in zip(Av, Bs))
186 if c > best[0]: best = (c, s, dx, dy)
187 return best
188
189def zoom(path, args, cut_res=None):
190 cr = cut_res or cuts(path, args)
191 info = probe(path); w, h = 96, 54; fd = 1 / info["fps"]
192 rows = []
193 for t in cr["cutTimes"]:
194 a, b = gray_frames(path, args, w, h, times=[t - 2 * fd, t + fd])
195 if not a or not b: continue
196 c, s, dx, dy = best_scale(a, b, w, h)
197 kind = "zoom" if c > 0.75 and abs(s - 1) >= 0.06 else ("jump" if c > 0.75 else "hard")
198 rows.append({"t": t, "corr": round(c, 2), "scale": s, "kind": kind})
199 z = [r for r in rows if r["kind"] == "zoom"]
200 ins = [r["scale"] for r in z if r["scale"] > 1]
201 outs = [1 / r["scale"] for r in z if r["scale"] < 1]
202 n = len(rows) or 1
203 return {"cutsChecked": len(rows), "zoomCutShare": round(len(z) / n, 2), "jumpCutShare": round(sum(r["kind"] == "jump" for r in rows) / n, 2),
204 "hardCutShare": round(sum(r["kind"] == "hard" for r in rows) / n, 2),
205 "punchInMedian": pct(ins, 50), "punchOutMedian": pct(outs, 50), "steps": pct(ins + outs, 50),
206 "zoomsPerMin": round(len(z) / cr["duration"] * 60, 2) if cr["duration"] else None, "rows": rows}
207
208def join_jumps(path, times):
209 """How far the picture jumps at each join time (output seconds): mean grey change, 0-255, of
210 64x36 frames either side. Hard jumps are over 3 and 2.5x the median of this edit's joins."""
211 fd = 1 / probe(path)["fps"]; rows = []
212 for t in times:
213 a, b = gray_frames(path, {}, 64, 36, times=[t - 1.5 * fd, t + 0.5 * fd])
214 if a and b: rows.append({"at": round(t, 3), "jump": round(sum(abs(x - y) for x, y in zip(a, b)) / len(a), 1)})
215 med = pct([r["jump"] for r in rows], 50) or 0
216 for r in rows: r["hard"] = r["jump"] > max(3.0, 2.5 * med)
217 return {"medianJump": med, "joins": rows, "hardJumps": [r for r in rows if r["hard"]]}
218
219def ssim(path, t1, t2, w=320, h=180):
220 r = run(["ffmpeg", "-v", "info", "-ss", f"{t1:.3f}", "-i", path, "-ss", f"{t2:.3f}", "-i", path, "-filter_complex",
221 f"[0:v]scale={w}:{h},format=gray[a];[1:v]scale={w}:{h},format=gray[b];[a][b]ssim", "-frames:v", "1", "-f", "null", "-"])
222 m = re.search(r"All:([\d.]+)", r.stderr)
223 return float(m.group(1)) if m else None
224
225def loop(path, args):
226 info = probe(path); d = info["duration"]; fd = 1 / info["fps"]
227 lv = levels(path, {})
228 tail = lv[-50:]; head = lv[:50]; mid = sorted(lv)[len(lv) // 2] if lv else -90
229 def rms(xs): return round(sum(xs) / len(xs), 1) if xs else None
230 # fade detection: level in the last 0.5 s against the 2 s before it
231 last05, before = rms(lv[-50:]), rms(lv[-250:-50])
232 return {"duration": round(d, 2), "ssimFirstLast": ssim(path, 0, d - 2 * fd), "ssimFirst_vs_1s": ssim(path, 0, min(1, d / 2)),
233 "levelLast0.5sDb": last05, "level2sBeforeDb": before, "fadeOutDb": round(before - last05, 1) if last05 and before else None,
234 "levelFirst0.5sDb": rms(head), "medianLevelDb": round(mid, 1)}
235
236def motion(path, args, fps=2, w=160, h=90, still=0.004):
237 """Share of pixels that change between samples; runs below `still` are holds."""
238 fr = gray_frames(path, args, w, h, fps=fps)
239 ch = []
240 for a, b in zip(fr, fr[1:]):
241 ch.append(sum(abs(x - y) > 12 for x, y in zip(a, b)) / (w * h))
242 holds, i = [], 0
243 while i < len(ch):
244 if ch[i] < still:
245 j = i
246 while j < len(ch) and ch[j] < still: j += 1
247 holds.append(round((j - i) / fps, 2)); i = j
248 else: i += 1
249 dur = len(fr) / fps
250 return {"duration": round(dur, 1), "holds": len(holds), "holdMaxS": max(holds) if holds else 0,
251 "holdsOver2s": sum(x > 2 for x in holds), "holdsOver5s": sum(x > 5 for x in holds),
252 "stillShare": round(sum(holds) / dur, 3) if dur else None, "changeMedian": pct(ch, 50)}
253
254def main():
255 if len(sys.argv) < 3: print(__doc__); sys.exit(1)
256 cmd, path = sys.argv[1], sys.argv[2]; args = {}
257 rest = sys.argv[3:]
258 for k in ("start", "dur"):
259 if f"--{k}" in rest: args[k] = float(rest[rest.index(f"--{k}") + 1])
260 if cmd == "audio": out = audio(path, args)
261 elif cmd == "cuts": out = cuts(path, args)
262 elif cmd == "zoom": out = zoom(path, args)
263 elif cmd == "loop": out = loop(path, args)
264 elif cmd == "motion": out = motion(path, args)
265 elif cmd == "joins":
266 # joins: measure.py joins OUT.mp4 --keep '[[in,out],...]' (a cut's keep list, source seconds)
267 keep = json.loads(rest[rest.index("--keep") + 1]); acc, ts = 0.0, []
268 for a0, b0 in keep[:-1]:
269 acc += b0 - a0; ts.append(acc)
270 out = join_jumps(path, ts)
271 lens = [b0 - a0 for a0, b0 in keep]
272 out["shortPieces"] = [{"at": round(sum(lens[:i]), 3), "seconds": round(L, 2)} for i, L in enumerate(lens) if L < 1.0 and 0 < i < len(lens) - 1]
273 elif cmd == "all":
274 c = cuts(path, args); z = zoom(path, args, c)
275 out = {"audio": audio(path, args), "cuts": {k: v for k, v in c.items() if k != "cutTimes"},
276 "zoom": {k: v for k, v in z.items() if k != "rows"}}
277 else: print(__doc__); sys.exit(1)
278 print(json.dumps(out, indent=1))
279
280if __name__ == "__main__":
281 main()
282
1#!/usr/bin/env python3
2"""Render source ranges back to back with ffmpeg, levelled to a loudness target.
3
4Python 3 standard library only; needs ffmpeg.
5
6 render.py ranges.json OUT.mp4 [--lufs -14] [--tp -1] [--fade 0.02] [--crf 20] [--threads 4] [--preview]
7
8ranges.json is cutplan.py's output (or {"media": path, "ranges": [[in, out], ...]}). Every join
9gets a short audio fade (--fade seconds each side) so it never clicks. Loudness is measured in a
10first pass and applied as one linear gain in the second, so the voice is not pumped.
11
12 --preview 540p, fast encode, for looking at only
13"""
14import json, re, subprocess, sys
15
16def probe(path):
17 r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,r_frame_rate",
18 "-of", "json", path], capture_output=True, text=True)
19 s = json.loads(r.stdout)["streams"][0]; n, _, d = s["r_frame_rate"].partition("/")
20 return s["width"], s["height"], float(n) / float(d or 1)
21
22def even(x): return int(round(x / 2) * 2)
23
24def graph(ranges, fade, fps, ow=None, oh=None, audio_only=False):
25 """Video: one select pass (decode once) keeps the frames of every range. Audio: each range
26 trimmed with a short fade at both ends, then joined."""
27 n = len(ranges); parts = []
28 if not audio_only:
29 h = 0.5 / fps
30 sel = "+".join(f"between(t,{a - h:.4f},{b - h:.4f})" for a, b in ranges)
31 size = f",scale={ow}:{oh}:flags=lanczos" if ow else ""
32 parts.append(f"[0:v]select='{sel}'{size},setsar=1,setpts=N/({fps:.5f}*TB)[vc]")
33 parts.append(f"[0:a]asplit={n}" + "".join(f"[a{i}]" for i in range(n)))
34 for i, (a, b) in enumerate(ranges):
35 d = b - a; f = min(fade, d / 4)
36 parts.append(f"[a{i}]atrim=start={a:.4f}:end={b:.4f},asetpts=PTS-STARTPTS,"
37 f"afade=t=in:d={f:.3f},afade=t=out:st={d - f:.4f}:d={f:.3f}[A{i}]")
38 parts.append("".join(f"[A{i}]" for i in range(n)) + f"concat=n={n}:v=0:a=1[ac]")
39 return ";".join(parts)
40
41def main():
42 a = sys.argv[1:]
43 if len(a) < 2: print(__doc__); sys.exit(1)
44 opt = lambda k, d: a[a.index(k) + 1] if k in a else d
45 plan = json.load(open(a[0])); out = a[1]
46 media, ranges = plan["media"], [r[:2] for r in plan["ranges"]]
47 for (a0, b0), (a1, b1) in zip(ranges, ranges[1:]):
48 if a1 < b0 - 1e-6: sys.exit(f"ranges overlap or go back in time at {a1}; run cutplan.py plan again")
49 sw, sh, fps = probe(media)
50 preview = "--preview" in a
51 ow, oh = (even(sw * 540 / min(sw, sh)), even(sh * 540 / min(sw, sh))) if preview else (None, None)
52 fade, lufs, tp = float(opt("--fade", 0.02)), float(opt("--lufs", -14)), float(opt("--tp", -1))
53 threads = opt("--threads", "4")
54 # pass 1: measure the joined audio
55 g = graph(ranges, fade, fps, audio_only=True)
56 r = subprocess.run(["ffmpeg", "-v", "info", "-nostats", "-threads", threads, "-i", media, "-filter_complex",
57 g + f";[ac]loudnorm=I={lufs}:TP={tp}:LRA=11:print_format=json[o]", "-map", "[o]", "-f", "null", "-"],
58 capture_output=True, text=True)
59 m = json.loads(r.stderr[r.stderr.rfind("{"):r.stderr.rfind("}") + 1])
60 ln = (f"loudnorm=I={lufs}:TP={tp}:LRA=11:measured_I={m['input_i']}:measured_TP={m['input_tp']}:"
61 f"measured_LRA={m['input_lra']}:measured_thresh={m['input_thresh']}:offset={m['target_offset']}:linear=true")
62 g = graph(ranges, fade, fps, ow, oh)
63 cmd = ["ffmpeg", "-v", "error", "-y", "-threads", threads, "-i", media, "-filter_complex",
64 g + f";[ac]{ln},aresample=48000[ao]", "-map", "[vc]", "-map", "[ao]",
65 "-c:v", "libx264", "-preset", "veryfast" if preview else "medium", "-crf", "26" if preview else opt("--crf", "20"),
66 "-pix_fmt", "yuv420p", "-r", f"{fps:.5f}", "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", out]
67 p = subprocess.run(cmd, capture_output=True, text=True)
68 if p.returncode: print(p.stderr[-2000:]); sys.exit(p.returncode)
69 print(f"{out}: {len(ranges)} ranges, {sum(b - a for a, b in ranges):.2f} s, {ow or sw}x{oh or sh}, measured {m['input_i']} LUFS -> {lufs}")
70
71if __name__ == "__main__":
72 main()
73
1#!/usr/bin/env python3
2"""Check a rendered cut against what was meant to be kept.
3
4Python 3 standard library only; needs ffmpeg, ffprobe and whisper-cli (or --heard with your own
5transcript of the output).
6
7 verify.py OUT.mp4 words.json edl.json ranges.json --model MODEL.bin [--max-pause 0.30]
8 verify.py OUT.mp4 words.json edl.json ranges.json --heard out_transcript.json
9
10Reports, as JSON:
11 words expected words not heard in the output (clipped or dropped), and which sit at a join
12 (the usual sign of a clipped edge); extra words heard, each with its source time span
13 and whether it is a filler the transcript missed (add those spans to edl "cutTimes")
14 retakes neighbouring sentences in the output that still share >= 60% of their words
15 pauses silences inside the speech: median, p90, every one over --max-pause, and pauses
16 that hold a breath (the voice band quiet for over 0.3 s; silence alone misses them)
17 joins joins that fall while the sound is loud (10 dB or more over the silence level): a
18 chopped word or a click; move that edge to a pause. hardJumps: joins where the
19 picture jumps far more than at the others (a big change of pose: mean grey change over 3 (0-255 scale)
20 and 2.5x the median); shortPieces: pieces under 1.0 s between two cuts
21 av video and audio stream durations and their difference
22 loudness integrated LUFS and true peak
23A clean result has no missing join words, no extra fillers, no retakes, no pause over the limit, no loud join, an A/V difference under one frame, and loudness on target.
24"""
25import difflib, json, os, re, subprocess, sys
26sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
27from measure import audio, levels, pct, speech_gaps, join_jumps
28from words import load, model_name
29from cutplan import norm, sentences, FILLERS
30
31def to_source(plan, t):
32 """Output time -> source time, through the ranges."""
33 acc = 0.0
34 for a, b in plan["ranges"]:
35 if t <= acc + (b - a): return round(a + t - acc, 3)
36 acc += b - a
37 return round(plan["ranges"][-1][1], 3)
38
39def stream_durations(path):
40 """Decoded lengths: video frames x frame time, audio samples / rate. Container durations
41 include the AAC encoder's priming and padding, which are not heard."""
42 r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_packets", "-show_entries",
43 "stream=nb_read_packets,r_frame_rate", "-of", "json", path], capture_output=True, text=True)
44 v = json.loads(r.stdout)["streams"][0]; n, _, d = v["r_frame_rate"].partition("/")
45 vd = int(v["nb_read_packets"]) / (float(n) / float(d or 1))
46 pcm = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-map", "0:a:0", "-ac", "1", "-ar", "48000", "-f", "s16le", "-"],
47 capture_output=True).stdout
48 return round(vd, 3), round(len(pcm) / 2 / 48000, 3)
49
50def transcribe(path, model):
51 base = os.path.splitext(path)[0] + ".verify"
52 subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", path, "-ac", "1", "-ar", "16000", base + ".wav"], check=True)
53 subprocess.run(["whisper-cli", "-m", model, "-f", base + ".wav", "-ojf", "-of", base, "-t", "4",
54 "--dtw", model_name(model), "-nfa", "--prompt", "Umm, so, I I mean, like, uh, you know, the the thing is, hmm."], capture_output=True, check=True)
55 os.remove(base + ".wav")
56 return base + ".json"
57
58def main():
59 a = sys.argv[1:]
60 if len(a) < 4: print(__doc__); sys.exit(1)
61 out, words, edl, plan = a[0], json.load(open(a[1])), json.load(open(a[2])), json.load(open(a[3]))
62 max_pause = float(a[a.index("--max-pause") + 1]) if "--max-pause" in a else 0.30
63 heard_path = a[a.index("--heard") + 1] if "--heard" in a else transcribe(out, a[a.index("--model") + 1])
64 heard, _ = load(heard_path, out)
65 exp = [words[i] for item in edl["keep"] for i in range(int(item[0]), int(item[1]) + 1)]
66 edge_idx = set()
67 for item in edl["keep"]:
68 edge_idx.update({int(item[0]), int(item[1])})
69 E = [norm(w["w"]) for w in exp]; H = [norm(w["w"]) for w in heard]
70 sm = difflib.SequenceMatcher(None, E, H, autojunk=False)
71 missing, extra = [], []
72 for op, i1, i2, j1, j2 in sm.get_opcodes():
73 if op in ("delete", "replace"):
74 for k in range(i1, i2):
75 missing.append({"word": exp[k]["i"], "text": exp[k]["w"], "atJoin": exp[k]["i"] in edge_idx})
76 if op in ("insert", "replace"):
77 for k in range(j1, j2):
78 extra.append({"text": heard[k]["w"], "at": heard[k]["start"],
79 "source": [to_source(plan, heard[k]["start"]), to_source(plan, heard[k]["end"])],
80 "filler": norm(heard[k]["w"]) in FILLERS})
81 # retakes left in the output
82 rets = []
83 ss = sentences(heard)
84 for (a0, a1), (b0, b1) in zip(ss, ss[1:]):
85 A = [norm(w["w"]) for w in heard[a0:a1 + 1] if norm(w["w"])]; B = {norm(w["w"]) for w in heard[b0:b1 + 1]}
86 if len(A) >= 3 and sum(x in B for x in A) / len(A) >= 0.6:
87 rets.append({"at": heard[a0]["start"], "first": " ".join(w["w"] for w in heard[a0:a1 + 1]),
88 "second": " ".join(w["w"] for w in heard[b0:b1 + 1])})
89 au = audio(out, {})
90 lv = levels(out, {}); thr, gaps, _ = speech_gaps(lv)
91 long = [{"at": s, "seconds": g} for s, g in gaps if g > max_pause]
92 # a join should fall where the sound is quiet; a loud join is a chopped word or a click
93 joins, t = [], 0.0
94 for r in plan["ranges"][:-1]:
95 t += r[1] - r[0]
96 i = int(t / 0.01)
97 near = lv[max(0, i - 2):i + 2]
98 if near and max(near) > thr + 10: joins.append({"at": round(t, 2), "source": round(r[1], 3), "levelOverSilenceDb": round(max(near) - thr, 1)})
99 # picture at each join: how far the frame jumps, and pieces short enough to flash past
100 jt, acc = [], 0.0
101 for r in plan["ranges"][:-1]:
102 acc += r[1] - r[0]; jt.append(acc)
103 jj = join_jumps(out, jt); med = jj["medianJump"]
104 hard = [dict(j, source=round(plan["ranges"][k][1], 3)) for k, j in enumerate(jj["joins"]) if j["hard"]]
105 lens = [r[1] - r[0] for r in plan["ranges"]]
106 short = [{"at": round(sum(lens[:i]), 3), "seconds": round(L, 2)} for i, L in enumerate(lens) if L < 1.0 and 0 < i < len(lens) - 1]
107 vd, ad = stream_durations(out)
108 res = {"words": {"expected": len(E), "heard": len(H), "match": round(sm.ratio(), 3),
109 "missingAtJoins": [m for m in missing if m["atJoin"]], "missingElsewhere": len([m for m in missing if not m["atJoin"]]),
110 "missing": missing[:40], "extraFillers": [x for x in extra if x["filler"]], "extra": [x for x in extra if not x["filler"]][:40]},
111 "retakes": rets, "pauses": {"median": au["gapMedianS"], "p90": au["gapP90S"], "overLimit": long,
112 "breathGapsOver0.3": au["breathGapsOver0.3"], "breathGapsLongest": au["breathGapsLongest"]},
113 "joins": {"count": len(plan["ranges"]) - 1, "loudJoins": joins, "medianJump": med, "hardJumps": hard,
114 "shortPieces": short},
115 "av": {"video": vd, "audio": ad, "diff": round(abs((vd or 0) - (ad or 0)), 3)},
116 "loudness": {"lufs": au["lufs"], "truePeak": au["truePeak"]}, "heardTranscript": heard_path}
117 print(json.dumps(res, indent=1))
118
119if __name__ == "__main__":
120 main()
121
1#!/usr/bin/env python3
2"""Turn a transcript into numbered words with times, and print it for reading.
3
4Python 3 standard library only.
5
6 words.py TRANSCRIPT.json [--media FILE] [--offset S] [-o words.json]
7
8With --media, word times are placed on the sound: whisper.cpp's own token times can be 0.5 s or
9more off, so run whisper-cli with --dtw <model name> -nfa (token anchors that sit within about
100.08 s of each word's end) and pass the media here. Each boundary between two words is then moved
11into the silence nearest its anchor (within 0.35 s), measured from the file's 10 ms levels.
12Voiced stretches with no word in them (a breath, an "uh" the transcriber dropped, a lip smack)
13are written to sounds.json next to the output and shown in the text as <sound 0.4s>.
14
15Reads whisper.cpp JSON (-ojf, token times), whisper.cpp -oj with -ml 1,
16openai-whisper / faster-whisper JSON with word timestamps ("segments"[].words), or a plain
17{"words": [{"word"|"text", "start", "end"}]} list. Writes words.json:
18 [{"i": 0, "w": "So", "start": 1.23, "end": 1.41}, ...]
19and prints one line per sentence: "[first-last] start-end text", with gaps of 0.3 s or more
20marked as "/0.8s/" so pauses and restarts are visible while reading.
21"""
22import json, re, sys
23
24def model_name(path):
25 """ggml-small.en-q5_1.bin -> small.en, the name whisper-cli's --dtw expects."""
26 import os
27 b = os.path.basename(path)
28 b = re.sub(r"^ggml-", "", re.sub(r"\.bin$", "", b))
29 return re.sub(r"-q\d.*$", "", b).replace("large-v", "large.v")
30
31def from_whisper_dtw(d):
32 """Words with DTW anchors: [text, anchor of first token, anchor of last token]."""
33 out = []
34 for seg in d.get("transcription", []):
35 for tk in seg.get("tokens", []):
36 txt = tk["text"]
37 if txt.startswith("[_") or tk.get("t_dtw", -1) < 0: continue
38 t = tk["t_dtw"] / 100
39 if txt.startswith(" ") or not out:
40 if txt.strip(): out.append([txt.strip(), t, t])
41 else:
42 out[-1][0] += txt; out[-1][2] = t
43 return out
44
45def silences(lv, thr, min_len=0.06, hop=0.01):
46 out, i = [], 0
47 while i < len(lv):
48 if lv[i] <= thr:
49 j = i
50 while j < len(lv) and lv[j] <= thr: j += 1
51 if (j - i) * hop >= min_len: out.append([round(i * hop, 3), round(j * hop, 3)])
52 i = j
53 else: i += 1
54 return out
55
56def snap(ws, media, end_bias=0.06, win=0.35):
57 """Place [text, a0, a1] DTW words on the sound. Returns words and untranscribed sounds."""
58 import os
59 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
60 from measure import levels, pct
61 lv = levels(media, {})
62 floor, voice = pct(lv, 10), pct(lv, 90)
63 thr = max(floor + 6, voice - 25) if voice - floor > 12 else floor + (voice - floor) * 0.5
64 S = silences(lv, thr)
65 b = [w[2] + end_bias for w in ws] # estimated boundary after each word
66 claim = {}
67 for s, e in S:
68 best = None
69 for i, bi in enumerate(b):
70 d = 0 if s - 0.05 <= bi <= e + 0.05 else min(abs(bi - s), abs(bi - e))
71 if d <= win and (best is None or d < best[0]): best = (d, i)
72 if best:
73 i = best[1]
74 if i not in claim or e - s > claim[i][1] - claim[i][0]: claim[i] = (s, e)
75 out = []
76 for i, w in enumerate(ws):
77 end = claim[i][0] if i in claim else b[i]
78 if i == 0:
79 c = [e for s, e in S if e <= end - 0.05]
80 start = c[-1] if c else max(0.0, end - 0.4)
81 else:
82 start = claim[i - 1][1] if (i - 1) in claim else b[i - 1]
83 if end - start > 1.5: # a long word usually swallowed a pause or a dropped word
84 inner = [x for x in S if start < x[0] and x[1] < end]
85 if inner: start = inner[-1][1] if w[1] + end_bias > inner[-1][1] else start
86 if end <= start: end = start + 0.05
87 out.append([w[0], round(start, 3), round(end, 3)])
88 # voiced stretches between silences that no word touches
89 sounds, prev = [], 0.0
90 edges = S + [[len(lv) * 0.01, len(lv) * 0.01]]
91 for s, e in edges:
92 a, z = prev, s
93 if z - a >= 0.08 and not any(min(z, w[2]) - max(a, w[1]) > 0.5 * min(z - a, w[2] - w[1]) for w in out):
94 seg = lv[int(a / 0.01):int(z / 0.01)]
95 pk = max(seg) if seg else thr
96 sounds.append({"start": round(a, 3), "end": round(z, 3), "seconds": round(z - a, 2),
97 "underVoiceDb": round(voice - pk, 1)})
98 prev = e
99 return out, sounds
100
101def from_whisper_cpp(d):
102 out = []
103 for seg in d.get("transcription", []):
104 toks = seg.get("tokens")
105 if not toks: # -oj with -ml 1: one word per segment
106 t = seg["text"].strip()
107 if t: out.append([t, seg["offsets"]["from"] / 1000, seg["offsets"]["to"] / 1000])
108 continue
109 for tk in toks:
110 txt = tk["text"]
111 if txt.startswith("[_") or not txt.strip() and not out:
112 continue
113 t0, t1 = tk["offsets"]["from"] / 1000, tk["offsets"]["to"] / 1000
114 if txt.startswith(" ") or not out:
115 if txt.strip(): out.append([txt.strip(), t0, t1])
116 else:
117 out[-1][0] += txt; out[-1][2] = max(out[-1][2], t1)
118 for k in range(len(out) - 1):
119 if out[k][2] <= out[k][1]: out[k][2] = max(out[k][1] + 0.05, min(out[k + 1][1], out[k][1] + 1.2))
120 if out and out[-1][2] <= out[-1][1]: out[-1][2] = out[-1][1] + 0.4
121 return out
122
123def load(path, media=None):
124 d = json.load(open(path))
125 sounds = None
126 if isinstance(d, dict) and "transcription" in d:
127 dtw = from_whisper_dtw(d)
128 if media and dtw and len(dtw) >= 0.9 * len(from_whisper_cpp(d)):
129 ws, sounds = snap(dtw, media)
130 else:
131 if media: print("no DTW anchors in this transcript (run whisper-cli with --dtw <model name> -nfa); times are whisper's own and can be 0.5 s off", file=sys.stderr)
132 ws = from_whisper_cpp(d)
133 elif isinstance(d, dict) and "segments" in d:
134 ws = [[(w.get("word") or w.get("text")).strip(), w["start"], w["end"]] for s in d["segments"] for w in s.get("words", [])]
135 else:
136 lst = d["words"] if isinstance(d, dict) else d
137 ws = [[(w.get("word") or w.get("text") or w.get("w")).strip(), w["start"], w["end"]] for w in lst]
138 ws = [w for w in ws if w[0] and not re.fullmatch(r"[\[\(].*[\]\)]", w[0])] # drop [MUSIC], (laughs)
139 res = [{"i": i, "w": w, "start": round(a, 3), "end": round(b, 3)} for i, (w, a, b) in enumerate(ws)]
140 return (res, sounds) if media is not None else res
141
142def show(words, gap=0.3, sounds=()):
143 line, first = [], 0
144 for k, w in enumerate(words):
145 if k:
146 for s in sounds:
147 if words[k - 1]["end"] - 0.02 <= s["start"] and s["end"] <= w["start"] + 0.02:
148 line.append(f"<sound {s['seconds']:.1f}s>")
149 if line and w["start"] - words[k - 1]["end"] >= gap:
150 line.append(f"/{w['start'] - words[k - 1]['end']:.1f}s/")
151 line.append(w["w"])
152 if re.search(r"[.?!]$", w["w"]) or k == len(words) - 1:
153 print(f"[{first}-{k}] {words[first]['start']:.2f}-{w['end']:.2f} {' '.join(line)}")
154 line, first = [], k + 1
155
156if __name__ == "__main__":
157 a = sys.argv[1:]
158 if not a: print(__doc__); sys.exit(1)
159 off = float(a[a.index("--offset") + 1]) if "--offset" in a else 0.0
160 out = a[a.index("-o") + 1] if "-o" in a else "words.json"
161 media = a[a.index("--media") + 1] if "--media" in a else None
162 ws, sounds = load(a[0], media or "") if media else (load(a[0]), None)
163 for w in ws: w["start"] = round(w["start"] + off, 3); w["end"] = round(w["end"] + off, 3)
164 json.dump(ws, open(out, "w"), indent=0)
165 if sounds is not None:
166 import os
167 for x in sounds: x["start"] = round(x["start"] + off, 3); x["end"] = round(x["end"] + off, 3)
168 sp = os.path.join(os.path.dirname(os.path.abspath(out)), "sounds.json")
169 json.dump(sounds, open(sp, "w"), indent=0)
170 print(f"{len(sounds)} untranscribed sounds -> {sp}", file=sys.stderr)
171 show(ws, sounds=sounds or ())
172 print(f"{len(ws)} words -> {out}", file=sys.stderr)
173
Reviews
No reviews yet. Installed it? Tell others how it went.
Versions
- v1.0.0First version25 Nov 2026
More for talking head
Word-Pop Captions
NewBold 1-3 word pop-up captions timed to every word, burned in and safe-zone checked
Talking head, Podcast9:16 video, SRT or VTT
Stickman Video Director
NewTurn a topic, article or script into a narrated stickman video, in 17 styles.
Script16:9 video, 9:16 video, SRT or VTT
VideoAnimated story shorts
New55-70 s vertical cartoon story shorts: flat 2D characters in a painted 3D world.
Script9:16 video