@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,1237 @@
|
|
|
1
|
+
"""The optional local speech-to-text bridge, and the SRT the rest of the skill reads and writes.
|
|
2
|
+
|
|
3
|
+
No speech engine is ever required. Nothing here runs unless a caller asked for a transcript:
|
|
4
|
+
`caption.py --transcribe` and `silence.py --filler --transcribe` share this one engine probe, so
|
|
5
|
+
the "no engine found" message, its install lines and its exit code are stated once rather than
|
|
6
|
+
copied per tool. What a call used (engine, model, routing, words, notes) comes back in its
|
|
7
|
+
Transcription, never in module state. This module is neither ffprobe nor a decision, which is
|
|
8
|
+
why it is its own file.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import unicodedata
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Dict, List, NamedTuple, Optional, Tuple
|
|
18
|
+
|
|
19
|
+
from _common.decision import _unspaced_script, fmt_srt_time, parse_time
|
|
20
|
+
from _common.emit import die, info
|
|
21
|
+
from _common.runner import parse_json, read_json, read_text_or_die
|
|
22
|
+
|
|
23
|
+
# The engines this skill knows how to drive, and how to install each -- one string, so every
|
|
24
|
+
# tool that needs a transcript refuses in the same words. The two Parakeet engines are
|
|
25
|
+
# English-first (the default v2 model is English-only): under `--engine auto` they run only for
|
|
26
|
+
# English speech and the Whisper engines take every other language.
|
|
27
|
+
PARAKEET_ENGINES = ("parakeet-mlx", "parakeet.cpp")
|
|
28
|
+
WHISPER_ENGINES = ("whisper.cpp", "faster-whisper", "openai-whisper")
|
|
29
|
+
ASR_ENGINES = PARAKEET_ENGINES + WHISPER_ENGINES
|
|
30
|
+
ENGINE_CHOICES = ("auto",) + ASR_ENGINES
|
|
31
|
+
ASR_ENGINE_ENV = "FFMPEG_SKILL_ASR_ENGINE"
|
|
32
|
+
# This machine's default --model (#328); --model wins, and without either the model is "base".
|
|
33
|
+
ASR_MODEL_ENV = "FFMPEG_SKILL_ASR_MODEL"
|
|
34
|
+
DEFAULT_WHISPER_MODEL = "base"
|
|
35
|
+
# whisper.cpp conditions every window on the text before it, and once a hallucinated line is in that
|
|
36
|
+
# context it can repeat it to the end of the file (#318: one sentence ~300 times, ~7 minutes of speech
|
|
37
|
+
# lost). -mc / --max-context 0 keeps no previous text. Given to the commands that write a transcript,
|
|
38
|
+
# not to language detection (-dl), which writes none.
|
|
39
|
+
WHISPER_CPP_NO_CONTEXT = ["-mc", "0"]
|
|
40
|
+
PARAKEET_MLX_DEFAULT_MODEL = "mlx-community/parakeet-tdt-0.6b-v2"
|
|
41
|
+
# Every engine transcribes on this machine: the audio is never uploaded. Three of them fetch
|
|
42
|
+
# their model weights the first time they run, which the hint says, so "offline" is never
|
|
43
|
+
# promised for a first run that is not. The skill's own code opens no connection, but
|
|
44
|
+
# faster-whisper is a library run inside this process, so its first-run fetch is made from here.
|
|
45
|
+
ASR_INSTALL_HINT = (
|
|
46
|
+
"Install one (each transcribes on this machine; the audio never leaves it):\n"
|
|
47
|
+
" parakeet-mlx: uv tool install parakeet-mlx (Apple Silicon; English; the first run\n"
|
|
48
|
+
" downloads the model from Hugging Face, " + PARAKEET_MLX_DEFAULT_MODEL + ")\n"
|
|
49
|
+
" parakeet.cpp: parakeet-cli from github.com/mudler/parakeet.cpp releases, plus a\n"
|
|
50
|
+
" tdt-0.6b-v2 .gguf in ~/.cache/parakeet.cpp/ (English)\n"
|
|
51
|
+
" whisper.cpp: brew install whisper-cpp (then download a model: ggml-base.bin)\n"
|
|
52
|
+
" faster-whisper: pip install faster-whisper (the first run downloads its model)\n"
|
|
53
|
+
" openai-whisper: pip install openai-whisper (the first run downloads its model)")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Transcription:
|
|
57
|
+
"""What one transcription produced, and what produced it.
|
|
58
|
+
|
|
59
|
+
transcribe_result() and transcribe_words_result() return one instead of leaving it in module
|
|
60
|
+
state, so two transcriptions in one process (mcp/server.py, batch.py, a test) can never read
|
|
61
|
+
each other's engine, words or routing.
|
|
62
|
+
|
|
63
|
+
cues [(start, end, text)]: what transcribe_result() wrote to the SRT (a Parakeet word
|
|
64
|
+
run fills them too; a whisper word run leaves them [])
|
|
65
|
+
words [{word, start, end}]: transcribe_words_result()'s word timings; from
|
|
66
|
+
transcribe_result(), a Parakeet engine's word timings for --karaoke ([] for a
|
|
67
|
+
whisper engine, whose word timings are read from a JSON next to the SRT instead)
|
|
68
|
+
engine the engine that produced them, or None
|
|
69
|
+
facts the result document's `transcription` block, in its key order:
|
|
70
|
+
{routing, detected_language?, engine, model, language}
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(self, cues: Optional[List[Tuple[float, float, str]]] = None,
|
|
74
|
+
words: "Optional[List[Dict[str, Any]]]" = None, engine: Optional[str] = None,
|
|
75
|
+
facts: Optional[Dict[str, Any]] = None) -> None:
|
|
76
|
+
self.cues: List[Tuple[float, float, str]] = list(cues or [])
|
|
77
|
+
self.words: "List[Dict[str, Any]]" = [dict(w) for w in (words or [])]
|
|
78
|
+
self.engine = engine
|
|
79
|
+
self.facts: Dict[str, Any] = dict(facts or {})
|
|
80
|
+
|
|
81
|
+
def __repr__(self) -> str:
|
|
82
|
+
return (f"Transcription(engine={self.engine!r}, cues={len(self.cues)}, words={len(self.words)}, "
|
|
83
|
+
f"facts={self.facts!r})")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# A line that starts a cue even with no blank line before it: a clock time, "-->", a clock time,
|
|
87
|
+
# then nothing or whitespace (ffmpeg's position fields, X1:.. Y1:..). ffmpeg's SRT demuxer starts
|
|
88
|
+
# an event at every such line; the first line of a block holding "-->" is a timing line whatever
|
|
89
|
+
# its shape.
|
|
90
|
+
_SRT_CUE_START = re.compile(r"^\s*\d+:\d+[\d:.,]*\s*-->\s*\d+:\d+[\d:.,]*(\s|$)")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def srt_blocks(text: str) -> List[Tuple[str, List[str]]]:
|
|
94
|
+
"""(timing line, text lines) of every cue in SRT text whose line ends are already `\\n`.
|
|
95
|
+
|
|
96
|
+
A blank (or whitespace-only) line ends a cue, and the first line holding "-->" in a run of
|
|
97
|
+
lines is its timing line; the lines before it (the index) are not text. Inside a run, a later
|
|
98
|
+
line shaped like a timing line (_SRT_CUE_START) starts the next cue, and a bare number just
|
|
99
|
+
before it is that cue's index, so an SRT written without blank lines between cues reads as
|
|
100
|
+
ffmpeg reads it rather than as one cue. A later line that merely contains "-->" is text."""
|
|
101
|
+
out: List[Tuple[str, List[str]]] = []
|
|
102
|
+
for run in re.split(r"\n\s*\n", text):
|
|
103
|
+
lines = [ln for ln in run.split("\n") if ln.strip()]
|
|
104
|
+
first = next((i for i, ln in enumerate(lines) if "-->" in ln), None)
|
|
105
|
+
if first is None:
|
|
106
|
+
continue
|
|
107
|
+
timing, body = lines[first], []
|
|
108
|
+
for ln in lines[first + 1:]:
|
|
109
|
+
if _SRT_CUE_START.match(ln):
|
|
110
|
+
if body and body[-1].strip().isdigit():
|
|
111
|
+
body.pop()
|
|
112
|
+
out.append((timing, body))
|
|
113
|
+
timing, body = ln, []
|
|
114
|
+
else:
|
|
115
|
+
body.append(ln)
|
|
116
|
+
out.append((timing, body))
|
|
117
|
+
return out
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def srt_timing_times(line: str) -> Tuple[str, str]:
|
|
121
|
+
"""The start and end tokens of an SRT timing line: what is before the first "-->", and the
|
|
122
|
+
first word after it. ffmpeg reads the two times and ignores the rest (position fields
|
|
123
|
+
`X1:.. X2:.. Y1:.. Y2:..`, or a stray second "-->")."""
|
|
124
|
+
a, _sep, b = line.partition("-->")
|
|
125
|
+
words = b.split()
|
|
126
|
+
return a.strip(), words[0] if words else ""
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# WebVTT's inline word timestamps and its class, voice and language spans (YouTube's automatic
|
|
130
|
+
# captions: `hello<00:00:01.500><c> world</c>`); <i>, <b> and <u> are SRT's too and stay
|
|
131
|
+
_VTT_INLINE = re.compile(r"<\d{1,2}:\d{2}(?::\d{2})?\.\d{3}>|</?(?:c|v|lang)(?:[.\s][^>]*)?>")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def parse_srt(path: str) -> List[Tuple[float, float, str]]:
|
|
135
|
+
cues: List[Tuple[float, float, str]] = []
|
|
136
|
+
source = read_text_or_die(path, "--srt")
|
|
137
|
+
# only in a file that says it is WebVTT: ffmpeg's own WebVTT reader drops these tags, and the
|
|
138
|
+
# cues this function returns were burned with them in the text (#404)
|
|
139
|
+
vtt = source.lstrip().upper().startswith("WEBVTT")
|
|
140
|
+
for times, body in srt_blocks(source):
|
|
141
|
+
a, b = srt_timing_times(times)
|
|
142
|
+
text = "\n".join(body).strip()
|
|
143
|
+
if vtt:
|
|
144
|
+
text = _VTT_INLINE.sub("", text).strip()
|
|
145
|
+
try:
|
|
146
|
+
cues.append((parse_time(a), parse_time(b), text))
|
|
147
|
+
except ValueError as e: # includes MissingFpsError: SRT timings are hh:mm:ss,ms, never frames
|
|
148
|
+
die(f"{path}: cannot read the timing line {times.strip()!r}: {e}", kind="input")
|
|
149
|
+
if not cues:
|
|
150
|
+
die(f"no cues found in {path}", kind="input")
|
|
151
|
+
return cues
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
NO_SPEECH_REASON = "no_speech"
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def die_no_speech(engine: str, video: str) -> None:
|
|
158
|
+
"""An engine ran and heard nothing: kind input, `reason: "no_speech"`, naming the engine and
|
|
159
|
+
the input -- not the "no engine found" refusal (one was found) and not "no cues found in"
|
|
160
|
+
the engine's own temporary SRT (a path the caller never gave and that is already deleted)."""
|
|
161
|
+
# the reason is error.reason as every refusal's is (#414), and stays top-level where 2.x put it
|
|
162
|
+
die(f"{engine} found no speech in {video}", kind="input", reason=NO_SPEECH_REASON, engine=engine,
|
|
163
|
+
error_extra={"reason": NO_SPEECH_REASON, "details": {"engine": engine}},
|
|
164
|
+
hint="check that the input (and --audio-stream) carries the speech, or write the cues by hand with --text")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
ENGINE_FAILED_REASON = "engine_failed"
|
|
168
|
+
ENGLISH_ONLY_REASON = "english_only"
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def die_engine_failed(engine: str, video: str, tried: "List[Dict[str, str]]", installed: bool) -> None:
|
|
172
|
+
"""A named --engine that did not transcribe. kind missing_tool only when it is not installed;
|
|
173
|
+
one that is installed and failed is kind input, `reason: "engine_failed"`, with the engine's
|
|
174
|
+
own last line in `detail` -- a JSON caller never sees the log line above it."""
|
|
175
|
+
if not installed:
|
|
176
|
+
die(f"--engine {engine} is not installed" + (
|
|
177
|
+
" (parakeet-cli and a .gguf model it can find: --model, PARAKEET_CPP_MODEL or ~/.cache/parakeet.cpp/)"
|
|
178
|
+
if engine == "parakeet.cpp" else ""),
|
|
179
|
+
kind="missing_tool", hint="install it (see --help), or use --engine auto to use whichever engine is installed")
|
|
180
|
+
detail = next((t["detail"] for t in tried if t["engine"] == engine), "failed")
|
|
181
|
+
die(f"--engine {engine} could not transcribe {video}: {engine} {detail}", kind="input",
|
|
182
|
+
reason=ENGINE_FAILED_REASON, engine=engine, detail=detail,
|
|
183
|
+
error_extra={"reason": ENGINE_FAILED_REASON, "details": {"engine": engine, "detail": detail}},
|
|
184
|
+
hint="fix the engine (its own message is in detail), or use --engine auto to fall back to another installed engine")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def die_engines_failed(tried: "List[Dict[str, str]]", video: str, flag: str, alternative: str) -> None:
|
|
188
|
+
"""--engine auto found engines and none transcribed: name each and why. Not die_no_engine():
|
|
189
|
+
its install lines would tell the caller to install what is installed. kind input;
|
|
190
|
+
`reason` is "english_only" when the only engines found were Parakeet engines auto passed over
|
|
191
|
+
for a language that is not English, else "engine_failed"; `engines` lists them all."""
|
|
192
|
+
failed = [t for t in tried if t["reason"] != ENGLISH_ONLY_REASON]
|
|
193
|
+
hints = ["fix the engine that failed (its own message is in engines[].detail)"] if failed else []
|
|
194
|
+
if len(failed) < len(tried):
|
|
195
|
+
hints.append("name the spoken language when it is not known (engines[].detail says with which flag), install a Whisper "
|
|
196
|
+
"engine for this language (see --help), or name a Parakeet engine with --engine and give it a multilingual (v3) model")
|
|
197
|
+
hint = "; or ".join(hints)
|
|
198
|
+
die(f"no installed speech-to-text engine could transcribe {video} for {flag}:\n"
|
|
199
|
+
+ "\n".join(f" {t['engine']} {t['detail']}" for t in tried) + "\n" + alternative,
|
|
200
|
+
kind="input", reason=ENGINE_FAILED_REASON if failed else ENGLISH_ONLY_REASON,
|
|
201
|
+
engine=(failed or tried)[0]["engine"], engines=[dict(t) for t in tried], hint=hint,
|
|
202
|
+
error_extra={"reason": ENGINE_FAILED_REASON if failed else ENGLISH_ONLY_REASON,
|
|
203
|
+
"details": {"engine": (failed or tried)[0]["engine"], "engines": [dict(t) for t in tried]}})
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _failed(engine: str, detail: str) -> "Dict[str, str]":
|
|
207
|
+
return {"engine": engine, "reason": ENGINE_FAILED_REASON, "detail": detail}
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _failure_line(proc: Any, errors_on_stdout: bool = False) -> str:
|
|
211
|
+
"""The line that says why an engine run failed, for the log and the failure document.
|
|
212
|
+
|
|
213
|
+
Its last stderr line, else its last stdout line. parakeet-mlx (`errors_on_stdout`) prints its
|
|
214
|
+
errors to stdout through rich -- "Error loading model ...", wrapped onto continuation lines --
|
|
215
|
+
while stderr may hold only a download's progress bars, so its last error line comes first."""
|
|
216
|
+
if errors_on_stdout:
|
|
217
|
+
lines = [ln.strip() for ln in (proc.stdout or "").splitlines()]
|
|
218
|
+
for i in range(len(lines) - 1, -1, -1):
|
|
219
|
+
if "error" in lines[i].lower():
|
|
220
|
+
end = i + 1
|
|
221
|
+
while end < len(lines) and lines[end]:
|
|
222
|
+
end += 1
|
|
223
|
+
return " ".join(lines[i:end])[:200]
|
|
224
|
+
for text in (proc.stderr, proc.stdout):
|
|
225
|
+
lines = [ln.strip() for ln in (text or "").splitlines() if ln.strip()]
|
|
226
|
+
if lines:
|
|
227
|
+
return lines[-1][:200]
|
|
228
|
+
return "?"
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _engine_cues(srt: str, engine: str, video: str) -> List[Tuple[float, float, str]]:
|
|
232
|
+
"""The cues of an SRT an engine wrote; an SRT with no cue in it is die_no_speech()."""
|
|
233
|
+
try:
|
|
234
|
+
text = Path(srt).read_text(encoding="utf-8", errors="replace")
|
|
235
|
+
except OSError:
|
|
236
|
+
text = ""
|
|
237
|
+
if "-->" not in text:
|
|
238
|
+
die_no_speech(engine, video)
|
|
239
|
+
return parse_srt(srt)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def write_srt(cues: List[Tuple[float, float, str]], path: str) -> None:
|
|
243
|
+
with open(path, "w", encoding="utf-8") as fh:
|
|
244
|
+
for i, (s, e, t) in enumerate(cues, 1):
|
|
245
|
+
# A blank line is SRT's own block separator (index/timecode/text, blank, next block).
|
|
246
|
+
# Cue text can contain one -- parse_text_cues() turns a bare "|" into "\n", so a source
|
|
247
|
+
# line with two adjacent pipes ("a||b") becomes "a\n\nb" -- and writing that blank line
|
|
248
|
+
# raw would split one cue into two malformed half-blocks (the second missing its own
|
|
249
|
+
# index/timecode). Collapse any run of blank lines within the cue text to a single
|
|
250
|
+
# newline so the cue's own text can never fake the format's block boundary. A line of
|
|
251
|
+
# only spaces or tabs is blank to every SRT reader too, so it goes the same way.
|
|
252
|
+
t = "\n".join(ln for ln in t.split("\n") if ln.strip())
|
|
253
|
+
fh.write(f"{i}\n{fmt_srt_time(s)} --> {fmt_srt_time(e)}\n{t}\n\n")
|
|
254
|
+
# under batch.py: this SRT as written is the run's own (an edit made after it is not)
|
|
255
|
+
from _common.runner import report_committed
|
|
256
|
+
report_committed(path)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def transcribe_result(video: str, out_srt: str, language: Optional[str], model: Optional[str], audio_stream: int = 0,
|
|
260
|
+
engine: Optional[str] = None) -> Transcription:
|
|
261
|
+
"""Optional local ASR bridge: the SRT written to `out_srt`, and a Transcription saying what
|
|
262
|
+
produced it. `model` (else $FFMPEG_SKILL_ASR_MODEL, else base: requested_model()) is the
|
|
263
|
+
model; `engine` (else $FFMPEG_SKILL_ASR_ENGINE, else auto) picks the engine; auto tries
|
|
264
|
+
Parakeet (parakeet-mlx, parakeet.cpp) for English speech, then whisper-cli / main
|
|
265
|
+
(whisper.cpp), faster-whisper (python), whisper (openai-whisper CLI). No engine installed ->
|
|
266
|
+
clear error with install hints; the skill never depends on one."""
|
|
267
|
+
import shutil
|
|
268
|
+
import subprocess
|
|
269
|
+
import tempfile
|
|
270
|
+
from _common import require_tool
|
|
271
|
+
ffmpeg = require_tool("ffmpeg")
|
|
272
|
+
wanted = requested_engine(engine)
|
|
273
|
+
model, parakeet_model = requested_model(model)
|
|
274
|
+
tmpdir = tempfile.mkdtemp(prefix="ffskill_asr_")
|
|
275
|
+
try:
|
|
276
|
+
# the engines' own CLIs are looked up and launched by full path, never from the working directory
|
|
277
|
+
from _common.runner import SafeShutil
|
|
278
|
+
return _transcribe_in(tmpdir, video, out_srt, language, model, audio_stream, ffmpeg, SafeShutil(shutil), subprocess, wanted,
|
|
279
|
+
parakeet_model=parakeet_model)
|
|
280
|
+
finally:
|
|
281
|
+
shutil.rmtree(tmpdir, ignore_errors=True)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def transcribe(video: str, out_srt: str, language: Optional[str], model: Optional[str], audio_stream: int = 0,
|
|
285
|
+
engine: Optional[str] = None) -> List[Tuple[float, float, str]]:
|
|
286
|
+
"""transcribe_result()'s cues alone: the call shape caption.transcribe has always had. A caller
|
|
287
|
+
that reports which engine ran (caption.py does) calls transcribe_result() instead."""
|
|
288
|
+
return transcribe_result(video, out_srt, language, model, audio_stream, engine).cues
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _asr_run(cmd: List[str], subprocess, name: str, env: "Optional[Dict[str, str]]" = None) -> "subprocess.CompletedProcess":
|
|
292
|
+
"""Run a speech-to-text engine under the same wall-clock limit as an ffmpeg call."""
|
|
293
|
+
from _common import STATE, die
|
|
294
|
+
limit = STATE.timeout or None
|
|
295
|
+
try:
|
|
296
|
+
return subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace",
|
|
297
|
+
timeout=limit, **({"env": env} if env is not None else {}))
|
|
298
|
+
except subprocess.TimeoutExpired:
|
|
299
|
+
die(f"{name} exceeded the {limit:.0f} s time limit and was killed; raise --timeout for a long recording",
|
|
300
|
+
code=124, kind="timeout")
|
|
301
|
+
return None # unreachable
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _parakeet_attempt(engines: "List[str]", facts: Dict[str, Any], wanted: str, language: Optional[str],
|
|
305
|
+
wav: str, tmpdir: str, model: Optional[str], shutil, subprocess, video: str,
|
|
306
|
+
language_flag: str, need_words: bool = False,
|
|
307
|
+
tried: "Optional[List[Dict[str, str]]]" = None) -> Optional[Tuple[Transcription, str]]:
|
|
308
|
+
"""(Transcription, the model's file name) from the first of `engines` that transcribes, or None.
|
|
309
|
+
|
|
310
|
+
Under --engine auto with no language named or detected, an English-only model does not run:
|
|
311
|
+
it would write English words for whatever was said, and a note in the result is read after the
|
|
312
|
+
captions are burned (4.0.0). It is added to `tried` as english_only, with the flag that names
|
|
313
|
+
the language, and the caller's refusal lists it. A multilingual (v3) model assumes nothing and
|
|
314
|
+
runs; its routing says so. `need_words`: an engine whose cues read but whose word times do not is passed over
|
|
315
|
+
(silence.py --filler can cut nothing on cues), unless it was asked for by name. An engine that
|
|
316
|
+
ran and did not transcribe is added to `tried`."""
|
|
317
|
+
unknown = wanted == "auto" and not language and not facts.get("detected_language")
|
|
318
|
+
for eng in engines:
|
|
319
|
+
if unknown and _parakeet_available(eng, shutil, model) and not _parakeet_multilingual(_parakeet_model_for(eng, model, None)):
|
|
320
|
+
info(f"{eng} not run: its model is English-only and the spoken language is not known")
|
|
321
|
+
if tried is not None:
|
|
322
|
+
tried.append({"engine": eng, "reason": ENGLISH_ONLY_REASON,
|
|
323
|
+
"detail": "is installed, but its model is English-only and the spoken language is not known here: "
|
|
324
|
+
f"name it with {language_flag} (en when the speech is English)"})
|
|
325
|
+
continue
|
|
326
|
+
got = run_parakeet(eng, wav, tmpdir, model, language, shutil, subprocess, video, tried)
|
|
327
|
+
if got and need_words and not got[1] and wanted not in PARAKEET_ENGINES:
|
|
328
|
+
# cues read but no word times (a caption could use them; this caller cannot); a
|
|
329
|
+
# named engine keeps its own "no word-level timings" refusal instead
|
|
330
|
+
info(f"{eng} gave cues but no readable word timings; trying the next engine")
|
|
331
|
+
if tried is not None:
|
|
332
|
+
tried.append(_failed(eng, "gave cues but no readable word timings"))
|
|
333
|
+
got = None
|
|
334
|
+
if not got:
|
|
335
|
+
continue
|
|
336
|
+
cues, words, chosen = got
|
|
337
|
+
run = Transcription(cues=cues, words=words, engine=eng,
|
|
338
|
+
facts=dict(facts, engine=eng, model=chosen, language=language or facts.get("detected_language")))
|
|
339
|
+
if unknown:
|
|
340
|
+
run.facts["routing"] += ROUTING_MULTILINGUAL
|
|
341
|
+
return run, os.path.basename(chosen)
|
|
342
|
+
return None
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _skipped_parakeet(route: "Route", language: Optional[str], language_flag: str) -> "List[Dict[str, str]]":
|
|
346
|
+
"""The installed Parakeet engines --engine auto passed over for a language that is not English."""
|
|
347
|
+
what = f"{language_flag} {language}" if language else f"the detected language {route.facts.get('detected_language')}"
|
|
348
|
+
return [{"engine": e, "reason": ENGLISH_ONLY_REASON,
|
|
349
|
+
"detail": f"is installed, but --engine auto runs Parakeet only for English speech, and {what} is not English"}
|
|
350
|
+
for e in route.skipped]
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _transcribe_in(tmpdir: str, video: str, out_srt: str, language: Optional[str], model: str, audio_stream: int,
|
|
354
|
+
ffmpeg: str, shutil, subprocess, wanted: str = "auto",
|
|
355
|
+
parakeet_model: Optional[str] = None) -> Transcription:
|
|
356
|
+
"""`model` is what the Whisper engines run; the Parakeet engines are offered `parakeet_model`
|
|
357
|
+
(default `model`), which differs only for a Parakeet model from $FFMPEG_SKILL_ASR_MODEL."""
|
|
358
|
+
from _common import STATE
|
|
359
|
+
pmodel = model if parakeet_model is None else parakeet_model
|
|
360
|
+
language = engine_language(language)
|
|
361
|
+
wav = os.path.join(tmpdir, "audio.wav")
|
|
362
|
+
engine_wav(ffmpeg, video, audio_stream, wav)
|
|
363
|
+
# every engine found that did not transcribe, and why: the refusal names them rather than
|
|
364
|
+
# telling the caller to install what is installed
|
|
365
|
+
tried: "List[Dict[str, str]]" = []
|
|
366
|
+
|
|
367
|
+
def parakeet(engines: "List[str]", facts: Dict[str, Any]) -> Optional[Transcription]:
|
|
368
|
+
done = _parakeet_attempt(engines, facts, wanted, language, wav, tmpdir, pmodel, shutil, subprocess, video, "--language",
|
|
369
|
+
tried=tried)
|
|
370
|
+
if not done:
|
|
371
|
+
return None
|
|
372
|
+
run, model_name = done
|
|
373
|
+
info(f"transcribed with {run.engine} (model {model_name})")
|
|
374
|
+
write_srt(run.cues, out_srt)
|
|
375
|
+
return run
|
|
376
|
+
|
|
377
|
+
# 0. Parakeet (English), when auto-routing picks it or it was asked for by name
|
|
378
|
+
route = parakeet_route(wanted, language, wav, shutil, subprocess, pmodel, whisper_model=model)
|
|
379
|
+
done = parakeet(route.first, route.facts)
|
|
380
|
+
if done:
|
|
381
|
+
return done
|
|
382
|
+
tried.extend(_skipped_parakeet(route, language, "--language"))
|
|
383
|
+
if wanted in PARAKEET_ENGINES:
|
|
384
|
+
die_engine_failed(wanted, video, tried, _parakeet_available(wanted, shutil, pmodel))
|
|
385
|
+
facts = route.facts
|
|
386
|
+
if route.first:
|
|
387
|
+
# auto chose Parakeet and no Parakeet engine transcribed it: the routing says why Whisper ran
|
|
388
|
+
facts = dict(facts, routing=facts["routing"] + ROUTING_PARAKEET_FAILED)
|
|
389
|
+
# the language each Whisper engine is told: the named one, else the one auto's detector named
|
|
390
|
+
lang = language or facts.get("detected_language")
|
|
391
|
+
# 1. whisper.cpp
|
|
392
|
+
cli = _whisper_cpp_cli(shutil) if wanted in ("auto", "whisper.cpp") else None
|
|
393
|
+
if cli:
|
|
394
|
+
model_path = _whisper_cpp_model(model)
|
|
395
|
+
base = os.path.join(tmpdir, "out")
|
|
396
|
+
# whisper.cpp's own default is -l en: without "auto" it decodes any speech as English
|
|
397
|
+
cmd = [cli, "-m", model_path, "-f", wav, "-osrt", "-of", base, "-l", lang or "auto", *WHISPER_CPP_NO_CONTEXT]
|
|
398
|
+
proc = _asr_run(cmd, subprocess, "whisper.cpp")
|
|
399
|
+
if proc.returncode == 0 and os.path.exists(base + ".srt"):
|
|
400
|
+
info(f"transcribed with whisper.cpp ({os.path.basename(cli)}, model {os.path.basename(model_path)})")
|
|
401
|
+
cues = _engine_cues(base + ".srt", "whisper.cpp", video)
|
|
402
|
+
write_srt(cues, out_srt)
|
|
403
|
+
return Transcription(cues=cues, engine="whisper.cpp",
|
|
404
|
+
facts=dict(facts, engine="whisper.cpp", model=model_path, language=lang))
|
|
405
|
+
line = _failure_line(proc)
|
|
406
|
+
info("whisper.cpp found but failed: " + line)
|
|
407
|
+
tried.append(_failed("whisper.cpp", "found but failed: " + line))
|
|
408
|
+
# 2. faster-whisper (python package)
|
|
409
|
+
try:
|
|
410
|
+
if wanted not in ("auto", "faster-whisper"):
|
|
411
|
+
raise ImportError
|
|
412
|
+
from faster_whisper import WhisperModel # type: ignore
|
|
413
|
+
import threading
|
|
414
|
+
result: list = []
|
|
415
|
+
crashed: list = []
|
|
416
|
+
heard: list = [] # the language faster-whisper decoded, when it names one
|
|
417
|
+
|
|
418
|
+
def work() -> None:
|
|
419
|
+
try:
|
|
420
|
+
m = WhisperModel(model, device="cpu", compute_type="int8")
|
|
421
|
+
segments, decoded = m.transcribe(wav, language=lang, word_timestamps=False)
|
|
422
|
+
result.extend((seg.start, seg.end, seg.text.strip()) for seg in segments if seg.text.strip())
|
|
423
|
+
heard.append(getattr(decoded, "language", None))
|
|
424
|
+
except Exception as exc: # noqa: BLE001 -- a model that would not load or run: a failed engine
|
|
425
|
+
crashed.append(exc)
|
|
426
|
+
|
|
427
|
+
# An in-process engine gets the same wall-clock limit as the CLI engines and ffmpeg.
|
|
428
|
+
t = threading.Thread(target=work, daemon=True)
|
|
429
|
+
t.start()
|
|
430
|
+
t.join(STATE.timeout or None)
|
|
431
|
+
if t.is_alive():
|
|
432
|
+
die(f"faster-whisper exceeded the {STATE.timeout:.0f} s time limit; raise --timeout for a long recording", code=124, kind="timeout")
|
|
433
|
+
if crashed:
|
|
434
|
+
# it failed (a model it could not fetch or load), which is not "found no speech":
|
|
435
|
+
# move on to the next engine, as a failed whisper.cpp does
|
|
436
|
+
line = str(crashed[0])[:200] or type(crashed[0]).__name__
|
|
437
|
+
info("faster-whisper found but failed: " + line)
|
|
438
|
+
tried.append(_failed("faster-whisper", "found but failed: " + line))
|
|
439
|
+
else:
|
|
440
|
+
cues = list(result)
|
|
441
|
+
if not cues:
|
|
442
|
+
die_no_speech("faster-whisper", video)
|
|
443
|
+
info("transcribed with faster-whisper")
|
|
444
|
+
write_srt(cues, out_srt)
|
|
445
|
+
return Transcription(cues=cues, engine="faster-whisper",
|
|
446
|
+
facts=dict(facts, engine="faster-whisper", model=model,
|
|
447
|
+
language=lang or _heard_language(heard)))
|
|
448
|
+
except ImportError:
|
|
449
|
+
pass
|
|
450
|
+
# 3. openai-whisper CLI
|
|
451
|
+
whisper_exe = shutil.which("whisper") if wanted in ("auto", "openai-whisper") else None
|
|
452
|
+
if whisper_exe:
|
|
453
|
+
cmd = [whisper_exe, wav, "--model", model, "--output_format", "srt", "--output_dir", tmpdir]
|
|
454
|
+
if lang:
|
|
455
|
+
cmd += ["--language", lang]
|
|
456
|
+
proc = _asr_run(cmd, subprocess, "openai-whisper")
|
|
457
|
+
srt = os.path.join(tmpdir, "audio.srt")
|
|
458
|
+
if proc.returncode == 0 and os.path.exists(srt):
|
|
459
|
+
info("transcribed with openai-whisper")
|
|
460
|
+
cues = _engine_cues(srt, "openai-whisper", video)
|
|
461
|
+
write_srt(cues, out_srt)
|
|
462
|
+
return Transcription(cues=cues, engine="openai-whisper",
|
|
463
|
+
facts=dict(facts, engine="openai-whisper", model=model, language=lang))
|
|
464
|
+
line = _failure_line(proc)
|
|
465
|
+
info("openai-whisper found but failed: " + line)
|
|
466
|
+
tried.append(_failed("openai-whisper", "found but failed: " + line))
|
|
467
|
+
# 4. Parakeet after all, when the language was never known and every Whisper engine failed
|
|
468
|
+
if route.last:
|
|
469
|
+
info("no Whisper engine transcribed it; a multilingual Parakeet model may")
|
|
470
|
+
done = parakeet(list(route.last), {"routing": ROUTING_LAST_RESORT})
|
|
471
|
+
if done:
|
|
472
|
+
return done
|
|
473
|
+
if wanted != "auto":
|
|
474
|
+
die_engine_failed(wanted, video, tried, any(t["engine"] == wanted for t in tried))
|
|
475
|
+
if tried:
|
|
476
|
+
die_engines_failed(tried, video, "--transcribe", "Or write the cues by hand with --text cues.txt (see format above).")
|
|
477
|
+
die_no_engine("Or write the cues by hand with --text cues.txt (see format above).")
|
|
478
|
+
return Transcription()
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def die_no_engine(alternative: str, flag: str = "--transcribe") -> None:
|
|
482
|
+
"""The one "no local speech-to-text engine" refusal, in the one set of words.
|
|
483
|
+
|
|
484
|
+
kind missing_tool (3.1.0; it was kind input, which read as a bad argument), `reason:
|
|
485
|
+
"asr_engine_missing"`, exit 1, and the three install lines -- caption.py and silence.py both
|
|
486
|
+
land here rather than each spelling out its own version of the same missing dependency.
|
|
487
|
+
"""
|
|
488
|
+
die(f"no local speech-to-text engine found for {flag}.\n" + ASR_INSTALL_HINT + "\n" + alternative,
|
|
489
|
+
kind="missing_tool", error_extra={"reason": "asr_engine_missing", "details": {}},
|
|
490
|
+
hint="install one of the engines above; `python3 scripts/_contract.py doctor` shows which are found")
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def whisper_word_timings(srt_path: Optional[str]) -> List[Tuple[float, float, str]]:
|
|
494
|
+
"""Word timings from a whisper JSON transcript sitting next to the SRT, if there is one.
|
|
495
|
+
|
|
496
|
+
whisper (and faster-whisper, and whisper.cpp's --output-json) can emit per-word start/end
|
|
497
|
+
times; when they are there, --karaoke should follow the real speech instead of splitting the
|
|
498
|
+
cue evenly. Looked for as <stem>.json and <stem>.words.json next to the SRT, in either the
|
|
499
|
+
{"segments": [{"words": [{"word": ..., "start": ..., "end": ...}]}]} or a bare
|
|
500
|
+
{"words": [...]} shape. Anything unreadable is simply "no word timings".
|
|
501
|
+
"""
|
|
502
|
+
if not srt_path:
|
|
503
|
+
return []
|
|
504
|
+
stem = os.path.splitext(srt_path)[0]
|
|
505
|
+
for cand in (stem + ".words.json", stem + ".json"):
|
|
506
|
+
if not os.path.exists(cand):
|
|
507
|
+
continue
|
|
508
|
+
try:
|
|
509
|
+
data = read_json(cand)
|
|
510
|
+
except (OSError, ValueError):
|
|
511
|
+
continue
|
|
512
|
+
# the shape is not checked first: a segment that is a string or a list, or "segments" that
|
|
513
|
+
# is a number, is simply no words, as _dicts() reads every engine's JSON
|
|
514
|
+
raw = []
|
|
515
|
+
if isinstance(data, dict):
|
|
516
|
+
raw = _dicts(data.get("words"))
|
|
517
|
+
for seg in _dicts(data.get("segments")):
|
|
518
|
+
raw.extend(_dicts(seg.get("words")))
|
|
519
|
+
words = []
|
|
520
|
+
for w in raw:
|
|
521
|
+
try:
|
|
522
|
+
text = str(w.get("word") or w.get("text") or "").strip()
|
|
523
|
+
start, end = float(w["start"]), float(w["end"])
|
|
524
|
+
# NaN / Infinity are valid to json.loads and place no word anywhere
|
|
525
|
+
if text and math.isfinite(start) and math.isfinite(end):
|
|
526
|
+
words.append((start, end, text))
|
|
527
|
+
except (AttributeError, KeyError, TypeError, ValueError):
|
|
528
|
+
continue
|
|
529
|
+
if words:
|
|
530
|
+
info(f"karaoke: word timings from {os.path.basename(cand)} ({len(words)} words)")
|
|
531
|
+
return sorted(words)
|
|
532
|
+
return []
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
# ------------------------------------------------------- word-level timings (1.17)
|
|
536
|
+
#
|
|
537
|
+
# transcribe() above produces an SRT, which is all --transcribe on caption.py ever needed: a cue
|
|
538
|
+
# has a start and an end and that is what gets burnt in. silence.py --filler needs something
|
|
539
|
+
# stricter -- a start and an end PER WORD -- and no amount of reading an SRT back produces one.
|
|
540
|
+
# Each engine has its own flag for it, and each writes a different shape, so each is driven and
|
|
541
|
+
# parsed here rather than in the tool.
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _words_from_whisper_cpp_json(path: str) -> "List[Dict[str, Any]]":
|
|
545
|
+
"""whisper.cpp --output-json-full: transcription[].tokens[] with offsets in MILLISECONDS.
|
|
546
|
+
|
|
547
|
+
Token text carries leading spaces and the model's special tokens ([_BEG_], [_TT_123]); those
|
|
548
|
+
are dropped, and a token that is a word continuation (no leading space) is glued onto the
|
|
549
|
+
previous word so "un" + "believable" is one word with one span, not two. Chinese, Japanese
|
|
550
|
+
and Thai have no spaces, so there every token would continue the one before and a whole
|
|
551
|
+
segment became one "word": between two whole characters of such a script the tokens stay
|
|
552
|
+
apart, as openai-whisper and faster-whisper split them (filler_spans() finds the word
|
|
553
|
+
boundaries). A token that is part of a character (U+FFFD) is still glued.
|
|
554
|
+
"""
|
|
555
|
+
try:
|
|
556
|
+
doc = read_json(path)
|
|
557
|
+
except (OSError, ValueError):
|
|
558
|
+
return []
|
|
559
|
+
out: "List[Dict[str, Any]]" = []
|
|
560
|
+
for seg in _dicts(doc.get("transcription")) if isinstance(doc, dict) else []:
|
|
561
|
+
for tok in _dicts(seg.get("tokens")):
|
|
562
|
+
text = str(tok.get("text") or "")
|
|
563
|
+
if not text.strip() or text.strip().startswith("[_"):
|
|
564
|
+
continue
|
|
565
|
+
offsets = tok.get("offsets") or {}
|
|
566
|
+
try:
|
|
567
|
+
start, end = float(offsets["from"]) / 1000.0, float(offsets["to"]) / 1000.0
|
|
568
|
+
except (KeyError, TypeError, ValueError):
|
|
569
|
+
continue
|
|
570
|
+
prev = out[-1]["word"] if out else ""
|
|
571
|
+
# "嗯" + "," + "呃": the comma stays with the word before it and ends that word
|
|
572
|
+
core = prev
|
|
573
|
+
while core and unicodedata.category(core[-1]).startswith("P"):
|
|
574
|
+
core = core[:-1]
|
|
575
|
+
unspaced = (core and _unspaced_script(core[-1]) and _unspaced_script(text.lstrip()[:1] or " ")
|
|
576
|
+
and "\ufffd" not in prev[-1:] + text)
|
|
577
|
+
if out and not text.startswith(" ") and not unspaced:
|
|
578
|
+
out[-1]["word"] += text
|
|
579
|
+
out[-1]["end"] = end
|
|
580
|
+
else:
|
|
581
|
+
out.append({"word": text.strip(), "start": start, "end": end})
|
|
582
|
+
return [w for w in out if w["word"].strip()]
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def _whisper_json_language(path: str) -> Optional[str]:
|
|
586
|
+
"""The language a Whisper engine's JSON says it decoded: whisper.cpp's `result.language`, or
|
|
587
|
+
openai-whisper's top-level `language`. None when the file has neither."""
|
|
588
|
+
try:
|
|
589
|
+
doc = read_json(path) or {}
|
|
590
|
+
lang = str(((doc.get("result") or {}).get("language")) or doc.get("language") or "").strip().lower()
|
|
591
|
+
except (OSError, ValueError, AttributeError):
|
|
592
|
+
return None
|
|
593
|
+
return lang or None
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def _heard_language(heard: list) -> Optional[str]:
|
|
597
|
+
"""The language an in-process engine decoded (faster-whisper's info.language), lower-cased, or None."""
|
|
598
|
+
lang = next((str(h).strip().lower() for h in heard if h), "")
|
|
599
|
+
return lang or None
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def _words_from_openai_whisper_json(path: str) -> "List[Dict[str, Any]]":
|
|
603
|
+
"""openai-whisper --word_timestamps True --output_format json: segments[].words[]."""
|
|
604
|
+
try:
|
|
605
|
+
doc = read_json(path)
|
|
606
|
+
except (OSError, ValueError):
|
|
607
|
+
return []
|
|
608
|
+
out: "List[Dict[str, Any]]" = []
|
|
609
|
+
for seg in _dicts(doc.get("segments")) if isinstance(doc, dict) else []:
|
|
610
|
+
for w in _dicts(seg.get("words")):
|
|
611
|
+
try:
|
|
612
|
+
out.append({"word": str(w.get("word") or w.get("text") or "").strip(),
|
|
613
|
+
"start": float(w["start"]), "end": float(w["end"])})
|
|
614
|
+
except (KeyError, TypeError, ValueError):
|
|
615
|
+
continue
|
|
616
|
+
return [w for w in out if w["word"]]
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
# ------------------------------------------------------- Parakeet engines and routing
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
def _words_from_parakeet_mlx_json(path: str) -> "List[Dict[str, Any]]":
|
|
623
|
+
"""parakeet-mlx --output-format json: sentences[].tokens[] of SUB-word pieces, times in seconds.
|
|
624
|
+
|
|
625
|
+
A piece with a leading space starts a word; a bare " " piece is a separator, so the piece
|
|
626
|
+
after it starts a word too (" m" "is" "ter" " " "Q" "u" "il" "ter" -> "mister", "Quilter").
|
|
627
|
+
"""
|
|
628
|
+
try:
|
|
629
|
+
doc = read_json(path)
|
|
630
|
+
except (OSError, ValueError):
|
|
631
|
+
return []
|
|
632
|
+
out: "List[Dict[str, Any]]" = []
|
|
633
|
+
for sent in _dicts(doc.get("sentences")) if isinstance(doc, dict) else []:
|
|
634
|
+
brk = True # every sentence starts a new word
|
|
635
|
+
for tok in _dicts(sent.get("tokens")):
|
|
636
|
+
text = str(tok.get("text") or "")
|
|
637
|
+
try:
|
|
638
|
+
start, end = float(tok["start"]), float(tok["end"])
|
|
639
|
+
except (KeyError, TypeError, ValueError):
|
|
640
|
+
continue
|
|
641
|
+
if not text.strip():
|
|
642
|
+
brk = True
|
|
643
|
+
continue
|
|
644
|
+
if brk or text.startswith(" ") or not out:
|
|
645
|
+
out.append({"word": text.strip(), "start": start, "end": end})
|
|
646
|
+
else:
|
|
647
|
+
out[-1]["word"] += text
|
|
648
|
+
out[-1]["end"] = end
|
|
649
|
+
brk = False
|
|
650
|
+
return [w for w in out if w["word"]]
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def _cues_from_parakeet_mlx_json(path: str) -> List[Tuple[float, float, str]]:
|
|
654
|
+
"""parakeet-mlx's own sentence segmentation, as cues."""
|
|
655
|
+
try:
|
|
656
|
+
doc = read_json(path)
|
|
657
|
+
except (OSError, ValueError):
|
|
658
|
+
return []
|
|
659
|
+
cues: List[Tuple[float, float, str]] = []
|
|
660
|
+
for sent in _dicts(doc.get("sentences")) if isinstance(doc, dict) else []:
|
|
661
|
+
try:
|
|
662
|
+
text = str(sent.get("text") or "").strip()
|
|
663
|
+
if text:
|
|
664
|
+
cues.append((float(sent["start"]), float(sent["end"]), text))
|
|
665
|
+
except (KeyError, TypeError, ValueError):
|
|
666
|
+
continue
|
|
667
|
+
return cues
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
def _dicts(value: Any) -> "List[Dict[str, Any]]":
|
|
671
|
+
"""The dict items of a JSON list; anything else (a number, a string, null) is no items. The
|
|
672
|
+
engines' JSON is parsed defensively: a wrong shape yields no words, never a traceback."""
|
|
673
|
+
return [v for v in value if isinstance(v, dict)] if isinstance(value, list) else []
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def _words_from_parakeet_cpp_json(text: str) -> "List[Dict[str, Any]]":
|
|
677
|
+
"""parakeet-cli transcribe --json: {"words": [{"w", "start", "end", "conf"}]}, times in seconds."""
|
|
678
|
+
try:
|
|
679
|
+
doc = parse_json(text)
|
|
680
|
+
except ValueError:
|
|
681
|
+
return []
|
|
682
|
+
out: "List[Dict[str, Any]]" = []
|
|
683
|
+
for w in _dicts(doc.get("words")) if isinstance(doc, dict) else []:
|
|
684
|
+
try:
|
|
685
|
+
word = str(w.get("w") or w.get("word") or "").strip()
|
|
686
|
+
if word:
|
|
687
|
+
out.append({"word": word, "start": float(w["start"]), "end": float(w["end"])})
|
|
688
|
+
except (AttributeError, KeyError, TypeError, ValueError):
|
|
689
|
+
continue
|
|
690
|
+
return out
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
# Cue boundaries for an engine that gives words but no sentences (parakeet.cpp): the same limits
|
|
694
|
+
# parakeet-mlx's own segmentation is run with, so both Parakeet engines cut cues alike.
|
|
695
|
+
CUE_MAX_SECONDS = 7.0
|
|
696
|
+
CUE_MAX_CHARS = 84
|
|
697
|
+
CUE_GAP_SECONDS = 0.8
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
def cues_from_words(words: "List[Dict[str, Any]]") -> List[Tuple[float, float, str]]:
|
|
701
|
+
"""Group timed words into cues: a cue ends after sentence-final punctuation, before a pause of
|
|
702
|
+
CUE_GAP_SECONDS or more, or before it would pass CUE_MAX_SECONDS / CUE_MAX_CHARS."""
|
|
703
|
+
cues: List[Tuple[float, float, str]] = []
|
|
704
|
+
cur: "List[Dict[str, Any]]" = []
|
|
705
|
+
|
|
706
|
+
def flush() -> None:
|
|
707
|
+
if cur:
|
|
708
|
+
cues.append((cur[0]["start"], cur[-1]["end"], " ".join(w["word"] for w in cur)))
|
|
709
|
+
cur.clear()
|
|
710
|
+
|
|
711
|
+
for w in words:
|
|
712
|
+
if cur:
|
|
713
|
+
text_len = len(" ".join(x["word"] for x in cur)) + 1 + len(w["word"])
|
|
714
|
+
if (w["start"] - cur[-1]["end"] >= CUE_GAP_SECONDS or w["end"] - cur[0]["start"] > CUE_MAX_SECONDS
|
|
715
|
+
or text_len > CUE_MAX_CHARS):
|
|
716
|
+
flush()
|
|
717
|
+
cur.append(w)
|
|
718
|
+
if w["word"][-1:] in ".?!":
|
|
719
|
+
flush()
|
|
720
|
+
flush()
|
|
721
|
+
return cues
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
def requested_engine(engine: Optional[str]) -> str:
|
|
725
|
+
"""--engine, else $FFMPEG_SKILL_ASR_ENGINE, else "auto"; an unknown env value is refused."""
|
|
726
|
+
name = engine or os.environ.get(ASR_ENGINE_ENV, "").strip() or "auto"
|
|
727
|
+
if name not in ENGINE_CHOICES:
|
|
728
|
+
die(f"{ASR_ENGINE_ENV}={name!r} is not a speech engine this skill drives (one of {', '.join(ENGINE_CHOICES)})",
|
|
729
|
+
kind="input", hint=f"unset {ASR_ENGINE_ENV} or set it to one of {', '.join(ENGINE_CHOICES)}")
|
|
730
|
+
return name
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
def requested_model(model: Optional[str]) -> Tuple[str, str]:
|
|
734
|
+
"""(the model the Whisper engines run, the model the Parakeet engines are offered): --model,
|
|
735
|
+
else $FFMPEG_SKILL_ASR_MODEL, else base.
|
|
736
|
+
|
|
737
|
+
--model is one call's choice and goes to whichever engine runs, as it always has. The
|
|
738
|
+
variable is this machine's default for every call, so it never hands an engine a model that
|
|
739
|
+
engine cannot load: a Parakeet model there (an mlx-community/parakeet-* repo or a .gguf) goes
|
|
740
|
+
to the Parakeet engines only, and the Whisper engines keep base. A Whisper name reaches the
|
|
741
|
+
Parakeet engines too, which pass over it for their own model, as they do for --model."""
|
|
742
|
+
if model:
|
|
743
|
+
return model, model
|
|
744
|
+
name = os.environ.get(ASR_MODEL_ENV, "").strip()
|
|
745
|
+
if not name:
|
|
746
|
+
return DEFAULT_WHISPER_MODEL, DEFAULT_WHISPER_MODEL
|
|
747
|
+
if _names_parakeet_model(name):
|
|
748
|
+
return DEFAULT_WHISPER_MODEL, name
|
|
749
|
+
return name, name
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
def _is_english(language: Optional[str]) -> bool:
|
|
753
|
+
# "eng" too: caption.py's --language is also the mux track tag, where ISO 639-2 is natural
|
|
754
|
+
return (language or "").lower().split("-")[0].split("_")[0] in ("en", "eng", "english")
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def engine_language(language: Optional[str]) -> Optional[str]:
|
|
758
|
+
"""`--language` as the engines take it. "auto" (caption.py's documented default, spelled out)
|
|
759
|
+
is no language: None, the undetected route. Every spelling of English (en-US, eng, English)
|
|
760
|
+
is "en", which Parakeet accepts as English and Whisper accepts as a language code; any other
|
|
761
|
+
value is its two-letter primary language (ja-JP -> ja)."""
|
|
762
|
+
named = (language or "").strip()
|
|
763
|
+
if not named or named.lower() == "auto":
|
|
764
|
+
return None
|
|
765
|
+
if _is_english(named):
|
|
766
|
+
return "en"
|
|
767
|
+
# Whisper takes the two-letter code: a regional or script subtag (ja-JP, pt-BR, zh-Hant) names the
|
|
768
|
+
# same language to it, and an ISO 639-2 code (jpn) is passed as given
|
|
769
|
+
primary = named.replace("_", "-").split("-")[0].lower()
|
|
770
|
+
return primary if len(primary) == 2 else named
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
def _whisper_cpp_cli(shutil) -> Optional[str]:
|
|
774
|
+
cli = shutil.which("whisper-cli") or shutil.which("whisper-cpp")
|
|
775
|
+
if not cli:
|
|
776
|
+
# older whisper.cpp builds ship the binary as plain `main`; accept it only when it lives
|
|
777
|
+
# in a directory that names whisper, so an unrelated /usr/bin/main is never run
|
|
778
|
+
main_bin = shutil.which("main")
|
|
779
|
+
if main_bin and "whisper" in os.path.dirname(os.path.realpath(main_bin)).lower():
|
|
780
|
+
cli = main_bin
|
|
781
|
+
return cli
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
def _whisper_cpp_model(model: str) -> str:
|
|
785
|
+
if os.path.exists(model):
|
|
786
|
+
return model
|
|
787
|
+
for cand in (os.path.expanduser(f"~/.cache/whisper.cpp/ggml-{model}.bin"), f"models/ggml-{model}.bin",
|
|
788
|
+
f"/usr/local/share/whisper/ggml-{model}.bin"):
|
|
789
|
+
if os.path.exists(cand):
|
|
790
|
+
return cand
|
|
791
|
+
return model
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def detect_language(wav: str, shutil, subprocess) -> Optional[str]:
|
|
795
|
+
"""The spoken language of `wav` from whisper.cpp's detector (-dl), or None when it cannot tell.
|
|
796
|
+
|
|
797
|
+
The smallest installed ggml model is used: detection reads the first 30 s once, and a small
|
|
798
|
+
model answers it in well under a second on the GPU.
|
|
799
|
+
"""
|
|
800
|
+
cli = _whisper_cpp_cli(shutil)
|
|
801
|
+
if not cli:
|
|
802
|
+
return None
|
|
803
|
+
model = next((p for p in (_whisper_cpp_model(m) for m in ("tiny", "base", "small", "tiny.en"))
|
|
804
|
+
if os.path.exists(p) and not _english_only_whisper_model(p)), None)
|
|
805
|
+
if not model:
|
|
806
|
+
return None
|
|
807
|
+
proc = _asr_run([cli, "-m", model, "-f", wav, "-dl", "-l", "auto"], subprocess, "whisper.cpp language detection")
|
|
808
|
+
m = re.search(r"auto-detected language:\s*([a-z]{2,3})", (proc.stderr or "") + (proc.stdout or ""))
|
|
809
|
+
return m.group(1) if m else None
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
ROUTING_ASSUMED_ENGLISH = "auto: language not detectable here and no Whisper engine"
|
|
813
|
+
ROUTING_UNDETECTED_WHISPER = "auto: language not detectable here, Whisper first (Parakeet is English-only)"
|
|
814
|
+
ROUTING_LAST_RESORT = "auto: language not detectable here and no Whisper engine transcribed it"
|
|
815
|
+
ROUTING_PARAKEET_MODEL = "auto: --model names a Parakeet model and the language is not detectable here"
|
|
816
|
+
# appended to those three when a Parakeet engine ran: only a multilingual model does, with the language unknown
|
|
817
|
+
ROUTING_MULTILINGUAL = "; the Parakeet model is multilingual"
|
|
818
|
+
# appended to the routing auto chose Parakeet for, when no Parakeet engine transcribed it and a
|
|
819
|
+
# Whisper engine did
|
|
820
|
+
ROUTING_PARAKEET_FAILED = ", no Parakeet engine transcribed it"
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
class Route(NamedTuple):
|
|
824
|
+
"""parakeet_route()'s answer: which Parakeet engines run, and when."""
|
|
825
|
+
first: List[str] # Parakeet engines to try before any Whisper engine
|
|
826
|
+
facts: Dict[str, Any] # the routing facts for the result document's `transcription`
|
|
827
|
+
last: Tuple[str, ...] = () # Parakeet engines to try once every Whisper engine has failed
|
|
828
|
+
skipped: Tuple[str, ...] = () # installed Parakeet engines auto passed over: the language is not English
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
def parakeet_route(engine: str, language: Optional[str], wav: str, shutil, subprocess,
|
|
832
|
+
model: Optional[str] = None, whisper_model: Optional[str] = None) -> Route:
|
|
833
|
+
"""Route(the Parakeet engines to try first, routing facts for the result document, the ones to
|
|
834
|
+
try last, the installed ones passed over).
|
|
835
|
+
|
|
836
|
+
`auto` tries Parakeet only for English: an explicit --language, else whisper.cpp's detector.
|
|
837
|
+
When neither can say, the English-only model is not trusted with it: a Whisper engine that
|
|
838
|
+
can run (`whisper_model`, default `model`) goes first and Parakeet only after every Whisper
|
|
839
|
+
engine failed; with no Whisper engine (or a --model that names a Parakeet model, which no
|
|
840
|
+
Whisper engine can load), only a multilingual Parakeet model runs (_parakeet_attempt()): an
|
|
841
|
+
English-only one is refused, naming the flag for the language. A named Parakeet engine always runs; with a non-English --language it
|
|
842
|
+
needs a multilingual (v3) model, which _parakeet_model_for() checks.
|
|
843
|
+
"""
|
|
844
|
+
if engine in PARAKEET_ENGINES:
|
|
845
|
+
return Route([engine], {"routing": "requested"})
|
|
846
|
+
if engine != "auto":
|
|
847
|
+
return Route([], {"routing": "requested"})
|
|
848
|
+
installed = tuple(e for e in PARAKEET_ENGINES if _parakeet_available(e, shutil, model))
|
|
849
|
+
if not installed:
|
|
850
|
+
return Route([], {"routing": "auto: no Parakeet engine installed"})
|
|
851
|
+
if language:
|
|
852
|
+
if _is_english(language):
|
|
853
|
+
return Route(list(PARAKEET_ENGINES), {"routing": "auto: --language is English"})
|
|
854
|
+
info(f"{' and '.join(installed)} passed over: --engine auto runs Parakeet only for English speech (--language {language})")
|
|
855
|
+
return Route([], {"routing": f"auto: --language {language} is not English"}, (), installed)
|
|
856
|
+
detected = detect_language(wav, shutil, subprocess)
|
|
857
|
+
if detected is None:
|
|
858
|
+
wmodel = whisper_model if whisper_model is not None else model
|
|
859
|
+
if _names_parakeet_model(wmodel or "base"):
|
|
860
|
+
return Route(list(PARAKEET_ENGINES), {"routing": ROUTING_PARAKEET_MODEL})
|
|
861
|
+
if _whisper_ready(shutil, wmodel):
|
|
862
|
+
info("the spoken language could not be detected here; a Whisper engine takes it (Parakeet's model is English-only)")
|
|
863
|
+
return Route([], {"routing": ROUTING_UNDETECTED_WHISPER}, PARAKEET_ENGINES)
|
|
864
|
+
return Route(list(PARAKEET_ENGINES), {"routing": ROUTING_ASSUMED_ENGLISH})
|
|
865
|
+
if _is_english(detected):
|
|
866
|
+
return Route(list(PARAKEET_ENGINES), {"routing": "auto: detected English", "detected_language": detected})
|
|
867
|
+
info(f"{' and '.join(installed)} passed over: --engine auto runs Parakeet only for English speech (detected {detected})")
|
|
868
|
+
return Route([], {"routing": f"auto: detected {detected}, not English", "detected_language": detected}, (), installed)
|
|
869
|
+
|
|
870
|
+
|
|
871
|
+
def _module_importable(name: str) -> bool:
|
|
872
|
+
"""`import name` would find something, without importing it (faster-whisper pulls in ctranslate2)."""
|
|
873
|
+
import importlib.util
|
|
874
|
+
import sys
|
|
875
|
+
try:
|
|
876
|
+
return importlib.util.find_spec(name) is not None
|
|
877
|
+
except (ImportError, ValueError): # a module already in sys.modules with no __spec__ (a stub)
|
|
878
|
+
return sys.modules.get(name) is not None
|
|
879
|
+
|
|
880
|
+
|
|
881
|
+
def _names_parakeet_model(name: str) -> bool:
|
|
882
|
+
"""`name` is a Parakeet model (an mlx-community/parakeet-* repo or a .gguf), which no Whisper engine loads."""
|
|
883
|
+
return "parakeet" in name.lower() or name.lower().endswith(".gguf")
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
def _english_only_whisper_model(name: str) -> bool:
|
|
887
|
+
"""An English-only Whisper model: tiny.en, base.en, ... or a ggml-*.en.bin file, in any
|
|
888
|
+
quantisation (ggml-base.en-q5_1.bin, tiny.en-q8_0) or variant (ggml-small.en-tdrz.bin)."""
|
|
889
|
+
base = os.path.basename(name).lower()
|
|
890
|
+
return re.search(r"\.en(-[a-z0-9_]+)*$", base[:-4] if base.endswith(".bin") else base) is not None
|
|
891
|
+
|
|
892
|
+
|
|
893
|
+
def _whisper_ready(shutil, model: Optional[str]) -> bool:
|
|
894
|
+
"""A Whisper engine that --engine auto would run with `model` on speech in any language:
|
|
895
|
+
whisper.cpp with that model on disk, faster-whisper importable, or the openai-whisper CLI. A
|
|
896
|
+
Parakeet model name is no Whisper model, and an English-only one (base.en, ggml-*.en.bin)
|
|
897
|
+
handles English alone, so both answer False."""
|
|
898
|
+
name = (model or "base")
|
|
899
|
+
if _names_parakeet_model(name) or _english_only_whisper_model(name):
|
|
900
|
+
return False
|
|
901
|
+
if _whisper_cpp_cli(shutil):
|
|
902
|
+
path = _whisper_cpp_model(name)
|
|
903
|
+
if os.path.exists(path) and not _english_only_whisper_model(path):
|
|
904
|
+
return True
|
|
905
|
+
return _module_importable("faster_whisper") or bool(shutil.which("whisper"))
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def _parakeet_available(engine: str, shutil, model: Optional[str] = None) -> bool:
|
|
909
|
+
if engine == "parakeet-mlx":
|
|
910
|
+
return bool(shutil.which("parakeet-mlx"))
|
|
911
|
+
gguf = _parakeet_cpp_gguf(model)
|
|
912
|
+
return bool(shutil.which("parakeet-cli")) and gguf is not None and os.path.isfile(gguf)
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
def _parakeet_cpp_gguf(model: Optional[str]) -> Optional[str]:
|
|
916
|
+
"""--model when it is a .gguf, else $PARAKEET_CPP_MODEL, else an English tdt-0.6b-v2 .gguf in
|
|
917
|
+
~/.cache/parakeet.cpp/ (f16 first, then q8_0, then any other quantisation)."""
|
|
918
|
+
if model and model.lower().endswith(".gguf"):
|
|
919
|
+
return os.path.expanduser(model)
|
|
920
|
+
env = os.environ.get("PARAKEET_CPP_MODEL", "").strip()
|
|
921
|
+
if env:
|
|
922
|
+
return os.path.expanduser(env)
|
|
923
|
+
cache = Path(os.path.expanduser("~/.cache/parakeet.cpp"))
|
|
924
|
+
found = sorted(cache.glob("tdt-0.6b-v2-*.gguf")) if cache.is_dir() else []
|
|
925
|
+
for pref in ("-f16.gguf", "-q8_0.gguf"):
|
|
926
|
+
for p in found:
|
|
927
|
+
if p.name.endswith(pref):
|
|
928
|
+
return str(p)
|
|
929
|
+
return str(found[0]) if found else None
|
|
930
|
+
|
|
931
|
+
|
|
932
|
+
def _parakeet_model_for(engine: str, model: Optional[str], language: Optional[str]) -> str:
|
|
933
|
+
"""The model the Parakeet engine runs: --model when it names a Parakeet model, else the
|
|
934
|
+
engine's own environment variable, else the English v2 default. A non-English --language on a
|
|
935
|
+
model without "v3" in its name is refused: v2 would transcribe it as English gibberish."""
|
|
936
|
+
if engine == "parakeet-mlx":
|
|
937
|
+
chosen = model if model and "parakeet" in model.lower() and not model.lower().endswith(".gguf") else \
|
|
938
|
+
(os.environ.get("PARAKEET_MODEL", "").strip() or PARAKEET_MLX_DEFAULT_MODEL)
|
|
939
|
+
else:
|
|
940
|
+
chosen = _parakeet_cpp_gguf(model) or ""
|
|
941
|
+
if language and not _is_english(language) and not _parakeet_multilingual(chosen):
|
|
942
|
+
die(f"{engine} with model {os.path.basename(chosen) or '?'} is English-only; --language {language} needs a multilingual (v3) Parakeet model",
|
|
943
|
+
kind="input", hint="pass --model with a parakeet-tdt-0.6b-v3 model, or --engine auto / whisper.cpp for this language")
|
|
944
|
+
return chosen
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
def _parakeet_multilingual(model: str) -> bool:
|
|
948
|
+
"""A multilingual Parakeet model (tdt-0.6b-v3, 25 European languages) rather than the English-only v2."""
|
|
949
|
+
return "v3" in os.path.basename(model or "").lower()
|
|
950
|
+
|
|
951
|
+
|
|
952
|
+
def run_parakeet(engine: str, wav: str, tmpdir: str, model: Optional[str], language: Optional[str], shutil, subprocess,
|
|
953
|
+
video: str, tried: "Optional[List[Dict[str, str]]]" = None,
|
|
954
|
+
) -> Optional[Tuple[List[Tuple[float, float, str]], "List[Dict[str, Any]]", str]]:
|
|
955
|
+
"""(cues, words, model) from one Parakeet engine, or None when it is not installed or failed
|
|
956
|
+
(an info line says which, and a failed run is added to `tried`), so the caller moves on to the
|
|
957
|
+
next engine. Output that yields no words is only "no speech" when it is the engine's own empty
|
|
958
|
+
answer; anything else it could not be read, which is a failed run too."""
|
|
959
|
+
if not _parakeet_available(engine, shutil, model):
|
|
960
|
+
info(f"{engine} not available" + (" (no readable .gguf: --model, PARAKEET_CPP_MODEL, or tdt-0.6b-v2 in ~/.cache/parakeet.cpp)"
|
|
961
|
+
if engine == "parakeet.cpp" and shutil.which("parakeet-cli") else ""))
|
|
962
|
+
return None
|
|
963
|
+
chosen = _parakeet_model_for(engine, model, language)
|
|
964
|
+
|
|
965
|
+
def failed(detail: str) -> None:
|
|
966
|
+
info(f"{engine} {detail}")
|
|
967
|
+
if tried is not None:
|
|
968
|
+
tried.append(_failed(engine, detail))
|
|
969
|
+
|
|
970
|
+
if engine == "parakeet-mlx":
|
|
971
|
+
outdir = os.path.join(tmpdir, "pmlx")
|
|
972
|
+
exe = shutil.which("parakeet-mlx")
|
|
973
|
+
if not exe: # never the bare name: the OS would look for it in the working directory
|
|
974
|
+
failed("not on PATH")
|
|
975
|
+
return None
|
|
976
|
+
cmd = [exe, wav, "--model", chosen, "--output-format", "json", "--output-dir", outdir,
|
|
977
|
+
"--max-duration", f"{CUE_MAX_SECONDS:g}", "--silence-gap", f"{CUE_GAP_SECONDS:g}"]
|
|
978
|
+
# the JSON is looked for as <outdir>/audio.json: a host PARAKEET_OUTPUT_TEMPLATE would name it otherwise
|
|
979
|
+
env = {k: v for k, v in os.environ.items() if k != "PARAKEET_OUTPUT_TEMPLATE"}
|
|
980
|
+
proc = _asr_run(cmd, subprocess, "parakeet-mlx", env=env)
|
|
981
|
+
doc = os.path.join(outdir, os.path.splitext(os.path.basename(wav))[0] + ".json")
|
|
982
|
+
if proc.returncode != 0 or not os.path.exists(doc):
|
|
983
|
+
failed("found but failed: " + _failure_line(proc, errors_on_stdout=True))
|
|
984
|
+
return None
|
|
985
|
+
cues, words = _cues_from_parakeet_mlx_json(doc), _words_from_parakeet_mlx_json(doc)
|
|
986
|
+
try:
|
|
987
|
+
raw, key = Path(doc).read_text(encoding="utf-8", errors="replace"), "sentences"
|
|
988
|
+
except OSError:
|
|
989
|
+
raw, key = "", "sentences"
|
|
990
|
+
else:
|
|
991
|
+
exe = shutil.which("parakeet-cli")
|
|
992
|
+
if not exe:
|
|
993
|
+
failed("not on PATH")
|
|
994
|
+
return None
|
|
995
|
+
cmd = [exe, "transcribe", "--model", chosen, "--input", wav, "--json"]
|
|
996
|
+
proc = _asr_run(cmd, subprocess, "parakeet.cpp")
|
|
997
|
+
if proc.returncode != 0:
|
|
998
|
+
failed("found but failed: " + _failure_line(proc))
|
|
999
|
+
return None
|
|
1000
|
+
words = _words_from_parakeet_cpp_json(proc.stdout)
|
|
1001
|
+
cues = cues_from_words(words)
|
|
1002
|
+
raw, key = proc.stdout or "", "words"
|
|
1003
|
+
if not cues:
|
|
1004
|
+
if _heard_nothing(raw, key):
|
|
1005
|
+
die_no_speech(engine, video)
|
|
1006
|
+
failed(f"ran but wrote output this skill cannot read as a transcript ({(raw.strip() or 'nothing')[:80]!r})")
|
|
1007
|
+
return None
|
|
1008
|
+
return cues, words, chosen
|
|
1009
|
+
|
|
1010
|
+
|
|
1011
|
+
def _heard_nothing(text: str, key: str) -> bool:
|
|
1012
|
+
"""True when an engine's JSON is its well-formed empty answer, {key: []}: what parakeet-cli
|
|
1013
|
+
("words") and parakeet-mlx ("sentences") both write for silence (measured on 3 s of it).
|
|
1014
|
+
Anything else that yields no words -- not JSON, the wrong shape, entries that do not parse --
|
|
1015
|
+
is output that could not be read, not a finding that nobody spoke."""
|
|
1016
|
+
try:
|
|
1017
|
+
doc = parse_json(text)
|
|
1018
|
+
except ValueError:
|
|
1019
|
+
return False
|
|
1020
|
+
return isinstance(doc, dict) and doc.get(key) == []
|
|
1021
|
+
|
|
1022
|
+
|
|
1023
|
+
def _whisper_heard_nothing(path: str, key: str) -> bool:
|
|
1024
|
+
"""True when a Whisper engine's JSON is well formed and none of its segments (`key`:
|
|
1025
|
+
whisper.cpp's "transcription", openai-whisper's "segments") holds any text: the engine heard
|
|
1026
|
+
no speech (#414). A document with text and no word timings is a build without them, not
|
|
1027
|
+
silence, and stays the "no word-level timings" refusal."""
|
|
1028
|
+
try:
|
|
1029
|
+
doc = read_json(path)
|
|
1030
|
+
except (OSError, ValueError):
|
|
1031
|
+
return False
|
|
1032
|
+
if not isinstance(doc, dict) or not isinstance(doc.get(key), list):
|
|
1033
|
+
return False
|
|
1034
|
+
# every segment a dict with a text field, all of them blank: a segment with no `text` at all is
|
|
1035
|
+
# output this skill cannot read, not silence (as _heard_nothing() reads Parakeet's)
|
|
1036
|
+
return all(isinstance(seg, dict) and isinstance(seg.get("text"), str) and not seg["text"].strip()
|
|
1037
|
+
for seg in doc[key])
|
|
1038
|
+
|
|
1039
|
+
|
|
1040
|
+
def engine_wav(ffmpeg: str, video: str, audio_stream: int, wav: str) -> None:
|
|
1041
|
+
"""The 16 kHz mono WAV an engine transcribes, on the file's clock: a sound that starts after
|
|
1042
|
+
the file's start is padded with silence to its place (aresample first_pts=0, as
|
|
1043
|
+
decode_pcm_mono() does since #409), so every cue and word time counts from the file's start,
|
|
1044
|
+
not from the sound's first sample (#414: a sound 0.276 s late gave cues 0.276 s early).
|
|
1045
|
+
A measurement input in our own temp dir, not a deliverable, so not a run() call (no
|
|
1046
|
+
--dry-run gate, not recorded); it keeps the time limit and reports an unreadable input as
|
|
1047
|
+
kind ffmpeg instead of a CalledProcessError traceback."""
|
|
1048
|
+
from _common import run_analysis
|
|
1049
|
+
run_analysis([ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i", video,
|
|
1050
|
+
"-map", f"0:a:{audio_stream}", "-vn", "-af", "aresample=async=1:first_pts=0",
|
|
1051
|
+
"-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", wav])
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
def transcribe_words(video: str, language: "Optional[str]" = None, model: "Optional[str]" = None,
|
|
1055
|
+
audio_stream: int = 0, engine: "Optional[str]" = None) -> "Tuple[List[Dict[str, Any]], Optional[str]]":
|
|
1056
|
+
"""transcribe_words_result()'s (words, engine) alone: the call shape this function has had
|
|
1057
|
+
since 1.17. A caller that reports which engine ran (silence.py does) calls
|
|
1058
|
+
transcribe_words_result() instead."""
|
|
1059
|
+
run = transcribe_words_result(video, language, model, audio_stream, engine)
|
|
1060
|
+
return run.words, run.engine
|
|
1061
|
+
|
|
1062
|
+
|
|
1063
|
+
def transcribe_words_result(video: str, language: "Optional[str]" = None, model: "Optional[str]" = None,
|
|
1064
|
+
audio_stream: int = 0, engine: "Optional[str]" = None,
|
|
1065
|
+
language_flag: str = "--filler-lang", prompt: "Optional[str]" = None) -> Transcription:
|
|
1066
|
+
"""[{word, start, end}, ...] from a local speech engine, as a Transcription naming the engine.
|
|
1067
|
+
|
|
1068
|
+
`model` (else $FFMPEG_SKILL_ASR_MODEL, else base: requested_model()) is the model and
|
|
1069
|
+
`engine` (else $FFMPEG_SKILL_ASR_ENGINE, else auto) picks it; auto tries Parakeet for English
|
|
1070
|
+
speech first (parakeet-mlx sub-word tokens merged into words, parakeet.cpp `--json` words),
|
|
1071
|
+
then drives whichever whisper is installed with ITS word-timestamp option -- whisper.cpp
|
|
1072
|
+
`--output-json-full`, faster-whisper `word_timestamps=True`, openai-whisper
|
|
1073
|
+
`--word_timestamps True` -- and returns the words it measured. Words [] with the engine set
|
|
1074
|
+
when the engine ran but its build produced no word-level timings, so the caller can refuse
|
|
1075
|
+
naming that engine instead of pretending the audio had no words in it. No engine at all
|
|
1076
|
+
raises through die_no_engine(), the same refusal caption.py gives. `language_flag` is the
|
|
1077
|
+
caller's flag for the language, named in the refusal of an English-only model. `prompt` is passed to a
|
|
1078
|
+
Whisper engine as its initial prompt (whisper.cpp --prompt, faster-whisper initial_prompt,
|
|
1079
|
+
openai-whisper --initial_prompt): Whisper writes clean text and leaves out "uh"/"um" unless
|
|
1080
|
+
the context shows it that they are wanted, so silence.py --filler primes it with its own list.
|
|
1081
|
+
"""
|
|
1082
|
+
import shutil as _shutil
|
|
1083
|
+
from _common.runner import SafeShutil
|
|
1084
|
+
_shutil = SafeShutil(_shutil) # look engines up and launch them by full path, never from the working directory
|
|
1085
|
+
import subprocess as _subprocess
|
|
1086
|
+
import tempfile as _tempfile
|
|
1087
|
+
from _common import require_tool, STATE
|
|
1088
|
+
ffmpeg = require_tool("ffmpeg")
|
|
1089
|
+
wanted = requested_engine(engine)
|
|
1090
|
+
language = engine_language(language)
|
|
1091
|
+
model, parakeet_model = requested_model(model)
|
|
1092
|
+
tmpdir = _tempfile.mkdtemp(prefix="ffskill_asrw_")
|
|
1093
|
+
try:
|
|
1094
|
+
wav = os.path.join(tmpdir, "audio.wav")
|
|
1095
|
+
engine_wav(ffmpeg, video, audio_stream, wav)
|
|
1096
|
+
|
|
1097
|
+
tried: "List[Dict[str, str]]" = [] # engines found that gave no words, and why
|
|
1098
|
+
|
|
1099
|
+
def parakeet(engines: "List[str]", facts: Dict[str, Any]) -> Optional[Transcription]:
|
|
1100
|
+
done = _parakeet_attempt(engines, facts, wanted, language, wav, tmpdir, parakeet_model,
|
|
1101
|
+
_shutil, _subprocess, video, language_flag, need_words=True, tried=tried)
|
|
1102
|
+
if not done:
|
|
1103
|
+
return None
|
|
1104
|
+
run, model_name = done
|
|
1105
|
+
info(f"word timings from {run.engine} ({len(run.words)} words, model {model_name})")
|
|
1106
|
+
return run
|
|
1107
|
+
|
|
1108
|
+
# 0. Parakeet (English), when auto-routing picks it or it was asked for by name
|
|
1109
|
+
route = parakeet_route(wanted, language, wav, _shutil, _subprocess, parakeet_model, whisper_model=model)
|
|
1110
|
+
done = parakeet(route.first, route.facts)
|
|
1111
|
+
if done:
|
|
1112
|
+
return done
|
|
1113
|
+
tried.extend(_skipped_parakeet(route, language, language_flag))
|
|
1114
|
+
if wanted in PARAKEET_ENGINES:
|
|
1115
|
+
die_engine_failed(wanted, video, tried, _parakeet_available(wanted, _shutil, parakeet_model))
|
|
1116
|
+
facts = route.facts
|
|
1117
|
+
if route.first:
|
|
1118
|
+
facts = dict(facts, routing=facts["routing"] + ROUTING_PARAKEET_FAILED)
|
|
1119
|
+
lang = language or facts.get("detected_language")
|
|
1120
|
+
failed: Optional[str] = None # the first Whisper engine that ran and wrote no word-timing JSON
|
|
1121
|
+
# Undetected speech (Parakeet waits in route.last) was routed to Whisper because some
|
|
1122
|
+
# Whisper engine can take it, so each one gets its turn; otherwise the first that ran
|
|
1123
|
+
# and failed is the one the caller's refusal names, as before.
|
|
1124
|
+
every_whisper = bool(route.last)
|
|
1125
|
+
|
|
1126
|
+
# 1. whisper.cpp
|
|
1127
|
+
cli = _whisper_cpp_cli(_shutil) if wanted in ("auto", "whisper.cpp") else None
|
|
1128
|
+
if cli:
|
|
1129
|
+
model_path = _whisper_cpp_model(model)
|
|
1130
|
+
base = os.path.join(tmpdir, "out")
|
|
1131
|
+
# whisper.cpp's own default is -l en: without "auto" it decodes any speech as English
|
|
1132
|
+
cmd = [cli, "-m", model_path, "-f", wav, "--output-json-full", "-of", base, "-l", lang or "auto",
|
|
1133
|
+
*WHISPER_CPP_NO_CONTEXT] + (["--prompt", prompt] if prompt else [])
|
|
1134
|
+
proc = _asr_run(cmd, _subprocess, "whisper.cpp")
|
|
1135
|
+
if proc.returncode == 0 and os.path.exists(base + ".json"):
|
|
1136
|
+
words = _words_from_whisper_cpp_json(base + ".json")
|
|
1137
|
+
if not words and _whisper_heard_nothing(base + ".json", "transcription"):
|
|
1138
|
+
die_no_speech("whisper.cpp", video)
|
|
1139
|
+
info(f"word timings from whisper.cpp ({len(words)} words)")
|
|
1140
|
+
return Transcription(words=words, engine="whisper.cpp",
|
|
1141
|
+
facts=dict(facts, engine="whisper.cpp", model=model_path,
|
|
1142
|
+
language=lang or _whisper_json_language(base + ".json")))
|
|
1143
|
+
line = _failure_line(proc)
|
|
1144
|
+
info("whisper.cpp found but produced no word-timing JSON: " + line)
|
|
1145
|
+
tried.append(_failed("whisper.cpp", "found but produced no word-timing JSON: " + line))
|
|
1146
|
+
failed = "whisper.cpp"
|
|
1147
|
+
|
|
1148
|
+
# 2. faster-whisper
|
|
1149
|
+
try:
|
|
1150
|
+
if (failed and not every_whisper) or wanted not in ("auto", "faster-whisper"):
|
|
1151
|
+
raise ImportError
|
|
1152
|
+
from faster_whisper import WhisperModel # type: ignore
|
|
1153
|
+
import threading
|
|
1154
|
+
collected: list = []
|
|
1155
|
+
crashed: list = []
|
|
1156
|
+
heard: list = []
|
|
1157
|
+
spoke: list = [] # a segment with text: speech was heard, word timings or not
|
|
1158
|
+
|
|
1159
|
+
def work() -> None:
|
|
1160
|
+
try:
|
|
1161
|
+
m = WhisperModel(model, device="cpu", compute_type="int8")
|
|
1162
|
+
segments, decoded = m.transcribe(wav, language=lang, word_timestamps=True,
|
|
1163
|
+
**({"initial_prompt": prompt} if prompt else {}))
|
|
1164
|
+
heard.append(getattr(decoded, "language", None))
|
|
1165
|
+
for seg in segments:
|
|
1166
|
+
if str(getattr(seg, "text", "") or "").strip():
|
|
1167
|
+
spoke.append(True)
|
|
1168
|
+
for w in (getattr(seg, "words", None) or []):
|
|
1169
|
+
collected.append({"word": str(w.word).strip(),
|
|
1170
|
+
"start": float(w.start), "end": float(w.end)})
|
|
1171
|
+
except Exception as exc: # noqa: BLE001 -- a model that would not load or run
|
|
1172
|
+
crashed.append(exc)
|
|
1173
|
+
|
|
1174
|
+
t = threading.Thread(target=work, daemon=True)
|
|
1175
|
+
t.start()
|
|
1176
|
+
t.join(STATE.timeout or None)
|
|
1177
|
+
if t.is_alive():
|
|
1178
|
+
die(f"faster-whisper exceeded the {STATE.timeout:.0f} s time limit; raise "
|
|
1179
|
+
"--timeout for a long recording", code=124, kind="timeout")
|
|
1180
|
+
if crashed:
|
|
1181
|
+
line = str(crashed[0])[:200] or type(crashed[0]).__name__
|
|
1182
|
+
info("faster-whisper found but failed: " + line)
|
|
1183
|
+
tried.append(_failed("faster-whisper", "found but failed: " + line))
|
|
1184
|
+
failed = failed or "faster-whisper"
|
|
1185
|
+
else:
|
|
1186
|
+
if not collected and not spoke:
|
|
1187
|
+
die_no_speech("faster-whisper", video)
|
|
1188
|
+
info(f"word timings from faster-whisper ({len(collected)} words)")
|
|
1189
|
+
return Transcription(words=[w for w in collected if w["word"]], engine="faster-whisper",
|
|
1190
|
+
facts=dict(facts, engine="faster-whisper", model=model,
|
|
1191
|
+
language=lang or _heard_language(heard)))
|
|
1192
|
+
except ImportError:
|
|
1193
|
+
pass
|
|
1194
|
+
|
|
1195
|
+
# 3. openai-whisper CLI
|
|
1196
|
+
whisper_exe = _shutil.which("whisper") if (not failed or every_whisper) and wanted in ("auto", "openai-whisper") else None
|
|
1197
|
+
if whisper_exe:
|
|
1198
|
+
cmd = [whisper_exe, wav, "--model", model, "--word_timestamps", "True",
|
|
1199
|
+
"--output_format", "json", "--output_dir", tmpdir]
|
|
1200
|
+
if lang:
|
|
1201
|
+
cmd += ["--language", lang]
|
|
1202
|
+
if prompt:
|
|
1203
|
+
cmd += ["--initial_prompt", prompt]
|
|
1204
|
+
proc = _asr_run(cmd, _subprocess, "openai-whisper")
|
|
1205
|
+
doc = os.path.join(tmpdir, "audio.json")
|
|
1206
|
+
if proc.returncode == 0 and os.path.exists(doc):
|
|
1207
|
+
words = _words_from_openai_whisper_json(doc)
|
|
1208
|
+
if not words and _whisper_heard_nothing(doc, "segments"):
|
|
1209
|
+
die_no_speech("openai-whisper", video)
|
|
1210
|
+
info(f"word timings from openai-whisper ({len(words)} words)")
|
|
1211
|
+
return Transcription(words=words, engine="openai-whisper",
|
|
1212
|
+
facts=dict(facts, engine="openai-whisper", model=model,
|
|
1213
|
+
language=lang or _whisper_json_language(doc)))
|
|
1214
|
+
line = _failure_line(proc)
|
|
1215
|
+
info("openai-whisper found but produced no word-timing JSON: " + line)
|
|
1216
|
+
tried.append(_failed("openai-whisper", "found but produced no word-timing JSON: " + line))
|
|
1217
|
+
failed = failed or "openai-whisper"
|
|
1218
|
+
|
|
1219
|
+
# 4. Parakeet after all, when the language was never known and no Whisper engine gave words
|
|
1220
|
+
if route.last:
|
|
1221
|
+
info("no Whisper engine produced word timings; a multilingual Parakeet model may")
|
|
1222
|
+
done = parakeet(list(route.last), {"routing": ROUTING_LAST_RESORT})
|
|
1223
|
+
if done:
|
|
1224
|
+
return done
|
|
1225
|
+
if failed and not route.last:
|
|
1226
|
+
# it ran: the caller refuses naming it ("no word-level timings"), not "no engine".
|
|
1227
|
+
# After a last-resort Parakeet run, the refusal below names every engine tried.
|
|
1228
|
+
return Transcription(engine=failed, facts=facts)
|
|
1229
|
+
if wanted != "auto":
|
|
1230
|
+
die_engine_failed(wanted, video, tried, False)
|
|
1231
|
+
if tried:
|
|
1232
|
+
die_engines_failed(tried, video, "--filler --transcribe", "or pass --words with a transcript you already have.")
|
|
1233
|
+
die_no_engine("or pass --words with a transcript you already have.",
|
|
1234
|
+
flag="--filler --transcribe")
|
|
1235
|
+
return Transcription()
|
|
1236
|
+
finally:
|
|
1237
|
+
_shutil.rmtree(tmpdir, ignore_errors=True)
|