@auscera/cleoedits 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -2
- package/cli.mjs +149 -0
- package/lib/dependencies.mjs +384 -0
- package/lib/run.mjs +114 -0
- package/lib/workspace.mjs +167 -0
- package/package.json +240 -3
- package/workspace/.agents/skills/cleoedits/SKILL.md +29 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/audiogram.json +41 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/facebook.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/linkedin.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/podcast.json +23 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/reels.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/shorts.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/tiktok.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/x.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/youtube-shorts.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/youtube.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/assets/LICENSE-SimpleIcons +30 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/assets/logos.json +1 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Anton-Regular.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/ArchivoBlack-Regular.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/InstrumentSerif-Italic.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Inter.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/LICENSE-PermanentMarker.txt +202 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Montserrat.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Anton.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-ArchivoBlack.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-InstrumentSerif.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Inter.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Montserrat.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-PlayfairDisplay.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Poppins.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-SpaceMono.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PermanentMarker-Regular.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PlayfairDisplay-Italic.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PlayfairDisplay.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-Black.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-Bold.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-ExtraBold.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/SpaceMono-Bold.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/LICENSE-MediaPipe +218 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/LICENSE-YuNet +21 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/NOTICE.md +4 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/selfie_segmenter.tflite +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/yunet.onnx +0 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/LICENSE +21 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/audio-app-ui/STYLE.md +65 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/STYLE.md +53 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/index.html +328 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/data-story/STYLE.md +65 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/data-story/index.html +575 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/design-app-ui/STYLE.md +68 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/editor-ui/STYLE.md +73 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/STYLE.md +54 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/index.html +189 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/explainer-diagram/STYLE.md +64 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/explainer-diagram/index.html +620 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/STYLE.md +55 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/index.html +238 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/growing-city/STYLE.md +66 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/growing-city/index.html +602 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/ink-line/STYLE.md +66 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/ink-line/index.html +777 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/STYLE.md +56 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/index.html +186 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/motion-app-ui/STYLE.md +68 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/STYLE.md +56 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/index.html +244 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-world/STYLE.md +67 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-world/index.html +663 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/particle-field/STYLE.md +59 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/particle-field/index.html +395 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/STYLE.md +52 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/index.html +194 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/STYLE.md +58 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/index.html +242 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/STYLE.md +53 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/index.html +138 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-kinetic/STYLE.md +63 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-kinetic/index.html +599 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/time-travel/STYLE.md +65 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/time-travel/index.html +1297 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/weather-widget/STYLE.md +69 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/weather-widget/index.html +674 -0
- package/workspace/.agents/skills/cleoedits/references/audio-clearervoice-elevenlabs.md +11 -0
- package/workspace/.agents/skills/cleoedits/references/ffmpeg-and-reels.md +15 -0
- package/workspace/.agents/skills/cleoedits/references/hyperframes-workflows.md +13 -0
- package/workspace/.agents/skills/cleoedits/references/kdenlive-cli-and-mcp.md +12 -0
- package/workspace/.agents/skills/cleoedits/references/motion-design-pipeline.md +7 -0
- package/workspace/.agents/skills/cleoedits/references/motion-taste-emil.md +5 -0
- package/workspace/.agents/skills/cleoedits/references/playwright-demo-capture.md +9 -0
- package/workspace/.agents/skills/cleoedits/references/remotion-workflows.md +13 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/LICENSE +21 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_ass_overlay.py +399 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/__init__.py +235 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/alpha.py +560 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/asr.py +1237 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/color.py +540 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/decision.py +2452 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/drawtext.py +290 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/emit.py +1309 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/emoji.py +518 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/fonts.py +875 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/pacing.py +263 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/pacing_edit.py +432 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/probe.py +1613 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/runner.py +3994 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/text.py +73 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/timeline.py +721 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/wrap.py +981 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_contract.py +2454 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_platforms.py +258 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_review.html +754 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_review.py +258 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_smartcut.py +450 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/audio.py +867 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/background.py +136 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/batch.py +1409 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/broll.py +282 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/caption.py +2207 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/check.py +815 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/color.py +695 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/crop.py +91 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/cropdetect.py +214 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/cut.py +2076 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/deinterlace.py +90 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/denoise.py +94 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/export.py +1033 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/fit.py +729 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/freeze.py +197 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/graphics.py +920 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/grid.py +235 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/insert.py +142 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/join.py +1083 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/look.py +475 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/loop.py +395 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/loudness.py +397 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/metadata.py +416 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/multicam.py +414 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/overlay.py +766 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/pad.py +121 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/probe.py +145 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/proxy.py +93 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/redact.py +162 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/render.py +2424 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/report.py +354 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/reverse.py +114 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/scenes.py +439 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sequence.py +285 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/silence.py +945 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/speedramp.py +193 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sphere.py +137 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/stabilize.py +141 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/straighten.py +120 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sync.py +500 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/verify.py +411 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/waveform.py +502 -0
- package/workspace/.agents/skills/cleoedits/scripts/kdenlive_builder.py +284 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/LICENSE-claude-motion +21 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/LICENSE-motion-design +21 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/_media.py +43 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/pacing_check.py +90 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/storyboard.py +77 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/LICENSE +26 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/fx.py +2717 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/logos.py +194 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/sfx.py +105 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/trim.py +99 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/words.py +60 -0
- package/workspace/.claude/commands/blender-3d.md +12 -0
- package/workspace/.claude/commands/business-short-form-reels.md +12 -0
- package/workspace/.claude/commands/color-grade.md +12 -0
- package/workspace/.claude/commands/cutout-grid-reel.md +12 -0
- package/workspace/.claude/commands/depth-ui-reel.md +12 -0
- package/workspace/.claude/commands/explainer-panel-reel.md +12 -0
- package/workspace/.claude/commands/freeze-frame.md +12 -0
- package/workspace/.claude/commands/glass-graph.md +12 -0
- package/workspace/.claude/commands/over-the-shoulder.md +12 -0
- package/workspace/.claude/commands/personal-short-form-reels.md +12 -0
- package/workspace/.claude/commands/ranking-format.md +12 -0
- package/workspace/.claude/commands/relight.md +12 -0
- package/workspace/.claude/commands/reverse-engineer.md +12 -0
- package/workspace/.claude/commands/text-behind.md +12 -0
- package/workspace/.claude/commands/tier-list.md +12 -0
- package/workspace/.claude-plugin/plugin.json +8 -0
- package/workspace/.npmignore +15 -0
- package/workspace/AGENTS.md +30 -0
- package/workspace/README.md +63 -0
- package/workspace/assets/fonts/TikTokSans-OFL.txt +93 -0
- package/workspace/assets/fonts/TikTokSans-Variable.ttf +0 -0
- package/workspace/assets/luts/clean_warm.cube +4917 -0
- package/workspace/assets/luts/golden_hour.cube +4917 -0
- package/workspace/assets/luts/moody_dark.cube +4917 -0
- package/workspace/assets/luts/teal_orange.cube +4917 -0
- package/workspace/assets/sfx/NOTICE.txt +1 -0
- package/workspace/assets/sfx/click.wav +0 -0
- package/workspace/assets/sfx/pop.wav +0 -0
- package/workspace/assets/sfx/riser.wav +0 -0
- package/workspace/assets/sfx/whoosh.wav +0 -0
- package/workspace/generators/hyperframes/index.html +39 -0
- package/workspace/generators/hyperframes/package.json +15 -0
- package/workspace/generators/hyperframes/pnpm-lock.yaml +1181 -0
- package/workspace/generators/hyperframes/pnpm-workspace.yaml +10 -0
- package/workspace/generators/remotion/eslint.config.mjs +3 -0
- package/workspace/generators/remotion/package.json +36 -0
- package/workspace/generators/remotion/pnpm-lock.yaml +4179 -0
- package/workspace/generators/remotion/pnpm-workspace.yaml +10 -0
- package/workspace/generators/remotion/remotion.config.ts +13 -0
- package/workspace/generators/remotion/src/Root.tsx +52 -0
- package/workspace/generators/remotion/src/index.css +1 -0
- package/workspace/generators/remotion/src/index.ts +4 -0
- package/workspace/generators/remotion/tsconfig.json +15 -0
- package/workspace/pipeline/scripts/_codec.py +28 -0
- package/workspace/pipeline/scripts/ai_media_api.py +109 -0
- package/workspace/pipeline/scripts/blender_render.py +166 -0
- package/workspace/pipeline/scripts/composite.py +49 -0
- package/workspace/pipeline/scripts/melt.sh +68 -0
- package/workspace/pipeline/scripts/normalize_audio.py +39 -0
- package/workspace/pipeline/scripts/person_matte.py +216 -0
- package/workspace/pipeline/scripts/record_demo.py +69 -0
- package/workspace/pipeline/scripts/whisper_cut.py +98 -0
- package/workspace-manifest.json +908 -0
|
@@ -0,0 +1,945 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Remove silences / dead air (jump-cut editing) or just list them.
|
|
3
|
+
|
|
4
|
+
Detects quiet stretches with ffmpeg's silencedetect, keeps a margin on each
|
|
5
|
+
side so words are not clipped, drops gaps shorter than --min-silence, and
|
|
6
|
+
writes a frame-accurate re-encode: the kept ranges are re-cut from the source the way
|
|
7
|
+
cut.py --segments --accurate cuts them (both streams on one set of frame-grid bounds).
|
|
8
|
+
|
|
9
|
+
Examples:
|
|
10
|
+
python3 silence.py talk.mp4 # -35 dB, gaps >= 0.6 s, 0.2 s margin
|
|
11
|
+
python3 silence.py talk.mp4 --threshold -40 --min-silence 1 --margin 0.25
|
|
12
|
+
python3 silence.py talk.mp4 --margin-lead 0.1 --margin-tail 0.4 # less before a word, more after one
|
|
13
|
+
python3 silence.py talk.mp4 --words talk.json --min-silence 0.2 --sentence-min-silence 0.3 --sentence-margin-tail 0.3
|
|
14
|
+
# pauses inside a sentence from 0.2 s, after one from 0.3 s with a longer tail
|
|
15
|
+
python3 silence.py talk.mp4 --list # print the silences and the resulting cut list, no output
|
|
16
|
+
python3 silence.py talk.mp4 --edl keep.txt # also save the kept ranges (START-END per line, cut.py --segments format)
|
|
17
|
+
"""
|
|
18
|
+
import argparse
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
import os
|
|
22
|
+
import sys
|
|
23
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
24
|
+
|
|
25
|
+
# `detect` moved into _common/probe.py in 1.16.0 so metadata.py --auto-chapters can measure the
|
|
26
|
+
# same silences without importing this tool; the body is unchanged and the name still lives here.
|
|
27
|
+
from _common import (filler_spans, FILLER_WORDS, FILLER_AMBIGUOUS, FILLER_DISCOURSE_MARKERS,
|
|
28
|
+
FILLER_PAD, read_text_or_die)
|
|
29
|
+
from _common import asr as _asr
|
|
30
|
+
from _common.emit import warn
|
|
31
|
+
from _common.asr import _dicts
|
|
32
|
+
from _common.runner import parse_json, replace_checked, same_file
|
|
33
|
+
from _common import guard_sidecar, refuse_existing_outputs, refuse_unwritten_output, refuse_output_is_input, _check_output_path
|
|
34
|
+
from _common.emit import refuse
|
|
35
|
+
from _common import detect_silences as detect, STATE, add_common, apply_common, default_output, die, emit, info, is_audio_output, print_json, probe, X264_PRESETS, measured_level_dbfs, fmt_secs
|
|
36
|
+
from _common.decision import frame_rate, grid_at_or_after, stream_starts
|
|
37
|
+
from _common.probe import PROBED_AUDIO
|
|
38
|
+
from _common.emit import input_length
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def merge_spans(spans: List[Tuple[float, float]]) -> List[Tuple[float, float]]:
|
|
43
|
+
"""`spans` sorted and coalesced: any pair that touches or overlaps becomes one.
|
|
44
|
+
|
|
45
|
+
keep_ranges() walks a single cursor forward, so it needs a removal list in which no span
|
|
46
|
+
starts before the previous one ended. Silences and filler spans are each merged only among
|
|
47
|
+
themselves -- and a mumbled "um" is very often quiet enough to sit INSIDE a detected silence --
|
|
48
|
+
so the union has to be taken before the two lists are handed over as one.
|
|
49
|
+
"""
|
|
50
|
+
out: List[Tuple[float, float]] = []
|
|
51
|
+
for s, e in sorted(spans):
|
|
52
|
+
if out and s <= out[-1][1]:
|
|
53
|
+
out[-1] = (out[-1][0], max(out[-1][1], e))
|
|
54
|
+
else:
|
|
55
|
+
out.append((s, e))
|
|
56
|
+
return out
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# around each cut, how many seconds on either side the level is measured over, and how close to
|
|
60
|
+
# --threshold (in dB) that level may come before the cut is flagged: room tone sits far below the
|
|
61
|
+
# threshold, a breath or a word's weak tail just under it
|
|
62
|
+
CUT_LEVEL_WINDOW = 0.05
|
|
63
|
+
CUT_SOUND_MARGIN_DB = 10.0
|
|
64
|
+
CUT_LEVEL_RATE = 8000
|
|
65
|
+
CUT_LEVEL_CHANNELS = 2 # measured one by one; a surround source is folded to two first
|
|
66
|
+
DIGITAL_SILENCE_DB = -90.0 # 2.20: at or below this a span is digital silence (16-bit dither sits near -96)
|
|
67
|
+
BREATH_FLOOR = 0.12 # shortest gap silencedetect is asked for under --speech-aware
|
|
68
|
+
# a transcript word that ends in one of these (after any closing quote or bracket) ends a sentence
|
|
69
|
+
SENTENCE_END = ".!?\u3002\uff01\uff1f\u2026\u0964\u061f"
|
|
70
|
+
SENTENCE_CLOSERS = "\"'\u201d\u2019\u300d\u300f\uff09)]\u3011 "
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def ends_sentence(word: str) -> bool:
|
|
74
|
+
"""Whether a transcript word carries sentence-final punctuation: read off the text the speech
|
|
75
|
+
engine wrote, never guessed from the sound."""
|
|
76
|
+
text = str(word or "").rstrip(SENTENCE_CLOSERS)
|
|
77
|
+
return bool(text) and text[-1] in SENTENCE_END
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def silence_positions(silences: List[Tuple[float, float]], words: "list",
|
|
81
|
+
duration: Optional[float] = None) -> List[str]:
|
|
82
|
+
"""Per silence, `sentence_end` when the word spoken before it ends a sentence, else `inside`.
|
|
83
|
+
The word before a silence is the last one whose own midpoint lies before the silence's
|
|
84
|
+
midpoint; a silence that runs to the end of the file ends at `duration`. An engine
|
|
85
|
+
stretches a word's timing into the pause beside it, the end of the word before or the start
|
|
86
|
+
of the word after (on demos/footage/ai_talk_en.mp4 three word starts sit 0.45 to 0.5 s before
|
|
87
|
+
the sound does), and a word's midpoint stays on its own side of the pause either way. A
|
|
88
|
+
silence with no word before it is `inside`."""
|
|
89
|
+
import bisect
|
|
90
|
+
timed = sorted(words, key=lambda w: w["start"] + w["end"])
|
|
91
|
+
mids = [(w["start"] + w["end"]) / 2 for w in timed]
|
|
92
|
+
out: List[str] = []
|
|
93
|
+
for s, e in silences:
|
|
94
|
+
if e == float("inf"):
|
|
95
|
+
e = max(s, duration) if duration is not None else s
|
|
96
|
+
# the last word whose midpoint is before the silence's: a binary search, not a scan of the
|
|
97
|
+
# whole transcript per silence (an hour of speech has thousands of each)
|
|
98
|
+
k = bisect.bisect_left(mids, (s + e) / 2)
|
|
99
|
+
out.append("sentence_end" if k and ends_sentence(timed[k - 1]["word"]) else "inside")
|
|
100
|
+
return out
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def sentence_words(args) -> "Tuple[list, str]":
|
|
104
|
+
"""(word timings, where they came from) for --sentence-min-silence / --sentence-margin-tail.
|
|
105
|
+
Under --filler the transcript that run read or made is reused; otherwise --words is read, or
|
|
106
|
+
--transcribe runs the local engine. Refuses without one: where a sentence ends is taken from
|
|
107
|
+
the transcript's punctuation, and there is no reading it off a pause."""
|
|
108
|
+
def usable(words: "list", source: str) -> "Tuple[list, str]":
|
|
109
|
+
# a word with no length or a time that is not a number cannot be placed against a pause
|
|
110
|
+
timed = [w for w in words if math.isfinite(w["start"]) and math.isfinite(w["end"]) and w["end"] > w["start"]]
|
|
111
|
+
if not timed:
|
|
112
|
+
die(f"no usable word timings in the transcript ({source}): every word's start and end must be "
|
|
113
|
+
"numbers with the end after the start, or there is nothing to place a sentence end against a pause",
|
|
114
|
+
kind="input")
|
|
115
|
+
return timed, source
|
|
116
|
+
|
|
117
|
+
if getattr(args, "_words", None) is not None:
|
|
118
|
+
return usable(args._words, args._words_source)
|
|
119
|
+
if args.words:
|
|
120
|
+
try:
|
|
121
|
+
raw = parse_json(read_text_or_die(args.words, "--words"))
|
|
122
|
+
except ValueError as exc:
|
|
123
|
+
die(f"--words {args.words}: not readable JSON ({exc})", kind="input")
|
|
124
|
+
words, _had_segments, _untimed = _words_from_words_file(args.words, raw)
|
|
125
|
+
if not words:
|
|
126
|
+
die(f"no word timings in {args.words}: the sentence flags need "
|
|
127
|
+
'{"words": [{"word": ..., "start": ..., "end": ...}]} (or the same inside "segments").',
|
|
128
|
+
kind="input")
|
|
129
|
+
return usable(words, f"whisper-json:{args.words}")
|
|
130
|
+
if args.transcribe:
|
|
131
|
+
asr_run = _asr.transcribe_words_result(args.input, None, model=args.model, engine=args.engine)
|
|
132
|
+
if not asr_run.words:
|
|
133
|
+
die(f"{asr_run.engine or 'the local engine'} ran but produced no word-level timings, so there is "
|
|
134
|
+
"nothing to tell a sentence end from. Pass a transcript with word timings as --words.", kind="input")
|
|
135
|
+
family = "parakeet" if asr_run.engine in _asr.PARAKEET_ENGINES else "whisper"
|
|
136
|
+
return usable(asr_run.words, f"{family}:{asr_run.engine}" if asr_run.engine else "whisper")
|
|
137
|
+
die("--sentence-min-silence and --sentence-margin-tail need word timings: pass --words transcript.json "
|
|
138
|
+
"(a whisper JSON with word timestamps) or --transcribe. A sentence end is read from the transcript's "
|
|
139
|
+
"punctuation; a pause's length does not say where one is.", kind="input")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def speech_aware_silences(path: str, threshold: float, min_silence: float) -> "Tuple[List[Tuple[float, float]], List[Tuple[float, float]]]":
|
|
143
|
+
"""(sentence-boundary silences to remove, breaths kept) for --speech-aware.
|
|
144
|
+
|
|
145
|
+
Re-runs the same silencedetect() already used everywhere else in this file, but with a much
|
|
146
|
+
shorter minimum duration, so short in-sentence breaths are measured at all -- the plain
|
|
147
|
+
`detect()` call above never sees them because its own --min-silence floor filters them out
|
|
148
|
+
before they reach Python. Every gap silencedetect measured that is still shorter than
|
|
149
|
+
--min-silence sits *inside* a sentence -- the two speech-flagged stretches on either side of
|
|
150
|
+
it are close together in time because nothing longer separated them from the gaps around
|
|
151
|
+
them -- and is kept rather than cut; --min-silence keeps the meaning it already has for
|
|
152
|
+
--filler and the plain run: the shortest gap this tool will remove."""
|
|
153
|
+
floor = min(BREATH_FLOOR, min_silence)
|
|
154
|
+
fine = detect(path, threshold, floor)
|
|
155
|
+
boundaries, breaths = [], []
|
|
156
|
+
for s, e in fine:
|
|
157
|
+
length = (e - s) if e != float("inf") else float("inf")
|
|
158
|
+
if length >= min_silence:
|
|
159
|
+
boundaries.append((s, e))
|
|
160
|
+
else:
|
|
161
|
+
breaths.append((s, e))
|
|
162
|
+
return boundaries, breaths
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
# how close to the start or the end of the sound a silence's edge may sit and still be where the sound
|
|
166
|
+
# starts or ends: silencedetect closes a silence that runs to the end at its last decoded block (7.509
|
|
167
|
+
# for a sound probed as 7.500), and an AAC stream's stated start sits a priming frame off its samples
|
|
168
|
+
SOUND_EDGE = 0.05
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def sound_span(meta: Dict[str, Any], duration: float) -> Tuple[float, float]:
|
|
172
|
+
"""Where the sound starts and ends on the clock silencedetect reports on (the file's), for
|
|
173
|
+
inside_margin(): its start, and its own end (the file's length when that is not stated). The
|
|
174
|
+
end is stream_end()'s: a Matroska DURATION tag is already where the sound ends, and adding the
|
|
175
|
+
start to it put the end of a sound from 1 s to 6 s at 7 s."""
|
|
176
|
+
from _common.emit import file_origin, stream_end
|
|
177
|
+
a0 = stream_starts(meta)[1]
|
|
178
|
+
end = stream_end(meta, "audio")
|
|
179
|
+
return a0, (end - file_origin(meta)) if end is not None else duration
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def inside_margin(silences: List[Tuple[float, float]], duration: float, margin: float,
|
|
183
|
+
lead: Optional[float] = None,
|
|
184
|
+
sound: Optional[Tuple[float, float]] = None) -> List[Tuple[float, float]]:
|
|
185
|
+
"""Each silence with a margin kept on both sides: the stretch actually removed. `margin` is
|
|
186
|
+
kept after the speech that ends where the silence starts (--margin-tail), `lead` before the
|
|
187
|
+
speech that starts where it ends (--margin-lead; the same as `margin` when not given). A
|
|
188
|
+
silence too short to hold both removes nothing (it is dropped, never turned inside out).
|
|
189
|
+
|
|
190
|
+
A silence with no speech on one side keeps no margin on that side (#462 A40): one that starts
|
|
191
|
+
where the sound does (`sound`, from sound_span()) is removed from the file's start, and one
|
|
192
|
+
that runs to where the sound ends (or that silencedetect never closed, `inf`) to the file's end.
|
|
193
|
+
A margin there kept dead air as a piece of its own, with a jump cut after it; FFmpeg 6.1 closes
|
|
194
|
+
a silence at the end of the file, so the `inf` end alone never caught the last one.
|
|
195
|
+
|
|
196
|
+
The margin is applied to the silences alone, before they are merged with filler spans (#414):
|
|
197
|
+
a filler word's span is the word itself plus --filler-pad, and taking a 0.2 s margin off each
|
|
198
|
+
side of it turned every word narrower than 2 x --margin inside out -- kept, and still counted
|
|
199
|
+
as removed."""
|
|
200
|
+
out: List[Tuple[float, float]] = []
|
|
201
|
+
for s, e in silences:
|
|
202
|
+
opens = sound is not None and s <= sound[0] + SOUND_EDGE
|
|
203
|
+
closes = e == float("inf") or (sound is not None and e >= sound[1] - SOUND_EDGE)
|
|
204
|
+
a = 0.0 if opens else s + margin
|
|
205
|
+
b = duration if closes else min(duration, e - (margin if lead is None else lead))
|
|
206
|
+
if b > a:
|
|
207
|
+
out.append((a, b))
|
|
208
|
+
return out
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def keep_ranges(silences: List[Tuple[float, float]], duration: float, margin: float, min_keep: float) -> List[Tuple[float, float]]:
|
|
212
|
+
keeps: List[Tuple[float, float]] = []
|
|
213
|
+
cursor = 0.0
|
|
214
|
+
for s, e in sorted(silences):
|
|
215
|
+
if e != float("inf") and e - margin <= s + margin:
|
|
216
|
+
continue # narrower than two margins: nothing of it is removed (#414)
|
|
217
|
+
s_adj = max(cursor, s + margin)
|
|
218
|
+
if s_adj - cursor >= min_keep:
|
|
219
|
+
keeps.append((cursor, s_adj))
|
|
220
|
+
# max(cursor, ...) so the walk is monotone. A span nested inside the previous one used to
|
|
221
|
+
# rewind the cursor and hand back the very stretch that had just been removed: with a
|
|
222
|
+
# filler word inside a detected silence, adding --filler made the tool remove LESS.
|
|
223
|
+
# merge_spans() above is the caller-side fix; this keeps the function safe on its own.
|
|
224
|
+
cursor = max(cursor, min(duration, e - margin) if e != float("inf") else duration)
|
|
225
|
+
if duration - cursor >= min_keep:
|
|
226
|
+
keeps.append((cursor, duration))
|
|
227
|
+
return keeps
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def rendered_ranges(keeps: List[Tuple[float, float]], meta: Dict[str, Any], duration: float,
|
|
231
|
+
video_out: bool) -> List[Tuple[float, float]]:
|
|
232
|
+
"""The source ranges the render holds, and is given: with a picture, each bound moves to the
|
|
233
|
+
nearest frame time, for the sound too, so cut.py's re-cut (which cuts at the first frame at or
|
|
234
|
+
after a bound) cuts exactly there. A measured bound sits a few microseconds off a frame
|
|
235
|
+
(silencedetect's 4.00002), which "at or after" would have turned into a whole frame dropped.
|
|
236
|
+
Sound alone is cut where asked. --timemap is built from these, so its times are the output's."""
|
|
237
|
+
rate = frame_rate(meta) if video_out else 0.0
|
|
238
|
+
if not rate:
|
|
239
|
+
return list(keeps)
|
|
240
|
+
v0 = stream_starts(meta)[0]
|
|
241
|
+
|
|
242
|
+
def snap(t: float) -> float:
|
|
243
|
+
# a video that starts after the sound puts frame times before 0 on its grid's extension: a
|
|
244
|
+
# bound there moves to the first one at or after 0, which is where the re-cut starts (#462 A43)
|
|
245
|
+
t = v0 + round((t - v0) * rate) / rate
|
|
246
|
+
return min(t if t >= 0 else grid_at_or_after(0.0, v0, rate), duration)
|
|
247
|
+
return [(a, b) for a, b in ((snap(s), snap(e)) for s, e in keeps) if b > a]
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _edl_time(t: float, on_frames: bool) -> str:
|
|
251
|
+
"""An EDL bound: a frame time truncated to the millisecond (below 1000 fps the frame at or
|
|
252
|
+
after it is still that frame), any other time rounded as before."""
|
|
253
|
+
return f"{math.floor(t * 1000 + 1e-6) / 1000:.3f}" if on_frames else f"{t:.3f}"
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def time_map(keeps: List[Tuple[float, float]], duration: float) -> Dict[str, Any]:
|
|
257
|
+
"""Each kept range with its time in the source and in the output, and each removed range with
|
|
258
|
+
the output time it was cut at: re-timing subtitles, or finding a removed sentence again.
|
|
259
|
+
`keeps` are the ranges the render holds (rendered_ranges): the output advances by each one's
|
|
260
|
+
exact length, rounded only for display."""
|
|
261
|
+
kept: List[Dict[str, float]] = []
|
|
262
|
+
removed: List[Dict[str, float]] = []
|
|
263
|
+
out, prev = 0.0, 0.0
|
|
264
|
+
for s, e in keeps:
|
|
265
|
+
if s - prev > 0.0005:
|
|
266
|
+
removed.append({"source_start": round(prev, 3), "source_end": round(s, 3), "output_time": round(out, 3)})
|
|
267
|
+
kept.append({"source_start": round(s, 3), "source_end": round(e, 3),
|
|
268
|
+
"output_start": round(out, 3), "output_end": round(out + (e - s), 3)})
|
|
269
|
+
out += e - s
|
|
270
|
+
prev = e
|
|
271
|
+
if duration - prev > 0.0005:
|
|
272
|
+
removed.append({"source_start": round(prev, 3), "source_end": round(duration, 3), "output_time": round(out, 3)})
|
|
273
|
+
return {"kept": kept, "removed": removed}
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def write_time_map(path: str, tm: Dict[str, Any]) -> None:
|
|
277
|
+
"""--timemap: JSON, or CSV for a .csv path (one row per kept and removed range)."""
|
|
278
|
+
if os.path.splitext(path)[1].lower() == ".csv":
|
|
279
|
+
rows = ["type,source_start,source_end,output_start,output_end"]
|
|
280
|
+
rows += [f"kept,{k['source_start']:.3f},{k['source_end']:.3f},{k['output_start']:.3f},{k['output_end']:.3f}" for k in tm["kept"]]
|
|
281
|
+
rows += [f"removed,{r['source_start']:.3f},{r['source_end']:.3f},{r['output_time']:.3f},{r['output_time']:.3f}" for r in tm["removed"]]
|
|
282
|
+
text = "\n".join(rows) + "\n"
|
|
283
|
+
else:
|
|
284
|
+
text = json.dumps(tm, indent=2) + "\n"
|
|
285
|
+
# staged and swapped in, so a full disk or an interrupted write leaves the previous map whole;
|
|
286
|
+
# the staging name is short and unique, so it neither outgrows the name limit nor truncates a
|
|
287
|
+
# sibling that happens to exist
|
|
288
|
+
import tempfile
|
|
289
|
+
fd, tmp = tempfile.mkstemp(prefix=".tm", suffix=".tmp", dir=os.path.dirname(os.path.abspath(path)))
|
|
290
|
+
try:
|
|
291
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
292
|
+
fh.write(text)
|
|
293
|
+
mask = os.umask(0) # mkstemp makes the file 0600; give the map the mode open() would have
|
|
294
|
+
os.umask(mask)
|
|
295
|
+
os.chmod(tmp, 0o666 & ~mask)
|
|
296
|
+
# under the map's lock, and only while it is the file refuse_existing_outputs() decided about
|
|
297
|
+
replace_checked(tmp, path)
|
|
298
|
+
except BaseException:
|
|
299
|
+
try:
|
|
300
|
+
os.remove(tmp)
|
|
301
|
+
except OSError:
|
|
302
|
+
pass
|
|
303
|
+
raise
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def cut_levels(path: str, tm: Dict[str, Any], duration: float,
|
|
307
|
+
filler_spans_: List[Tuple[float, float]]) -> Optional[List[Dict[str, Any]]]:
|
|
308
|
+
"""The RMS level just around every cut, in dBFS (None for digital silence), measured on the
|
|
309
|
+
source: one decode at CUT_LEVEL_RATE, CUT_LEVEL_WINDOW on each side of the cut point. A probe
|
|
310
|
+
of the output can say its length and streams are right, not whether a cut landed in a breath
|
|
311
|
+
or a word's weak tail; the level there is the measurable part of that question. `edge` is
|
|
312
|
+
`out` where the source is left, `in` where it is picked up again; `filler` marks an edge that
|
|
313
|
+
sits on a removed word (it is meant to sit in sound). Each channel is measured on its own and
|
|
314
|
+
the loudest is reported: a mono mix reads antiphase stereo as silence. The PCM goes to a temp
|
|
315
|
+
file and only the windows are read back, so an hour of audio is not held in memory. None when
|
|
316
|
+
the decode fails: an unmeasured cut is not a silent one."""
|
|
317
|
+
import array
|
|
318
|
+
import math
|
|
319
|
+
import tempfile
|
|
320
|
+
from _common import require_tool, run_analysis
|
|
321
|
+
points = []
|
|
322
|
+
for r in tm["removed"]:
|
|
323
|
+
for t, edge in ((r["source_start"], "out"), (r["source_end"], "in")):
|
|
324
|
+
if (edge == "out" and t <= 0.0005) or (edge == "in" and t >= duration - 0.0005):
|
|
325
|
+
continue
|
|
326
|
+
# this edge, not the whole removed range: a filler merged into a silence leaves the
|
|
327
|
+
# silence's own edge next to speech, and that one still gets checked
|
|
328
|
+
on_word = any(fs - CUT_LEVEL_WINDOW <= t <= fe + CUT_LEVEL_WINDOW for fs, fe in filler_spans_)
|
|
329
|
+
points.append((t, r["output_time"], edge, on_word))
|
|
330
|
+
if not points:
|
|
331
|
+
return []
|
|
332
|
+
channels = CUT_LEVEL_CHANNELS
|
|
333
|
+
half = int(CUT_LEVEL_WINDOW * CUT_LEVEL_RATE)
|
|
334
|
+
frame = 2 * channels
|
|
335
|
+
out = []
|
|
336
|
+
with tempfile.TemporaryDirectory(prefix="silence-levels-") as tmp:
|
|
337
|
+
raw = os.path.join(tmp, "pcm.s16le")
|
|
338
|
+
# padded from the file's start, as decode_pcm_mono() pads it: the windows are read at
|
|
339
|
+
# t x rate, so a sound that starts late was read that far after each cut (#462 A42)
|
|
340
|
+
proc = run_analysis([require_tool("ffmpeg"), "-hide_banner", "-loglevel", "error", "-nostdin", "-i", path,
|
|
341
|
+
"-map", f"0:{PROBED_AUDIO}", "-vn", "-af", "aresample=async=1:first_pts=0",
|
|
342
|
+
"-ac", str(channels), "-ar", str(CUT_LEVEL_RATE), "-f", "s16le", "-y", raw],
|
|
343
|
+
check=False, text=False)
|
|
344
|
+
if proc.returncode != 0 or not os.path.isfile(raw) or not os.path.getsize(raw):
|
|
345
|
+
return None
|
|
346
|
+
with open(raw, "rb") as fh:
|
|
347
|
+
for t, ot, edge, on_word in points:
|
|
348
|
+
first = max(0, int(round(t * CUT_LEVEL_RATE)) - half)
|
|
349
|
+
fh.seek(first * frame)
|
|
350
|
+
data = fh.read(2 * half * frame)
|
|
351
|
+
block = array.array("h")
|
|
352
|
+
block.frombytes(data[: len(data) // frame * frame])
|
|
353
|
+
if sys.byteorder == "big":
|
|
354
|
+
block.byteswap()
|
|
355
|
+
level = None
|
|
356
|
+
if block:
|
|
357
|
+
n = len(block) // channels
|
|
358
|
+
peak = max(math.sqrt(sum(x * x for x in block[c::channels]) / n) for c in range(channels)) / 32768.0
|
|
359
|
+
level = round(20 * math.log10(peak), 1) if peak > 0 else None
|
|
360
|
+
entry = {"source_time": round(t, 3), "output_time": round(ot, 3), "edge": edge, "rms_dbfs": level}
|
|
361
|
+
if on_word:
|
|
362
|
+
entry["filler"] = True
|
|
363
|
+
out.append(entry)
|
|
364
|
+
return out
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _word_list(text: "str") -> "list":
|
|
368
|
+
return [w.strip() for w in str(text or "").replace(",", "\n").splitlines() if w.strip()]
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def resolve_filler(args, meta):
|
|
372
|
+
"""(the `filler` result block, the spans to remove) for --filler. Refuses before any encode.
|
|
373
|
+
|
|
374
|
+
Never without measured word timings: no heuristic fallback, no guess from the filename. The
|
|
375
|
+
three refusals below are the whole safety story for this flag.
|
|
376
|
+
"""
|
|
377
|
+
if not args.words and not args.transcribe:
|
|
378
|
+
die("--filler needs word timings: pass --words transcript.json (a whisper JSON with word "
|
|
379
|
+
"timestamps) or --transcribe. There is no way to find a filler word without them -- "
|
|
380
|
+
"cutting the short quiet blips instead would remove real speech.", kind="input")
|
|
381
|
+
source, engine, raw, transcription = None, None, None, {}
|
|
382
|
+
untimed: list = [] # transcript words without a usable timing (a --words file can carry them)
|
|
383
|
+
if args.words:
|
|
384
|
+
try:
|
|
385
|
+
raw = parse_json(read_text_or_die(args.words, "--words"))
|
|
386
|
+
except ValueError as exc:
|
|
387
|
+
die(f"--words {args.words}: not readable JSON ({exc})", kind="input")
|
|
388
|
+
source = f"whisper-json:{args.words}"
|
|
389
|
+
words, had_segments, untimed = _words_from_words_file(args.words, raw)
|
|
390
|
+
length = float(meta.get("duration") or 0.0)
|
|
391
|
+
late = [w for w in words if w["start"] >= length] if length > 0 else []
|
|
392
|
+
if late:
|
|
393
|
+
# nothing said it: the cuts were planned on times the input does not have (#404)
|
|
394
|
+
warn(f"--words {args.words}: {len(late)} of {len(words)} word timings start at or after the end of the input "
|
|
395
|
+
f"({length:.3f}s; the last at {max(w['start'] for w in late):g}s) -- a transcript of another file, or "
|
|
396
|
+
"times in milliseconds (a whisper JSON's start/end are seconds); no word is cut there",
|
|
397
|
+
"words_outside_input", count=len(late), words=len(words), duration=round(length, 3))
|
|
398
|
+
if not words:
|
|
399
|
+
if had_segments:
|
|
400
|
+
die(f"the transcript in {args.words} has segment timings but no word timings; "
|
|
401
|
+
"--filler removes words, and cutting on segment boundaries would remove whole "
|
|
402
|
+
"sentences. Re-run whisper with word timestamps (whisper.cpp "
|
|
403
|
+
"--output-json-full / faster-whisper word_timestamps=True), or use --list to "
|
|
404
|
+
"see the pauses instead.", kind="input")
|
|
405
|
+
die(f"no word timings in {args.words}: --filler needs "
|
|
406
|
+
'{"words": [{"word": ..., "start": ..., "end": ...}]} (or the same inside '
|
|
407
|
+
'"segments").', kind="input")
|
|
408
|
+
else:
|
|
409
|
+
# No pre-check for an installed engine here: transcribe_words_result() probes for one and
|
|
410
|
+
# raises the same die_no_engine() refusal when there is none. Two places deciding "is
|
|
411
|
+
# whisper here" is two places to disagree.
|
|
412
|
+
# The engine is driven with ITS word-timestamp option (whisper.cpp --output-json-full,
|
|
413
|
+
# faster-whisper word_timestamps=True, openai-whisper --word_timestamps True). An SRT
|
|
414
|
+
# cannot answer this question: a cue has a start and an end, a word does not.
|
|
415
|
+
# The call's own result, not module state: engine, routing and notes belong to this run.
|
|
416
|
+
# Whisper leaves "uh"/"um" out of its text unless the context shows them: prime it with the
|
|
417
|
+
# filler list of the language asked for (English under auto, where most filler cuts are)
|
|
418
|
+
primer = FILLER_WORDS.get(args.filler_lang if args.filler_lang != "auto" else "en") or []
|
|
419
|
+
prompt = (", ".join(sorted(primer)[:8]).capitalize() + ". So, I mean...") if primer else None
|
|
420
|
+
asr_run = _asr.transcribe_words_result(args.input, args.filler_lang if args.filler_lang != "auto" else None,
|
|
421
|
+
model=args.model, engine=args.engine, prompt=prompt)
|
|
422
|
+
words, engine = asr_run.words, asr_run.engine
|
|
423
|
+
transcription = dict(asr_run.facts)
|
|
424
|
+
family = "parakeet" if engine in _asr.PARAKEET_ENGINES else "whisper"
|
|
425
|
+
source = f"{family}:{engine}" if engine else "whisper"
|
|
426
|
+
if not words:
|
|
427
|
+
die(f"{engine or 'the local engine'} ran but produced no word-level timings, so there "
|
|
428
|
+
"is nothing for --filler to cut on. Some builds do not support word timestamps. "
|
|
429
|
+
"Re-run that engine yourself with them (whisper.cpp --output-json-full / "
|
|
430
|
+
"faster-whisper word_timestamps=True / openai-whisper --word_timestamps True) and "
|
|
431
|
+
"pass the result with --words.", kind="input")
|
|
432
|
+
|
|
433
|
+
args._words, args._words_source = words, source # the sentence flags read the same transcript
|
|
434
|
+
lang = args.filler_lang
|
|
435
|
+
reported_lang = lang
|
|
436
|
+
if lang == "auto":
|
|
437
|
+
# the language the transcript says it is in: a --words document's own field, else what the
|
|
438
|
+
# engine was told or detected for this run (`--transcribe`). A language that is known and has
|
|
439
|
+
# no built-in list is refused, as --filler-lang names it: the English list would cut real
|
|
440
|
+
# words of that language (Norwegian "er" is "is"), and a transcript with no language at all
|
|
441
|
+
# (or one that says "auto", which is no language either) keeps the English list it always had
|
|
442
|
+
# the ISO 639-2 spellings of the languages that have a built-in list (the mux tag uses them)
|
|
443
|
+
iso3 = {"eng": "en", "spa": "es", "deu": "de", "ger": "de", "fra": "fr", "fre": "fr",
|
|
444
|
+
"ita": "it", "jpn": "ja", "por": "pt", "kor": "ko", "zho": "zh", "chi": "zh",
|
|
445
|
+
"rus": "ru", "nld": "nl", "dut": "nl", "pol": "pl", "tur": "tr"}
|
|
446
|
+
names = {"spanish": "es", "german": "de", "portuguese": "pt", "chinese": "zh", "mandarin": "zh",
|
|
447
|
+
"dutch": "nl", "polish": "pl", "turkish": "tr"}
|
|
448
|
+
|
|
449
|
+
def _code(value) -> str:
|
|
450
|
+
value = str(value or "").strip().lower().replace("_", "-")
|
|
451
|
+
if value in ("", "auto"):
|
|
452
|
+
return ""
|
|
453
|
+
# a regional tag names its primary language (ja-JP is ja); a three-letter code that is not
|
|
454
|
+
# in the table stays as it is (est is Estonian, not the Spanish "es"); a word such as
|
|
455
|
+
# "english" is cut to its two-letter code; a name whose first two letters are not its
|
|
456
|
+
# code ("spanish" is es, "chinese" zh) is looked up, as whisper's own language table spells it
|
|
457
|
+
primary = value.split("-")[0]
|
|
458
|
+
if primary in iso3:
|
|
459
|
+
return iso3[primary]
|
|
460
|
+
if primary in names:
|
|
461
|
+
return names[primary]
|
|
462
|
+
return primary[:2] if len(primary) > 3 else primary
|
|
463
|
+
# openai-whisper's top-level `language`, or whisper.cpp's `result.language` (its
|
|
464
|
+
# --output-json-full document is read for its words too: _words_from_words_file())
|
|
465
|
+
result = raw.get("result") if isinstance(raw, dict) else None
|
|
466
|
+
spoken = _code(raw.get("language") or (result.get("language") if isinstance(result, dict) else None)) \
|
|
467
|
+
if isinstance(raw, dict) else ""
|
|
468
|
+
spoken = spoken or _code(transcription.get("language") or transcription.get("detected_language"))
|
|
469
|
+
if spoken and spoken not in FILLER_WORDS and not args.filler_words:
|
|
470
|
+
die(f"the transcript is in {spoken}, which has no built-in filler list. The languages with one are "
|
|
471
|
+
f"{', '.join(sorted(FILLER_WORDS))}; pass --filler-words FILE with your own list for {spoken}, or "
|
|
472
|
+
"--filler-lang for a language that has one.", kind="input")
|
|
473
|
+
lang = spoken if spoken in FILLER_WORDS else "en"
|
|
474
|
+
# with a custom list the run goes ahead, and the result names the language it heard, not the
|
|
475
|
+
# English list it did not use
|
|
476
|
+
reported_lang = spoken or lang
|
|
477
|
+
listname = "builtin"
|
|
478
|
+
if args.filler_words:
|
|
479
|
+
wordlist = set(_word_list(read_text_or_die(args.filler_words, "--filler-words")))
|
|
480
|
+
listname = args.filler_words
|
|
481
|
+
else:
|
|
482
|
+
if lang not in FILLER_WORDS:
|
|
483
|
+
die(f"--filler-lang {lang}: no built-in filler list for that language. The languages "
|
|
484
|
+
f"with one are {', '.join(sorted(FILLER_WORDS))}; pass --filler-words FILE with "
|
|
485
|
+
"your own list for anything else.", kind="input")
|
|
486
|
+
wordlist = set(FILLER_WORDS[lang])
|
|
487
|
+
wordlist |= set(_word_list(args.filler_extra))
|
|
488
|
+
wordlist -= set(_word_list(args.filler_keep))
|
|
489
|
+
|
|
490
|
+
kept: dict = {}
|
|
491
|
+
spans = filler_spans(list(words) + untimed, wordlist, pad=args.filler_pad, stats=kept)
|
|
492
|
+
removed_words = sorted({s["word"] for s in spans})
|
|
493
|
+
warnings = []
|
|
494
|
+
ambiguous = sorted(set(FILLER_AMBIGUOUS.get(lang, ())) & set(
|
|
495
|
+
t for s in spans for t in s["word"].split()))
|
|
496
|
+
if ambiguous:
|
|
497
|
+
warnings.append(
|
|
498
|
+
f"removed {', '.join(ambiguous)} -- in {lang} these are as often ordinary words as "
|
|
499
|
+
f"fillers. Keep one with --filler-keep {ambiguous[0]} and re-run if a sentence lost "
|
|
500
|
+
"its meaning.")
|
|
501
|
+
if FILLER_DISCOURSE_MARKERS.get(lang):
|
|
502
|
+
extra_markers = sorted(set(_word_list(args.filler_extra))
|
|
503
|
+
& set(FILLER_DISCOURSE_MARKERS[lang]))
|
|
504
|
+
if extra_markers:
|
|
505
|
+
warnings.append(f"--filler-extra {', '.join(extra_markers)}: a discourse marker, not a "
|
|
506
|
+
"disfluency -- this will cut real sentences.")
|
|
507
|
+
block = {
|
|
508
|
+
"lang": reported_lang, "source": source, "engine": engine,
|
|
509
|
+
**({"transcription": transcription} if engine and transcription else {}),
|
|
510
|
+
"words": sorted(wordlist), "removed": [dict(s) for s in spans],
|
|
511
|
+
"removed_count": len(spans),
|
|
512
|
+
"removed_seconds": round(sum(s["end"] - s["start"] for s in spans), 3),
|
|
513
|
+
"word_timings": len(words), "list": listname, "removed_words": removed_words,
|
|
514
|
+
"warnings": warnings,
|
|
515
|
+
# listed words this run did not cut, and why: a transcript word with no timing has
|
|
516
|
+
# nothing to cut on, and one longer than a filler is a held vowel someone meant
|
|
517
|
+
"matched_untimed": kept.get("matched_untimed", 0),
|
|
518
|
+
"matched_too_long": kept.get("matched_too_long", 0),
|
|
519
|
+
}
|
|
520
|
+
if block["matched_untimed"]:
|
|
521
|
+
warn(f"--filler: {block['matched_untimed']} listed word(s) in the transcript carry no usable timing and were "
|
|
522
|
+
"not removed (nothing measured to cut on)", "filler_words_untimed", count=block["matched_untimed"])
|
|
523
|
+
return block, [(s["start"], s["end"]) for s in spans]
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def _words_from_words_file(path, data):
|
|
527
|
+
"""_words_from_transcript() for a --words file, plus whisper.cpp's own shape: its
|
|
528
|
+
--output-json-full document (transcription[].tokens[], offsets in milliseconds) is what the
|
|
529
|
+
refusals here tell a caller to make, and it was then refused for having no word timings (#404).
|
|
530
|
+
Read as --transcribe reads the same file."""
|
|
531
|
+
words, had_segments, untimed = _words_from_transcript(data)
|
|
532
|
+
if not words and isinstance(data, dict) and isinstance(data.get("transcription"), list):
|
|
533
|
+
words = _asr._words_from_whisper_cpp_json(path)
|
|
534
|
+
had_segments = had_segments or bool(data["transcription"])
|
|
535
|
+
return words, had_segments, untimed
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _words_from_transcript(data):
|
|
539
|
+
"""([{word,start,end}], whether the document had segments at all, [{word}] of the words
|
|
540
|
+
that carried no usable timing) from a whisper JSON. The third list lets --filler count a
|
|
541
|
+
listed word it could not cut instead of dropping it unseen."""
|
|
542
|
+
raw, had_segments = [], False
|
|
543
|
+
if isinstance(data, dict):
|
|
544
|
+
# a "words" or "segments" that is not a list, and a segment that is not an object, carry no
|
|
545
|
+
# words: the file is then refused for having none, not by a traceback
|
|
546
|
+
raw = _dicts(data.get("words"))
|
|
547
|
+
segments = _dicts(data.get("segments"))
|
|
548
|
+
had_segments = bool(segments)
|
|
549
|
+
for seg in segments:
|
|
550
|
+
raw.extend(_dicts(seg.get("words")))
|
|
551
|
+
elif isinstance(data, list):
|
|
552
|
+
raw = list(data)
|
|
553
|
+
out, untimed = [], []
|
|
554
|
+
for w in raw:
|
|
555
|
+
if not isinstance(w, dict):
|
|
556
|
+
continue
|
|
557
|
+
try:
|
|
558
|
+
out.append({"word": str(w.get("word") or w.get("text") or ""),
|
|
559
|
+
"start": float(w["start"]), "end": float(w["end"])})
|
|
560
|
+
except (KeyError, TypeError, ValueError):
|
|
561
|
+
untimed.append({"word": str(w.get("word") or w.get("text") or "")})
|
|
562
|
+
return out, had_segments, untimed
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def silence_kinds(path: str, silences: "List[Tuple[float, float]]", duration: float,
|
|
566
|
+
threshold: float) -> "Dict[str, Any]":
|
|
567
|
+
"""Which detected silences are digital silence and which are quiet sound under the threshold
|
|
568
|
+
(2.20). Both are removed alike, but they are not the same finding: a room tone, a breath or a
|
|
569
|
+
whisper under --threshold is sound, and a report that called all of it "silence" hid that the
|
|
570
|
+
cut took audible material. One more silencedetect pass at DIGITAL_SILENCE_DB finds the digital
|
|
571
|
+
spans; a detected silence that is at least 99% digital counts as digital."""
|
|
572
|
+
if not silences or STATE.dry_run:
|
|
573
|
+
return {}
|
|
574
|
+
digital = [(s, duration if e == float("inf") else e) for s, e in detect(path, DIGITAL_SILENCE_DB, 0.02)]
|
|
575
|
+
labels, tally = [], {"digital": [0, 0.0], "below_threshold": [0, 0.0]}
|
|
576
|
+
for s, e in silences:
|
|
577
|
+
e = duration if e == float("inf") else e
|
|
578
|
+
span = max(e - s, 1e-9)
|
|
579
|
+
covered = sum(max(0.0, min(e, de) - max(s, ds)) for ds, de in digital)
|
|
580
|
+
kind = "digital" if covered / span >= 0.99 else "below_threshold"
|
|
581
|
+
labels.append(kind)
|
|
582
|
+
tally[kind][0] += 1
|
|
583
|
+
tally[kind][1] += e - s
|
|
584
|
+
return {"silence_kinds": labels,
|
|
585
|
+
"silence_breakdown": {"digital": {"count": tally["digital"][0], "seconds": round(tally["digital"][1], 3),
|
|
586
|
+
"level_db": DIGITAL_SILENCE_DB},
|
|
587
|
+
"below_threshold": {"count": tally["below_threshold"][0],
|
|
588
|
+
"seconds": round(tally["below_threshold"][1], 3),
|
|
589
|
+
"level_db": threshold}}}
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def main() -> int:
|
|
593
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
594
|
+
ap.add_argument("input")
|
|
595
|
+
ap.add_argument("-o", "--output", help="output file (default: <name>_tight.<ext>)")
|
|
596
|
+
ap.add_argument("--threshold", type=float, default=-35.0, help="silence level in dBFS (default -35; use -40 to -45 for quiet rooms)")
|
|
597
|
+
ap.add_argument("--min-silence", "--min-duration", type=float, default=0.6, help="the min duration of a pause: only remove gaps at least this long in seconds (default 0.6)")
|
|
598
|
+
ap.add_argument("--margin", "--padding", type=float, default=0.2, help="the padding: seconds of silence to keep on each side of speech (default 0.2; 0.15 before 2.22)")
|
|
599
|
+
ap.add_argument("--margin-lead", type=float, default=None, metavar="SECONDS",
|
|
600
|
+
help="seconds of silence to keep before speech starts, when it should differ from --margin "
|
|
601
|
+
"(default: --margin)")
|
|
602
|
+
ap.add_argument("--margin-tail", type=float, default=None, metavar="SECONDS",
|
|
603
|
+
help="seconds of silence to keep after speech ends, when it should differ from --margin "
|
|
604
|
+
"(default: --margin); a speaker whose last syllable trails off needs more here than "
|
|
605
|
+
"before the next word")
|
|
606
|
+
ap.add_argument("--sentence-min-silence", type=float, default=None, metavar="SECONDS",
|
|
607
|
+
help="for a silence after a word that ends a sentence, remove it only when it is at least this "
|
|
608
|
+
"long, instead of --min-silence. Needs --words or --transcribe: a sentence end is the "
|
|
609
|
+
"transcript's punctuation")
|
|
610
|
+
ap.add_argument("--sentence-margin-tail", type=float, default=None, metavar="SECONDS",
|
|
611
|
+
help="for a silence after a word that ends a sentence, keep this much after the speech instead "
|
|
612
|
+
"of --margin-tail. Needs --words or --transcribe")
|
|
613
|
+
ap.add_argument("--min-keep", type=float, default=0.2, help="drop kept pieces shorter than this (default 0.2)")
|
|
614
|
+
ap.add_argument("--speech-aware", action="store_true",
|
|
615
|
+
help="keep breaths shorter than --min-silence when they sit inside a sentence "
|
|
616
|
+
"(measured by re-running silence detection at a much shorter floor), and "
|
|
617
|
+
"only cut at sentence-boundary pauses (--min-silence or longer). Composes "
|
|
618
|
+
"with --filler through the same keep_ranges() removal list.")
|
|
619
|
+
ap.add_argument("--list", action="store_true", help="only print silences and the kept ranges")
|
|
620
|
+
ap.add_argument("--edl", help="write the kept ranges to this file, one START-END per line")
|
|
621
|
+
ap.add_argument("--timemap", metavar="FILE",
|
|
622
|
+
help="write the source-to-output time map: every kept range with its source and output "
|
|
623
|
+
"times and every removed range with the output time it was cut at; .csv for CSV, "
|
|
624
|
+
"otherwise JSON (re-time subtitles, find a removed sentence again)")
|
|
625
|
+
fil = ap.add_argument_group("filler words (1.17)")
|
|
626
|
+
fil.add_argument("--filler", action="store_true",
|
|
627
|
+
help="also remove filler words. Needs measured word timings: pass --words or "
|
|
628
|
+
"--transcribe. There is no heuristic fallback -- a word is cut only where "
|
|
629
|
+
"a speech engine timed it.")
|
|
630
|
+
fil.add_argument("--filler-lang", choices=["auto"] + sorted(FILLER_WORDS), default="auto",
|
|
631
|
+
help="which built-in list to use (default auto: the transcript's language field)")
|
|
632
|
+
fil.add_argument("--filler-words", metavar="FILE",
|
|
633
|
+
help="one word per line; replaces the built-in list for this run")
|
|
634
|
+
fil.add_argument("--filler-extra", metavar="W[,W...]",
|
|
635
|
+
help="add words to the list. 'like', 'tipo' and 'cio\u00e8' live here rather than in "
|
|
636
|
+
"the defaults: they are discourse markers, not disfluencies, and cutting "
|
|
637
|
+
"them cuts real sentences.")
|
|
638
|
+
fil.add_argument("--filler-keep", metavar="W[,W...]",
|
|
639
|
+
help="remove words from the built-in list (e.g. --filler-keep \u306a\u3093\u304b)")
|
|
640
|
+
fil.add_argument("--filler-pad", type=float, default=FILLER_PAD,
|
|
641
|
+
help=f"seconds trimmed either side of a filler word (default {FILLER_PAD})")
|
|
642
|
+
fil.add_argument("--words", metavar="FILE",
|
|
643
|
+
help="a whisper JSON with word-level timings, for --filler and the sentence flags")
|
|
644
|
+
fil.add_argument("--transcribe", action="store_true",
|
|
645
|
+
help="produce the word timings with a local speech engine, Parakeet or whisper (never required; the same "
|
|
646
|
+
"bridge caption.py uses)")
|
|
647
|
+
fil.add_argument("--engine", choices=_asr.ENGINE_CHOICES, default=None,
|
|
648
|
+
help="speech engine for --transcribe (default: $FFMPEG_SKILL_ASR_ENGINE, else auto = Parakeet "
|
|
649
|
+
"for English speech when installed, else whisper)")
|
|
650
|
+
fil.add_argument("--model", default=None,
|
|
651
|
+
help="speech model for --transcribe, as caption.py's: a whisper model name/path (default: "
|
|
652
|
+
"$FFMPEG_SKILL_ASR_MODEL, else base), or a Parakeet model for the Parakeet engines")
|
|
653
|
+
fil.add_argument("--filler-list", action="store_true",
|
|
654
|
+
help="report what --filler would remove and write nothing")
|
|
655
|
+
fil.add_argument("--max-cuts", type=int, default=400,
|
|
656
|
+
help="refuse to render above this many removal ranges (default 400): that many cuts usually "
|
|
657
|
+
"means --threshold, --min-silence or the filler list is catching speech. --list and "
|
|
658
|
+
"--filler-list report them without the limit")
|
|
659
|
+
ap.set_defaults(crf=18) # --quality's default (the --crf alias was removed in 2.0)
|
|
660
|
+
ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
|
|
661
|
+
ap.add_argument("--profile", help="pacing-profile@1 JSON path or sns-short, youtube-talk, podcast-natural")
|
|
662
|
+
ap.add_argument("--protect-ranges", help="JSON intervals in source milliseconds to preserve")
|
|
663
|
+
ap.add_argument("--extract-profile", action="store_true", help="measure a reusable pacing profile, optionally written with -o")
|
|
664
|
+
ap.add_argument("--references", action="extend", nargs="+", help="additional completed videos for --extract-profile")
|
|
665
|
+
add_common(ap)
|
|
666
|
+
args = ap.parse_args()
|
|
667
|
+
apply_common(args)
|
|
668
|
+
if args.extract_profile or args.references or args.profile or args.protect_ranges:
|
|
669
|
+
from _common.pacing_edit import cli
|
|
670
|
+
return cli(args, checking=False)
|
|
671
|
+
if args.timemap:
|
|
672
|
+
if os.path.splitext(args.timemap)[1].lower() not in (".json", ".csv"):
|
|
673
|
+
die(f"--timemap must end in .json or .csv: {args.timemap}", kind="input")
|
|
674
|
+
# before any decode or write, so a dry run predicts it too: a missing directory or a
|
|
675
|
+
# directory at the path is a `kind: input` refusal, not a traceback from open()
|
|
676
|
+
_check_output_path([args.timemap])
|
|
677
|
+
# --overwrite allows replacing an old map, never the source, the cut or the EDL
|
|
678
|
+
refuse_output_is_input(args.timemap, *[p for p in (args.input, args.words, args.filler_words) if p])
|
|
679
|
+
for flag, other in (("-o", args.output), ("--edl", args.edl), ("--plan", getattr(args, "plan", None))):
|
|
680
|
+
if other and same_file(other, args.timemap):
|
|
681
|
+
refuse("input", "timemap_path_taken",
|
|
682
|
+
f"--timemap {args.timemap} is the same file as {flag}; give the map its own path",
|
|
683
|
+
timemap=args.timemap, flag=flag, path=other)
|
|
684
|
+
refuse_existing_outputs([args.timemap])
|
|
685
|
+
media_out = None if (args.list or args.filler_list) else (args.output or default_output(args.input, "tight"))
|
|
686
|
+
guard_sidecar(args.edl, args.input, args.words, args.filler_words, siblings=(media_out,))
|
|
687
|
+
if media_out:
|
|
688
|
+
# the word timings and the filler list are read here, never as an -i: run()'s guard did not
|
|
689
|
+
# see a cut named like one of them (#522's sweep). Before any decode, so a dry run says it too
|
|
690
|
+
refuse_output_is_input(media_out, *[p for p in (args.words, args.filler_words) if p])
|
|
691
|
+
# the cut is encoded: a .wma name is refused before the detection pass (#517)
|
|
692
|
+
refuse_unwritten_output(media_out)
|
|
693
|
+
|
|
694
|
+
if not math.isfinite(args.margin) or args.margin < 0:
|
|
695
|
+
# nan made inside_margin() drop every silence and re-encode the whole file unchanged
|
|
696
|
+
die(f"--margin must be a finite number of seconds, 0 or more (got {args.margin:g})", kind="input")
|
|
697
|
+
if args.min_silence < 0:
|
|
698
|
+
# A52: a negative length reached silencedetect, which refused it (kind ffmpeg)
|
|
699
|
+
die(f"--min-silence must be 0 or more seconds, got {args.min_silence:g}", kind="input")
|
|
700
|
+
for flag, value in (("--margin-lead", args.margin_lead), ("--margin-tail", args.margin_tail)):
|
|
701
|
+
if value is not None and (not math.isfinite(value) or value < 0):
|
|
702
|
+
die(f"{flag} must be a finite number of seconds, 0 or more (got {value:g})", kind="input")
|
|
703
|
+
# what is kept after speech ends and before it starts again; --margin is the value of both
|
|
704
|
+
# unless one is named
|
|
705
|
+
tail = args.margin if args.margin_tail is None else args.margin_tail
|
|
706
|
+
lead = args.margin if args.margin_lead is None else args.margin_lead
|
|
707
|
+
by_sentence = args.sentence_min_silence is not None or args.sentence_margin_tail is not None
|
|
708
|
+
for flag, value in (("--sentence-min-silence", args.sentence_min_silence),
|
|
709
|
+
("--sentence-margin-tail", args.sentence_margin_tail)):
|
|
710
|
+
if value is not None and (not math.isfinite(value) or value < 0):
|
|
711
|
+
die(f"{flag} must be a finite number of seconds, 0 or more (got {value:g})", kind="input")
|
|
712
|
+
if by_sentence and args.speech_aware:
|
|
713
|
+
die("--speech-aware and the sentence flags answer the same question two ways: --speech-aware takes a "
|
|
714
|
+
"pause of --min-silence or longer as a sentence boundary, --sentence-min-silence and "
|
|
715
|
+
"--sentence-margin-tail take the transcript's punctuation. Pass one of them.", kind="input")
|
|
716
|
+
if by_sentence and not (args.words or args.transcribe):
|
|
717
|
+
sentence_words(args) # refuses: no transcript to read a sentence end from
|
|
718
|
+
sentence_min = args.min_silence if args.sentence_min_silence is None else args.sentence_min_silence
|
|
719
|
+
sentence_tail = tail if args.sentence_margin_tail is None else args.sentence_margin_tail
|
|
720
|
+
if args.filler_pad < 0:
|
|
721
|
+
die("--filler-pad cannot be negative: a negative pad turns each word's span inside out "
|
|
722
|
+
"(end before start) and the span is then silently dropped, so nothing is removed",
|
|
723
|
+
kind="input")
|
|
724
|
+
if args.max_cuts < 1:
|
|
725
|
+
die("--max-cuts must be at least 1", kind="input")
|
|
726
|
+
if args.filler_list and not args.filler:
|
|
727
|
+
die("--filler-list reports what --filler would remove: pass --filler as well", kind="input")
|
|
728
|
+
meta = probe(args.input)
|
|
729
|
+
if not meta.get("audio"):
|
|
730
|
+
die("input has no audio stream to analyse")
|
|
731
|
+
duration = input_length(meta)
|
|
732
|
+
sound = sound_span(meta, duration)
|
|
733
|
+
breaths: List[Tuple[float, float]] = []
|
|
734
|
+
if args.speech_aware:
|
|
735
|
+
silences, breaths = speech_aware_silences(args.input, args.threshold, args.min_silence)
|
|
736
|
+
elif args.filler and not by_sentence:
|
|
737
|
+
silences = [] # --filler alone: remove only the filler-word spans, not generic dead air
|
|
738
|
+
else:
|
|
739
|
+
# with the sentence flags each kind of pause has its own floor: measure at the shorter one
|
|
740
|
+
silences = detect(args.input, args.threshold, min(args.min_silence, sentence_min) if by_sentence else args.min_silence)
|
|
741
|
+
filler_info, filler_ranges = resolve_filler(args, meta) if args.filler else (None, [])
|
|
742
|
+
positions: List[str] = []
|
|
743
|
+
sentence_info: Optional[Dict[str, Any]] = None
|
|
744
|
+
if by_sentence:
|
|
745
|
+
words, words_source = sentence_words(args)
|
|
746
|
+
found = silence_positions(silences, words, duration)
|
|
747
|
+
# a silence that runs to the end of the file is as long as what is left of the file
|
|
748
|
+
kept_pairs = [(span, pos) for span, pos in zip(silences, found)
|
|
749
|
+
if (duration if span[1] == float("inf") else span[1]) - span[0]
|
|
750
|
+
>= (sentence_min if pos == "sentence_end" else args.min_silence)]
|
|
751
|
+
silences = [span for span, _ in kept_pairs]
|
|
752
|
+
positions = [pos for _, pos in kept_pairs]
|
|
753
|
+
marked = sum(1 for w in words if ends_sentence(w["word"]))
|
|
754
|
+
sentence_info = {"min_silence": sentence_min, "margin_tail": sentence_tail, "source": words_source,
|
|
755
|
+
"word_timings": len(words), "sentence_end_words": marked,
|
|
756
|
+
"silences": positions.count("sentence_end")}
|
|
757
|
+
if not marked:
|
|
758
|
+
warn("the transcript has no sentence-final punctuation, so no silence was taken as a sentence end: "
|
|
759
|
+
"every silence used --min-silence and --margin-tail", "sentence_ends_not_found")
|
|
760
|
+
|
|
761
|
+
def margined(spans: List[Tuple[float, float]]) -> List[Tuple[float, float]]:
|
|
762
|
+
"""The stretch of each silence that is removed: its own tail for one after a sentence end."""
|
|
763
|
+
if not by_sentence:
|
|
764
|
+
return inside_margin(spans, duration, tail, lead, sound)
|
|
765
|
+
out: List[Tuple[float, float]] = []
|
|
766
|
+
for span, pos in zip(spans, positions):
|
|
767
|
+
out += inside_margin([span], duration, sentence_tail if pos == "sentence_end" else tail, lead, sound)
|
|
768
|
+
return out
|
|
769
|
+
# One sorted, merged removal list through the graph the tool already has: filler removal IS
|
|
770
|
+
# time-range removal, so it reuses keep_ranges() and the same select chain.
|
|
771
|
+
# --margin is kept around the silences only (inside_margin), not around filler spans, whose
|
|
772
|
+
# own trim is --filler-pad (#414); the merged list then goes through with no further margin.
|
|
773
|
+
removals = merge_spans(margined(silences) + list(filler_ranges))
|
|
774
|
+
keeps = keep_ranges(removals, duration, 0.0, args.min_keep)
|
|
775
|
+
# what the render holds (on a picture, each bound on its nearest frame): the report, the EDL
|
|
776
|
+
# and the time map all describe these, so a re-cut or a sum of `keep` is the rendered edit
|
|
777
|
+
# from the -o given, under --list and --filler-list too (which write no media): a list for an
|
|
778
|
+
# audio -o reported frame-snapped ranges that the audio run does not cut (#462 A48)
|
|
779
|
+
video_out = bool(meta.get("video")) and not is_audio_output(args.output or "")
|
|
780
|
+
held = rendered_ranges(keeps, meta, duration, video_out)
|
|
781
|
+
kept = sum(e - s for s, e in held)
|
|
782
|
+
removed = max(0.0, duration - kept)
|
|
783
|
+
# `removed_seconds` keeps the meaning it has had since this tool existed: the seconds of
|
|
784
|
+
# SILENCE this run removes. It must not quietly start counting filler time as well, because a
|
|
785
|
+
# caller that has been reading it since 1.0 asked how much dead air went. The silence-only
|
|
786
|
+
# figure is the one the same run would have reported without --filler, so it is computed from
|
|
787
|
+
# the silences alone; everything removed is `removed_seconds_total`.
|
|
788
|
+
silence_only = removed
|
|
789
|
+
if args.filler:
|
|
790
|
+
silence_keeps = keep_ranges(merge_spans(margined(silences)), duration, 0.0, args.min_keep)
|
|
791
|
+
silence_only = max(0.0, duration - sum(e - s for s, e in rendered_ranges(silence_keeps, meta, duration, video_out)))
|
|
792
|
+
kinds = silence_kinds(args.input, silences, duration, args.threshold)
|
|
793
|
+
summary = {
|
|
794
|
+
"silences": [[round(s, 3), None if e == float("inf") else round(e, 3)] for s, e in silences],
|
|
795
|
+
"keep": [[round(s, 3), round(e, 3)] for s, e in held],
|
|
796
|
+
"input_duration": round(duration, 3),
|
|
797
|
+
"kept_duration": round(kept, 3),
|
|
798
|
+
"removed_seconds": round(silence_only, 3),
|
|
799
|
+
}
|
|
800
|
+
if silences or not args.filler or args.speech_aware or by_sentence:
|
|
801
|
+
# the seconds of each silence this run kept: `tail` from where the silence starts (after
|
|
802
|
+
# the speech before it), `lead` up to where it ends (before the speech after it). Absent
|
|
803
|
+
# under --filler with neither --speech-aware nor a sentence flag: no silence is detected.
|
|
804
|
+
summary["margins"] = {"lead": lead, "tail": tail}
|
|
805
|
+
if sentence_info is not None:
|
|
806
|
+
# which of `silences` follow a sentence end, and the floor and tail those were given
|
|
807
|
+
summary["silence_positions"] = positions
|
|
808
|
+
summary["sentence"] = sentence_info
|
|
809
|
+
if kinds:
|
|
810
|
+
summary.update(kinds)
|
|
811
|
+
if args.speech_aware:
|
|
812
|
+
summary["speech_aware"] = {
|
|
813
|
+
"min_silence": args.min_silence, "floor": min(BREATH_FLOOR, args.min_silence),
|
|
814
|
+
"breaths_kept": len(breaths),
|
|
815
|
+
"breaths_kept_seconds": round(sum((e - s) for s, e in breaths if e != float("inf")), 3),
|
|
816
|
+
"breaths": [[round(s, 3), None if e == float("inf") else round(e, 3)] for s, e in breaths],
|
|
817
|
+
}
|
|
818
|
+
info(f"--speech-aware: {len(breaths)} breath(s) kept "
|
|
819
|
+
f"({summary['speech_aware']['breaths_kept_seconds']:.2f}s), "
|
|
820
|
+
f"{len(silences)} sentence-boundary silence(s) cut")
|
|
821
|
+
if filler_info is not None:
|
|
822
|
+
# removed_seconds above is the silence-only figure, unchanged in meaning; the filler share
|
|
823
|
+
# is reported inside `filler`, and removed_seconds_total is the additive sibling that
|
|
824
|
+
# covers everything this run took out.
|
|
825
|
+
summary["filler"] = filler_info
|
|
826
|
+
summary["removed_seconds_total"] = round(removed, 3)
|
|
827
|
+
info(f"--filler: {filler_info['removed_count']} filler word(s), "
|
|
828
|
+
f"{filler_info['removed_seconds']:.2f}s, from {filler_info['word_timings']} word timings "
|
|
829
|
+
f"({filler_info['lang']}, list {filler_info['list']})")
|
|
830
|
+
for warning in filler_info.get("warnings") or []:
|
|
831
|
+
warn(warning, "filler_removal_caution")
|
|
832
|
+
filler_only = args.filler and not args.speech_aware and not by_sentence
|
|
833
|
+
if filler_only:
|
|
834
|
+
info(f"--filler only (no --speech-aware): skipping generic silence detection, "
|
|
835
|
+
f"keeping {len(keeps)} range(s): {kept:.2f}s of {duration:.2f}s (removing {removed:.2f}s, filler only)")
|
|
836
|
+
else:
|
|
837
|
+
info(f"{len(silences)} silences, keeping {len(keeps)} ranges: {kept:.2f}s of {duration:.2f}s (removing {removed:.2f}s)")
|
|
838
|
+
if not silences and not filler_only and not (STATE.dry_run and not os.path.exists(args.input)):
|
|
839
|
+
# Nothing under the threshold is a valid result, not a failure -- but an agent that only
|
|
840
|
+
# sees "0 silences" tends to reach for raw ffmpeg next. Say what the floor actually is and
|
|
841
|
+
# what threshold would bite, so the retry is a flag change, not a workaround.
|
|
842
|
+
level = measured_level_dbfs(args.input)
|
|
843
|
+
if level:
|
|
844
|
+
suggested = min(-5.0, round(level["mean_dbfs"] + 6.0))
|
|
845
|
+
summary["hint"] = (f"no passage sits below {args.threshold:g} dBFS for {args.min_silence:g}s; the track's mean level is "
|
|
846
|
+
f"{level['mean_dbfs']:.1f} dBFS (peak {level['peak_dbfs']:.1f}). For a quiet-room recording try "
|
|
847
|
+
f"--threshold {suggested:g}, or a shorter --min-silence")
|
|
848
|
+
else:
|
|
849
|
+
summary["hint"] = f"no passage sits below {args.threshold:g} dBFS for {args.min_silence:g}s; try a higher --threshold (e.g. -25) or a shorter --min-silence"
|
|
850
|
+
info("hint: " + summary["hint"])
|
|
851
|
+
|
|
852
|
+
tm = time_map(held, duration)
|
|
853
|
+
cuts = len(tm["removed"])
|
|
854
|
+
if cuts > args.max_cuts and not (args.list or args.filler_list):
|
|
855
|
+
# the removal ranges, as --max-cuts says, not the kept ones; a list renders nothing and is
|
|
856
|
+
# how the caller sees what the limit is about (#462 A49)
|
|
857
|
+
die(f"{cuts} removal ranges is above --max-cuts {args.max_cuts}: that many cuts usually means "
|
|
858
|
+
"--threshold, --min-silence or the filler list is catching speech. Check them with --list, then "
|
|
859
|
+
"raise --max-cuts if you mean it, or use --min-silence/--filler-pad to merge the short ones.",
|
|
860
|
+
kind="input")
|
|
861
|
+
points: Any = False # False: not measured (a dry run over a pending input); None: the decode failed
|
|
862
|
+
if not (STATE.dry_run and not os.path.exists(args.input)):
|
|
863
|
+
points = cut_levels(args.input, tm, duration, list(filler_ranges))
|
|
864
|
+
if points is None:
|
|
865
|
+
warn("could not decode the source to measure the level at each cut; cut_points and cut_warnings are null "
|
|
866
|
+
"(unmeasured, not silent): listen at the cuts", "cut_levels_unmeasured")
|
|
867
|
+
summary["cut_points"] = summary["cut_warnings"] = None
|
|
868
|
+
elif points is not False:
|
|
869
|
+
near = [{k: v for k, v in c.items() if k != "filler"} for c in points
|
|
870
|
+
if not c.get("filler") and c["rms_dbfs"] is not None and c["rms_dbfs"] > args.threshold - CUT_SOUND_MARGIN_DB]
|
|
871
|
+
summary["cut_points"] = points
|
|
872
|
+
summary["cut_warnings"] = near
|
|
873
|
+
if near:
|
|
874
|
+
where = ", ".join("%.2fs" % c["source_time"] for c in near[:5]) + (", ..." if len(near) > 5 else "")
|
|
875
|
+
warn(f"{len(near)} cut point(s) sit within {CUT_SOUND_MARGIN_DB:g} dB of --threshold ({where}): "
|
|
876
|
+
"a breath or a word's weak tail may be cut; listen there, or lower --threshold / raise --margin "
|
|
877
|
+
"(--margin-tail for an `out` edge, --margin-lead for an `in` edge)",
|
|
878
|
+
"cut_near_sound", cuts=len(near))
|
|
879
|
+
|
|
880
|
+
def finish_time_map() -> None:
|
|
881
|
+
"""Written last, once the cut it describes exists (or under --list, where the map is the
|
|
882
|
+
result): a map left beside a failed or refused encode would describe media never made."""
|
|
883
|
+
if not args.timemap:
|
|
884
|
+
return
|
|
885
|
+
if not STATE.dry_run: # an artifact like the EDL: a plan writes nothing
|
|
886
|
+
write_time_map(args.timemap, tm)
|
|
887
|
+
info(f"wrote {args.timemap}")
|
|
888
|
+
summary["timemap"] = args.timemap
|
|
889
|
+
|
|
890
|
+
def finish_edl() -> None:
|
|
891
|
+
"""Written with the time map, once the cut exists (or under --list): an EDL left by a
|
|
892
|
+
refused run (an existing -o, -o the input, nothing kept) or a failed encode described
|
|
893
|
+
media never made, and then blocked the corrected retry as an existing file (#462 A41)."""
|
|
894
|
+
if not args.edl:
|
|
895
|
+
return
|
|
896
|
+
if not STATE.dry_run: # the EDL is an artifact like the cut itself: a plan writes nothing
|
|
897
|
+
with open(args.edl, "w", encoding="utf-8") as fh:
|
|
898
|
+
on_frames = bool(video_out and frame_rate(meta))
|
|
899
|
+
for s, e in held:
|
|
900
|
+
# a frame-time bound is written down to the millisecond, not rounded up past
|
|
901
|
+
# its frame: cut.py --segments cuts at the first frame at or after it (#416 review)
|
|
902
|
+
fh.write(f"{_edl_time(s, on_frames)}-{_edl_time(e, on_frames)}\n")
|
|
903
|
+
info(f"wrote {args.edl}")
|
|
904
|
+
|
|
905
|
+
if args.list or args.filler_list:
|
|
906
|
+
finish_edl()
|
|
907
|
+
finish_time_map()
|
|
908
|
+
if args.json:
|
|
909
|
+
emit(None, **summary)
|
|
910
|
+
else:
|
|
911
|
+
print_json(summary)
|
|
912
|
+
return 0
|
|
913
|
+
if not keeps or not held:
|
|
914
|
+
die("nothing would be kept; raise --threshold (e.g. -45) or check the audio")
|
|
915
|
+
if removed < 0.05:
|
|
916
|
+
# what the render removes, filler spans included: --filler alone has no silences at all
|
|
917
|
+
info(f"no removable {'filler' if filler_only else 'silence or filler' if args.filler else 'silence'} found; output would equal the input")
|
|
918
|
+
|
|
919
|
+
output = args.output or default_output(args.input, "tight")
|
|
920
|
+
# the join of more than 32 ranges concats a list of chunks, so its last command never names the
|
|
921
|
+
# source and run()'s own check cannot see -o replace it (#416 review)
|
|
922
|
+
refuse_output_is_input(output, args.input)
|
|
923
|
+
# The kept ranges are re-cut from the source as cut.py --segments --accurate cuts them (#409):
|
|
924
|
+
# each range is its own seeked input, both streams cut on the same frame-grid bounds and shifted
|
|
925
|
+
# by one constant, the sound padded to the range's origin, at most 32 ranges per ffmpeg call.
|
|
926
|
+
# The one-pass select/ametadata graph this replaced rounded every range twice, the picture to
|
|
927
|
+
# whole frames and the sound to whole AAC frames, and the errors added up (150 ms over 21 ranges
|
|
928
|
+
# on a 61 s source); its asetpts=N/SR also moved a sound that starts late by its whole offset.
|
|
929
|
+
# No declick fade: the joins sit in the --margin the tool keeps, as they always have.
|
|
930
|
+
# imported here, not at the top: the contract and MCP load every tool's parser on its own
|
|
931
|
+
import cut as _cut
|
|
932
|
+
_cut.DECLICK_S = 0.0
|
|
933
|
+
import tempfile
|
|
934
|
+
with tempfile.TemporaryDirectory(prefix="ffskill_silence_") as tmp:
|
|
935
|
+
_cut.join_from_source(args.input, held, output, meta, args.crf, args.preset, tmp)
|
|
936
|
+
r = probe(output, role="output")
|
|
937
|
+
info(f"wrote {output} ({fmt_secs(r['duration'])}, expected ~{kept:.3f}s)")
|
|
938
|
+
finish_edl()
|
|
939
|
+
finish_time_map()
|
|
940
|
+
emit(output, **summary)
|
|
941
|
+
return 0
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
if __name__ == "__main__":
|
|
945
|
+
sys.exit(main())
|