Dicklesworthstone/franken_whisper
About
Agent-first Rust ASR stack built on a real in-process pure-Rust Whisper engine (no FFI, no Python, no subprocess), with adaptive Bayesian routing across whisper.cpp/insanely-fast-whisper/diarization backends, real-time NDJSON streaming, DTW word timestamps, SQLite run history, and a conformance harness.
AI & Machine LearningWhat you can do
- tui - Enable the interactive TUI via ftui
- fj-oracle - Enable the FrankenJAX differential conformance oracle tests; not a production acceleration backend
- supports_diarization - false (TinyDiarize exists separately) - true (with HF token) - true
- supports_translation - true - true - false
Measured star growth
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- +5
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README.md
Originalfranken_whisper
Agent-first Rust ASR stack with a real in-process pure-Rust Whisper engine (no FFI, no Python, no subprocess), adaptive Bayesian backend routing, real-time NDJSON streaming (true-live mic/pipe streaming via fw robot listen; batch robot mode streams sequenced stage events), DTW word timestamps, and SQLite-backed run history. In current live-incumbent, same-invocation matched-greedy CPU comparisons, the native large-v3-turbo engine is 2.99× faster than whisper.cpp on a 124.5-second whole job; tiny.en is 1.52× faster on a 124.5-second transcribe-only workload and 1.51× faster on a 300-second transcribe-only workload. These ratios were measured with the int8 encoder, which is now opt-in (FW_ENC_ATTN_OUT_I8I32=1); the default f32 encoder is slower (turbo whole job 1.38× in a same-binary A/B).
Install in one line
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/franken_whisper/main/install.sh?$(date +%s)" | bash
SHA-256-verified prebuilt binaries for Linux (x86_64 / aarch64), macOS (Intel / Apple Silicon), and WSL — proxy-aware, airgap-capable (--offline), reversible (--uninstall). Windows users: grab windows_amd64.zip from the newest vX.Y.Z release on the releases page (model packages are published as releases too). All flags: Installation.
Agent quickstart
The release installs two equivalent binary names: fw is the concise
agent-facing name, and franken_whisper remains the descriptive name. Start
with the live triage payload instead of scraping help text:
fw --version
fw robot triage
fw capabilities --json
fw models --json
fw pull all --json
fw doctor --json
fw robot schema
fw robot listen --list-devices # live streaming capture check
fw robot run --input AUDIO --backend auto streams NDJSON. Robot syntax
errors are also emitted as one path-safe JSON object on stdout with exit code
2; runtime failures use one of the 13 exact FW-* codes published by
fw capabilities --json. Discovery, inference, and doctor commands do not
download models. fw pull all is the explicit in-binary network path for the
native defaults. It streams the 1,624,555,275-byte Whisper package and the
separately licensed 491,570,584-byte Sortformer package into the per-user cache,
then admits each only after its compiled size and SHA-256 trust roots pass. The
installer runs that command by default. A doctor ready result means both
packages passed static preflight; the payload still sets
operationally_verified: false until an actual transcription succeeds. The
model weights are never stored in Git. Whisper is distributed as the
whisper-large-v3-turbo-f16-v1 release artifact; its GGML f16 bytes are
identity-preserved from the pinned upstream revision and selected for the native
Rust loader and optimized FrankenTorch kernels. Sortformer is distributed as
sortformer-v2.1-f32-v1 beside the NVIDIA Open Model License, required notice,
and deterministic conversion receipt.
Release archives also carry THIRD_PARTY_NOTICES.md,
which records the licensed libc++ selection logic translated into safe Rust for
the pinned PyTorch CPU top-k parity contract.
The native engine is real, fast, and benchmarked at matched decode settings. The in-process pure-Rust Whisper engine (built on FrankenTorch kernels) is compared below against the actual
whisper-cliincumbent, side-by-side in one harness invocation with both engines using greedy decode. The whole-job turbo row's transcript is within WER 0.025090 of whisper.cpp's (7 edits over 279 words); the tiny.en reference conformance remains WER 0.0000. The full measurement record is in the performance ledger. These rows ran the int8 encoder, the default when they were measured. The default encoder is now f32 because int8 measured more word errors on a 389-utterance corpus (DISC-010);FW_ENC_ATTN_OUT_I8I32=1selects the encoder those rows measured. The default's incumbent ratios have not been re-certified.
Model / workload Mode Matched-greedy result large-v3-turbo, 124.5 s / 5 windows whole job, no timestamps 2.99× faster tiny.en, 124.5 s / 5 windows transcribe only, no timestamps 1.52× faster tiny.en, 300 s / 10 windows transcribe only, no timestamps 1.51× faster
Browser playground
The browser application in site/ runs the WebAssembly transcription
and speaker-attribution pipeline locally. Each run keeps the recording,
language, audio clean-up setting, and speaker names selected when it starts.
Selecting another file or editing those settings prepares the next run and
does not rename or relabel the current result.
Stop cancels a pending file read or stops processing once the engine has started. Text already received remains available as an incomplete Markdown or HTML download, with timestamps relative to the original recording. These exports contain only received transcript windows and omit speaker attribution; they do not claim the recording was fully processed. File-read and engine failures also preserve received text. If no new text arrived, an earlier result remains available.
Stopping an active engine requires Reload cached models before another run. Verified files stay in browser storage and are rechecked on reload; only missing files need downloading. A stopped file read leaves already-loaded models ready to use. Late messages from an old worker or run cannot overwrite a newer result.
The browser lifecycle regression suite runs the actual application and worker JavaScript with controlled DOM, worker, WASM, and loader boundaries:
node --experimental-vm-modules --test site/harness/app-lifecycle.test.mjs
It checks cancellation, partial exports, run ownership, recovery, and message ordering without downloading models or running inference. It does not replace real-browser rendering or model-runtime validation.
The Problem
Speech-to-text pipelines are fragmented. Existing stacks combine whisper.cpp for speed, insanely-fast-whisper for GPU batching, and Python diarization systems for speaker attribution. Each has its own CLI, output format, error handling, and deployment story. Orchestrating them from scripts means parsing inconsistent stdout, handling timeouts manually, killing zombie subprocesses, and losing all run history when something crashes.
Agent workflows make the problem worse. Modern LLM agents need structured, streaming, machine-readable output, not human-oriented terminal decorations that break the moment they touch jq, pipes, or SSH.
The Solution
franken_whisper is a single Rust binary that wraps every major Whisper backend behind a unified, agent-first interface — and ships its own engine:
- A real in-process Whisper engine, in pure Rust. ggml model parsing, log-mel frontend, encoder/decoder transformer inference on FrankenTorch CPU kernels, greedy decoding with whisper.cpp's full timestamp-rule suite, and cross-attention DTW word timestamps. No FFI, no Python, no subprocess — drop a ggml model file in place and transcribe.
- Rust-native Sortformer speaker diarization by default. The in-process fused model emits anonymous activity lanes and overlapping turns for up to four speakers, then projects that independent timeline onto Whisper segments. It remains development-uncertified: four lanes are a hard capacity boundary, not proof that a recording has no additional speakers. Known intervals and requests beyond that capacity use the bounded acoustic path, which is an available but uncertified fallback. Explicit ECAPA modes remain available for experiments with pinned speaker embeddings. None of these modes claims gender or biometric identity.
- Adaptive Bayesian backend routing. Each
autorequest runs a formal decision contract with an explicit loss matrix, per-backend Beta posteriors, Brier-scored calibration, and deterministic fallback when the model is mis-calibrated. - Real-time NDJSON streaming. Every pipeline stage emits sequenced, timestamped events on stable schema
v1.1.0(the 1.0.0 contract plus the additive listen-event family). No fragile regex; agents parse JSON. - Durable run history. Every transcription persists to SQLite with full event logs, replay envelopes, and JSONL export/import, even when the process crashes mid-run.
- Cooperative cancellation. Ctrl+C propagates through the pipeline via cancellation tokens. Owned subprocess trees are terminated and verified, transactions roll back via savepoints, and finalizers run within a bounded budget. Cleanup failures are reported instead of being relabeled as clean cancellation.
- No external decoder for common audio. MP3, AAC, FLAC, WAV, OGG,
Vorbis, and ALAC decode in-process via
symphonia.ffmpegis a fallback for video and exotic codecs, and is auto-provisioned on Linux x86_64 if missing. - Native engine rollout governance. In-process Rust replacements follow a 5-stage rollout (Shadow → Validated → Fallback → Primary → Sole). The shipped default is
Sole, so bridges run only after an explicit operator opt-out or rollout override. - TTY audio transport. Compressed audio (mu-law + zlib + base64) over PTY links with handshake, integrity hashes, deterministic retransmission, and an adaptive bitrate controller. A transcript-streaming control-frame vocabulary (protocol v2) is defined with library emitters and parsers; no CLI command yet streams a live transcription over the link (handshakes still negotiate v1).
- Word-level timestamps. First-class support via
whisper.cpp's word-timestamp pipeline, with the cancellation token threaded into the inner extraction loop.
Why franken_whisper?
| Feature | whisper.cpp | insanely-fast-whisper | whisper-diarization | franken_whisper |
|---|---|---|---|---|
| Streaming output | partial | — | — | sequenced NDJSON stage events |
| Machine-readable errors | exit code only | exceptions | exceptions | 13 exact FW-* error codes |
| Adaptive backend selection | — | — | — | Bayesian decision contract |
| Run persistence | — | — | — | SQLite + JSONL replay packs |
| Diarization | TinyDiarize hints | yes (HF token) | yes | native Sortformer default + Rust acoustic fallback + explicit ECAPA |
| Compute acceleration | CUDA / Metal | CUDA / MPS | CUDA | FrankenTorch CPU kernels + automatic Metal on macOS |
| Cancellation | SIGKILL |
KeyboardInterrupt |
SIGKILL |
cooperative CancellationToken |
| TTY audio relay | — | — | — | mulaw + zlib + base64 NDJSON |
| Native audio decode | WAV only | needs ffmpeg | needs ffmpeg | MP3 / AAC / FLAC / WAV / OGG / ALAC |
| Memory-safety boundary | C++ | Python | Python | safe Rust with explicitly scoped, audited native kernels |
Quick Example
# Native Whisper transcription plus native Sortformer diarization is the default.
# MP3 / FLAC / OGG / AAC are decoded in process; no ffmpeg is needed.
franken_whisper transcribe --input meeting.mp3 --json
# Skip diarization when only a transcript is needed.
franken_whisper transcribe --input meeting.mp3 --no-diarize --json
# Transcribe a video file. Audio extracted automatically via ffmpeg fallback.
franken_whisper transcribe --input presentation.mp4 --json
# Stream real-time pipeline events for agents
franken_whisper robot run --input meeting.mp3 --backend auto
# Speculative streaming: fast partial transcripts with quality-model corrections
franken_whisper robot run --input meeting.mp3 --speculative \
--fast-model tiny.en --quality-model large-v3
# Select the built-in acoustic fallback explicitly (no Python or HF token)
franken_whisper transcribe --input meeting.mp3 \
--diarization-engine acoustic --json
# Explicit ECAPA identity fused with bounded acoustic channel evidence
# (requires the pinned local ECAPA package, but no Python or HF token)
franken_whisper transcribe --input meeting.mp3 \
--diarization-engine ecapa-fused --json
# TinyDiarize: speaker-turn hints from a TinyDiarize-trained model (no HF token needed)
franken_whisper transcribe --input meeting.mp3 --model ./ggml-small.en-tdrz.bin --tiny-diarize --json
# Discover available backends and their capabilities
franken_whisper robot backends
# System health check (backends, ffmpeg, database, resources)
franken_whisper robot health
# Query run history
franken_whisper runs --limit 10 --format json
# Export run history to a portable JSONL snapshot (full or incremental)
franken_whisper sync export-jsonl --output ./snapshot
# Compressed audio over a text-only channel (PTY, SSH, serial)
franken_whisper tty-audio encode --input audio.wav > frames.ndjson
cat frames.ndjson | franken_whisper tty-audio decode --output restored.wav
Design Philosophy
Agent-First, Human-Optional
The primary interface is robot. Every command in robot mode emits sequenced, timestamped NDJSON on stdout with schema version 1.1.0 (bumped additively from 1.0.0 when the listen event family landed; batch events are unchanged). Human-friendly output (transcribe without --json) is the exception. Robot mode never mixes decorative stderr into the data stream; structured run_error envelopes replace human prose even for argument-parsing failures.
Deterministic by Default
Given identical inputs and parameters, franken_whisper produces identical outputs. The TTY retransmit loop, replay envelopes, replay packs, and conformance harness all enforce determinism. Random elements (UUIDs, wall-clock timestamps) are quarantined to metadata fields; they never enter computational output.
Fail Loud, Recover Gracefully
Every error has a structured code (FW-IO, FW-CMD-TIMEOUT, FW-BACKEND-UNAVAILABLE, FW-STAGE-TIMEOUT, …) and propagates through the NDJSON event stream. Cancellation tokens let in-flight work checkpoint and clean up instead of dying mid-write. In-progress SQLite transactions roll back via savepoints; owned subprocess trees are terminated and checked; temporary resources are handled by registered finalizers under a bounded budget.
Composition Over Configuration
The pipeline is composed dynamically per request. The 10 canonical stages (Ingest, Normalize, VAD, Source Separate, Backend, Accelerate, Align, Punctuate, Diarize, Persist) are skipped when unnecessary, budgeted independently, and profiled automatically. The PipelineBuilder validates ordering at build time; runtime never hits "stage X requires stage Y" errors.
Audited Unsafe Boundaries
The crate uses #![deny(unsafe_code)]. Native-engine SIMD and
fully-overwritten-buffer kernels opt in at explicit sites with local safety
arguments; unannotated unsafe code is rejected. The performance rationale and
measurements are retained in
docs/NEGATIVE_EVIDENCE.md.
No External Decoder for Common Audio
franken_whisper decodes MP3, AAC, FLAC, WAV, OGG (Vorbis), and ALAC entirely in-process via symphonia; no ffmpeg, no Python, no PATH lookup. ffmpeg is only invoked as a fallback for video files, exotic codecs (AC3, DTS, Opus-in-MKV), and live microphone capture. When ffmpeg is needed and missing on Linux x86_64, it is downloaded once into the per-user state directory.
Adaptive Controllers With Conservative Fallbacks
Every adaptive controller in the system (the backend router, the speculative window controller, the budget tuner, the TTY adaptive bitrate controller, the correction tracker) ships with an explicit alien-artifact engineering contract: state space, action space, loss matrix, posterior, calibration metric, deterministic fallback, and an evidence ledger. When models drift, the system falls back to a deterministic policy rather than confidently making bad decisions.
The Whisper Ecosystem Landscape
+--------------------------------------------------------------+
| INFERENCE ENGINES (run the model) |
| |
| whisper.cpp (C++, CPU/Metal/CUDA) |
| faster-whisper (Python/CTranslate2) |
| OpenAI Whisper (Python/PyTorch) |
+--------------------------------------------------------------+
|
+------------------------------v-------------------------------+
| ENHANCED PIPELINES (add features on top) |
| |
| WhisperX (faster-whisper + wav2vec2 + pyannote)|
| whisper-diarization (Whisper + Demucs + NeMo TitaNet) |
| insanely-fast-whisper (HuggingFace Transformers, max GPU) |
| whisper-timestamped (DTW word timestamps) |
+--------------------------------------------------------------+
|
+------------------------------v-------------------------------+
| ORCHESTRATION (manage engines/pipelines) |
| |
| > franken_whisper < (Rust, Bayesian routing, |
| 10-stage pipeline, conformance |
| gating, native engine rollout, |
| evidence-based decisions) |
+--------------------------------------------------------------+
Most tools occupy one level. franken_whisper is the orchestration layer: it wraps inference engines and enhanced pipelines behind a unified interface, then adds capabilities none of them provide individually.
How franken_whisper Compares
Orchestration & Architecture
| Capability | whisper.cpp | faster-whisper | WhisperX | WhisperLive | WhisperS2T | franken_whisper |
|---|---|---|---|---|---|---|
| Language | C++ | Python | Python | Python | Python | Rust |
| Multi-backend | — | — | — | 3 | 4 | 3 bridge families + native counterparts |
| Backend selection | — | — | — | manual | manual | Bayesian decision contract |
| Pipeline stages | monolithic | monolithic | 3 | monolithic | monolithic | 10 composable stages |
| Per-stage budgets | — | — | — | — | — | independent timeouts + auto profiling |
| Speculative streaming | — | — | — | single-model | — | dual-model fast+quality with retraction |
| Conformance validation | — | — | — | — | — | cross-engine, 50 ms tolerance, drift detection |
| Native rollout governance | — | — | — | — | — | 5-stage Shadow → Sole with conformance gates |
| Memory-safety boundary | C++ | Python GC | Python GC | Python GC | Python GC | safe Rust with explicitly scoped, audited native kernels |
Persistence & Observability
| Capability | whisper.cpp | faster-whisper | WhisperX | WhisperLive | franken_whisper |
|---|---|---|---|---|---|
| Run history | — | — | — | — | SQLite WAL + JSONL export/import |
| Decision audit trail | — | — | — | — | 200-entry evidence ledger |
| Replay envelopes | — | — | — | — | SHA-256 content + output hashes |
| Replay packs | — | — | — | — | 4-artifact deterministic reproducibility bundle |
| Structured errors | exit code | exceptions | exceptions | — | 13 exact terminal FW-* codes |
| NDJSON streaming | partial | — | — | WebSocket | sequenced stage events |
| Cancellation | SIGKILL |
KeyboardInterrupt |
— | — | cooperative CancellationToken |
| Resource cleanup | none guaranteed | GC | GC | GC | RAII + bounded LIFO finalizers |
| Latency profiling | — | — | — | — | per-stage utilization with tuning recommendations |
Audio & Format Support
| Capability | whisper.cpp | faster-whisper | WhisperX | franken_whisper |
|---|---|---|---|---|
| Native audio decode | WAV only | needs ffmpeg | needs ffmpeg | MP3 / AAC / FLAC / WAV / OGG / Vorbis / ALAC via symphonia |
| ffmpeg required? | for non-WAV | always | always | fallback only (video + exotic codecs + mic) |
| Video audio extraction | — | — | — | automatic via -vn |
| TTY audio transport | — | — | — | mulaw + zlib + base64 NDJSON |
| Microphone capture | — | — | — | cpal (CoreAudio/ALSA/WASAPI) with ffmpeg fallback |
| Auto-provisioned ffmpeg | — | — | — | downloads static binary if missing (Linux x86_64) |
Commercial API Comparison
| Capability | Groq Whisper API | Deepgram Nova-3 | AssemblyAI | franken_whisper |
|---|---|---|---|---|
| Runs locally | no | no | no | yes |
| Open source | no | no | no | yes (MIT + rider) |
| Data leaves machine | yes | yes | yes | never by core; external tools are explicit and operator-controlled |
| Billing model | usage-priced | usage-priced | usage-priced | local compute only |
| Inference speed | very fast | fast | moderate | depends on selected backend |
| Multi-model routing | — | — | — | Bayesian adaptive |
| Diarization | limited | yes | yes | native Sortformer default, acoustic fallback, explicit ECAPA/external routes |
| Custom pipeline stages | — | — | — | 10 composable stages |
Installation
Quick Install (Pre-built Binary)
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/franken_whisper/main/install.sh?$(date +%s)" | bash
The installer downloads the release asset for the detected platform, verifies
its SHA-256 checksum, validates the staged binary's self-reported version, and
installs both fw and franken_whisper to ~/.local/bin. It then downloads
and verifies the pinned native Whisper and Sortformer packages (about 2.12 GB
combined). Interactive installs show a Y/n prompt with Yes as the default;
quiet and headless installs provision automatically. --no-pull is the explicit
opt-out. An offline install accepts a preseeded verified cache or requires
--no-pull; it never contacts the network. Under sudo ... --system, model
provisioning drops back to the validated invoking user so the packages do not
land in root's private cache. A release download failure never silently falls
back to a source build; use --from-source explicitly. Before a fresh model
pull, the installer requires at least 2.4 GB free on the cache filesystem; an
already-complete cache is admitted after both compiled trust roots are verified.
Options:
| Flag | Purpose |
|---|---|
--system |
Install to /usr/local/bin instead of ~/.local/bin |
--easy-mode |
Auto-update shell PATH and rc files |
--verify |
Verify both binary names, agent schemas, and both native model packages |
--no-pull |
Skip automatic native Whisper and Sortformer model provisioning |
--version vX.Y.Z |
Pin to a specific release |
--force |
Reinstall even if the same version is present |
--offline TARBALL |
Airgap install from a local archive (verifies sibling .sha256) |
--from-source |
Build from a source clone (clones sibling FrankenSuite deps) |
--quiet / --no-gum |
Script-friendly / plain-ANSI output |
--no-verify |
Skip checksum verification (testing only) |
--uninstall |
Remove both binary names and installer-added PATH lines |
HTTP_PROXY/HTTPS_PROXY are honored on every download.
FW_INSTALL_PROMPT_TIMEOUT changes the interactive prompt timeout from 120
seconds, and FRANKEN_WHISPER_MODEL_DIR selects an absolute cache root shared
by fw pull all, model discovery, and the installer. Prebuilt targets are
linux_amd64, linux_arm64, darwin_amd64, darwin_arm64, and
windows_amd64 (zip; manual install on native Windows).
Homebrew
brew install dicklesworthstone/tap/franken-whisper
fw pull all
Homebrew installs both binary names but does not bundle model weights. The second command downloads the same SHA-256-pinned native Whisper and Sortformer packages used by the installer. Model inference remains offline after that one-time provisioning step.
From Source
git clone https://github.com/Dicklesworthstone/franken_whisper.git
cd franken_whisper
# Provision the exact clean sibling commits used by release builds.
# Existing mismatched sibling directories are never modified.
scripts/prepare_release_siblings.sh
# Stable SIMD, using the pinned sibling checkouts
cargo build --locked --release --bin fw
# Optional std::simd implementation, using the repository's pinned nightly
cargo "+$(cat scripts/nightly-toolchain)" build --locked --release --bin fw --features nightly-simd
# with TUI support
cargo build --release --features tui
The native engine always uses FrankenTorch CPU kernels. On macOS, large eligible
matrix operations automatically use the target-gated Metal kernel when a Metal
device is available; FRANKEN_WHISPER_GPU=0 forces CPU execution. Audio preprocessing, the mel FFT and projection, and
layer normalization use eight-lane wide vectors by default. The optional
nightly-simd feature selects std::simd for those kernels. The tui feature
enables the terminal UI and fj-oracle enables the FrankenJAX test oracle. The release
profile uses opt-level = 3, full LTO, one codegen unit, panic = "unwind", and
stripped symbols.
Prerequisites
- Rust 1.95.0 or later for the default source build. The checkout pins 1.95.0 for the CLI, Apple bindings, and serial WebAssembly builds. The optional
nightly-simdbackend and threaded WebAssembly build use the dated nightly inscripts/nightly-toolchain. The threaded build also needs that toolchain’srust-srccomponent. - ALSA on Linux. Version 0.10.0 adds native microphone capture through CPAL. Both Linux executables require the ALSA runtime library
libasound.so.2at startup, including for file transcription. Install your distribution's ALSA runtime package before using a prebuilt release; source builds also require the ALSA development headers andpkg-config. The installer validates both executable names before replacing an existing installation and reports this prerequisite if executable validation fails. - ffmpeg (optional): needed for video files, exotic codecs
symphoniacannot decode, batchtranscribe --mic, and as the fallback live-capture backend when cpal cannot open the device. On Linux x86_64 it is auto-provisioned on first use unlessFRANKEN_WHISPER_AUTO_PROVISION_FFMPEG=0. - The two native default model packages. The installer provisions them, or run
fw pull all. Native Whisper uses the pinnedwhisper-large-v3-turbo-f16-v1GGML f16 release; native diarization uses the pinned four-lanesortformer-v2.1-f32-v1package. Both are hash-checked against compiled trust roots. No external backend binary is required for the default pipeline. For an operator-selected--modelpath or short name, native discovery and loading also accept GGML f32, f16, Q4_0, Q4_1, Q8_0, Q5_0, Q5_1, and Q2_K–Q6_K.binfiles, including versioned quantization headers such as2007for Q8_0. On desktop, quantized weights can expand to f32 for inference; file-format support is not a speed, memory, or transcript-quality guarantee. The authenticated default stays f16 (seedocs/native_engine_contract.mdfor the format contract anddocs/PERF_LEDGER.mdfor measured performance). - The pinned ECAPA package (only for
ecapaorecapa-fused):ecapa_tdnn_voxceleb.safetensors, SHA-2569276a840c52cdd2e9afb73cd87a38e15749e12bf494d3ca47b5bc162f237cbcc, under$FRANKEN_WHISPER_MODEL_DIR/aux/or~/.cache/franken_whisper/models/aux/. The converted artifact is not published, soscripts/fetch_aux_models.shprints the pinned conversion instructions and expected digest instead of downloading it. - Bridge backend binaries (optional explicit alternates):
whisper-cli(from whisper.cpp); override viaFRANKEN_WHISPER_WHISPER_CPP_BINinsanely-fast-whisper(Python entry point); override viaFRANKEN_WHISPER_INSANELY_FAST_BINpython3withpyannote.audioinstalled (only for the optional external diarization backend); override viaFRANKEN_WHISPER_PYTHON_BIN
- HuggingFace token (external diarization only):
--hf-token,FRANKEN_WHISPER_HF_TOKEN, orHF_TOKEN. Native acoustic and ECAPA diarization need neither Python nor a token; the ECAPA modes do require the local package above.
Sibling Crate Dependencies
franken_whisper integrates several crates from the FrankenSuite ecosystem.
Published packages resolve them from crates.io. A source checkout uses
versioned path dependencies for the exact local FrankenSQLite, FrankenTorch,
FrankenTTS, optional FrankenTUI, and optional FrankenJAX sources;
scripts/prepare_release_siblings.sh stages
the release-pinned sibling commits without modifying an existing mismatched
checkout.
| Crate | Source | Purpose |
|---|---|---|
asupersync |
crates.io =0.7.0 |
Cancel-correct orchestration primitives |
franken-kernel |
crates.io =0.7.0 |
Budget, TraceId, time utilities |
franken-evidence |
crates.io =0.7.0 |
Evidence ledger primitives |
franken-decision |
crates.io =0.7.0 |
Decision contract framework |
fsqlite / fsqlite-types |
crates.io ^0.5.1; source path ../frankensqlite |
Pure-Rust SQLite persistence and value types |
ft-core / ft-kernel-cpu |
crates.io 0.1.0; source path ../frankentorch |
Required tensor types and native Whisper CPU kernels |
ft-kernel-metal (macOS) |
crates.io 0.1.0; source path ../frankentorch |
Automatic Metal compute for eligible large operations |
ftts-kernels |
crates.io 0.1; source path ../frankentts |
Required FastEnhancer-S denoising kernels |
ftui (feature: tui) |
crates.io 0.7.0; source path ../frankentui |
Optional terminal UI framework |
fj-lax / fj-core (feature: fj-oracle) |
source path ../frankenjax |
Independent differential oracle for native-kernel conformance tests (seeded, 1e-4 tolerance; see docs/conformance-contract.md) |
Quick Start
1. Basic Transcription
# one "[HH:MM:SS.mmm --> HH:MM:SS.mmm] [SPEAKER_00] text" line per segment
# (plain text with --no-timestamps)
franken_whisper transcribe --input audio.mp3
# full JSON report (segments + timing + backend identity + replay envelope)
franken_whisper transcribe --input audio.mp3 --json
# explicit backend
franken_whisper transcribe --input audio.mp3 --backend whisper-cpp --json
# language hint
franken_whisper transcribe --input audio.mp3 --language ja --json
2. Robot Mode (Agent Integration)
franken_whisper robot run --input audio.mp3 --backend auto
Output (one JSON object per line, schema 1.1.0):
{"event":"run_start","schema_version":"1.1.0","request":{"input":"audio.mp3","backend":"auto"}}
{"event":"stage","schema_version":"1.1.0","run_id":"...","seq":1,"ts":"2026-07-28T00:00:00Z","stage":"ingest","code":"ingest.start","message":"materializing input","payload":{}}
{"event":"stage","schema_version":"1.1.0","run_id":"...","seq":2,"ts":"2026-07-28T00:00:01Z","stage":"normalize","code":"normalize.ok","message":"audio normalized","payload":{}}
{"event":"stage","schema_version":"1.1.0","run_id":"...","seq":3,"ts":"2026-07-28T00:00:02Z","stage":"backend","code":"backend.routing.decision_contract","message":"routing decision","payload":{"chosen_action":"try_whisper_cpp"}}
{"event":"run_complete","schema_version":"1.1.0","run_id":"...","trace_id":"...","started_at":"2026-07-28T00:00:00Z","finished_at":"2026-07-28T00:00:03Z","backend":"whisper_cpp","language":"en","transcript":"Hello world...","segments":[],"acceleration":null,"diarization":null,"warnings":[],"evidence":[]}
3. Speaker Diarization
franken_whisper transcribe --input meeting.mp3 --json
The default path runs the native four-lane Sortformer package and returns
anonymous SPEAKER_NN turns. It is fast, in-process, and development-
uncertified: a lane count is not a calibrated estimate of the true number of
speakers, and recordings with more than four speakers exceed the model's
capacity. Use --no-diarize for transcription only.
Turn evidence is fused into the transcript (projection-fusion-v1): every
segment that overlaps a labeled turn gets that speaker, segments in short turn
gaps take the nearest labeled turn within 2 seconds, and word-level speaker
changes snap to the nearest sentence-final punctuation within four words so
turn-initial words land on the speaker who says them. The result also carries
diarization.speaker_segments, a merged view of consecutive same-speaker runs
with joined text and duration-weighted turn confidence, so consumers do not
rebuild the turn/segment join. Untimed segments and audio beyond the gap bound
stay speaker: null. Requests with known
intervals or count constraints beyond the four-lane boundary fall back to the
native acoustic engine under the default acoustic fallback policy.
On this project's Apple M4 Pro development host, a repeated-public-audio ten-minute probe took 35.86 seconds end to end for Sortformer (29.91 seconds of model inference, inference RTF 0.04984). That scales to about 3.6 minutes of diarization per audio hour when one model load is included. The matched native Whisper probe took about 9.0 minutes per audio hour, for roughly 12.6 minutes combined. This is a throughput orientation row, not a natural-conversation accuracy result or a promise for other hardware.
Omitting all count options means inference intent. Acoustic and ECAPA reports
contain a versioned speaker_count.estimate object and retain explicit
uncalibrated/unresolved mass. A soft preference can be added with
--speaker-count-range 2..5 or
--speaker-count-prior 2=0.25,3=0.75. Use
--speaker-count-hard 3 only when the caller intentionally wants a hard search
constraint; it never fabricates occupancy or removes UNKNOWN. Soft count
options are supported by the native acoustic, ecapa, and ecapa-fused
engines; external backends reject them rather than silently hardening them.
Known intervals can enroll an opaque speaker reference without retaining the hint document's source path or raw source bytes:
{"schema_version":"speaker-hints-v1","known_intervals":[
{"speaker_ref":"caller_a","start_ms":1200,"end_ms":5400,
"confidence":0.98,"policy":"hard_must_link"}
]}
Pass it with --speaker-hints /private/path/hints.json. Hard intervals are
immutable must-links; soft enrollment can be rejected when acoustically
contradictory. Parsed hint fields are part of the typed request and are
persisted with the run unless --no-persist is used. Labels remain within-run
references, not biometric identities.
When known_intervals is nonempty, execution rejects both an external engine
and --diarization-fallback external: external labels cannot enforce immutable
hint identities, so this combination fails closed instead of discarding them.
Evaluation uses the frozen diarization-scorer-v5 contract. In addition to
DER/JER, it reports typed speaker-count evidence with explicit authority,
unresolved and zero-probability outcomes, effective occupancy,
dominant/reference collapse, phantom labels, and optional transcript-free
aligned-word WDER. Fixed-safe results are explicitly uncalibrated, and current
probabilistic results are development-uncertified; neither is described as a
calibrated posterior unless a future certified authority says so.
This prevents a nominally correct label count from hiding a run where one
label received nearly all speech. Public ablations aggregate these metrics by
reference count and duration; diarization-eval emits the same evidence only
as a path-free, aggregate-only confidential result. Aligned-word inputs retain
opaque non-lexical IDs and timing/speaker annotations, never token text. See
docs/acoustic_diarization_contract.md
for the versioned schemas and fail-closed policy.
The multiscale acoustic sidecar is exposed only through the separate public
evaluation command diarization-corpus sidecar-study, using
public-diarization-acoustic-sidecar-study-v6 and its v8 runner. It is not a
transcribe option: normal segmentation, clustering, robot output,
persistence, and the normal transcription route are not mutated by the
sidecar study. This is a routing guarantee, not a claim that current reports
are byte-identical to historical acoustic-v2 reports. The command runs a
frozen full-v2 baseline plus twelve ordered sidecar lanes, retains only
aggregate path-free and transcript-free evidence, and creates both outputs in
external directories on Linux, Android, and Apple platforms. Other targets
return public_corpus.output_platform before corpus materialization. On a
successful supported-platform run, stdout bytes exactly match the retained
study evidence file.
The frozen protocol uses oracle VAD speech regions while leaving speaker count in inferred mode. Its DER/JER and speaker-count results therefore measure segmentation and clustering conditioned on reference speech activity; they are not end-to-end VAD-accuracy evidence.
Development fits separate adjacent-boundary and lagged different-speaker
calibrations. The boundary-fusion-v2 configuration hash binds the selected change-detector
mode as well as the sidecar/calibration and selector constants, so materially
different fallback and peak-selection behavior cannot share an identity.
Conditional diagnostics begin with one lane-independent universe
of uniquely reference-labeled 25/50/100/200-frame-lag pairs. Each recording
retains at most 4,096 members by a score-, label-, and availability-independent
selection-key-v3 SHA-256 over normalized clipped PCM identity, frame indices,
and lag. The pair scorer is separately protocol-bound and is not part of that
key. A reference-labeled selected-sequence-v2 digest binds every retained key,
frame pair, lag, and same/different label and must match across evaluated lanes. Evidence
retains aggregate selected/scored same/different counts, overall and per-class
score coverage, recording support, linked reliability moments, and a 100-bin
score-order histogram; it retains no selected keys, labels, frame indices, or
probabilities. The producer bins exact clamped-f32 scores. The verifier checks
linked counts, class moments, and first/second-moment feasibility against each
bin's exact clamped-f32 support, which rejects direct aggregate
contradictions. Because the individual selected probabilities are
intentionally omitted, those sufficient statistics cannot establish every
member's bin assignment or replay score ordering; they are aggregate internal-
consistency evidence, not member-level provenance. Promotion requires at least
0.25 total and per-class score coverage, 100 scored pairs and five recordings in each class, pair
discrimination/calibration bounds, and substantial owner-specific same-speaker
auxiliary-dominance evidence wherever Voice and that owner coexist.
A completed study is not an automatic promotion. The artifact records whether
each candidate was rejected, advanced for held-out certification, or adopted,
and no lane has such authority until a real public-corpus result establishes
it. When any lane is accuracy-eligible, development ranks one winner first; if
that lane fails an operational bound, no lower-ranked lane advances. RTF and
RSS are host-dependent observations against the live unfused baseline in the
same invocation; passing them is not a speed or memory-win claim. The
deterministic accuracy projection removes performance-only failures and
NotSelectedByRanking, zeros timing/RSS, allocator capacities, and target-sized
retained-state bytes, and clears certification's locked development result hash
while retaining its accuracy hash before recomputing selection/adoption.
The verifier recomputes aggregate metrics, fine/coarse score-distribution consistency, coverages, gates, ranking, dispositions, and hashes. It validates calibration fingerprints and fit-count provenance, but aggregate evidence cannot prove each omitted probability's histogram membership, refit calibrations, regenerate selected pairs, replay audio-derived metrics, or reproduce bootstrap intervals; verification proves aggregate internal consistency, not member-level provenance or corpus replay. Paired intervals use a fixed versioned lane/split seed and a cancellable SplitMix64 stream. Reference annotations use a monotonic overlap-aware sweep instead of rescanning all turns every 10 ms.
The library's adversarial_corpus module supplies a Rust-native, public-safe
accuracy harness without checking audio fixtures into the repository. It
generates transcript-free harmonic calls with deterministic speaker, turn,
overlap, pitch, playback, and stereo regimes, then applies bounded gain,
muffling, band-limit, resampling, quantization, clipping, noise, reverb,
interruption, silence, channel-shift, playback, channel-swap, and overlap
recipes. Retained repro seeds contain parameters, stable classifications, and
content hashes—not samples, paths, transcripts, embeddings, or real speaker
identifiers. Plans declare synthetic source authority or bind a hash of an
external public-license acknowledgement. The same API attributes the first
divergent pipeline stage and delta-minimizes a failing transform sequence while
preserving its exact classification.
For development-only differential diagnosis, diarization-oracle can compare
the native stage document with an operator-installed pyannote, NeMo spectral,
VBx, EEND, DiaPer, or Sortformer adapter. Start with
franken_whisper diarization-oracle registry, then run the selected adapter
against absolute external audio and stage-document paths. Comparisons are
separate for speech activity, opaque word timing, change boundaries,
label-permutation-invariant clusters, overlap, and final projection. Missing
or failing tools produce a path-free skipped report; disagreements are
diagnostic only and can never certify that the native path is wrong. External
tools remain optional subprocesses with no normal runtime or Cargo dependency.
The Sortformer entry is narrower than the generic adapters: it pins
nvidia/diar_streaming_sortformer_4spk-v2.1
at immutable revision fafaab5faa1617a0ca52d38dd3dc4bd636800d3d, requires
canonical mono 16 kHz PCM16 WAV input, and freezes the documented high-latency
340/40/40/300/188 streaming-cache profile plus untuned 0.5/0.5 post-processing.
The 300 value is the configured cache-update period. Pinned NeMo only warns
when it is shorter than the 340-frame chunk; its FIFO update computes
min(max(configured, chunk - fifo_capacity + current_fifo), current_fifo + chunk).
That moves 300 frames on the first full chunk and 340 in the full-chunk steady
state, while tail chunks remain state-dependent.
The accepted v2 operator adapter fails closed unless installed package metadata
binds NeMo to commit 40ace43c7cf151af78dc22027c02feeca7e06b6a and the frozen
Python/PyTorch/torchaudio/NumPy versions. It derives BLAS and CPU-feature facts
from the installed runtimes and asserts the raw streaming profile plus the
derived FIFO-pop schedule after NeMo validates it; those facts may not be
supplied by literals alone.
The operator-installed adapter remains an explicit trust boundary. The host
hashes its resolved path before execution, rejects an initial mismatch against
the compiled SHA-256 pin, and rechecks the path after the version probe and
oracle run before validating schema and attestations. This catches ordinary
drift, but a swap-and-restore inside the remaining hash-to-exec window is still
an open oracle-authority gate. Activation-seam capture therefore uses a
separately reviewed exporter and digest; the final-output adapter pin does not
authorize intermediate values.
The first admitted activation pack is synthetic-only: four deterministic
non-human frontend fixtures, 46 F32/I64 tensors, and 44 stage-level replay
observations that are byte-exact across five runs requested in each configured
one-thread and eight-thread regime.
Rust authenticates the separate receipt/package roots and runs the complete f32
graph in process through L8 anonymous speaker turns. The same engine powers the
default pipeline and remains available through a focused diagnostic command:
fw pull sortformer --json
fw sortformer-diarize --input call.m4a
# Optional caller assertions/suggestions for anonymous-lane mapping:
fw sortformer-diarize --input call.m4a --speaker-hints /private/hints.json
The bounded hint file can be a bare interval array or this versioned form:
{
"schema_version": "speaker-hints-v1",
"known_intervals": [
{
"speaker_ref": "speaker-a",
"start_ms": 1200,
"end_ms": 4800,
"confidence": 1.0,
"policy": "hard_must_link",
"provenance": "caller-context"
}
]
}
fw pull is restartable across verified per-file cache hits, cooperative under
Ctrl+C, and never emits cache paths in JSON mode. The installer invokes
fw pull all by default; inference stays offline. Behind a TLS-inspecting
proxy, point FRANKEN_WHISPER_CA_BUNDLE (or the conventional SSL_CERT_FILE)
at a PEM bundle to add its roots; every artifact stays pinned to its SHA-256
digest and size, so an added root cannot change which bytes are accepted. An
unusable FRANKEN_WHISPER_CA_BUNDLE is an error; an unusable SSL_CERT_FILE
is logged and ignored. The focused diarization command
rehashes the cached package and conversion receipt, runs completely offline,
and emits one path-free sortformer-diarization-v1 object with turns, inferred
active-lane count, timing, and the candid capacity status
four_lane_capped_output_true_speaker_count_unknown; an inferred lane count is
never presented as proof that the recording contains no additional speakers.
Hard known intervals may bind a
unique anonymous lane to a caller-provided opaque reference; contradictory or
ambiguous hard evidence fails closed. Soft intervals remain non-authoritative
suggestions, every non-hard-bound lane remains anonymous, and inference never
mutates model weights. --diarization-engine auto now selects this native
runtime under the owner-directed default. The model registry and focused
diagnostic command report development_uncertified. The
authenticated NVIDIA-recommended streaming
truth pack covers four public fixtures and 4,540 L1-L8 tensors. On its complete
102-second three-speaker row, native L5 probabilities stayed within the frozen
envelope (maximum absolute difference 1.072883606e-6, relative L2
8.214150678e-8), and L7 activity plus all 16 L8 turns were byte-exact. The
historical four one-frame boundary differences came from comparing the old
archive-default streaming geometry with the recommended profile, not from a
same-profile Rust/source loss. Same-host L6 tied-selection parity is resolved
by the pinned safe libc++ nth_element translation. This is parity evidence,
not broad corpus accuracy, greater-than-four-speaker capacity, cross-platform,
or broad accuracy certification evidence; the registry and focused diagnostic
command therefore report development_uncertified. The converted f32 package is
491,570,584 bytes
(SHA-256 487fa30cb0aa9799c77bd9985e6787962c3991fab8d4d576a4f1221d45298f6a).
Its distribution policy is github_release_with_license_and_notice: weights
remain outside Git and are attached to the dedicated model release with the
license, notice, and authenticated conversion receipt.
The default cache is ~/.cache/franken_whisper/models; an override through
FRANKEN_WHISPER_MODEL_DIR must be absolute. Partially downloaded files retain
hidden staging names for diagnosis and are never admitted as model artifacts.
Speaker-hints JSON must be a bounded regular non-symlink file.
Full proof details and current performance/resource rows are in
SORTFORMER_RUST_PORT.md.
The external Sortformer adapter's version probe must bind the frozen contract
hash, independently verify that
the 471,367,680-byte local artifact hashes to the pinned Hugging Face LFS
SHA-256, and retain a path-free runtime fingerprint. The frozen evaluation row
is CPU-only float32 with autocast and quantization disabled, deterministic
algorithms enabled, zero data-loader workers, eight PyTorch intra-op threads,
and one inter-op thread. Output labels are arrival-ordered speaker_0 through
speaker_3; a reference containing five or more speakers is retained as an
explicit model-capacity skip rather than being dropped or forced into four
labels. The external Python/NeMo oracle remains operator-installed. This is
separate from the native Rust runtime's explicit fw pull sortformer cache.
The full adapter protocol, environment overrides, privacy rules, and authority
boundary are in the
acoustic diarization contract.
ReDimNet2-B2 is a separate compact speaker-embedding experiment, not an
end-to-end diarizer and not an auto route. The offline
scripts/export_redimnet2.py command accepts the pinned upstream checkpoint,
the exact v1.0.0 source tree, and a new output directory:
python3 scripts/export_redimnet2.py INPUT.pt SOURCE_ROOT OUTPUT_DIR
All three arguments must resolve outside this checkout, OUTPUT_DIR must not
exist, and the command performs no download. The exporter installs a Python
audit hook that denies socket and child-process events for the full conversion.
Its exporter and conversion-receipt schemas are v3; the synthetic truth tensor
contract remains v1. It requires Python 3.12.12 with
torch/torchaudio 2.7.1, NumPy 2.2.6, SciPy 1.15.3, and safetensors 0.5.3. It
hash-binds the 15,897,450-byte upstream checkpoint and 14 source files, rejects
every unmanifested regular file, symlink, bytecode file, or native extension in
the executable redimnet2 package tree, disables bytecode writes, and refuses
preloaded ReDimNet modules. The receipt binds the interpreter binary, Python
implementation/cache tag, distribution RECORD/METADATA digests, and a
path-free commitment after verifying every hashed RECORD entry's bytes. It also
binds the Torch Git/build identity and build-configuration digest. It
drops only 68 scalar batch counters, and writes a metadata-free 15,745,544-byte
f32 package (SHA-256
d41a729f5ef008d70c6d6bf4ab7ca27e299a478ff665665a4e31afff7f46ddeb),
an 8,828,392-byte non-human synthetic seam pack (SHA-256
21042537873c3dacafafd134d7c9e296318458f55f1a429c00bc9542f95f3238),
and a canonical path-free receipt. Two final hardened v2 exports were
byte-identical; their immutable v2 receipt SHA-256 is
e4e5aab1838dd386895425acc11e3405191e30ce2111c313c2734bfc2bccd77e. The
model has 3,677,760 total parameters, of which 3,676,320 are trainable and 1,440
are frozen; its raw 192-vector is retained separately from consumer-side L2
normalization. Every manually captured terminal embedding must equal the real
upstream forward output bit-for-bit. Known upstream warnings and the one
pinned initialization message are captured and retained only as path-free
code/count/byte/digest records; any unknown warning or console output fails.
Publication uses a stable destination directory handle with no-follow,
create-exclusive files, inode checks, and
fsync. Those historical v2 receipts remain operator_local_no_release; they
are not relabeled by the v3 schema. The immutable v1.0.0 README identifies the
repository's official pretrained weights, links the exact release assets, and
declares MIT. Its source commit and GitHub release record predate the checkpoint
upload, so this is contemporaneous scope evidence rather than a later
retroactive inference. The exporter pins that README at SHA-256
27d500b510a1cdc054a8ccbad484cf6062639fcb9d6b661714214fe766ed4e76 and
pins the later canonical 1,067-byte MIT payload at commit 2a8d15f65b1d,
SHA-256 3d5a4bf9936a7d09dd770588c0d7cb116fc16916a0310d71fb1fff5d64562101.
Fresh v3 receipts therefore mark license scope resolved while keeping artifacts
operator_local_pending_release_manifest. A public raw or converted package
must still carry that exact license payload and notice and be bound by a
separate identity-checked release manifest before it may claim
github_release_with_license_and_notice. No ReDimNet weights, truth tensors,
feature values, local paths, audio, transcripts, or biometric vectors belong in
Git or public runtime reports. The historical package, truth, and v2 receipt
hashes above are not evidence that a fresh v3 receipt has been reproduced.
The two explicit Rust-native ECAPA modes run the pinned ECAPA-TDNN speaker representation in process through the common segmentation, known-speaker constraints, profile/count machinery, temporal UNKNOWN/overlap handling, canonical labels, and transcript projection:
--diarization-engine ecapauses ECAPA embeddings for speaker identity and does not add acoustic channel evidence to pair scoring.--diarization-engine ecapa-fusedauthorizes ECAPA speaker identity plus bounded acoustic channel evidence and consensus. If no selected consensus merge joins a compatible pair with valid channel features, it conservatively reports generic consensus provenance instead. The library/JSON request spelling isecapa_fused.
Both modes remain outside auto, and both are development-uncertified rather
than production-accuracy claims. Neither downloads a model: the exact
converted package must already resolve through the auxiliary model search
path. The library freezes and verifies the
license-compatible source revision, deterministic 200-tensor safetensors
package, exact package hash and metadata, a scalar conformance oracle, public
analytic golden stages, and fail-closed numerical tolerances. The bounded
safe-Rust runtime path implements a fixed-FFT periodic-Hamming PCM frontend,
TDNN/SE-Res2 aggregation, attentive statistics pooling, projection, and
embedding normalization on explicit FrankenTorch CPU kernels, with cooperative
cancellation, content-hash-validated process caching, and content-redacted
diagnostics. The package verifier reuses the native safetensors loader; no
parallel weight format or sidecar manifest is introduced. A
separately authenticated 2,160,320-byte public seven-stage oracle lets the
external conformance test compare all 539,616 frontend and neural f32 values,
then recheck all 523,456 neural values through the composed Rust frontend, not
only selected checkpoints. Safe RAII logical-buffer leases enforce and report
the preplanned ECAPA-owned logical f32 scratch-payload bound. Both generated
artifacts remain outside Git. The
project does not vendor weights or parse PyTorch checkpoints at runtime. The
current provider identity is
ecapa-tdnn-voxceleb-cosine-v6-development; the current clustering policy is
acoustic-clustering-probabilistic-v20-channel-evidence-bound-fused-consensus-development.
Reports distinguish the ECAPA-only ecapa_spherical partition from the
channel-aware five-lane ecapa_fused_consensus partition. The fused method is
emitted only after at least one selected consensus merge joins a compatible
ECAPA pair with valid channel features; otherwise the fused engine conservatively reports
generic probabilistic_consensus provenance and is ineligible for the
supported-profile redecode experiment. Cross-mode method claims fail
validation.
Its equal-loss different-speaker boundary is cosine distance 0.80, and robust
final-assignment and held-out-validation separation begin at the same 0.80.
Lane consensus and temporal recurrence may require stricter evidence, never a
hidden 0.70 gate. This is a versioned development decision bound, not an
accuracy-certification claim. Tracklets of at least two seconds use disjoint
discovery and held-out validation windows, each capped at three seconds;
shorter admitted tracklets use a discovery window, with sub-half-second input
zero-padded to the runtime minimum. Direct 192-dimensional cosine evidence is
marked development-uncertified;
failed public-development candidates remain negative evidence rather than
rollout authority. See the
ECAPA conformance boundary.
4. Microphone Capture
# record 30 seconds from the default mic
franken_whisper transcribe --mic --mic-seconds 30 --json
# specific device
franken_whisper transcribe --mic --mic-device "hw:0" --json
5. Stdin Input
cat audio.mp3 | franken_whisper transcribe --stdin --json
6. Batch Transcription (many files, one model load)
Repeat --input, or pass --inputs-from FILE (one path per line; - reads
the list from stdin; lines are taken verbatim, blank lines are skipped, a
leading UTF-8 byte order mark is ignored, and a relative path resolves against
the current directory). One process loads and
authenticates the native models once and runs every input through the normal
pipeline, so each input's result matches a single-input run with the same
flags. (A repeated input is answered from the in-process transcript cache:
same transcript, segments and timings, but its raw_output.decode_work retry
counters read 0 because no decode ran.)
ls narration/*.wav | fw transcribe --inputs-from - --json --no-diarize --no-persist \
--language en --max-segment-length 1 --split-on-word
--json prints one NDJSON record per input, in input order:
{"schema_version":"franken-whisper-batch-result-v1","index":0,"total":2,"input":"a.wav","status":"ok","report":{...}},
where report is exactly what single-input fw transcribe --json prints, or
"status":"error","error":{"code":"FW-...","message":"..."}. A failed input
does not stop the batch; the process exits 1 (FW-BATCH-INCOMPLETE) if any
input failed. fw transcribe --json prints no summary line, so its exit status
is the batch outcome: 0 when every input succeeded, 1 when an input failed or
the whole batch was invalid (then no records are printed and stderr says why),
130 when interrupted; the FW-BATCH-INCOMPLETE code itself appears only on the
robot stream below. --timeout bounds each input separately, not the batch: an
input that runs past it fails on its own and the next input starts with a fresh
budget (wrap the command in timeout(1) for a whole-batch limit). A panic
inside one input's run fails only that input, with FW-CONTRACT-VIOLATION, in
both commands, including the shipped release binary. The CLI requires panic
unwinding so its recovery boundaries remain active; library embedders must also
use unwinding to recover panics. fw robot run accepts the same flags: each input's run_start,
run_complete and run_error carry "batch":{"index","total","input"}, and
the stream ends with a batch.complete event, which carries
"code":"FW-BATCH-INCOMPLETE" when an input failed. Ctrl+C stops the batch
after the running input (which reports FW-CANCELLED); the process exits 130
and batch.complete says "status":"cancelled", "code":"FW-CANCELLED", even
when the interrupted input was the last one. If the stream's reader goes away,
the first event write that fails (EPIPE) cancels the input in flight: it stops
at its next checkpoint and is not persisted unless its persist stage had
already committed, no later input starts, and the process exits 1. fw notices only when it writes, so a reader that leaves while
a stage is silent (a long backend run) is noticed at that stage's next event.
A batch that is invalid as a whole
(shared flags, an unreadable list) fails before any input runs, like an invalid
single run: run_start, then run_error, neither tagged with batch, and no
batch.complete. Agents can feature-detect
this through fw capabilities --json | jq .batch. --stdin, --mic,
--speaker-hints and --transcript-path apply to one recording and are
rejected in batch mode. --output-* files go to ./<input stem>.<ext> as in
a single run, so a batch that names two different inputs with the same stem
(day1/part1.wav, day2/part1.wav) is rejected before any work instead of
letting one input's files overwrite the other's. Stems are compared ignoring
case (Talk.wav and talk.mp3 collide: ./Talk.srt and ./talk.srt are one
file on the default macOS and Windows file systems), on every OS, so a batch is
accepted or rejected the same way everywhere; one file named twice (a.wav,
./a.wav) is just a repeated input.
Custom vocabulary for domain phrases
Native transcription and both live interfaces accept a bounded vocabulary without adding the phrases to the initial prompt or consuming its token budget:
fw transcribe --input interview.wav --custom-vocab 'Kubernetes,café,FrankenWhisper'
fw transcribe --input first.wav --input second.wav --custom-vocab @domain-terms.txt
fw robot listen --custom-vocab @domain-terms.txt --custom-vocab-bias 2
fw tui listen --custom-vocab 'Kubernetes,FrankenWhisper'
An existing UTF-8 file is read once when the request or batch is prepared;
@FILE makes a missing or unreadable file an error. Files accept one phrase
per line, comma-separated fields, or both. CSV quotes preserve embedded commas
and doubled quotes. Blank fields are ignored; duplicate phrases are collapsed.
Limits are 512 phrases, 256 UTF-8 bytes per phrase, and 64 KiB of input.
The source filename is not stored, but the parsed vocabulary is part of the
persisted request unless --no-persist is set.
--custom-vocab-bias defaults to 2 and accepts finite values from 0 through 5.
The native decoder compiles phrases into model-specific BPE prefixes and boosts
only continuations of a phrase prefix it has already emitted. Matching is
case-sensitive and follows the bytes already emitted, including when the
decoder splits a name or part number differently from the prompt tokenizer.
For example, after emitting Em it can favor erson to complete
Emerson. Emitting the whole name in a single token receives no bonus.
A whitespace-only prefix cannot start a boost.
Timestamp and suppression rules retain priority, and the model's unbiased
no-speech estimate gates the preference. Reported confidence and quality gates
use unbiased model probabilities. The same configuration reaches greedy,
sampling, and beam decoding, and both fast and quality live lanes. External
subprocess backends return FW-UNSUPPORTED because they cannot honor this
native logit control. Defaults remain unchanged when no vocabulary is supplied.
Domain accuracy, silence behavior, and latency still require real-model corpus
qualification; deterministic tests cover the matching and request contracts.
YouTube Ingestion
franken_whisper youtube run downloads YouTube audio and transcribes each video into a clean, deep-linked markdown + JSON pair. Hand it individual video URLs, playlist URLs (auto-expanded to their videos), or a file of URLs — it downloads, transcribes, and writes one transcript per video into youtube_transcripts/ (override with --output-dir). Because the transcription runs on the same engine as transcribe, this pairs naturally with the in-process native engine: no cloud, no API keys, your audio never leaves the machine.
# Single video
franken_whisper youtube run "https://www.youtube.com/watch?v=jNQXAC9IVRw" --model tiny.en
# Several videos at once
franken_whisper youtube run \
"https://youtu.be/VIDEO_A" \
"https://youtu.be/VIDEO_B" \
--concurrency 4
# A whole playlist (expanded to its videos automatically)
franken_whisper youtube run "https://www.youtube.com/playlist?list=PLxxxxxxxx"
# A file with one URL per line (blank lines and #/;/] comments ignored)
franken_whisper youtube run --batch-file urls.txt --output-dir ./talks
URLs may be passed positionally or with repeated --url flags, and mixed freely with --batch-file. A watch?v=X&list=Y URL is treated as the single video X, not the surrounding playlist.
The same command group provides agent-oriented catalog helpers:
franken_whisper youtube search <QUERY> emits deduplicated JSON hits, and
franken_whisper youtube enrich <TARGET>... resolves full metadata for chosen
URLs or ids. Run each subcommand with --help for its focused flags.
Output
Each video produces a markdown transcript and a JSON sidecar. The default slug style is {upload_date}_{title}_{id} with lowercase ASCII title text and an intact, case-preserved YouTube id; --naming-style pretty selects the historical {upload_date} - {title} [{id}] layout. The downloaded audio is kept under audio/<id>.<ext> (delete it automatically with --no-keep-audio), and a .fw_youtube_manifest.json state file tracks per-video progress.
youtube_transcripts/
├── 20050424_me_at_the_zoo_jNQXAC9IVRw.md
├── 20050424_me_at_the_zoo_jNQXAC9IVRw.json
├── audio/
│ └── jNQXAC9IVRw.webm
└── .fw_youtube_manifest.json
The markdown leads with the title, a metadata line, a source link, and an honesty note, then paragraphs grouped on natural pauses and detected speaker changes. Each paragraph starts with a youtu.be deep-link to that moment. Pass --no-diarize to omit the speaker stage.
# Me at the zoo
**Channel:** jawed · **Uploaded:** 2005-04-24 · **Duration:** 0:19
**Source:** [www.youtube.com/watch?v=jNQXAC9IVRw](https://www.youtube.com/watch?v=jNQXAC9IVRw) · **Transcribed:** franken_whisper 0.2.0 (native, tiny.en)
> Note: machine transcription; timestamps are approximate and deep-link into the video.
---
**[0:00](https://youtu.be/jNQXAC9IVRw?t=0)** All right, so here we are in front of the elephants…
---
_Transcribed by franken_whisper 0.2.0 (native, tiny.en, auto) in 0.48s — RTF 0.025_
The JSON sidecar carries the structured form — video metadata, run metadata, native windows decode evidence, and a flat utterances array (one record per segment with start_sec / end_sec / text / confidence, plus speaker when diarized). External subprocess backends emit an empty windows array; an in-process native-v2 result must provide the complete typed window contract or rendering fails closed:
{
"video": { "id": "jNQXAC9IVRw", "title": "Me at the zoo", "channel": "jawed",
"upload_date": "20050424", "duration": 19,
"webpage_url": "https://www.youtube.com/watch?v=jNQXAC9IVRw" },
"run": { "model": "tiny.en", "engine": "native", "backend": "auto",
"version_tag": "0.2.0", "started": "2026-06-07T00:00:00Z",
"wall_ms": 480, "rtf": 0.025 },
"windows": [
{ "window_offset_sec": 0.0, "tokens": 23,
"avg_logprob": -0.31, "no_speech_prob": 0.02 }
],
"utterances": [
{ "i": 0, "start_sec": 0.0, "end_sec": 4.2,
"text": "All right, so here we are in front of the elephants…",
"confidence": 0.91, "speaker": null }
]
}
Flags
| Flag | Default | Description |
|---|---|---|
[URL]... / --url <U> |
— | Video or playlist URLs (positional or repeated --url) |
--batch-file <F> |
— | File with one URL per line (#/;/] comments and blanks ignored) |
--output-dir <DIR> |
youtube_transcripts |
Destination for markdown, JSON, and audio/ |
--model <M> |
backend-specific | Model name or path forwarded to the engine |
--language <L> |
auto-detect | Language hint (ISO 639-1) |
--backend <B> |
auto |
auto, whisper-cpp, insanely-fast, whisper-diarization |
--diarize |
true |
Explicitly retain the default speaker diarization stage |
--no-diarize |
false |
Disable native speaker diarization |
--concurrency <N> |
3 |
Maximum concurrent downloads |
--batch-size <N> |
0 |
Bound videos per download/transcribe wave (0 processes all in one wave) |
--naming-style <S> |
slug |
slug, pretty, or ASCII-lossy ascii artifact names |
--no-keep-audio |
false |
Delete each audio file after its transcript is written |
--no-retry |
false |
Do not retry videos previously marked failed in the manifest |
--abort-on-error |
false |
Stop scheduling later waves after a per-video failure |
--json-summary |
false |
Emit the final run summary as JSON on stdout (for scripting) |
--robot |
false |
Stream per-video NDJSON robot events (youtube.*, schema 1.1.0) on stdout |
Idempotent & Resumable
The .fw_youtube_manifest.json makes terminal work idempotent: a re-run skips videos already done for the same request and retries previously failed videos (unless --no-retry). Each entry records a versioned request fingerprint covering the model selection (including FRANKEN_WHISPER_NATIVE_DEFAULT_MODEL when no model is specified), language, backend, diarization, filename style, audio-retention setting, and product version. Changing these settings reprocesses the video with a fresh retry budget while reusing its validated retained audio; old manifests without fingerprints also reprocess because their settings are unknown. Invalidating a request preserves existing transcript files. Download concurrency, batch size, retry/abort controls, and robot output do not invalidate completed work. The fingerprint identifies requested settings, not the contents of a custom model file replaced at the same path. Incomplete intermediate work is recovered from either an explicit downloaded manifest state or a completed audio/<id>.<ext> artifact left between download and the terminal transition; partial files, symlinks, wrong ids, and paths outside the owned audio directory are rejected. Ctrl+C cancels cleanly — yt-dlp is killed, in-flight transcription aborts, and the manifest stays honest about what completed. By default a partial failure is recorded, emitted as youtube.failed, and the run continues; --abort-on-error stops scheduling later waves after a failure, while videos already running in the current wave may finish. Every robot run that gets past youtube.run_start funnels through exactly one terminal youtube.run_complete emission attempt.
Requires yt-dlp
This subcommand orchestrates yt-dlp, which you install separately:
brew install yt-dlp # macOS
pipx install yt-dlp # cross-platform, isolated
pip install -U yt-dlp # cross-platform
Point franken_whisper at a specific build with FRANKEN_WHISPER_YTDLP_BIN=/path/to/yt-dlp if it is not on PATH.
Keep yt-dlp current. YouTube changes its site frequently, and a stale
yt-dlp is a common cause of download failures. franken_whisper warns when the
resolved yt-dlp build is more than 90 days old. Update it with:
yt-dlp -U # update to the latest stable
yt-dlp --update-to nightly # or track the nightly channel for the freshest fixes
franken_whisper deliberately downloads with the forgiving bestaudio/best format selector rather than a strict codec filter, so a slightly stale yt-dlp still succeeds in more cases — but when YouTube breakage does occur, updating yt-dlp is the first and usually the only step.
Real-Time Streaming (fw robot listen)
fw robot listen is true live streaming: speak into a microphone (or pipe raw PCM / replay a WAV) and act on transcript events while the speaker is still talking. It calls the native engine directly in a bounded rolling-buffer loop (capture → resample → VAD → step decode → emission policy → NDJSON), with utterance boundaries and fast/quality model lanes designed for an unbounded session.
For an existing recording, ordinary fw robot run also delivers text during
native inference: completed ASR windows produce sequenced stage events with
code: "transcript.partial". The native diarization backend delivers this text
with speaker: null while speaker assignment is still pending. It uses the normal
file pipeline and one ASR model, with no --speculative flag required. The final run_complete
contains the authoritative transcript after alignment and speaker processing.
External backends that only return a completed batch deliver previews after that
batch finishes. See the robot interface below for the preview and retry contract.
Quickstart
# Live microphone -> agent-consumable NDJSON (default: multilingual tiny fast
# lane, tiny.en with --language en; AlignAtt policy)
fw robot listen | jq -r 'select(.event == "transcript.delta") | .text'
# No device needed: pipe any producer in as raw PCM (16 kHz mono s16le shown; rate/channels configurable)
ffmpeg -i stream.mp3 -f s16le -ar 16000 -ac 1 - | fw robot listen --source stdin-pcm
# Deterministic replay of a WAV through the identical event contract
fw robot listen --source file-replay --input meeting.wav --realtime-pace
# Add a session-continuous speaker timeline from the installed Sortformer package
fw pull sortformer
fw robot listen --diarize --quality-model none
WAV replay reads frames on demand, so opening a long recording does not load the whole waveform into memory. It accepts 8-, 16-, 24-, and 32-bit integer PCM and finite 32-bit float PCM, preserving channel order for the shared resampler/downmixer. Truncated frames and non-finite samples produce explicit input errors after any complete preceding frames have been delivered. Stopping replay closes the reader immediately. Other containers can use the PCM pipe shown above.
With live persistence enabled, the session retains only newly closed utterance text awaiting a successful transaction; the durable transcript stays in SQLite. A failed flush retains its pending text, segments, and events for an atomic retry. Healthy stats heartbeats flush immediately. Events and committed deltas also flush every five seconds, independently of speech and stats heartbeats, or when the batch reaches 64 rows or 256 KiB. The pending buffer is capped at 1,024 rows / 4 MiB; if a final retry cannot make room, the session stops with an explicit storage error before admitting more data. Quality corrections rebuild the authoritative history, and closing the session combines the stored prefix with any remaining suffix. Those correction and terminal operations still temporarily materialize the full transcript.
Latency percentiles cover the latest 2,048 observations per lane; mean step
latency and maximum confirmation lag cover the entire session. Stats events and
the robot schema declare those scopes in latency_contract. Durable warning
summaries retain up to 64 distinct bounded-length reasons plus an overflow
marker; individual warning events remain unchanged.
The event contract (schema 1.1.0)
One JSON object per line on stdout, explicitly flushed. Every event carries schema_version, a strictly increasing per-session seq, an RFC-3339 ts, and the session run_id. A live session IS a run: it never emits run_start/run_complete; a success stream ends with listen.session_stats {final: true}, a fatal error ends with run_error.
| Event | Meaning |
|---|---|
listen.session_start |
Session configuration echo: source, capture backend, device, models, policy, step cadence, VAD parameter snapshot |
speech_started |
VAD opened an utterance (utterance_id, monotonically increasing from 1; utterances never nest) |
transcript.delta |
Append-only committed text — concatenating an utterance's deltas yields its transcript; committed text is never rewritten by later events |
transcript.partial |
Mutable preview of the uncommitted tail (suppress with --no-partials; the first remedy for slow consumers) |
utterance_end |
The "act now" signal: full committed text (32 KiB cap with text_truncated flag; deltas always carry the full text), delta_count, close reason = endpoint | timeout | max_len | session_end |
transcript.confirm / transcript.correct |
Quality-lane verdicts keyed by utterance_id; may arrive after their utterance_end (async confirm lane; never blocks the live lane) |
diarization.update |
Opt-in finalized speaker activity over a contiguous session-time interval; four anonymous lanes, overlapping turns supported, independent of text deltas |
listen.warning |
Structured non-fatal degradation: silent_input, capture_overrun, fallback_capture_backend, fast_model_fallback, quality_model_unavailable, confirm_lag, forced_trim, decode_behind, persist_degraded, endpoint_flush_timeout, … |
listen.session_stats |
Liveness heartbeat (default every 30 s, silence included) and terminal stats: ttft_ms, mean/p95_step_latency_ms, deltas, utterances, capture_overruns, policy_holdbacks, confirm-lag p50/p95/max |
listen.controller |
Default-off --adaptive decision evidence: bounded cadence/holdback transition, Brier calibration, observation count, and deterministic-fallback status |
Lifecycle invariants (enforced by contract tests): every speech_started is matched by exactly one later utterance_end carrying the same utterance_id; an utterance whose decode commits nothing still closes with empty text (breath/cough triggers are normal, never errors); an utterance's deltas always precede its utterance_end; seq strictly increases across every event.
speech_started ──► transcript.delta* ─────► utterance_end ──► transcript.confirm/correct?
(VAD onset) append-only commits + (endpoint / timeout / async quality lane,
mutable partial previews max_len / session_end) keyed by utterance_id
Emission policies
--policy alignatt(default). AlignAtt (Simul-Whisper / SimulStreaming): a segment commits once its tokens' alignment-head cross-attention sits at least--alignatt-holdback-ms(default 200 ms) behind the live audio edge. Mid-utterance deltas flow as soon as attention stops attending near the buffer edge. A quality gate holds all commits for steps with high no-speech probability or very low mean log-prob (counted inpolicy_holdbacks) so non-speech audio does not hallucinate committed text.--policy endpoint-commit. Zero-intelligence baseline: mutable partials every step, one committed delta when the utterance closes. Kept forever as the latency harness's control arm.--policy local-agreement. LocalAgreement-2 fallback (whisper_streaming, arXiv 2307.14743): commit only the segment-text prefix two consecutive decodes agree on. Model-agnostic insurance (needs no attention tap); never the default.--policy local-agreement-word. Commit the words that two successive speech hypotheses share, even when their segment breaks differ. The live decoder computes DTW word ends for the audio cut and keeps the last word mutable. When word timings are unavailable, only complete agreed segments preceding the final segment can commit before the utterance closes.
jfk-style single-sentence utterances close before policies can differ; continuous monologues (>12 s single utterance) are where AlignAtt separates from endpoint-commit.
Flags
| Flag | Default | Meaning |
|---|---|---|
--source |
mic |
mic | stdin-pcm | file-replay |
--input + --realtime-pace |
— / off | WAV input for file-replay; pace at real time vs. as-fast-as-possible |
--capture-backend / --mic-device |
auto / system default |
capture backend auto|cpal|ffmpeg; input device name |
--list-devices |
off | enumerate input devices as NDJSON and exit (metadata only; never triggers a TCC prompt) |
--fast-model |
auto | fast-lane model override (default tiny.en for en, multilingual tiny otherwise) |
--policy / --alignatt-holdback-ms |
alignatt / 200 |
emission policy (above); AlignAtt danger-zone width |
--step-ms / --max-buffer-sec |
300 / 12 | decode cadence; rolling buffer cap |
--adaptive |
off | adapt cadence and AlignAtt holdback within fixed bounds; Brier calibration failures deterministically restore configured values and emit listen.controller evidence |
--language |
detect-and-pin | ISO 639-1 hint |
--max-seconds / --max-utterance-sec |
0 / 90 | listening-time cap from capture start, model load excluded (0 = unbounded); force-close long open speech |
--no-partials |
off | suppress mutable partial previews (first remedy for slow consumers) |
--stats-interval-sec |
30 | listen.session_stats heartbeat interval (0 = final only) |
--no-context / --capture-buffer-sec |
off / 30 | disable prompt carry; capture ring capacity |
--no-vad, --vad-gate-db, --vad-min-speech-ms, --vad-endpoint-ms |
off, 9, 250, 600 | VAD gating and tuning |
--quality-model, --confirm-drain-sec, --confirm-queue-bound |
auto, 10, 4 | confirm-lane controls (above) |
--diarize |
off | retain native Sortformer speaker state throughout the session and emit diarization.update |
--diarization-receipt / --diarization-package |
verified cache | paired explicit artifacts for --diarize; authenticated before capture starts |
--diarization-drain-sec |
10 | maximum wait for pending speaker activity at session end |
--db / --no-persist |
.franken_whisper/storage.sqlite3 / off |
persistence store; disable persistence |
--stdin-rate / --stdin-channels / --stdin-format |
16000 / 1 / s16le | stdin-pcm format |
Full semantics per flag: docs/realtime-streaming.md.
Models and the quality-confirm lane
The fast lane runs a small resident model: tiny.en when --language en, multilingual tiny otherwise (detect-and-pin). Missing fast-lane packages fall back to the turbo model with a fast_model_fallback warning; provision them with fw pull tiny / fw pull tiny-en.
The confirm lane re-transcribes each closed utterance with a quality model in a background thread. --quality-model auto (default) enables it iff the large-v3-turbo package is installed AND the fast lane did not fall back to turbo (self-confirmation is meaningless); none disables it; an explicit spec is honored unless it names the effective fast model. Verdicts reuse the batch CorrectionTracker and surface as transcript.confirm/transcript.correct. The live lane never blocks on the quality lane: more than --confirm-queue-bound (default 4) unconfirmed utterances drops the oldest with a confirm_lag warning, and session end waits at most --confirm-drain-sec (default 10) before a confirm_drain_timeout warning.
Optional live speaker activity
--diarize runs the native Sortformer model on a background lane with one
continuous frontend and one speaker-cache/FIFO state for the entire session.
Utterance boundaries, VAD silence, and quality-model text corrections do not
reset its anonymous speaker lanes. The model is authenticated and loaded before
capture starts; missing or invalid requested artifacts fail startup. The normal
verified cache comes from fw pull sortformer; explicit receipt/package paths
must be supplied together.
The speaker lane clamps its copied finite PCM to [-1, 1], including ordinary
FIR resampling overshoot, without changing the sample count or the audio used
by ASR and the integrity hash. Session metadata records that normalization.
The fixed model profile uses 27.2-second central blocks and 3.2 seconds of right context. The first full update therefore needs about 30.4 seconds of input, followed by inference time; later updates advance coverage by 27.2 seconds. Session end flushes a shorter final tail. This is delayed speaker attribution alongside the fast text stream. It is not a measured low-latency speaker-recognition claim, and the new incremental frontend remains development-uncertified.
Each diarization.update has a monotonic revision, exact start_sample and
end_sample coordinates at 16 kHz, equivalent t0_sec/t1_sec fields, and a
turns array. A turn carries the same sample/time coordinates plus speaker
(SPEAKER_00 through SPEAKER_03). Coverage is finalized, contiguous, and
append-only; turns are clipped to that update's interval and may overlap. An
empty turns array means no speaker activity was detected in that covered
interval. Audio after the coverage frontier remains pending or unknown.
These labels identify model lanes within this session, not named people or
biometric identities; four lanes do not establish that only four people spoke.
Consumers join this independent timeline to transcript timestamps, including the session-absolute timestamps in later quality corrections. A text delta may span several speakers, so speaker updates do not rewrite deltas or assign a single label to all their words. The TUI shows recent speaker intervals separately. Speaker events are retained in the session event log; the ordinary saved transcript segment rows remain unlabeled.
The speaker lane keeps at most 60 seconds of queued PCM and eight queued result
messages. Unlimited unpaced WAV replay waits for queue space, publishes results
while submitting audio, and drains all accepted speaker work at normal EOF.
This preserves the speaker timeline when file reading outruns inference while
keeping both queues bounded. Microphone, stdin, paced replay, and sessions with
an explicit --max-seconds retain nonblocking submission and a bounded final
drain. Capture gaps, queue overrun in those sessions, worker failure, or a drain
timeout produce explicit warnings with the last completed coverage boundary.
The lane stops attributing new audio instead of silently dropping context and
reusing speaker labels. Plan memory for this additional model;
--quality-model none keeps a separate quality ASR model out of that session
when it is not needed.
Persistence
Sessions persist to SQLite by default (--db, default .franken_whisper/storage.sqlite3; disable with --no-persist) as ONE run row with backend native-listen. Completed utterances, quality corrections, and speaker updates advance durability inside savepoint transactions. Mutable transcript.partial previews are deliberately NOT persisted (unlike batch, where every event is kept). A crashed session is recognizable as a listen run lacking its session-end marker; runs.finished_at is bumped at each flush as "last known alive".
Quality corrections replace the affected utterance in saved transcript history
and segment rows, with the correction event committed in the same transaction.
Replacement can change the number of segments and can arrive after later
utterances. Reconstruction uses the exact delta events and utterance IDs, so a
capped utterance_end.text cannot truncate saved text. Original emitted deltas
remain in the audit log. Correction timestamps use the session clock, and
failed writes retain their pending batch for retry or final close. This initial
correctness path replays transcript history for each correction; its work grows
with session history even though the live speaker buffers remain bounded.
Latency expectations (measured, not aspirational)
From the first streaming latency campaign (examples/listen_latency_ab.rs, release build, --source stdin-pcm, paced 20 ms PCM injection; PERF_LEDGER 2026-08-23, bd-rt-latency-harness-3dkh, artifact docs/perf_artifacts/listen_latency_campaign1_2026-08-23.json) on a loaded shared host (load average ≈28–43):
- TTFT (first
transcript.deltaminus speech-onset injection): medians 3.1–5.6 s across fixtures — dominated by model load + first decode under contention, not steady-state stepping. - Commit lag p50: ~0.79–1.21 s behind the audio being committed.
- Partial cadence: inter-partial p50 489 ms against
--step-ms 300(cadence = step interval + decode time). - Retraction count: 0 by construction (append-only deltas). Joined delta text was identical across policy arms on every fixture; the tone-only negative fixture produced zero output.
Honesty note: that campaign's A/A nulls missed the pre-declared band (host load), so it banks NO cross-policy comparison — quiet-host reruns can. Do not quote these rows as comparative wins; they are self-relative observations under load.
Live speaker activity requires --diarize; the default live session transcribes
without it. The fast lane decodes greedy-only (AlignAtt requires the attention
tap, which fails requests with beam > 1).
Agent integration
Python:
import json, sys, subprocess
proc = subprocess.Popen(
["fw", "robot", "listen", "--source", "stdin-pcm"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
)
for line in proc.stdout:
event = json.loads(line)
if event["event"] == "transcript.delta":
print("COMMIT:", event["text"]) # append-only: safe to persist
elif event["event"] == "utterance_end":
print("ACT ON UTTERANCE:", event["text"]) # complete turn, act now
elif event["event"] == "listen.warning":
print("DEGRADED:", event["reason"], file=sys.stderr)
elif event["event"] == "listen.session_stats" and event.get("final"):
break
Node.js:
import { spawn } from "node:child_process";
import readline from "node:readline";
const proc = spawn("fw", ["robot", "listen"]);
const rl = readline.createInterface({ input: proc.stdout });
for await (const line of rl) {
const event = JSON.parse(line);
if (event.event === "transcript.delta") console.log("COMMIT:", event.text);
if (event.event === "utterance_end") console.log("ACT ON UTTERANCE:", event.text);
if (event.event === "listen.session_stats" && event.final) break;
}
Key on transcript.delta for durable state (it never changes after arrival) and utterance_end for turn-taking actions (answering, tool calls). Treat transcript.partial as ephemeral display garnish. Full architecture, design rationale, tunables, and failure-mode tables: docs/realtime-streaming.md.
Command Reference
franken_whisper exposes ten top-level subcommands.
transcribe
Core transcription command. Runs ingest, normalization, native Whisper,
native speaker diarization, optional alignment/punctuation stages, and
persistence. Use --no-diarize for transcript-only work.
franken_whisper transcribe [OPTIONS]
Input (mutually exclusive):
| Flag | Description |
|---|---|
--input <PATH> |
Audio or video file path; repeat it for batch mode |
--inputs-from <FILE> |
Batch mode: one input path per line (- = stdin); see Batch Transcription |
--stdin |
Read audio bytes from stdin |
--mic |
Capture from microphone via ffmpeg |
Backend & Model:
| Flag | Default | Description |
|---|---|---|
--backend <KIND> |
auto |
auto, whisper_cpp, insanely_fast, whisper_diarization |
--model <MODEL> |
backend-specific | Model name or path forwarded to backend |
--language <LANG> |
auto-detect | Language hint (ISO 639-1) |
--translate |
false |
Translate to English |
--diarize |
true |
Explicitly retain the default typed speaker-diarization stage |
--no-diarize |
false |
Disable the speaker-diarization stage |
Output:
| Flag | Description |
|---|---|
--json |
Full JSON run report on stdout |
--output-txt |
Plain text (whisper.cpp side-output) |
--output-vtt |
WebVTT subtitles |
--output-srt |
SRT subtitles |
--output-csv |
CSV |
--output-json-full |
Extended JSON with metadata |
--output-lrc |
LRC karaoke format |
Storage:
| Flag | Default | Description |
|---|---|---|
--db <PATH> |
$FRANKEN_WHISPER_DB, else <state dir>/storage.sqlite3 |
SQLite database path |
--no-persist |
false |
Skip persistence entirely |
--timeout <SEC> |
— | Pipeline deadline (seconds) for one run; in batch mode it bounds each input separately |
Inference Tuning (whisper.cpp):
| Flag | Default | Description |
|---|---|---|
--threads <N> |
RAYON_NUM_THREADS, else every logical CPU on a host with at most 32, else the physical core count but at least 32 |
Compute threads: the whole run (model load, mel, encoder/decoder kernels, diarization) computes on one pool of the effective width, reused across a batch's inputs; the process adds at most 12 fixed non-compute threads (6 in a plain single-input run). All width sources, including environment and direct library calls, are clamped to the CPUs the process may use (affinity mask, cgroup CPU quota). An explicit oversized N emits a warning: on stderr (robot mode: an orchestration.threads_clamped stage event and a run_complete warning). Completed runs retain at most one idle pool per width and four idle pools in total; active runs keep their isolated workers |
--processors <N> |
1 | Parallel processors |
--no-gpu |
false |
Force CPU-only native inference, including native source separation and speaker diarization; preserve the existing bridge flag behavior |
--beam-size <N> |
5 | Beam search width |
--best-of <N> |
5 | Sampling candidates |
--temperature <F> |
0.0 | Sampling temperature |
--temperature-increment <F> |
— | Temperature fallback increment |
--entropy-threshold <F> |
— | Entropy threshold for fallback |
--logprob-threshold <F> |
— | Log-probability threshold |
--no-speech-threshold <F> |
— | No-speech probability threshold |
--max-context <N> |
— | Max context tokens from prior segment |
--max-segment-length <N> |
— | Max segment length (characters) |
--no-timestamps |
false |
Suppress timestamps |
--detect-language-only |
false |
Detect language and exit |
--split-on-word |
false |
Split segments on word boundaries |
--no-fallback |
false |
Disable temperature fallback |
--suppress-nst |
false |
Suppress non-speech tokens |
--tiny-diarize |
false |
Enable TinyDiarize (speaker-turn token injection) |
--normalize-segment-text |
false |
Opt in to rule-based segment-text normalization (sentence-casing + terminal periods); off by default so segments[].text stays byte-faithful to the transcript |
--prompt <TEXT> |
— | Initial prompt to guide transcription style |
--carry-initial-prompt |
false |
Keep the prompt as a prefix of every 30 s window's context, not just the first |
--custom-vocab <FILE_OR_CSV> |
— | Native phrase-continuation bias from a UTF-8 file (@FILE requires one) or comma-separated phrases; also supported by robot listen and tui listen |
--custom-vocab-bias <F> |
2 | Finite native continuation bias from 0 through 5; requires --custom-vocab and does not consume prompt context |
Audio Windowing (whisper.cpp):
| Flag | Default | Description |
|---|---|---|
--offset-ms <N> |
0 | Start transcription at offset (ms); honored by every native backend, the whisper.cpp bridge (-ot), and both lanes of speculative mode. Emitted timestamps stay in source-file time; VAD and diarization still cover the whole clip |
--duration-ms <N> |
— | Transcribe only this duration (ms); zero means the remaining audio. Speculative mode schedules only the selected interval and applies the window once. Non-speculative bridges that cannot honor the window (insanely-fast-whisper, whisper-diarization) record it in warnings |
--audio-ctx <N> |
— | Encoder audio context in frames (0 = full 30 s window); the native engine maps N > 0 to a fixed encoder context |
--word-threshold <F> |
— | Per-word confidence threshold (drop words below) |
--suppress-regex <REGEX> |
— | Suppress tokens matching regex |
Word-level timestamp extraction (max-len, token-threshold, token-sum-threshold) is exposed through the WordTimestampParams struct via the library API; the bridge parser already extracts nested words arrays from whisper.cpp output when those parameters are set programmatically.
VAD (Voice Activity Detection):
| Flag | Description |
|---|---|
--vad |
Enable Voice Activity Detection |
--vad-model <PATH> |
Custom VAD model path |
--vad-threshold <F> |
Speech detection threshold |
--vad-min-speech-ms <N> |
Minimum speech duration (ms) |
--vad-min-silence-ms <N> |
Minimum silence duration (ms) |
--vad-max-speech-s <F> |
Maximum speech duration (seconds) |
--vad-speech-pad-ms <N> |
Speech padding (ms) |
--vad-samples-overlap <N> |
Sample overlap between windows |
Batching (insanely-fast-whisper):
| Flag | Default | Description |
|---|---|---|
--batch-size <N> |
24 | Parallel inference batch size |
--gpu-device <DEV> |
auto | GPU device (0, cuda:0, mps) |
--flash-attention |
false |
Enable Flash Attention 2 |
--hf-token <TOKEN> |
env | HuggingFace token for diarization |
--timestamp-level |
chunk |
chunk or word granularity (word emits one segment per word) |
--transcript-path <PATH> |
— | Override transcript output path |
Diarization:
| Flag | Default | Description |
|---|---|---|
--diarization-engine <ENGINE> |
auto |
auto selects native Sortformer; alternatives are sortformer, acoustic, external, ecapa, and ecapa-fused |
--diarization-fallback <POLICY> |
acoustic |
unknown, acoustic, external, or error; the default handles missing/capacity-ineligible Sortformer evidence in Rust |
--speaker-hints <PATH> |
— | Read a speaker-hints-v1 document in place; the path is not retained, but parsed fields persist with the run unless --no-persist is used |
--enrollment-edge-guard-ms <N> |
100 |
Remove boundary-adjacent audio before enrolling a known interval |
--diarization-max-prototypes <N> |
512 |
Bounded global native-diarization prototype cap (1..=512) |
--persist-speaker-profiles |
false |
Record explicit persistence consent; schema v6 still stores privacy-safe summaries rather than reusable acoustic vectors |
--speaker-count-hard <K> |
— | Explicit hard search constraint; success still requires independent evidence for every speaker and uncertain speech remains UNKNOWN |
--speaker-count-range <MIN..MAX> |
— | Soft bounded count preference; native evidence may disagree or remain unresolved |
--speaker-count-prior <PRIOR> |
— | Soft point prior (K) or normalized distribution (K=P,K=P); never forces occupancy |
--no-stem |
false |
Disable external-backend vocal isolation |
--suppress-numerals |
false |
Spell out numbers for external alignment stability |
--diarization-model <MODEL> |
— | Override the external diarization model |
ECAPA fallback is deliberately asymmetric so a missing external result is not mistaken for successful fallback:
| Policy | ECAPA ran, but evidence is insufficient | ECAPA package/load/inference unavailable |
|---|---|---|
unknown |
Retain the native result, hard-hint assignments, and UNKNOWN where evidence is insufficient | Emit hard hints where possible and UNKNOWN elsewhere under native-ecapa-unavailable-v1 |
acoustic |
Rerun the common stack with acoustic-v2 speaker identity while retaining ECAPA provenance | Rerun acoustic identity and attach an unavailable-ECAPA summary |
external |
Use valid external labels when present; otherwise retain the insufficient ECAPA result | Use valid external labels when present; otherwise return an error |
error |
Return an inner-diarizer error | Return an error |
Speculative Streaming:
| Flag | Default | Description |
|---|---|---|
--speculative |
false |
Enable dual-model speculative cancel-correct mode |
--fast-model <MODEL> |
— | Fast model for low-latency partial transcripts |
--quality-model <MODEL> |
— | Quality model for correction / verification |
--speculative-window-ms <N> |
3000 | Sliding window size (ms) |
--speculative-overlap-ms <N> |
500 | Window overlap (ms) |
--correction-tolerance-wer <F> |
— | WER tolerance for confirmation vs. retraction |
--no-adaptive |
false |
Disable adaptive window sizing |
--always-correct |
false |
Force quality model on every window (evaluation mode) |
diarization-corpus
External-only preparation and aggregate evaluation for public or operator-licensed diarization corpora. The registry does not download data or accept a license on the operator's behalf.
registry is available on every supported CLI target. The artifact-writing
prepare-voxconverse, build, ablate, sidecar-study, and compare-models
commands require Linux, Android, or an Apple platform; Windows and other targets return
public_corpus.output_platform before reading corpus media or annotations.
# inspect frozen source, license, conversion, and acknowledgement contracts
franken_whisper diarization-corpus registry
# hash the official extracted VoxConverse WAV/RTTM files in place and write a
# deterministic descriptor beneath the external input root; no media is copied
franken_whisper diarization-corpus prepare-voxconverse \
--input-root /absolute/external/voxconverse \
--development-audio-root /absolute/external/voxconverse/dev-wav/audio \
--test-audio-root /absolute/external/voxconverse/test-wav/voxconverse_test_wav \
--annotation-root /absolute/external/voxconverse/labels \
--output /absolute/external/voxconverse/descriptor.json \
--source-version <IMMUTABLE_UPSTREAM_ARCHIVE_AND_LABEL_ID> \
--license-ack accept-voxconverse-cc-by-4.0-and-original-copyright
# validate external WAV/RTTM inputs and create one path-free bundle
franken_whisper diarization-corpus build \
--input-root /absolute/external/corpus \
--descriptor /absolute/external/corpus/descriptor.json \
--output /absolute/external/results/bundle.json \
--license-ack <REGISTRY_ACKNOWLEDGEMENT_ID>
# run the existing acoustic-v2 representation/detector/clustering ablation v8
franken_whisper diarization-corpus ablate \
--input-root /absolute/external/corpus \
--descriptor /absolute/external/corpus/descriptor.json \
--bundle-output /absolute/external/results/ablation-bundle.json \
--output /absolute/external/results/ablation-development.json \
--license-ack <REGISTRY_ACKNOWLEDGEMENT_ID> \
--stage development
# run the separate, evaluation-only multiscale sidecar study
franken_whisper diarization-corpus sidecar-study \
--input-root /absolute/external/corpus \
--descriptor /absolute/external/corpus/descriptor.json \
--bundle-output /absolute/external/results/sidecar-bundle.json \
--output /absolute/external/results/sidecar-development.json \
--license-ack <REGISTRY_ACKNOWLEDGEMENT_ID> \
--stage development
# compare all native lanes with the pinned operator-installed Sortformer oracle
RAYON_NUM_THREADS=8 franken_whisper diarization-corpus compare-models \
--input-root /absolute/external/corpus \
--descriptor /absolute/external/corpus/descriptor.json \
--bundle-output /absolute/external/results/model-comparison-bundle.json \
--output /absolute/external/results/model-comparison-development.json \
--license-ack <REGISTRY_ACKNOWLEDGEMENT_ID>
The VoxConverse adapter preserves original file hashes and applies one narrow, evidenced geometry normalization in memory: an official turn that starts before WAV EOF may be clipped when it overruns EOF by at most 100 ms. The preparation receipt and bundle retain clipped-turn and clipped-millisecond counts; larger overruns and turns beginning at EOF fail closed.
compare-models is a development-only, diagnostic comparison of
native_acoustic, native_ecapa, native_ecapa_fused, native_sortformer,
and external_sortformer. It infers speaker count, fixes native and Sortformer CPU
worker counts at eight, and applies the same frozen 1800-second attempt timeout
to every lane. The application downloads neither the ECAPA
package nor the external Sortformer adapter/model; the native Sortformer lane
uses the release-bound cache installed by the installer or fw pull sortformer. Absent
components become typed lane skips. Protocol v6 pins the complete effective native request
for each lane, its ordered payload-free outcome taxonomy, and its own canonical
digest. Any change to those bindings requires a new version-and-digest pair.
The comparison evidence is aggregate-only and cannot authorize a superiority or production-routing claim. Every lane/observation runs in a fresh process under the balanced Williams order. The worker rechecks the executable, audio, normalized PCM, reference, scorer, protocol, and applicable model artifact identities. Parent-observed wall time includes process launch, bounded IPC, worker identity validation, audio decode, model load, inference, output validation, scoring, parent-side post-run identity validation, and the native platform resource probe. The parent kills the complete descendant process group on cancellation or timeout, records a live recursive-descendant cancellation probe through the same bounded observer path used by real lanes. Cancellation, timeout, and output-limit checks run before observation. On Unix, cleanup reaps the root and verifies that the owned process group is absent; cleanup failure overrides a nominal success, cancellation, or timeout. An initial group-signal error is accepted only when the subsequent absence probe still certifies that the complete group is gone. Before reading its request, the worker opens an inherited kernel-pipe capability bound to its direct parent and starts a liveness watcher. Abrupt parent death closes the sole write end, causing the worker to terminate its complete process group; unsupported platforms fail before launching an observed worker. The RSS field is an approximate sampled maximum of the concurrent process-group sum, including nested subprocess adapters. Sample starts are no closer than 50 ms, and each platform probe has its own fixed bound; this is not an exact process high-water mark or a promise of exactly 50 ms between samples. A worker that exits before any sample is explicitly unavailable, while repeated disappearance of a still-live group fails the resource probe. The platform scan checks both cancellation and the enclosing attempt deadline. A matched live Linux group member cannot be silently omitted: every such member must expose a valid RSS field. A complete zero-only scan is treated as a missing sample, never as a measured zero, and repeated zero-only observations fail closed. Wall time, RTF, sampled whole-tree RSS, and cancellation latency carry explicit scope, authority, and cap dispositions rather than zero or shared-process estimates. The companion path-free public bundle is record-level scorer input and therefore retains opaque public recording/speaker IDs and reference timestamps, but no source path, filename, audio, or transcript.
verify_public_model_comparison_bundle_identity_pair validates both retained
artifacts and proves that their corpus, source, descriptor, bundle, split, and
recording-count identities agree. Because the evidence is aggregate-only, this
API does not derive its observation-set commitment or metrics from the bundle;
that stronger proof still requires source reconstruction and a fresh run.
All path arguments must be absolute. Entire output file names must use lowercase
ASCII letters, digits, period, underscore, and hyphen and end in the exact
suffix .json; a handle-relative preflight also rejects an existing
ASCII-case-fold sibling, making ordinary case-sensitive and case-insensitive
collisions fail consistently. Exact-name no-clobber publication remains the
atomic creation guard. Input data must
remain outside the checkout, and bundle/evidence parents must be outside both
the checkout and input root. Outputs use create-new semantics and are never overwritten. On
Linux, Android, and Apple platforms, complete JSON is privately staged relative
to an identity-bound directory handle and atomically published with no-clobber
semantics. The terminal parent may not be a symlink; it must be owned by the
effective user and not group/world writable. This protects handle-relative
directory contents while treating the effective user as trusted, because that
user can also alter a final artifact afterward. Requested and canonical
terminal-directory identities are checked throughout. Ancestor rename
authority, ACLs, privileged mount changes, and arbitrary mount aliases of a
checkout/input descendant are outside this boundary; use a privately controlled
output path and filesystem without broader ACL access. Other platforms fail
closed for this public-artifact path. Add
--maximum-recording-duration-ms <N> to freeze a deterministic prefix. A
pre-publication failure creates no final-name artifact and never modifies an
existing final-name entry. After permission verification, later failures
truncate and synchronize the private staging inode to a zero-length mode-0600
marker; this is not a secure block erase. Creation is followed by an explicit
mode-0600 permission operation and verification that the inode is a regular
file owned by the effective user with exactly those access bits; failure is
reported before payload serialization. POSIX/NFSv4 ACLs and mount policies
that grant access beyond Unix mode bits are outside this writer's authority, so
public-artifact output directories must reside on a filesystem where such
broader access is absent. A permission-establishment failure leaves an empty
marker but makes no mode claim. A storage failure during a payload scrub reports
public_corpus.output_cleanup_uncertain. An error after the
no-clobber rename is reported as
public_corpus.output_commit_uncertain, because the final artifact may already
exist and is not truncated. An ambiguous rename error uses the same
commit-uncertain result and conservatively preserves the held inode; only an
authoritative no-clobber conflict is treated as definitely pre-commit. Bundle
and evidence files are each published
atomically, but their two renames are not a cross-file transaction; successful
evidence publication is the completion signal for the pair. A
sidecar certification run uses --stage certification and must also supply
--locked-development-evidence <PATH>; it evaluates the unfused baseline and
only the single candidate selected by the exact locked development artifact.
Both stages parse and hash the complete descriptor and audit its path-free
cross-split metadata, but materialize WAV, RTTM, and optional word-annotation
bytes only for the stage's selected split. Certification validates the retained
development artifact's complete internal contract—including both calibration
fingerprints and provenance, selected lane, recomputed gates/ranking/disposition,
and result/accuracy hashes—then binds the current descriptor and protocol before
opening held-out inputs. This validation does not refit calibration or replay
development audio. Development and certification
therefore create distinct split-specific bundle hashes; the shared descriptor
and protocol hashes are the cross-stage lock.
Source paths, filenames, recording/speaker identifiers, per-recording
observations, feature values, audio, and transcripts never enter the aggregate
study evidence.
robot
Agent-first interface with structured NDJSON output and a stable schema contract.
# file transcription with stage events and native decoded-window previews
franken_whisper robot run [TRANSCRIBE_OPTIONS]
# live microphone / pipe streaming (see "Real-Time Streaming" section)
franken_whisper robot listen [--source mic|stdin-pcm|file-replay ...]
# emit the full JSON schema for every event type
franken_whisper robot schema
# discover backends and capabilities
franken_whisper robot backends
# system health diagnostics (backends, ffmpeg, database, resources)
franken_whisper robot health
# query routing decision history
franken_whisper robot routing-history [--run-id <ID>] [--limit 20]
Robot Event Catalog (schema 1.1.0; the six core listen.* / speech-lifecycle events and the optional adaptive-controller event are additive members of the same contract):
| Event | Description |
|---|---|
run_start |
Request accepted, pipeline starting |
stage |
Pipeline stage progress (sequenced, timestamped) |
run_complete |
Transcription finished with full result |
run_error |
Pipeline failed with structured error code |
backends.discovery |
Backend availability + per-backend capabilities |
routing_decision |
Backend routing decision: chosen action, calibration score, e-process, fallback state, recommended order |
health.report |
System health (backend / ffmpeg / DB / resource status) |
transcript.partial |
Speculative fast-model partial transcript (immediate) |
transcript.confirm |
Quality model confirms partial (drift within tolerance) |
transcript.retract |
Quality model retracts partial (drift exceeds tolerance) |
transcript.correct |
Quality model correction with corrected segments |
transcript.speculation_stats |
Aggregate speculation pipeline statistics |
listen.session_start |
Live session configuration echo (additive 1.1.0 family; a session never emits run_start/run_complete) |
speech_started |
VAD opened an utterance (utterance_id from 1, never nested) |
transcript.delta |
Append-only committed text for the live driver (concatenating deltas = the utterance transcript) |
utterance_end |
Utterance closed: full committed text (32 KiB cap + text_truncated), delta_count, close reason |
listen.warning |
Structured non-fatal degradation (confirm_lag, forced_trim, capture_overrun, …) |
listen.session_stats |
Heartbeat + terminal session stats (ttft_ms, step latencies, confirm-lag percentiles; final:true ends a success stream) |
listen.controller |
Default-off adaptive cadence/holdback decision with state transition, Brier calibration, observation count, and deterministic-fallback status |
youtube.run_start / youtube.run_complete |
YouTube ingestion request envelope and exactly-one terminal aggregate summary |
youtube.discovered |
Resolved video identity, title, and URL |
youtube.downloading / youtube.downloaded |
Per-video download lifecycle and resulting local audio artifact metadata |
youtube.transcribing / youtube.done |
Per-video native transcription start and written Markdown/JSON artifact summary |
youtube.skipped / youtube.failed |
Explicit terminal disposition for an unprocessed or failed video |
Stage Codes. Each pipeline stage emits paired *.start / *.ok codes (or *.error on failure, *.skip when not needed, *.cancelled on token fire, *.timeout on budget overrun):
ingest.start, ingest.ok, normalize.start, normalize.ok, vad.start, vad.ok, separate.start, separate.ok, backend.start, backend.ok, backend.routing.decision_contract, backend.dropped_windows, acceleration.start, acceleration.ok, align.start, align.ok, punctuate.start, punctuate.ok, diarize.rollout, diarize.start, diarize.ok, persist.start, persist.ok, orchestration.budgets, orchestration.threads_clamped, orchestration.latency_profile
backend.dropped_windows fires when the native engine discards a long-form
decode window without emitting a transcript; the same drop is recorded in
result.raw_output.dropped_windows and in the run's warnings, so a content
gap is never stderr-only.
File transcript previews. Ordinary robot run emits native ASR segments as
decode windows finish. Parallel insanely-fast workers
publish the completed prefix in recording order, preserving word timestamps and
subtitle groups across worker boundaries. Native whisper-diarization emits
unlabeled text before whole-clip speaker assignment; final labels and subtitle
groups arrive in run_complete. Select the existing stage envelope and read the
payload text:
fw robot run --input recording.wav --backend whisper-cpp \
| jq -r 'select(.event == "stage" and .stage == "backend" and .code == "transcript.partial") | .payload.text'
Each preview payload includes text, start_sec, end_sec, confidence,
speaker, zero-based attempt and segment_index, backend, implementation,
and provisional: true. Its run_id, seq, and ts match the outer stage event.
The timestamp includes any requested input offset. If an emitting backend
attempt fails, a transcript.reset stage event identifies its attempt,
discarded_segments, and reason (FW-* error code) before a fallback attempt
can emit text. A display should clear that attempt's previews; append-only text
filters such as the example above are for monitoring, not a final transcript.
Use run_complete for the final postprocessed text and speaker assignments.
These events do not imply speculative decoding, and the plain transcribe
command keeps its final-result output.
Health Report. robot health probes every subsystem and returns a structured diagnostic:
{
"event": "health.report",
"schema_version": "1.1.0",
"ts": "2026-04-25T00:00:00Z",
"backends": [
{"name": "whisper.cpp", "available": false, "path": null, "version": null, "issues": ["whisper.cpp backend not available"]},
{"name": "whisper.cpp-native", "available": true, "path": null, "version": null, "issues": []}
],
"ffmpeg": {"name": "ffmpeg", "available": true, "path": "/usr/bin/ffmpeg", "version": null, "issues": []},
"audio_input": {"probed": false, "available": false, "default_device": null, "device_count": 0, "backend": "cpal", "issues": ["audio input not probed; use `fw robot listen --list-devices` to enumerate hardware"]},
"database": {"name": "database", "available": true, "path": ".franken_whisper/storage.sqlite3", "version": null, "issues": []},
"resources": {"disk_free_bytes": 52341293056, "disk_total_bytes": 270582939648, "memory_available_bytes": 15991492608, "memory_total_bytes": 16876511232},
"overall_status": "ok"
}
runs
Query persisted run history.
franken_whisper runs [--limit 20] [--format plain|json|ndjson] [--id <RUN_ID>]
# Regenerate subtitles and transcripts from a saved run, without inference:
franken_whisper runs --id <RUN_ID> \
--export txt,srt,vtt,json-full --output-prefix ./exports/meeting --format json
| Flag | Default | Description |
|---|---|---|
--limit <N> |
20 | Max recent runs |
--format |
plain |
List/details output or export receipt: plain, json (pretty), ndjson (compact) |
--id <UUID> |
— | Fetch a specific run by ID |
--export <FORMATS> |
— | Comma-separated txt,vtt,srt,csv,json,json-full,lrc; requires --id and --output-prefix |
--output-prefix <PATH> |
— | Artifact destination prefix; parent directories are created |
Stored-result export does not need the original audio, models, or backend. It preserves the saved language, segment timing, materialized speaker labels, and full backend metadata. For live sessions it reads the durable transcript and segments from one database snapshot, including committed text available before session close. Its text includes the still-open utterance's durable delta tail, with exact intra-utterance spacing and no duplication after the utterance closes. In-flight audio or text that has not reached the database is not included. Live speaker updates remain a separate event timeline and are not reconstructed into these exported segments.
The example writes meeting.txt, meeting.srt, meeting.vtt, and
meeting.json_full. Plain output lists the completed paths; JSON and NDJSON
return an object with run_id and artifact_paths. The full JSON artifact records
the new export paths, while the saved run remains unchanged. Export cannot be
combined with --speaker-review. All formats are staged before publication as
described in Output Format Reference; an export
failure returns an error instead of a successful receipt.
When transcription completes but a requested artifact cannot be exported, the pipeline saves its result before returning an error. That error identifies the saved run and database for re-export without repeating inference. Persistence must be enabled and included in the pipeline; otherwise the error states that the result was not persisted. A persistence failure remains the returned error. Export errors also retain the incomplete-transcript recovery payload when ASR completed, so callers can recover public text even without saved history.
sync
One-way JSONL snapshot export / import with distributed lock safety.
# full export to JSONL
franken_whisper sync export-jsonl --output ./snapshot [--db <PATH>] [--state-root <PATH>]
# incremental export: only run aggregates changed since <state-root>/sync_cursor.json,
# plus an explicit deleted-run channel; add --gzip for *.jsonl.gz files
franken_whisper sync export-jsonl --incremental [--gzip] --output ./delta [--state-root <PATH>]
# import with a conflict policy (plain or gzip archives, full or incremental)
franken_whisper sync import-jsonl --input ./snapshot \
--conflict-policy reject|skip|overwrite|overwrite-strict \
[--db <PATH>] [--state-root <PATH>]
# compare a database against a full snapshot without importing (exit 1 on mismatch)
franken_whisper sync validate-jsonl --input ./snapshot [--db <PATH>]
Full exports publish format-2 snapshots: the root manifest.json selects an immutable snapshot-<id>/ directory containing runs.jsonl, segments.jsonl, and events.jsonl. All channels, checksums, and optional gzip compression finish before one atomic manifest replacement makes the new snapshot visible. A failed replacement preserves the previous complete backup. Each retained snapshot has its own standalone manifest and can be imported directly; earlier snapshots and incomplete staging directories are retained, so export history consumes additional disk space. Existing format-1 archives remain readable, and replacing one preserves its exact manifest and verified channel copies before publication. An incremental export keeps the format-1 root layout and also writes deleted_runs.jsonl, declared in the manifest; absence from a partial snapshot never implies deletion. Applying a listed deletion to an existing target run requires --conflict-policy overwrite or overwrite-strict. The default reject policy rolls back the import because a v1 tombstone cannot verify whether the target was changed or recreated; skip preserves that run and reports a conflict. An already-absent run is a no-op under every policy.
Import of a full snapshot automatically runs validate_sync() after the row inserts and reports validation_ok plus per-table count comparison; for an incremental archive it reports archive_mode: "incremental", runs_deleted, and skips the full-snapshot comparison (validation_ok: null).
Use a different --output directory for each incremental delta, retain the archives, and import them in order. Reusing an earlier destination after the source cursor advances fails before changing its files or cursor; a full export also refuses to replace an incremental archive or one declaring deletion records. If gzip fails after its manifest is written, the same directory can be retried while the source cursor still has that archive's starting position. If no usable manifest was published, preserve the partial files and retry into a new directory.
tty-audio
Low-bandwidth audio transport over TTY/PTY links using the mulaw+zlib+b64 NDJSON protocol.
# encode audio to NDJSON frames
franken_whisper tty-audio encode --input audio.wav [--chunk-ms 200]
# decode NDJSON frames to WAV
cat frames.ndjson | franken_whisper tty-audio decode --output restored.wav \
[--recovery fail_closed|skip_missing]
# generate a retransmit plan from a lossy stream
cat frames.ndjson | franken_whisper tty-audio retransmit-plan
# emit individual control frames
franken_whisper tty-audio control handshake
franken_whisper tty-audio control ack --up-to-seq 42
franken_whisper tty-audio control backpressure --remaining-capacity 64
franken_whisper tty-audio control retransmit-request --sequences 1,2,4
franken_whisper tty-audio control retransmit-response --sequences 1,2,4
# automated retransmit loop with strategy escalation
cat frames.ndjson | franken_whisper tty-audio control retransmit-loop --rounds 3
# convenience shorthands
franken_whisper tty-audio send-control handshake|eof|reset
cat frames.ndjson | franken_whisper tty-audio retransmit --rounds 3
Recovery Strategy Escalation. The retransmit loop escalates across rounds:
Simple (1 frame/round) → Redundant (2 frames/round) → Escalate (4 frames/round)
Integrity Checks. Every frame optionally carries CRC32 and SHA-256 hashes of the raw (pre-compression) audio. Mismatches drop the frame (skip_missing) or fail the stream (fail_closed).
Full protocol spec: docs/tty-audio-protocol.md. Determinism guarantees: docs/tty-replay-guarantees.md.
tui
Interactive terminal UI for human operators (feature-gated; build with
--features tui).
# browse persisted runs, transcript timelines, and stage events
franken_whisper tui
# watch a live session: accepts every `robot listen` flag
franken_whisper tui listen --source mic --language en
franken_whisper tui listen --source file-replay --input talk.wav --realtime-pace
Run history (tui):
- Browsable run history with timing and backend info
- Transcript timeline with speaker labels, timestamps, and confidence
- Stage-event pane for the run's NDJSON events
- Focus cycling between panes, paging, live reload from SQLite
Live session (tui listen):
- Runs the same session as
robot listen(identical configuration, persistence, and confirm lane) on a worker thread and renders its event stream; the robot NDJSON contract is unchanged - Append-only committed text per utterance, with the mutable partial tail shown in-place and an open-utterance marker
- Confirm-lane verdicts:
✓confirmed (with drift WER) or✎corrected text shown beneath the fast-lane text — humans see revisions that agents receive as separate events - Warnings pane, session-stats footer (TTFT, step latency, capture overruns)
- Bounded retention (10,000 utterances, oldest-first drain);
q/Ctrl+C cancels the session and waits for its cleanup
Built on the FrankenTUI framework.
Configuration
Environment Variables
| Variable | Default | Description |
|---|---|---|
FRANKEN_WHISPER_WHISPER_CPP_BIN |
whisper-cli |
whisper.cpp binary name or path |
FRANKEN_WHISPER_INSANELY_FAST_BIN |
insanely-fast-whisper |
insanely-fast-whisper entry point |
FRANKEN_WHISPER_PYTHON_BIN |
python3 |
Python interpreter for diarization |
FRANKEN_WHISPER_HF_TOKEN |
— | HuggingFace token (preferred over HF_TOKEN) |
HF_TOKEN |
— | HuggingFace token (fallback) |
FRANKEN_WHISPER_DIARIZATION_DEVICE |
— | GPU device for the diarization backend |
FRANKEN_WHISPER_ACOUSTIC_DIARIZATION_ROLLOUT |
shadow |
Legacy acoustic-only admission control; auto now selects native Sortformer and uses acoustic through the explicit fallback policy |
FRANKEN_WHISPER_STATE_DIR |
.franken_whisper |
State directory root: default database location, sync locks/cursor, per-run work dirs |
FRANKEN_WHISPER_DB |
<state dir>/storage.sqlite3 |
Run-history database used by every command when --db is not given |
FRANKEN_WHISPER_FFMPEG_BIN |
auto | Explicit ffmpeg binary path |
FRANKEN_WHISPER_FFPROBE_BIN |
auto | Explicit ffprobe binary path |
FRANKEN_WHISPER_AUTO_PROVISION_FFMPEG |
1 |
Auto-provision local ffmpeg/ffprobe when missing (0/false disables) |
FRANKEN_WHISPER_FORCE_FFMPEG_NORMALIZE |
0 |
Force normalization through ffmpeg even when the built-in decoder can handle it |
FRANKEN_WHISPER_NATIVE_EXECUTION |
1 |
In-process native dispatch; set 0 only to request legacy bridge execution |
FRANKEN_WHISPER_BRIDGE_NATIVE_RECOVERY |
1 |
In bridge-only mode, allow recoverable bridge failures to fall back to native engines |
FRANKEN_WHISPER_NATIVE_ROLLOUT_STAGE |
sole |
Native engine rollout stage (see below) |
FRANKEN_WHISPER_MODEL_DIR |
~/.cache/franken_whisper/models |
Shared root for native Whisper, Sortformer, auxiliary discovery, and fw pull all; overrides must be absolute |
FRANKEN_WHISPER_STAGE_BUDGET_DIARIZE_MS |
900000 |
Bounded native diarization budget (15 minutes); raise for multi-hour recordings on slower hosts |
XDG_STATE_HOME |
$HOME/.local/state |
Base for auto-provisioned ffmpeg + per-user tool state |
RUST_LOG |
franken_whisper=warn |
tracing filter (e.g. info for per-stage and routing diagnostics, franken_whisper=debug) |
Per-stage budget overrides. Every pipeline stage has an independent millisecond budget overridable via environment variable:
FRANKEN_WHISPER_STAGE_BUDGET_INGEST_MS, …NORMALIZE_MS, …PROBE_MS, …VAD_MS, …SEPARATE_MS, …BACKEND_MS, …ACCELERATION_MS, …ALIGN_MS, …PUNCTUATE_MS, …DIARIZE_MS, …PERSIST_MS, …CLEANUP_MS.
Cargo Features
| Feature | Description |
|---|---|
tui |
Enable the interactive TUI via ftui |
fj-oracle |
Enable the FrankenJAX differential conformance oracle tests; not a production acceleration backend |
No features are enabled by default. FrankenTorch CPU kernels and the macOS-only Metal dependency are target-selected implementation details, not optional features.
Backend Routing
The auto backend retains its adaptive Bayesian family decision contract, but
the default sole rollout executes the selected family through its native Rust
implementation. Bridge commands are opt-in compatibility paths.
Non-diarization priority (deterministic fallback): whisper_cpp → insanely_fast → whisper_diarization
Diarization priority (deterministic fallback): insanely_fast → whisper_diarization → whisper_cpp
Each auto run emits a backend.routing.decision_contract stage event containing explicit state / action / loss / posterior / calibration terms. When the calibration score drops below 0.3, the Brier score exceeds 0.35, or fewer than 5 observations are available, the router falls back to the deterministic priority list above.
Native Engine Rollout
Native Rust engine replacements follow a 5-stage rollout under conformance gating:
| Stage | Behavior |
|---|---|
shadow |
Deterministic bridge execution only; native conformance validated out-of-band |
validated |
Deterministic bridge execution only with stricter conformance gating |
fallback |
Deterministic bridge execution only; fallback policy and evidence paths hardened |
primary |
Native preferred with deterministic bridge fallback |
sole |
Native only (default) |
The execution-path metadata on every backend.ok event and replay envelope records the active stage so post-hoc analysis can correlate output drift with rollout transitions.
auto diarization resolves to the native Sortformer engine. If the verified
package is unavailable, known-speaker intervals require identity mapping, or a
count request exceeds four lanes, the default acoustic policy runs the
bounded Rust acoustic engine. Explicit engine selection remains available.
Every run emits diarize.rollout with the requested and resolved engine,
configuration validity, and fallback evidence.
Native CPU-only Requests
--no-gpu applies to all three native adapters and the native source-separation
and diarization stages. The policy reaches model loading, decoder kernels,
encoder helpers, and nested compute work. CPU-only requests decline the fused
Metal encoder and per-matrix offload before device probing or weight uploads
for that work. Concurrent automatic requests keep their own policy; the engine
does not change process environment variables to enforce a request flag.
Native results expose raw_output.compute_device_policy as auto or
cpu_only. This records permission, while encoder_execution records the
encoder route actually used. A separate machine-capability probe can still
initialize or discover a device outside a request, and earlier automatic runs
may have cached GPU resources.
Library callers can set DecodeParams.no_gpu or use with_compute_policy.
CPU-only permission is inherited and included in transcript-cache identity.
A batch mixing automatic and CPU-only jobs runs those jobs sequentially within
its worker budget. Nested calls cannot relax CPU-only permission. A nested
call that needs another pool while its current run holds an encoder policy
pin returns an error instead of waiting on a lock its caller cannot release.
Architecture
+------------------------------------+
| CLI / Robot |
| (clap + NDJSON emit) |
+------------------------------------+
|
+-----------------v------------------+
| FrankenWhisperEngine |
| (orchestrator.rs) |
| |
| 10-Stage Composable Pipeline: |
| 1. Ingest |
| 2. Normalize |
| 3. VAD |
| 4. Source Separate |
| 5. Backend Execution |
| 6. Confidence normalization |
| 7. Alignment |
| 8. Punctuation |
| 9. Diarization |
| 10. Persist |
+------------------------------------+
| | |
+------------------+ +----------+ +------------------+
| Backends | | Compute | | Storage |
| | | | | |
| whisper.cpp | | Franken- | | fsqlite (WAL) |
| insanely-fast | | Torch | | |
| whisper-diar | | CPU / | | JSONL export |
| + paired native | | Metal | | replay packs |
+------------------+ +----------+ +------------------+
+------------------+ +------------------+ +------------------+
| TTY Audio | | Conformance | | Replay |
| | | | | |
| mulaw + zlib | | 50 ms tolerance | | SHA-256 envelope |
| + base64 NDJSON | | cross-engine | | + 4-artifact pack|
| handshake / FEC | | comparator | | drift detection |
+------------------+ +------------------+ +------------------+
Data Flow
- Ingest: materialize input from file, stdin, or mic capture
- Normalize: convert to 16 kHz mono WAV via the built-in Rust decoder (
ffmpegfallback for video and exotic formats) - VAD (optional): Voice Activity Detection skips silence
- Source Separate (optional): vocal isolation for cleaner transcription
- Backend: dispatch to the selected engine (adaptive routing or explicit)
- Accelerate (optional): bounded, numerically stable confidence normalization
- Alignment (optional): forced alignment for word-level timestamps
- Punctuation (optional): punctuation restoration
- Diarization (optional): speaker identification and labeling
- Persist: write run report, segments, and events to SQLite
Every stage emits *.start and *.ok events to the NDJSON stream with sequence numbers, RFC-3339 timestamps, and structured payloads. Skipped stages emit *.skip so agents can distinguish "not needed" from "failed."
Technical Details
Bayesian Backend Router
When --backend auto is selected, franken_whisper runs a formal Bayesian decision contract rather than trying backends in a fixed order.
State Space (3 states):
all_available: all three backends found on PATH and responsivepartial_available: 1–2 backends operationalnone_available: nothing usable
Action Space (4 actions):
try_whisper_cpp,try_insanely_fast,try_diarization(reordered per request based on--diarize)fallback_error: return a structured error when nothing is available
Loss Matrix. The router builds a 3×4 loss matrix (states × actions). Each cell aggregates three weighted factors:
cost = (0.45 × latency_cost) + (0.35 × quality_cost) + (0.20 × failure_cost)
- Latency cost scales with audio duration (short / medium / long buckets) and a per-backend latency proxy
- Quality cost depends on backend capability relative to the request (diarization support, GPU availability)
- Failure cost is
(1.0 − p_success) × 100, wherep_successcomes from the Bayesian posterior
Bayesian Posterior. Each backend starts with a Beta prior reflecting expected reliability:
| Backend | Prior | Prior mean |
|---|---|---|
whisper_cpp |
Beta(7, 3) |
0.70 |
insanely_fast |
Beta(6, 4) |
0.60 |
whisper_diarization |
Beta(5, 5) |
0.50 |
After each run the posterior is updated with the observed outcome (success / failure).
Latency Proxy Model. Backend latency is estimated as a function of audio duration:
latency_cost = base + (sqrt(audio_duration_seconds) × multiplier)
| Backend | Base (s) | Multiplier (normal) | Multiplier (diarize) |
|---|---|---|---|
whisper_cpp |
12.0 | 1.0 | 1.25 |
insanely_fast |
8.0 | 1.0 | 1.25 |
whisper_diarization |
18.0 | 1.0 | 1.25 |
When at least 5 empirical observations are available the estimate blends prior and empirical:
(0.6 × prior_latency) + (0.4 × empirical_latency).
Quality Proxy Model. Each backend has a quality score that varies with whether diarization is requested:
| Backend | Quality (normal) | Quality (diarize) |
|---|---|---|
whisper_cpp |
0.84 | 0.55 |
insanely_fast |
0.80 | 0.82 |
whisper_diarization |
0.63 | 0.88 |
p_success = (α + quality_score × 2.0 + diarize_boost) / (α + β + quality_terms + penalty_terms).
A backend with a strong empirical track record can still be penalized when it lacks a capability the request needs (for example, whisper_cpp receiving a diarization request).
Availability Penalties. The loss matrix applies sharp penalties when backends are unavailable, dominating the loss calculation so the router never selects an unavailable backend even if its quality/latency profile is attractive.
Policy Versioning. The routing policy carries an identifier (backend-selection-v1.0). Every evidence-ledger entry includes a loss_matrix_hash so post-hoc analysis can detect when the policy weights themselves changed between runs.
Calibration & Fallback. The router tracks a sliding window of 50 prediction-outcome pairs and computes a Brier score. It falls back to deterministic static priority when any of these hold:
- fewer than 5 observations (insufficient data),
- calibration score < 0.3 (posterior margin too narrow),
- Brier score > 0.35 (predictions don't match reality).
The fallback path still records the adaptive prediction it would have made so calibration data continues accumulating even when the static policy is driving the routing. Once calibration improves, the system can recover automatically.
Evidence Ledger. Every routing decision is recorded in a circular buffer (capacity: 200 entries) containing the decision ID, trace ID, observed state, chosen action, posterior snapshot, calibration metrics, and fallback flag. Queryable via robot routing-history.
Pipeline Stage Budgets
Each stage runs under an independent millisecond budget. Defaults:
| Stage / Knob | Budget | Rationale |
|---|---|---|
| Ingest | 15 s | File I/O or mic capture |
| Normalize | 180 s | Audio decode + resample |
| VAD | 10 s | Lightweight energy detection |
| Source Separate | 30 s | Demucs-style vocal isolation |
| Backend | 900 s (15 min) | Full inference (long audio on CPU) |
| Acceleration | 20 s | CPU confidence mass normalization |
| Align | 30 s | CTC forced alignment |
| Punctuate | 10 s | Punctuation model inference |
| Diarize | 900 s (15 min) | Speaker diarization (native Sortformer / acoustic) |
| Persist | 20 s | SQLite transaction |
| Probe (internal) | 8 s | Backend / ffmpeg / database probing before pipeline starts |
| Cleanup (internal) | 5 s | Finalizer total budget |
All 12 budgets are overridable via FRANKEN_WHISPER_STAGE_BUDGET_<NAME>_MS. For example, FRANKEN_WHISPER_STAGE_BUDGET_BACKEND_MS=1800000 extends the backend stage to 30 minutes. Probe and Cleanup are tunable knobs without user-visible PipelineStage enum variants; they govern pre-pipeline health checks and post-pipeline finalizer execution respectively.
Automatic Latency Profiling. After each run, the orchestrator emits an orchestration.latency_profile stage event with per-stage timing decomposition. Each stage gets a utilization ratio (service_ms / budget_ms) and a tuning recommendation:
| Utilization | Recommendation |
|---|---|
| ≤ 30% | decrease_budget_candidate |
| 30–90% | keep_budget |
| ≥ 90% | increase_budget (suggest 1.25× current) |
Replay Envelopes & Drift Detection
Every completed run produces a ReplayEnvelope containing SHA-256 hashes:
+-------------------------------------------------+
| ReplayEnvelope |
+-------------------------------------------------+
| input_content_hash: SHA-256(normalized WAV) |
| backend_identity: "whisper-cli-v1.7.2" |
| backend_version: "1.7.2" |
| output_payload_hash: SHA-256(raw backend JSON) |
| native_rollout_stage: "sole" | … |
+-------------------------------------------------+
Given identical input audio and the same backend version, the output hash should be identical. If it changes between runs, something drifted; the conformance harness can pinpoint whether the drift came from the backend, the native engine rollout, or audio normalization.
Replay Packs
Self-contained replay packs capture everything needed to reproduce and analyze a run:
replay_pack/
env.json # EnvSnapshot: OS, arch, backend identity/version, fw version
manifest.json # PackManifest: trace_id, run_id, timestamps, content hashes
repro.lock # ReproLock: routing evidence, replay envelope, request params
tolerance_manifest.json # ToleranceManifest: schema version, timestamp tolerance
| File | Struct | Contents |
|---|---|---|
env.json |
EnvSnapshot |
OS, architecture, backend identity/version, franken_whisper version (compile-time CARGO_PKG_VERSION) |
manifest.json |
PackManifest |
trace_id, run_id, start/finish timestamps, input/output SHA-256 hashes, segment/event/evidence counts |
repro.lock |
ReproLock |
Routing evidence chain, frozen replay envelope, original backend request, diarize flag |
tolerance_manifest.json |
ToleranceManifest |
Schema version (tolerance-manifest-v2), timestamp tolerance, text/speaker exactness flags, optional validated native rollout stage, segment/event counts |
All four files are deterministic for the same RunReport and runtime environment. env.json deliberately records OS and architecture, so packs created on different platforms are expected to differ there; unexplained differences on the same runtime indicate pipeline or provenance drift.
Conformance Harness
The conformance module enforces cross-engine compatibility using a single canonical timestamp tolerance: CANONICAL_TIMESTAMP_TOLERANCE_SEC = 0.05 (50 ms). Segment comparison counts violations:
| Violation Type | Condition |
|---|---|
| Text mismatch | Segment text differs at the same index |
| Speaker mismatch | Speaker label differs (optional check) |
| Timestamp violation | start / end differs by > 50 ms |
| Length mismatch | Different segment counts |
Plus overlap detection (epsilon = 1 µs default), WER approximation (Levenshtein-based), and segment invariant validation: finite timestamps, non-negative values, start ≤ end, confidence in [0.0, 1.0], non-empty text.
The conformance corpus in tests/fixtures/conformance/ covers timestamp boundaries, speaker labels, text trimming, empty segments, overlapping speakers, unicode speaker labels, non-finite invariants, very long segments (15 min), word-level boundary cases, multilingual / code-switching / noisy-overlap audio, and replay envelope drift (input_hash_drift, output_drift, backend_identity_drift, backend_version_upgrade, …). The mapping from spec clauses to tests lives in tests/COVERAGE.md.
Speculative Streaming Architecture
Dual-model streaming for real-time transcription with quality corrections:
Audio Stream
|
+---> WindowManager (sliding windows with overlap)
| |
| +---> Fast Model ---> PartialTranscript (status: Pending)
| | |
| | v emit transcript.partial event
| |
| +---> Quality Model ---> CorrectionDrift analysis
| |
| +- drift below tolerance ---> transcript.confirm
| +- drift above tolerance ---> transcript.retract + corrected text
|
+---> CorrectionTracker (adaptive thresholds)
The CorrectionTracker maintains running drift statistics and adaptively tightens or relaxes confirmation thresholds.
Audio Normalization Pipeline
Input audio is normalized to 16 kHz mono 16-bit PCM WAV:
Input file (any format)
|
+-> Built-in Rust decoder (PRIMARY)
| symphonia: MP3, AAC, FLAC, WAV, OGG, Vorbis, ALAC, PCM variants
| Resampler: linear interpolation to 16 kHz
| Channel mixer: stereo/surround -> mono by sample averaging (using actual frame length)
| Output: normalized_16k_mono.wav (PCM S16LE)
|
+-> ffmpeg subprocess (FALLBACK; only if built-in decoder fails)
Triggered for: video files, exotic codecs (AC3, DTS, Opus-in-MKV, etc.)
Args: -hide_banner -loglevel error -y -i <input> -vn -ar 16000 -ac 1 -c:a pcm_s16le <output>
ffmpeg fallback chain:
- Explicit binary path (
FRANKEN_WHISPER_FFMPEG_BIN) - System-installed
ffmpegonPATH - Auto-provisioned local binary (Linux x86_64)
- If all fail:
FW-CMD-MISSINGerror with an actionable message
Set FRANKEN_WHISPER_FORCE_FFMPEG_NORMALIZE=1 to bypass the built-in decoder and always use ffmpeg.
Storage Internals
The storage layer uses fsqlite (from the FrankenSQLite project) with three
canonical run tables, four derived diarization index tables, and a key-value
metadata table. The schema is at version 5 at HEAD.
runs (id PK, started_at, finished_at, backend, input_path,
normalized_wav_path, request_json, result_json,
warnings_json, transcript, replay_json, acceleration_json)
-- all columns NOT NULL; replay_json + acceleration_json default to '{}'
segments (run_id, idx, start_sec, end_sec, speaker, text, confidence,
PRIMARY KEY (run_id, idx))
events (run_id, seq, ts_rfc3339, stage, code, message, payload_json,
PRIMARY KEY (run_id, seq))
diarization_reports (run_id PK, implementation, contract_version, ...)
diarization_turns (run_id, idx, start_ms, end_ms, speaker_ref, ...)
speaker_hints (run_id, idx, speaker_ref, start_ms, end_ms, ...)
speaker_profile_summaries (run_id, idx, speaker_ref, reliability, ...)
-- deterministic indexes rebuilt from runs.request_json/result_json
sync_run_mutations (mutation_seq INTEGER PK AUTOINCREMENT,
run_id TEXT NOT NULL UNIQUE)
-- bounded database-owned high-water mark for incremental export
_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)
-- holds 'schema_version' => '6' and a stable sync database identity
Schema Migrations. When opening older databases, the storage layer walks forward through the migration ladder:
- v1 → v2: add
runs.replay_jsonandruns.acceleration_json(defaulting to'{}'). - v2 → v3: create indexes on hot query paths (recent-runs listing, per-run segment / event lookup) for faster
robot healthandrunsqueries. - v3 → v4: add privacy-safe normalized diarization indexes and rebuild them from canonical typed request/result JSON.
- v4 → v5: add typed speaker-count status/outcome and per-hint evidence columns, then rebuild the derived index from canonical run JSON.
- v5 → v6: add a stable sync database identity plus the bounded per-run mutation sequence and parent/child triggers used by lossless incremental export; existing runs are backfilled.
The legacy column-add migration runs safely:
- Query current journal mode (
PRAGMA journal_mode;) - Switch from WAL to DELETE for DDL reliability
- Execute
ALTER TABLE ... ADD COLUMN - Restore WAL mode
- If the migration fails, log a contextual error and leave the database untouched
For severely corrupted databases the recovery path is JSONL-based: export from a known-good source, create a fresh database, import via sync import-jsonl.
Atomic Persistence with Retry. All inserts are wrapped in a single transaction with up to 8 retry attempts on SQLITE_BUSY, using linear backoff of 5 × (attempt + 1) ms (so 5, 10, 15, …, 40 ms across the retry budget; ~180 ms total worst case). The cancellation token is checked before each COMMIT.
Cancellation-Safe Writes. The token-checkpoint pattern ensures no partial data reaches the database:
SAVEPOINT fw_persist_N
INSERT INTO runs ...
INSERT INTO segments ... (N rows)
INSERT INTO events ... (M rows)
token.checkpoint()? -- rolls back if cancelled
RELEASE SAVEPOINT fw_persist_N
If the token fires between inserts, the savepoint rolls back cleanly. If the process is killed during RELEASE, SQLite's journal recovery handles it on next open. Savepoints (not top-level transactions) let concurrent sessions nest persist calls without deadlocking.
Concurrent Session Support. Multiple agents can persist in parallel through RunStore::begin_concurrent_session("agent_alpha"), which acquires a named savepoint (fw_session_{name}). Session names are validated to be [A-Za-z0-9_] only, so no SQL injection via session names is possible.
WAL Mode & Storage Configuration:
PRAGMA |
Value | Purpose |
|---|---|---|
journal_mode |
WAL |
Write-Ahead Logging for concurrent readers |
busy_timeout |
5000 (5 s) |
Wait for locks before returning SQLITE_BUSY |
Storage Diagnostics. StorageDiagnostics exposes:
| Field | Description |
|---|---|
page_count |
Total database pages |
page_size |
Bytes per page (typically 4096) |
journal_mode |
Current mode (wal, delete) |
wal_checkpoint |
WAL status: busy flag, log frames, checkpointed frames |
freelist_count |
Unused pages available for reuse |
integrity_check |
"ok" when the database passes PRAGMA integrity_check |
Accessible via robot health, which includes database diagnostics in the health report.
Backend Bridge Adapters
Each backend has a bridge adapter that spawns an external process and parses its output. Adapters normalize diverse output formats into a uniform TranscriptionResult.
whisper.cpp Bridge. Spawns whisper-cli (or FRANKEN_WHISPER_WHISPER_CPP_BIN) and parses the JSON output file, handling multiple layouts (transcription, segments, chunks) and extracting word-level timestamps from nested words arrays when requested.
insanely-fast-whisper Bridge. Spawns insanely-fast-whisper (or FRANKEN_WHISPER_INSANELY_FAST_BIN). Shares JSON segment extraction with the whisper.cpp bridge. Falls back to joining segment texts if the root "text" key is missing.
whisper-diarization Bridge. Spawns a Python script via python3 (or FRANKEN_WHISPER_PYTHON_BIN). Parses two output files: a .txt file with the full transcript and a .srt file with speaker-labeled subtitles. The SRT parser handles both comma- and dot-separated timing, and recognizes speaker patterns [SPEAKER_00], SPEAKER_00:, spk0:, s0:. Each bridge invocation logs through render_command_for_log(), which redacts --hf-token values so the HuggingFace token never appears in tracing output.
Native Engine Rollout Governance
Native Rust replacements for the bridge adapters ship behind a 5-stage rollout with conformance gating at every promotion. This prevents a buggy native engine from silently degrading transcription quality.
Rollout Stages:
Shadow → Validated → Fallback → Primary → Sole
| | | | |
| | | | +-- Native only, bridge removed
| | | +-- Native preferred, bridge fallback on error
| | +-- Bridge preferred, native fallback hardened
| +-- Bridge only, stricter conformance gating
+-- Bridge only, native conformance validated out-of-band
Conformance Gate. At each stage transition the harness compares native vs. bridge output on a fixture corpus. A native engine that produces timestamps > 50 ms different from the bridge adapter for the same audio is blocked from promotion. The harness also validates backend version drift, replay envelope drift, and segment invariants.
Segment Validation Rules.
- Timestamps must be finite (no NaN, no infinity)
start_secandend_secmust be non-negativestart ≤ end- No overlapping segments (configurable epsilon: 1 µs default)
- Confidence scores in
[0.0, 1.0] - Text non-empty
Runtime Control. Two environment variables jointly control native engine behavior:
FRANKEN_WHISPER_NATIVE_ROLLOUT_STAGE: which stage the deployment is atFRANKEN_WHISPER_NATIVE_EXECUTION: whether native dispatch is enabled at runtime (0/1)
Both default to native-only execution (1 and sole). Setting the execution
flag to 0 requests bridge-only compatibility behavior; selecting an earlier
rollout stage also changes the bridge/native policy explicitly.
Execution Path Metadata. Every backend.ok event and replay envelope includes explicit execution-path metadata: implementation (bridge / native), execution_mode, native_rollout_stage, and native_fallback_error (populated when native fails and bridge recovers). The contract is documented in docs/native_engine_contract.md.
Run Report Structure
Every transcription produces a RunReport, the complete record of what happened:
RunReport
run_id: "fw-run-abc123"
trace_id: "1710000000000-random64"
started_at_rfc3339: "2026-04-25T06:00:00Z"
finished_at_rfc3339: "2026-04-25T06:00:05Z"
input_path: "/path/to/audio.mp3"
normalized_wav_path: "/tmp/normalized_16k_mono.wav"
request: TranscribeRequest { ... } -- full input parameters
result: TranscriptionResult { ... } -- backend output
transcript: "Hello world..."
segments: [TranscriptionSegment { ... }] -- timed chunks
language: Some("en")
acceleration: AccelerationReport { ... } -- confidence normalization metadata
events: [RunEvent { ... }] -- pipeline stage events (sequenced)
warnings: ["..."] -- non-fatal issues
evidence: [Value { ... }] -- routing decision evidence
replay: ReplayEnvelope { ... } -- SHA-256 hashes for deterministic replay
The report is persisted to SQLite (split across runs, segments, and events) and optionally emitted as JSON via --json or as streaming NDJSON events in robot mode.
Robot Event Streaming Architecture
In robot mode the pipeline emits events in real time via an mpsc channel:
+-------------------+
| CLI (main.rs) |
| |
| event_rx poll |<--+
| (every 40 ms) | |
+-------------------+ |
| | mpsc channel
v |
+-------------------+ |
| stdout (NDJSON) | | StreamedRunEvent { run_id, event }
| one line per | |
| event | |
+-------------------+ |
|
+-------------------+ |
| Pipeline Worker |---+
| (background |
| thread) |
+-------------------+
The CLI thread polls the receive end of the channel every 40 ms, formatting each event as a single NDJSON line on stdout. The pipeline worker thread runs transcribe_with_stream() which emits StreamedRunEvent wrappers containing (run_id, RunEvent) pairs. When the worker completes, the CLI emits a final run_complete or run_error event (in batch mode each input ends that way and the stream's last event is batch.complete). If the worker thread itself panics, the CLI emits a structured run_error envelope on stdout (the panic message goes to stderr). The shipped release binary enables unwinding so these recovery boundaries remain active; the CLI rejects aborting builds at compile time.
Schema Contract Guarantees:
| Guarantee | Enforcement |
|---|---|
event and schema_version present on every event |
Hardcoded in all emit_* functions |
seq strictly increasing per run |
Auto-incremented from events.len() |
ts non-decreasing per run |
Generated from Utc::now().to_rfc3339() |
run_complete is always the final success event |
Emitted only after pipeline returns |
| Stage events follow pipeline order | Orchestrator executes stages sequentially |
Worker-thread panics emit run_error, including release builds |
emit_robot_error_from_fw wraps panic recovery; the CLI requires unwinding |
TTY Handshake Protocol
The TTY audio protocol begins with version and codec negotiation before any audio flows:
Encoder Decoder
| |
|-- Handshake { |
| min_version: 1, |
| max_version: 2, |
| supported_codecs: ["mulaw+zlib+b64"] |
| } --------------------------------------> |
| |
| <--------------------------------------- |
| HandshakeAck { |
| negotiated_version: 1, |
| negotiated_codec: "mulaw+zlib+b64" |
| } |
| |
|-- AudioFrame { seq: 0, ... } ------------> |
|-- AudioFrame { seq: 1, ... } ------------> |
| ... |
|-- SessionClose { last_data_seq: N } -----> |
| |
| <--- Ack { up_to_seq: N } |
Version Negotiation. The encoder advertises a supported range (currently 1–2). The decoder picks the highest version both support. If ranges don't overlap, the handshake fails.
Codec Negotiation. Currently "mulaw+zlib+b64" is the only defined codec. The protocol is extensible; future codecs (for example opus+b64) can be added by extending the supported_codecs array.
Session Close. The encoder sends SessionClose { reason, last_data_seq } to signal end of stream. The decoder verifies it has received all frames up to last_data_seq. Missing frames trigger the retransmit protocol; sequence gaps detected at finalize raise an explicit error rather than truncating silently.
Retransmit Loop Determinism
The retransmit system is designed to be fully deterministic for testing and debugging:
- Given the same frame buffer and the same loss pattern, the output and report are byte-identical across runs.
- No timing dependencies;
timeout_msis advisory (used for reporting) with no actual sleeps or waits. - Frame recovery proceeds in sequence-number order (not arrival order).
- Strategy escalation follows a fixed chain:
Simple → Redundant → Escalate. inject_loss()resets all prior recovery state, ensuring clean separation between test scenarios.
This determinism supports fuzz testing of the retransmit protocol without timing-dependent expectations.
ffmpeg Auto-Provisioning
When ffmpeg is needed but not installed, franken_whisper can automatically download a static binary (Linux x86_64 only):
Source: https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-amd64-static.tar.xz
Flow:
- Check
FRANKEN_WHISPER_AUTO_PROVISION_FFMPEG(default:1/ enabled) - Check if a provisioned binary already exists at
{state_root}/tools/ffmpeg/bin/ffmpeg - If missing: download via
curl -fsSLorwget --quiet(whichever is available) - Extract from
.tar.xzviatar -xfinto a tmpdir - Copy
ffmpegandffprobeto{state_root}/tools/ffmpeg/bin/ - Set executable permissions (
chmod 755) - Verify the extracted binaries are executable
Safeguards:
- 180-second download timeout, with the active ingest or normalization token also able to interrupt download, archive inspection, and extraction
- Downloads use a temporary file and enter the archive cache only after a successful transfer and cancellation check; interrupted transfers can be retried without treating a partial archive as complete
- Extraction uses a temporary directory. Ordinary provisioning failures log a warning and permit the built-in Rust decoder's fallback; cancellation and stage timeouts retain their error classification and stop the operation
- Honors
XDG_STATE_HOMEfor the install root - Disable entirely with
FRANKEN_WHISPER_AUTO_PROVISION_FFMPEG=0 - Non-Linux / non-x86_64 platforms get an actionable error explaining how to install ffmpeg manually
Graceful Shutdown
Ctrl+C
|
v
ctrlc handler
| sets AtomicBool (SeqCst)
v
CancellationToken.checkpoint()
| returns Err(Cancelled) at next checkpoint
v
Pipeline stage catches Cancelled
| rolls back any in-progress transaction (savepoint)
| cleans up temp files via finalizers
| kills active subprocesses
v
CLI exits with code 130 (128 + SIGINT)
The cancellation token is threaded through every pipeline stage, including the inner extraction loops in word-level timestamp processing, so an in-flight backend can be interrupted between checkpoints rather than after the entire backend invocation completes.
Batch stdin ingestion on Linux, Android, and Apple targets also checks for cancellation while its upstream pipe remains open without sending bytes. It preserves raw input and buffered stdin bytes, drains the final bytes before EOF, and restores the descriptor's original blocking mode on completion or failure. Other targets retain checkpoints between ordinary reads. Microphone capture uses the same cancellable subprocess supervision as inference, including first-use ffmpeg provisioning. Named ingest and normalization deadlines report stage timeouts; an earlier pipeline deadline or explicit cancellation remains a cancellation error.
Normalization keeps cancellation checkpoints through equal-rate copies,
resampling, and WAV output, preserving the existing arithmetic and completed
WAV bytes. Duration probing and the replay-envelope input hash finish within
the same supervised normalization stage. Cancellation or timeout during those
steps stops the stage before normalize.ok; ordinary unavailable metadata or
hash I/O errors retain their existing best-effort behavior.
Error Codes
| Code | Meaning |
|---|---|
FW-IO |
I/O error (file not found, permission denied) |
FW-JSON |
JSON serialization / deserialization failure |
FW-CMD-MISSING |
Required external binary not found on PATH |
FW-CMD-FAILED |
Backend subprocess exited with non-zero status |
FW-CMD-TIMEOUT |
Backend subprocess exceeded timeout |
FW-BACKEND-UNAVAILABLE |
No suitable backend found for the request |
FW-INVALID-REQUEST |
Malformed or contradictory request parameters |
FW-CONTRACT-VIOLATION |
An in-process producer violated a runtime contract |
FW-STORAGE |
SQLite persistence error |
FW-UNSUPPORTED |
Requested feature not available |
FW-MISSING-ARTIFACT |
Expected output file not produced by backend |
FW-CANCELLED |
Operation cancelled via token or Ctrl+C |
FW-STAGE-TIMEOUT |
Pipeline stage exceeded its budget |
FW-BATCH-INCOMPLETE |
A batch finished but at least one input failed (exit 1; each failed input carries its own code) |
Robot Error Contract. Public robot run_error envelopes expose the same
variant-specific codes as FwError::error_code(); agents do not need to
reverse-map a coarse error family. A batch never ends in a run_error for
FW-BATCH-INCOMPLETE: it ends with batch.complete (status: incomplete,
code: FW-BATCH-INCOMPLETE). Even Clap-level syntax failures produce one
path-safe FW-INVALID-REQUEST JSON object on stdout and exit with usage code
2. Semantically invalid requests emit run_start followed by the exact
terminal error. There is no robot path that degrades to human-readable stderr.
Engine Trait & Backend Capabilities
Every backend (bridge or native) implements the Engine trait:
pub trait Engine: Send + Sync {
fn name(&self) -> &'static str; // "whisper.cpp", "insanely-fast-whisper", etc.
fn kind(&self) -> BackendKind; // WhisperCpp, InsanelyFast, WhisperDiarization
fn capabilities(&self) -> EngineCapabilities;
fn is_available(&self) -> bool; // PATH probe via `which` crate
fn run(
&self,
request: &TranscribeRequest,
normalized_wav: &Path,
work_dir: &Path,
timeout: Duration,
) -> FwResult<TranscriptionResult>;
}
EngineCapabilities describe what each backend supports:
| Capability | whisper.cpp | insanely-fast | whisper-diarization |
|---|---|---|---|
supports_diarization |
false (TinyDiarize exists separately) | true (with HF token) | true |
supports_translation |
true | true | false |
supports_word_timestamps |
true | true | false |
supports_gpu |
true (CUDA / Metal) | true (CUDA / MPS) | true (CUDA) |
supports_streaming |
false | false | false |
These capabilities feed the Bayesian router's quality proxy: a backend that doesn't support a requested feature gets a lower quality score for that request.
Backend Availability Probing. Availability is checked via the which crate; each backend can be overridden with an environment variable, in which case the override path is checked directly.
Subprocess Execution & Cancellation
The process module provides three execution modes with increasing safety guarantees:
run_command (fire and forget with captured output):
Spawn child → wait → return (stdout, stderr, exit_status)
run_command_with_timeout (bounded execution):
Spawn child → poll exit every 50 ms → if timeout: kill + return TimeoutError
run_command_cancellable (full cooperative cancellation):
Spawn child
loop:
poll child.try_wait()
if exited: return output
token.checkpoint()? -- if cancelled: kill child, return Err(Cancelled)
sleep 50 ms
hard_timeout safety net: kill child regardless
The 50 ms poll interval bounds cancellation response time. The child process receives SIGKILL (not SIGTERM), ensuring immediate termination of backends that may be doing heavy GPU inference. Stdout and stderr are drained on dedicated threads to prevent pipe deadlock when subprocesses produce large output.
Secret Redaction. Command lines are routed through render_command_for_log() before being emitted into traces. The renderer redacts known secret-bearing flag values, most notably --hf-token for the diarization bridge, so HuggingFace tokens never appear in tracing output, log files, or test snapshots.
Mu-Law Audio Encoding
The TTY audio codec uses mu-law compression, a standard telephony algorithm that compresses 16-bit PCM to 8-bit with logarithmic companding. The actual transcoding is delegated to ffmpeg (-f mulaw -ar 8000 -ac 1) so the codec implementation isn't carried in the Rust source. franken_whisper instead handles framing, sequencing, integrity checks, base64 encoding, and zlib compression on top of the mu-law byte stream.
The codec definition itself is well-known and useful to understand for debugging wire traces:
Encoding (linear PCM → mu-law):
1. Input: 16-bit signed integer sample
2. Clamp to [-32635, 32635] (mu-law representable range)
3. Add bias: sample = |sample| + 132
4. Find segment: position of highest set bit (determines compression curve)
5. Extract mantissa: 4 bits from the segment position
6. Combine: segment (3 bits) + mantissa (4 bits) + sign (1 bit) = 8 bits
7. Invert all bits (wire format convention)
Decoding (mu-law → linear PCM):
1. Invert all bits
2. Extract sign, segment, mantissa
3. Reconstruct: ((mantissa << 3) + bias) << (segment + 1) - bias
4. Apply sign
This achieves ~2:1 compression (16-bit → 8-bit) while preserving speech intelligibility. The full pipeline:
Raw PCM (16-bit) → mu-law (8-bit) → zlib compress → base64 encode → NDJSON line
The inverse pipeline runs on decode. CRC32 and SHA-256 integrity hashes are computed on the raw (pre-compression) audio bytes, so corruption at any stage is detected.
TTY Audio Wire Format
Each audio frame is a single NDJSON line:
{
"protocol_version": 1,
"seq": 42,
"codec": "mulaw+zlib+b64",
"sample_rate_hz": 16000,
"channels": 1,
"payload_b64": "eJztwTEBAAAAwqD1T20ND...",
"crc32": 3141592653,
"payload_sha256": "a1b2c3d4e5f6..."
}
| Field | Type | Required | Description |
|---|---|---|---|
protocol_version |
u32 | yes | Protocol version (1 = audio, 2 = audio + transcript control) |
seq |
u64 | yes | Strictly increasing sequence number |
codec |
string | yes | Compression codec identifier |
sample_rate_hz |
u32 | yes | Mu-law audio sample rate (8000 — telephony standard for mu-law) |
channels |
u8 | yes | Channel count (always 1 for mono) |
payload_b64 |
string | yes | Base64-encoded compressed audio data |
crc32 |
u32 | optional | CRC32 of raw (pre-compression) audio bytes |
payload_sha256 |
string | optional | SHA-256 hex digest of raw audio bytes |
Control frames use the same NDJSON line format but with a "type" field instead of "seq":
{"type":"handshake","min_version":1,"max_version":2,"supported_codecs":["mulaw+zlib+b64"]}
{"type":"ack","up_to_seq":42}
{"type":"backpressure","remaining_capacity":64}
{"type":"session_close","reason":"complete","last_data_seq":100}
TTY Audio: Adaptive Bitrate & FEC
The AdaptiveBitrateController monitors link quality in real time and adjusts compression dynamically:
| Frame Loss Rate | Link Quality | Compression | Critical Frame FEC |
|---|---|---|---|
| < 1% | High | zlib level 1 (fast) | 1× (no duplication) |
| 1% – 10% | Moderate | zlib level 6 (default) | 2× |
| > 10% | Poor | zlib level 9 (best) | 3× |
Critical Frame FEC. Control frames essential for protocol correctness (handshake, session_close, ack) are emitted multiple times based on current link quality. Under 10% loss, every handshake frame is transmitted 3× to ensure at least one copy arrives. With independent frame loss at rate p, the probability all k copies are lost is p^k.
Link Quality Assessment.
frame_loss_rate = frames_lost / frames_sent
link_quality = 1.0 - frame_loss_rate
Quality transitions trigger compression changes on subsequent frames; this gives automatic adaptation without manual tuning.
Transcript Streaming over TTY (Protocol v2, library-level). Beyond raw audio, the TTY protocol defines three transcript control frame types. The library can emit and parse them (tty_audio::emit_tty_transcript_*), but no CLI command currently produces them from a live or speculative run, and handshakes still negotiate protocol v1:
| Frame Type | Direction | Purpose |
|---|---|---|
TranscriptPartial |
sender → receiver | Speculative partial transcript from fast model |
TranscriptRetract |
sender → receiver | Retract a previous partial (quality model disagrees) |
TranscriptCorrect |
sender → receiver | Send corrected transcript from quality model |
These frames carry TranscriptSegmentCompact payloads, a wire-efficient representation with single-letter field names (s / e / t / sp / c for start / end / text / speaker / confidence) to minimize bandwidth.
Telemetry Counters. The decode path tracks:
frames_decoded: successfully decoded audio framesgaps: sequence number discontinuities (with expected / actual pairs)duplicates: repeated sequence numbers (second copy discarded)integrity_failures: CRC32 / SHA-256 mismatches (frame dropped)dropped_frames: total frames discarded due to policy (integrity + duplicates)
Confidence Normalization (Acceleration)
The acceleration stage normalizes per-segment confidence scores into a proper probability distribution. Raw backend confidences are uncalibrated and incomparable across engines, so normalization is necessary for meaningful cross-backend analysis.
Algorithm:
- Extract confidence values from all segments
- Replace missing / invalid values (NaN, infinity, zero, negative) with a text-length-based baseline:
ln(1 + char_count) + 1.0 - Compute pre-mass:
sum(confidences)before normalization - Divide each positive finite value by the positive finite mass
- Compute post-mass:
sum(normalized)(should equal 1.0) - Record both masses in
AccelerationReportfor validation
Mass normalization (CPU path):
mass = sum(positive finite values)
safe[i] = value[i] if value[i] is positive and finite, otherwise 0
output[i] = safe[i] / mass -- normalize to sum = 1.0
Non-finite values (NaN, infinity) map to 0.0 in the output. If the sum is near zero (all values degenerate), the result falls back to a uniform distribution 1/N. The layer_norm_cpu helper clamps its epsilon floor to a safe minimum to prevent division by zero on pathological inputs.
segments[].confidence is therefore a share of the run's total, not a
per-segment probability. When native whisper.cpp diarization collapses its
temporary word units into speaker-split segments, normalization runs again
using the regrouped backend confidences and each final segment's text-length
fallback weight. The final shares sum to 1, and acceleration.input_values,
pre_mass, and post_mass describe those final segments. The earlier
acceleration.ok event still describes the word-unit stage that ran at that
point in the pipeline.
The backend's own per-segment values are kept in
acceleration.raw_confidences, an array parallel to segments (null where
the backend reported no usable value and step 2's fallback weight was used).
For the native engine that value is exp(mean text-token log-prob) of the
decoded segment; in word mode (--max-segment-length 1) every word carries
its segment's value, a --max-segment-length N > 1 group carries the mean of
its words' values, and segments rebuilt from diarization word units carry
their engine segment's value unchanged.
This confidence-normalization stage is deliberately CPU-only. Native Whisper inference acceleration is separate and uses the required FrankenTorch kernels described under Installation.
Speculative Streaming Internals
The speculative streaming system combines dual-model execution with Bayesian window sizing, drift quantification, and deterministic fallback.
WindowManager. Divides the audio stream into overlapping windows. Each window gets a unique window_id, an SHA-256 hash of its audio content, and slots for both the fast and quality model results. Window sizes range from 1,000 ms to 30,000 ms, with the default starting at the configured --speculative-window-ms (default: 3,000 ms).
--offset-ms and --duration-ms select the source interval before this schedule runs. Each lane receives only its window's audio; partials, corrections, and final segments retain source-file timestamps. A selection starting at or beyond EOF produces an empty transcript without running either lane. The merged language comes from the quality lane's reported language: absent or conflicting language evidence remains null, with a warning for conflicting windows. The segment-only library pipeline also leaves language unknown unless a caller supplies backend metadata.
Quality-lane timing evidence also survives merging. When every quality window supplies native timestamp or attention-DTW evidence, alignment preserves the merged source timestamps without another heuristic or energy-based adjustment. This aggregate provenance does not claim that seam processing retained a canonical DTW word projection. Native quality decode gaps are clipped to each window's owned overlap region and the selected input bounds, then included in raw_output.dropped_windows, run warnings, evidence, and a sequenced backend.dropped_windows event. Fast-lane gaps do not mark audio missing from the final quality transcript. Recovery retry totals describe the quality lane only.
CorrectionDrift Metrics. When the quality model disagrees with the fast model, the system quantifies the disagreement using four metrics:
| Metric | Meaning | Typical Range |
|---|---|---|
wer_approx |
Levenshtein-based approximate Word Error Rate | 0.0 (identical) – 1.0 (completely different) |
confidence_delta |
Absolute difference in mean segment confidence | 0.0 – 1.0 |
segment_count_delta |
quality_count - fast_count |
−N – +N |
text_edit_distance |
Levenshtein distance on concatenated transcript text | 0 – unbounded |
CorrectionTolerance. A partial transcript is confirmed when all drift metrics fall within tolerance, and retracted (with correction) when any metric exceeds its threshold:
| Threshold | Default Value | Meaning |
|---|---|---|
max_wer |
0.1 (10%) | Maximum word error rate before retraction |
max_confidence_delta |
0.15 | Maximum confidence difference |
max_edit_distance |
50 characters | Maximum text edit distance |
SpeculationWindowController (Adaptive Sizing). Uses the same alien-artifact engineering contract as the backend router:
- State space: observed correction rate (fraction of windows needing correction)
- Posterior:
Beta(α, β)distribution over expected correction rate - Calibration: sliding window of 20 prediction-outcome pairs with Brier score tracking
- Fallback trigger: Brier score > 0.25 with ≥ 10 observations
The controller adjusts window size based on correction patterns:
| Pattern | Action | Rationale |
|---|---|---|
| High correction rate (> 25%) | Shrink window by step_ms |
Smaller windows reduce correction latency |
| Low correction rate (< 6.25%) | Grow window by step_ms |
Larger windows reduce overhead |
| Runaway corrections (> 75%) | Force minimum window size | Bound correction churn |
| 20 consecutive zero corrections | Shrink (counterintuitive) | May be over-tolerant; tighten to validate |
| High WER (> 12.5%) | Shrink window | Fast model consistently wrong at this scale |
ConcurrentTwoLaneExecutor. Runs both models in parallel lanes with independent timeout budgets. Results are collected asynchronously, and the faster result (always the fast model by design) is emitted immediately while the quality result triggers correction logic when it arrives. Thread panics in either lane are propagated as FwErrors rather than silently hanging the pipeline, and mutex poisoning is recovered gracefully.
Built-In Audio Decoder Internals
The built-in normalizer (normalize_to_wav_with_builtin_decoder) is a pure-Rust audio pipeline that produces whisper-compatible WAV without spawning any subprocess.
Format Detection. symphonia::get_probe().format() uses file extension hints and magic-byte probing to identify the container. Supported containers include MP3 (MPEG Layer III), MP4/M4A (AAC), FLAC, WAV/RIFF, OGG (Vorbis), and WavPack.
Decoding Loop:
for each packet in format_reader:
decoded = codec_decoder.decode(packet)
convert decoded samples to f32
if multi-channel: average all channels -> mono (using actual frame length)
append to sample buffer
Sample conversion handles i16, i32, f32, and f64 source formats. Multi-channel audio is mixed to mono by averaging corresponding samples, using the actual frame length rather than the nominal channel count to handle truncated frames safely.
Resampling. A linear interpolation resampler converts from the source sample rate (commonly 44.1 kHz or 48 kHz) to whisper's required 16 kHz:
ratio = src_rate / dst_rate
for each output sample i:
position = i * ratio
left = input[floor(position)]
right = input[ceil(position)]
output[i] = left + frac(position) * (right - left)
Computationally lightweight (no FFT, no filter bank) while sufficient for speech. Whisper models tolerate minor resampling artifacts well.
WAV Output. The final mono f32 buffer is quantized to 16-bit signed PCM via clamp-and-round, then written as a standard RIFF WAV header + raw PCM data. The output is always normalized_16k_mono.wav in the work directory.
Empty-input guard. normalize_cpu (and the builtin decoder) guard the empty-input edge case so silent fixtures and zero-length captures produce a deterministic error instead of an out-of-bounds panic.
Sync Architecture
The sync module provides one-way JSONL snapshot export/import with distributed lock safety.
Lock Protocol. Before any export or import, a JSON lock file is created at {state_root}/locks/sync.lock:
{"pid": 12345, "created_at_rfc3339": "2026-04-25T12:00:00Z", "operation": "export"}
The lock is kept alive while the owning PID is still running and age-gated when the PID is unknown; stale locks are archived with a reason suffix and a new lock is acquired. PID-liveness checks handle Windows (tasklist errors treated as unknown rather than dead), Linux EPERM on kill -0 (treated as alive: the process exists but isn't ours), and missing /proc entries. The combined effect is that long sync jobs never get killed by spurious lock-stealing and crashed jobs never leave permanent locks.
Full Export Format. The root manifest selects one immutable snapshot through its channels_dir field. Copy the complete export directory when moving a backup, or copy one retained snapshot directory as a standalone archive. Import and validation resolve the selected snapshot from the same captured manifest, so an export finishing concurrently cannot switch channels during a read.
| Path within the export directory | Contents |
|---|---|
manifest.json |
Format 2, selected channels_dir, row counts, and SHA-256 checksums over logical uncompressed bytes |
snapshot-<id>/runs.jsonl |
One JSON object per run |
snapshot-<id>/segments.jsonl |
One JSON object per segment |
snapshot-<id>/events.jsonl |
One JSON object per event |
snapshot-<id>/manifest.json |
Standalone format-1 manifest for restoring this snapshot directly |
With --gzip, the channel files use .jsonl.gz. A full export never rewrites a previously published snapshot's channels. Previous generations are retained without automatic pruning; the root manifest identifies the current one. Legacy full archives and incremental exports use the original root-channel layout and remain readable. Library callers can use SyncManifest::channel_directory() to locate the selected channels.
Incremental Export (CLI and library). sync export-jsonl --incremental and sync::export_incremental() export cursor-based deltas. Schema v6 maintains one bounded sync_run_mutations row per run aggregate; database triggers assign a monotonic sequence whenever a run, segment, or event is inserted, updated, or deleted. The database identity and snapshot sequence high-water mark in sync_cursor.json prevent backdated inserts and child-only updates from being skipped and reject cursors from unrelated databases. Each selected run is exported with its complete current segment and event set from one read snapshot. The cursor advances after manifest publication and, when requested, successful gzip compression. Use a fresh output directory for each successful delta; an earlier delta cannot be overwritten with a later starting cursor. Failed compression can be retried in place while the original cursor still applies. An empty no-op delta may be reused because it contains no intervening mutations. Legacy cursors without a database identity cause a safe full re-export. Child deletion marks its surviving parent, whose complete aggregate can be applied with overwrite-strict. Parent deletion travels in the explicit deleted-runs-v1 channel; deleting an existing target aggregate requires an explicit overwrite policy.
JSONL Compression (CLI and library). sync export-jsonl --gzip compresses full snapshots before publishing their root manifest; incremental exports compress under the same sync lock and save the cursor only after compression succeeds. sync::export_with_compression() and sync::export_incremental_with_compression() expose the same behavior to library callers and return compressed file paths relative to the export directory. The individual sync::compress_jsonl() / sync::decompress_jsonl() helpers are also available. Import transparently reads plain or gzip channels, including concatenated gzip members, and checksums always cover the uncompressed logical bytes. The manifest stays uncompressed so it can be inspected without decompression.
Sync Validation. After import, validate_sync() compares the database state against the imported JSONL files, checking for row count mismatches and checksum mismatches. End-to-end integrity verification.
Conflict Policies.
| Policy | Behavior on duplicate run_id |
|---|---|
reject |
Fail the entire import |
skip |
Silently skip existing runs |
overwrite |
Replace conflicting runs rows, fail closed if child-row mutation is needed |
overwrite-strict |
Verified strict replacement including child-row updates (delete+insert) and stale child-row pruning |
Parallel Pipeline. Large imports run with a parallel segment / event import pipeline and per-stage progress tracking; off-by-one accounting bugs in the progress display were eliminated, so the displayed counts always match the row counts in the final commit.
PipelineBuilder Fluent API
The pipeline is composed using a builder pattern rather than a hardcoded stage list:
// Default 10-stage pipeline
let config = PipelineBuilder::default_stages().build()?;
// Custom pipeline (skip stages you don't need)
let config = PipelineBuilder::new()
.stage(PipelineStage::Ingest)
.stage(PipelineStage::Normalize)
.stage(PipelineStage::Backend)
.stage(PipelineStage::Persist)
.build()?;
// Remove stages from defaults
let config = PipelineBuilder::default_stages()
.without(PipelineStage::Vad)
.without(PipelineStage::Diarize)
.build()?;
build() validates the pipeline: Ingest must come before Normalize, Normalize before Backend, and Persist (if present) must be last. build_unchecked() skips validation for testing.
FinalizerRegistry & Bounded Cleanup
The FinalizerRegistry ensures resources are cleaned up even on cancellation or panic:
enum Finalizer {
TempDir(PathBuf), // Record cleanup; the TempDir guard owns removal
Custom(Box<dyn FnOnce() + Send>), // User-provided cleanup function
Process(u32), // Kill subprocess by PID
}
Execution semantics:
- Finalizers run in LIFO order (last registered, first cleaned up).
run_all_bounded(budget_ms)bounds the wait for each custom finalizer. A callback that exceeds its budget continues on its worker thread while later finalizers start. A zero budget uses synchronous cleanup.- The default cleanup budget is 5 seconds (from the pipeline's
Cleanupstage budget). - Process finalizers send
SIGKILL(immediate termination, no graceful shutdown for subprocesses). - Temp directory entries record cleanup; the owning
tempfile::TempDirguard removes the directory on drop. - Custom finalizer panics are caught in synchronous, zero-budget, and worker-thread cleanup, so later finalizers still run.
- Cleanup workers retain the caller's runtime context, including restricted capabilities and cancellation. If the OS cannot create a cleanup worker, cleanup falls back to the synchronous path instead of panicking during unwind; that fallback cannot bound an arbitrary callback's duration.
- Dropping a pipeline context drains any remaining finalizers with that run's cleanup budget, including when a pipeline panic skips the normal cleanup call. Explicitly drained finalizers do not run twice.
Dependency Graph
franken_whisper
|
+-- asupersync (crates.io =0.7.0) Cancel-correct orchestration
+-- franken-kernel (crates.io =0.7.0) Budget, TraceId, time utilities
+-- franken-evidence (crates.io =0.7.0) Evidence ledger primitives
+-- franken-decision (crates.io =0.7.0) Decision contract framework
|
+-- fsqlite (crates.io ^0.5.1) Pure-Rust SQLite implementation
+-- fsqlite-types (crates.io ^0.5.1) Core SQLite value types
|
+-- ft-core (crates.io 0.1.0) Tensor types
+-- ft-kernel-cpu (crates.io 0.1.0) Native Whisper CPU kernels
+-- [macOS] ft-kernel-metal (crates.io 0.1.0) Automatic Metal kernels
+-- ftts-kernels (crates.io 0.1) FastEnhancer-S denoising kernels
+-- [optional] ftui (crates.io 0.7.0, feature: tui) Terminal UI
+-- [optional] fj-lax/fj-core (0.1.0, feature: fj-oracle) Test-only differential oracle
Third-party dependencies (non-optional):
| Crate | Version | Purpose |
|---|---|---|
clap |
4.5 | CLI argument parsing with derive macros |
serde + serde_json |
1.0 | JSON serialization / deserialization |
chrono |
0.4 | Timestamp handling (RFC-3339) |
uuid |
1.15 | Run ID generation (v4 random) |
sha2 |
0.10 | SHA-256 content hashing |
crc32fast |
1.4 | CRC32 integrity checksums |
base64 |
0.22 | Base64 encoding for TTY wire format |
flate2 |
1.1 | Zlib compression (TTY audio, JSONL sync) |
symphonia |
0.5 | Native audio decoding (MP3, AAC, FLAC, OGG, WAV) |
hound |
3.5 | WAV file writing |
which |
7.0 | Backend binary PATH discovery |
ctrlc |
3.4 | Ctrl+C signal handling |
tracing |
0.1 | Structured logging and diagnostics |
tracing-subscriber |
0.3 | tracing subscribers (env-filter, json) |
thiserror |
2.0 | Error type derive macros |
tempfile |
3.17 | Temporary file / directory management |
Clippy & Lint Configuration
The codebase enforces strict linting beyond the crate-wide
#![deny(unsafe_code)] policy and its explicitly scoped native-kernel
exceptions:
[lints.clippy]
enum_glob_use = "warn" # No wildcard enum imports
explicit_into_iter_loop = "warn" # Use .iter() not .into_iter() on references
explicit_iter_loop = "warn" # Prefer for x in &collection
flat_map_option = "warn" # Use .flatten() instead of .flat_map(|x| x)
implicit_clone = "warn" # Prefer .clone() over implicit copies
semicolon_if_nothing_returned = "warn" # Consistent semicolons on unit functions
unused_self = "warn" # Flag methods that don't use self
cargo clippy --all-targets -- -D warnings is a release gate and promotes
these warnings to hard errors.
Why These Design Decisions?
Why Bayesian routing over multi-armed bandits? Multi-armed bandits (UCB, Thompson sampling) optimize for a single reward signal. Backend selection involves multiple conflicting objectives (latency, quality, failure risk) that vary per request (diarization changes the optimal backend). The Bayesian decision contract with an explicit loss matrix handles this naturally: each (state, action) pair has a multi-factor cost, and the posterior captures per-backend reliability independent of the cost model. Bandits would have to collapse the multi-factor cost into a single scalar reward, losing the ability to reason about tradeoffs.
Why savepoints instead of top-level transactions?
Top-level BEGIN/COMMIT transactions don't nest in SQLite. If a caller is already inside a transaction (for example, a concurrent session), a nested BEGIN either fails or starts an implicit savepoint depending on the driver. Explicit SAVEPOINT / RELEASE always nest correctly and make the isolation boundaries visible in the code. The naming convention (fw_persist_N for persistence, fw_session_<name> for concurrent sessions) provides debuggability when inspecting WAL state.
Why mu-law over Opus for TTY audio?
Opus would require either an FFI binding to libopus with a new unsafe boundary
or a substantial pure-Rust codec dependency. Mu-law is supported by ffmpeg,
has a fixed 2:1 conversion from 16-bit PCM to 8-bit samples, and leaves
redundancy that zlib can exploit. The conversion is delegated to ffmpeg via
-f mulaw -ar 8000 -ac 1, avoiding another codec implementation in this
crate. The extensible negotiation protocol can add opus+b64 later without
breaking existing peers.
Why not whisper-rs (Rust FFI bindings)?
whisper-rs provides Rust bindings to whisper.cpp via FFI, which is necessarily
unsafe. franken_whisper can orchestrate whisper.cpp as an external process,
while its native engine is a pure-Rust implementation that avoids FFI. The
5-stage rollout policy keeps bridge replacement subject to conformance evidence.
Why a 10-stage pipeline instead of a monolithic transcribe function?
Stage isolation provides three benefits. First, independent budgets: a slow normalize stage cannot eat into the backend's time budget. Second, observable progress: agents see exactly which stage is running via NDJSON events. Third, composability: the PipelineBuilder can skip stages that aren't needed, avoiding unnecessary work. Stage-management overhead is negligible (~1 ms per transition) compared to actual inference time.
Why NDJSON over WebSocket or gRPC?
NDJSON (newline-delimited JSON) has three advantages for agent consumption. First, zero dependencies: any language can parse it with a JSON library and readline(). Second, pipe-friendly: works with jq, grep, head, tail, and standard Unix tools. Third, TTY-safe: it flows over SSH, serial links, and PTY connections where binary protocols cannot. The bandwidth tradeoff is irrelevant for a speech-to-text pipeline where inference (not I/O) is the bottleneck.
Alien-Artifact Engineering Contracts
Every adaptive controller in franken_whisper follows a formal alien-artifact engineering contract, a design discipline that prevents adaptive systems from making unbounded bad decisions.
The problem it solves. Adaptive algorithms (Bayesian routers, auto-tuners, ML-based controllers) can behave unpredictably when their models are wrong. A Bayesian router with a bad prior will confidently make terrible decisions. An auto-tuner with noisy data will oscillate. The standard response ("just add more data" or "tune the hyperparameters") doesn't work for a CLI tool running on user machines with no ops team watching dashboards.
The contract requires every adaptive controller to declare:
| Component | Purpose | Example (Backend Router) |
|---|---|---|
| State space | What does the controller observe? | 3 availability states (all / partial / none) |
| Action space | What can it decide? | 4 actions (try each backend + error) |
| Loss matrix | What's the cost of each state × action? | 3×4 matrix: latency(45%) + quality(35%) + failure(20%) |
| Posterior terms | How confident is the model? | Beta distribution per backend |
| Calibration metric | How accurate are predictions? | Brier score on 50-observation sliding window |
| Deterministic fallback | What happens when the model is wrong? | Static priority list |
| Fallback trigger | When does fallback activate? | Brier > 0.35 or calibration < 0.3 or < 5 observations |
| Evidence ledger | Audit trail of all decisions | Circular buffer of 200 RoutingEvidenceLedgerEntry records |
What the contract buys you. Bounded worst-case behavior. Even if the Bayesian model is perfectly miscalibrated, the system falls back to a simple priority list that always works. The evidence ledger makes every decision inspectable after the fact. The loss matrix makes the tradeoffs explicit rather than buried in code. And fallback runs continue to record adaptive predictions so the calibration data keeps accumulating; once the model is good enough again, the adaptive controller can take over without manual intervention.
Controllers using this contract:
- Backend router (Bayesian backend selection)
- Adaptive bitrate controller (TTY audio link quality)
- Budget tuner (pipeline stage timeout recommendations)
- Correction tracker (speculation confirmation thresholds)
- Speculative window controller (adaptive window sizing)
Pipeline Composition & Stage Isolation
PipelineCx (Pipeline Context). Every pipeline run creates a PipelineCx that carries shared state through all stages:
| Field | Type | Purpose |
|---|---|---|
trace_id |
TraceId |
Unique identifier from (timestamp_ms, random_u64) |
deadline |
Option<DateTime<Utc>> |
Absolute wall-clock deadline for the entire pipeline |
budget |
Budget |
Remaining time budget (decremented by stage service times) |
evidence |
Vec<Value> |
JSON evidence accumulator for post-hoc analysis |
finalizers |
FinalizerRegistry |
Cleanup handlers run on pipeline exit (bounded to 5 s) |
CancellationToken (Copy + Send + Sync). A lightweight handle extracted from PipelineCx for passing into background threads and subprocess monitors:
struct CancellationToken {
deadline: Option<DateTime<Utc>>,
}
The token's checkpoint() method checks two conditions: (1) has Ctrl+C been pressed (global AtomicBool), and (2) has the deadline passed. If either is true, it returns Err(Cancelled). Stages call checkpoint() at safe points (between loop iterations, before COMMIT, after subprocess completion). The token is threaded down into stage budget loops so a long-running stage honors its budget even when the per-stage timer fires before the global deadline.
Dynamic Stage Composition. Not every run executes all 10 stages. The pipeline skips stages that aren't needed:
| Condition | Skipped Stages |
|---|---|
| Input is already 16 kHz mono WAV | Normalize (passthrough) |
--no-diarize flag |
Diarize |
No --vad flag |
VAD |
Accelerate excluded through PipelineBuilder |
Confidence normalization |
--no-persist flag |
Persist |
| Backend doesn't support alignment | Align |
--no-stem flag set |
Source Separate |
| VAD detects only silence | All post-Backend stages |
Skipped stages still emit *.skip events to the NDJSON stream so agents can distinguish "not needed" from "failed."
Word-Level Timestamps
franken_whisper supports word-level timestamps through WordTimestampParams (enabled, max_len, token_threshold, token_sum_threshold) on the library API. The CLI exposes --word-threshold as a per-word confidence filter (drop words below the threshold); the deeper WordTimestampParams fields are configured programmatically via the TranscribeRequest::word_timestamps slot.
When word-level timestamps are enabled:
- The
whisper.cppbackend is invoked with the appropriate word-timestamp flags (-ml,-wt,-wtps). - Word arrays are extracted from each segment in the backend's JSON output.
- The extraction loop honors the pipeline's cancellation token so an in-flight word extraction can be interrupted mid-segment rather than only after the entire backend invocation completes.
- Each word receives a
confidencescore (filtered by--word-thresholdif set) andstart/endtimestamps inside its parent segment. - Native engine pilots are required to match bridge word-level output to the 50 ms canonical tolerance before they can be promoted past the
validatedrollout stage.
Evidence Ledger & Routing History
Every routing decision records a RoutingEvidenceLedgerEntry in a 200-entry circular buffer:
| Field | Type | Purpose |
|---|---|---|
decision_id |
String | Unique decision identifier |
trace_id |
String | Links to pipeline trace |
timestamp_rfc3339 |
String | When the decision was made |
observed_state |
String | Availability state at decision time |
chosen_action |
String | Which backend was selected |
policy_id |
String | Which routing policy was active |
loss_matrix_hash |
String | Provenance tracking for the loss matrix |
availability |
Vec<(String, bool)> |
Per-backend availability snapshot |
duration_bucket |
String | Audio duration category (short / medium / long) |
diarize |
bool | Whether diarization was requested |
actual_outcome |
Option<RoutingOutcomeRecord> |
Observed success / failure (filled post-run) |
Queryable via robot routing-history and included in stage event payloads for post-hoc analysis. The loss_matrix_hash field enables detecting when the routing policy itself changed between runs.
Trace ID & Run ID Generation
Every pipeline run receives two identifiers:
Trace ID is a deterministic composite of wall-clock time and randomness:
trace_id = hex(timestamp_ms) + "-" + hex(uuid_v4_lower_80_bits)
Example: "18e4a0b1c00-a1b2c3d4e5f6"
The timestamp prefix enables time-range queries without parsing. The random suffix prevents collisions when multiple runs start in the same millisecond.
Run ID is a standard UUID v4:
run_id = uuid::Uuid::new_v4().to_string()
Example: "550e8400-e29b-41d4-a716-446655440000"
The trace_id links all events across the pipeline (including routing evidence); the run_id is the persistence key in SQLite.
Calibration Sliding Window
The router maintains a CalibrationState with a sliding window of prediction-outcome pairs:
struct CalibrationState {
observations: VecDeque<CalibrationObservation>, // bounded to 50 entries
window_size: usize, // ROUTER_HISTORY_WINDOW = 50
}
struct CalibrationObservation {
predicted_probability: f64, // router's confidence that the backend would succeed
actual_outcome: f64, // 1.0 if it did succeed, 0.0 if it failed
observed_at_rfc3339: String, // when the observation was recorded
}
Update cycle:
- Before each run, the router predicts
p_successfor the chosen backend. - After the run, the actual outcome (success / failure) is recorded.
- If the window exceeds 50 entries, the oldest observation is evicted.
- The Brier score is recomputed from the current window.
- Non-finite predictions (
NaN,±∞) are sanitized before being stored, so pathological backend signals can never poison the calibration buffer.
Brier Score Formula:
Brier = (1/N) * Σ_i (predicted_i - actual_i)^2
Brier = 0.0 means perfect calibration. Brier = 0.25 is the score of a coin flip. Brier > 0.35 triggers fallback to static priority routing.
The simpler calibration score tracks correct_predictions / total_predictions, where a prediction is "correct" if the predicted probability matched the outcome direction (predicted > 0.5 and succeeded, or predicted < 0.5 and failed). Quick sanity check independent of the Brier score.
Beta Distribution Posterior Updates
Each backend's reliability is modeled as Beta(α, β):
- Mean =
α / (α + β)(estimated success probability) - Variance =
α·β / ((α + β)² · (α + β + 1))(uncertainty)
The update rule blends the prior with empirical data:
if sample_count >= 5:
empirical_weight = min(sample_count, 20)
α += success_rate * empirical_weight
β += (1 - success_rate) * empirical_weight
The weight cap at 20 prevents a long history from making the posterior too rigid. A backend that succeeded 19 / 20 recent runs gets α += 19, β += 1, strongly increasing its selection probability. A backend that succeeded 10 / 20 gets α += 10, β += 10, pulling toward neutral.
Input Validation
Before the pipeline starts, the request is validated.
Mutually Exclusive Input Modes. Exactly one of --input, --stdin, or --mic must be specified. Zero inputs or multiple inputs produce an immediate error before pipeline construction; in robot mode, that error is a structured run_error envelope, never human stderr.
Pipeline Configuration Validation. PipelineConfig::validate() enforces ordering constraints:
Normalizemust come afterIngestBackendmust come afterNormalize- No duplicate stages in the pipeline
- All stage dependencies satisfied in execution order
These checks run at pipeline build time, so invalid configurations fail fast.
Path / Directory Guards. Input paths are validated with is_file (directories rejected); empty parent components are ignored when ensuring directories exist; stdin temporary files use sanitized extensions to prevent path traversal.
Timeout Conversion. The --timeout flag (seconds) converts to an absolute deadline:
timeout_ms = timeout_seconds * 1000 (with saturating_mul)
deadline = now + chrono::Duration::milliseconds(clamped_to_i64_max)
saturating_mul prevents overflow; the clamp to i64::MAX prevents chrono panics on unreasonably large timeouts.
Stage Failure Behavior
When a pipeline stage fails, behavior depends on the error type:
| Error Type | Behavior | Event Emitted |
|---|---|---|
Cancelled (Ctrl+C or deadline) |
Pipeline stops immediately | {stage}.cancelled |
StageTimeout (budget exceeded) |
Pipeline stops, timeout reported | {stage}.timeout |
| Other errors (I/O, backend, etc.) | Pipeline stops, error propagated | {stage}.error |
The stage_start timer is cleared on checkpoint failure so elapsed time from a cancelled stage never leaks into the next stage's profile. All stage failures produce a corresponding error event in the NDJSON stream before the pipeline terminates. In-progress SQLite transactions roll back via the savepoint mechanism. Registered finalizers (temp directory cleanup, subprocess kills) run within the 5-second cleanup budget. The final run_error event contains the structured error code and message, so agents can programmatically determine what failed and why.
Evidence Accumulation
The PipelineCx carries a Vec<serde_json::Value> evidence accumulator that grows throughout the pipeline:
- Routing decision: the backend router pushes its decision evidence (posterior snapshot, loss matrix, chosen action).
- Stage observations: individual stages record evidence about unusual conditions (e.g., normalization fallback to ffmpeg, high latency).
- Conformance results: when native engines run in shadow / validated mode, comparison results are recorded as evidence.
All accumulated evidence is included in the final RunReport.evidence field and persisted alongside the run in SQLite. This enables post-hoc debugging without needing to reproduce exact conditions.
TUI Internals
The interactive TUI (--features tui) provides a three-pane interface:
+-------------------+-------------------------------------+
| | |
| Runs List | Timeline / Transcript |
| (left pane) | (main pane) |
| | |
| - run-abc | [0.0s - 2.5s] Hello world |
| - run-def | [2.5s - 5.1s] How are you |
| > run-ghi | [5.1s - 7.3s] [SPK_01] Fine |
| | |
+-------------------+-------------------------------------+
| Event Details (bottom pane) |
| stage: backend | code: backend.ok | 4.2s |
+---------------------------------------------------------+
Keyboard Bindings:
| Key | Action |
|---|---|
Tab / Shift+Tab |
Cycle focus between panes |
Up / Down |
Move selection within focused pane |
PageUp / PageDown |
Jump by page |
r |
Reload data from SQLite |
h or ? |
Toggle help overlay |
q or Ctrl+C |
Quit |
Speaker Color Assignment. Speakers are assigned distinct colors via an FNV-1a-style hash of the speaker label, mapped to an 8-color palette. The same speaker always gets the same color within a session, making multi-speaker conversations visually parseable.
Segment Retention. To prevent unbounded memory growth during long sessions, the TUI caps displayed segments at 10,000 (DEFAULT_MAX_SEGMENTS). When the cap is exceeded, oldest segments are drained first, keeping the most recent transcription visible. Segments with None timestamps display gracefully rather than panicking; run detail load errors surface in the event-detail pane.
Microphone Capture
transcribe --mic (batch capture) shells out to ffmpeg using the host's input framework; the realtime fw robot listen driver prefers cpal (CoreAudio / ALSA / WASAPI) and falls back to ffmpeg when cpal cannot open a device:
| OS | ffmpeg Format | Default Device | Notes |
|---|---|---|---|
| Linux | alsa |
default |
ALSA subsystem |
| macOS | avfoundation |
:0 |
First audio input device |
| Windows | dshow |
audio=default |
DirectShow |
The batch microphone flow:
- Spawn ffmpeg with
-f <format> -i <device> -t <seconds> -ar 16000 -ac 1 -c:a pcm_s16le <output> - Wait for capture to complete (bounded by
--mic-seconds) - Output is already 16 kHz mono WAV, so the normalization stage becomes a passthrough
- Proceed to backend execution
Custom devices, formats, and sources can be overridden via --mic-device, --mic-ffmpeg-format, and --mic-ffmpeg-source flags. Active region boundaries are clamped to the actual audio duration of the captured file, preventing the pipeline from over-reading past the buffer when capture is cut short.
Segment Comparison Algorithm
The conformance comparator aligns expected vs. observed segment lists index-by-index:
Input: expected[0..N], observed[0..M], tolerance
1. If N != M: set length_mismatch = true
2. For i in 0..min(N, M):
a. Compare text:
if tolerance.require_text_exact && expected[i].text != observed[i].text:
text_mismatches += 1
b. Compare speaker:
if tolerance.require_speaker_exact && expected[i].speaker != observed[i].speaker:
speaker_mismatches += 1
c. Compare timestamps:
if |expected[i].start_sec - observed[i].start_sec| > tolerance.timestamp_tolerance_sec:
timestamp_violations += 1
if |expected[i].end_sec - observed[i].end_sec| > tolerance.timestamp_tolerance_sec:
timestamp_violations += 1
3. Return SegmentComparisonReport {
length_mismatch,
text_mismatches,
speaker_mismatches,
timestamp_violations,
segments_compared: min(N, M),
}
Default Tolerance Values:
| Parameter | Default | Meaning |
|---|---|---|
timestamp_tolerance_sec |
0.05 (50 ms) | Maximum acceptable timestamp drift |
require_text_exact |
true | Text must match exactly |
require_speaker_exact |
false | Speaker labels not required to match |
The 50 ms timestamp tolerance (CANONICAL_TIMESTAMP_TOLERANCE_SEC) is the single source of truth across the entire codebase; conformance tests, native engine rollout gates, and replay comparison all reference this constant.
WER Approximation Algorithm
The conformance module includes a Levenshtein-based Word Error Rate calculator used in both conformance testing and speculative streaming correction:
1. Tokenize both transcripts by whitespace -> word sequences
2. Compute Levenshtein edit distance between word sequences
(insertions, deletions, substitutions)
3. WER = edit_distance / max(reference_length, 1)
4. Clamp to [0.0, 1.0]
The conformance module normalizes by the reference (expected) length, while the speculation module normalizes by max(fast_length, quality_length) since neither model is the "reference."
Overlap Detection
The SegmentConformancePolicy can optionally reject overlapping segments, defined as a segment whose end_sec exceeds the next segment's start_sec beyond a configurable epsilon (default: 1 µs). This catches backends that produce garbled timeline output:
for each pair (segment[i], segment[i+1]):
if segment[i].end_sec > segment[i+1].start_sec + epsilon:
report overlap violation at index i
Overlap detection runs before cross-engine comparison so a backend producing self-overlapping output is flagged before being compared against a reference.
Metamorphic Testing
In addition to conventional unit and integration tests, the project ships dedicated metamorphic test suites that verify input → output relationships rather than oracle values:
| File | What it checks |
|---|---|
tests/metamorphic_audio_tests.rs |
Audio normalization is stable under permutation of decoder paths, silence padding is idempotent, stereo→mono averaging matches manual computation |
tests/metamorphic_accelerate_tests.rs |
Softmax is permutation-equivariant and scale-invariant; layer-norm output mean ≈ 0, variance ≈ 1; attention scoring respects masking |
tests/metamorphic_speculation_tests.rs |
String-distance functions are symmetric, satisfy the triangle inequality, and window-size adjustments respect bounds |
src/adversarial_corpus.rs |
Seventeen deterministic, public-safe diarization challenge families; bounded transform composition; exact time-shift contracts; stage-specific regression attribution; minimized content-free repro seeds |
Metamorphic tests catch entire categories of regressions where the "correct" answer is unknown but the relationship between inputs and outputs must hold.
Configuration Recipes
Fastest possible transcription (accuracy tradeoff):
franken_whisper transcribe --input audio.mp3 \
--backend whisper-cpp \
--model tiny.en \
--no-persist \
--no-timestamps \
--beam-size 1 \
--best-of 1 \
--json
Dependency-light native diarization:
franken_whisper transcribe --input meeting.mp3 \
--backend whisper-cpp \
--model large-v3 \
--diarize \
--diarization-engine acoustic \
--vad \
--json
Agent integration with health monitoring:
# Pre-flight check
franken_whisper robot health 2>/dev/null | jq -e '.overall_status == "ok"' > /dev/null
# Transcribe with full event stream
franken_whisper robot run \
--input audio.mp3 \
--backend auto 2>/dev/null | while IFS= read -r line; do
event=$(echo "$line" | jq -r '.event')
case "$event" in
stage) echo "[STAGE] $(echo "$line" | jq -r '.code')" ;;
run_complete) echo "[DONE] $(echo "$line" | jq -r '.transcript' | head -c 100)" ;;
run_error) echo "[FAIL] $(echo "$line" | jq -r '.code'): $(echo "$line" | jq -r '.message')" ;;
esac
done
Offline archival workflow:
# Transcribe everything into a custom DB
for f in archive/*.mp3; do
franken_whisper transcribe --input "$f" --db archive.sqlite3 --json > /dev/null
done
# Export to portable JSONL
franken_whisper sync export-jsonl --output ./archive_snapshot --db archive.sqlite3
# Optionally gzip the snapshot for storage (the import path auto-detects .gz)
gzip ./archive_snapshot/*.jsonl
# Re-import to validate; conflict-policy=skip is a no-op on the original DB
franken_whisper sync import-jsonl --input ./archive_snapshot --conflict-policy skip --db archive.sqlite3
Low-bandwidth remote transcription via TTY:
# On remote (has audio, no GPU):
franken_whisper tty-audio encode --input recording.wav --chunk-ms 100 > /tmp/frames.ndjson
# Transfer (works over any text channel):
scp /tmp/frames.ndjson gpu-server:/tmp/
# On GPU server (has whisper, fast inference):
cat /tmp/frames.ndjson | franken_whisper tty-audio decode --output /tmp/audio.wav
franken_whisper transcribe --input /tmp/audio.wav --backend whisper-cpp --model large-v3 --json
Release Binary Optimization
The release profile is aggressively optimized for deployment:
[profile.release]
opt-level = 3 # Optimize runtime performance
lto = true # Full link-time optimization across all crates
codegen-units = 1 # Single codegen unit for maximum optimization opportunity
panic = "unwind" # Preserve per-input isolation and robot error recovery
strip = true # Strip debug symbols from final binary
This prioritizes runtime performance while retaining a stripped distribution binary. The tradeoff is slower compilation (codegen-units = 1 + LTO). Unwinding preserves batch isolation, terminal robot errors, and cleanup when Rust code panics. Binary-size and inference-performance comparisons against older aborting releases must be measured again; earlier ratios do not establish the cost of this profile change.
Glossary
| Term | Definition |
|---|---|
| Backend | An external ASR engine (whisper.cpp, insanely-fast-whisper, whisper-diarization) or its native Rust replacement |
| Bridge adapter | Code that spawns an external backend process and parses its output into a TranscriptionResult |
| Brier score | Mean squared error between predicted probabilities and actual outcomes; measures calibration quality (0.0 = perfect, 0.25 = random) |
| Conformance | Cross-engine output comparison using the 50 ms timestamp tolerance and optional text / speaker matching |
| Decision contract | Formal specification of an adaptive controller's state space, action space, loss matrix, posterior, calibration, fallback, and evidence |
| Evidence ledger | Circular buffer recording every routing decision with full posterior snapshots for audit |
| Finalizer | A cleanup handler (temp dir removal, subprocess kill) registered during pipeline execution and run on exit within a bounded timeout |
| Metamorphic test | A test that verifies an input → output relationship (symmetry, invariance, etc.) rather than an expected oracle value |
| NDJSON | Newline-Delimited JSON; one JSON object per line, compatible with jq and standard Unix text tools |
| Native rollout stage | One of Shadow / Validated / Fallback / Primary / Sole — the conformance-gated promotion ladder for in-process Rust engines |
| Pipeline stage | One of 10 composable processing steps (Ingest, Normalize, VAD, Separate, Backend, Accelerate, Align, Punctuate, Diarize, Persist) |
| Posterior | Beta distribution Beta(α, β) modeling estimated success probability for a backend |
| Replay envelope | SHA-256 hash summary (input, backend identity, output) for detecting drift between runs |
| Replay pack | Four-artifact directory (env.json, manifest.json, repro.lock, tolerance_manifest.json) capturing everything needed to reproduce a run |
| Robot mode | The robot subcommand; emits structured NDJSON events for machine consumption rather than human-readable text |
| Savepoint | SQLite's nested transaction mechanism; used for concurrent session isolation and cancellation-safe writes |
| Speculative streaming | Dual-model pattern where a fast model emits partial transcripts immediately and a quality model confirms or corrects them |
| TTY audio | Protocol for transporting compressed audio over text-only channels (PTY, SSH, serial) using mu-law + zlib + base64 NDJSON frames |
| WAL mode | SQLite's Write-Ahead Logging; allows concurrent reads during writes |
Security & Privacy
Your Data Never Leaves Your Machine
franken_whisper is designed with privacy as a hard constraint:
+----------------------------------------------------------------+
| YOUR MACHINE |
| |
| +-----------+ +-------------+ +-----------+ |
| | Input |--->| Pipeline |--->| Output | |
| +-----------+ +-------------+ +-----------+ |
| |
| No network calls during transcription |
| No telemetry or analytics |
| No cloud sync |
| No API keys required for native ASR, acoustic, or ECAPA |
+----------------------------------------------------------------+
All processing happens on your hardware using local backend binaries. The only external network access is:
- ffmpeg auto-provisioning: one-time download, can be disabled via
FRANKEN_WHISPER_AUTO_PROVISION_FFMPEG=0 - HuggingFace model downloads: only when explicitly using an external diarization backend with pyannote models
Secrets Redaction
The HuggingFace token used by the diarization backend never appears in log output. Every command line is rendered through render_command_for_log() before being emitted into traces; the renderer redacts --hf-token values so neither structured tracing nor stdout transcripts contain the raw token. This applies to error messages and test snapshots as well; there is no path where the token leaks into a public artifact.
What's Stored Where
| Location | Contents | Sensitive? |
|---|---|---|
.franken_whisper/storage.sqlite3 |
Run history, transcripts, segments | Yes (contains transcription text) |
.franken_whisper/locks/ |
Sync lock files (PID, timestamp only) | No |
<work_dir>/normalized_16k_mono.wav |
Temporary normalized audio | Yes (audio content; cleaned up by finalizers) |
| JSONL snapshots | Exported run history | Yes (contains transcription text) |
{state_root}/tools/ffmpeg/bin/* |
Auto-provisioned ffmpeg binary | No |
Secure Deletion
# Remove all franken_whisper state
rm -rf .franken_whisper/
# Or just the database (preserves auto-provisioned ffmpeg)
rm .franken_whisper/storage.sqlite3
Library API
franken_whisper is both a CLI binary and a Rust library. The public API exposes every module for embedding ASR pipelines in other applications:
use franken_whisper::backend::{BackendRouter, Engine};
use franken_whisper::orchestrator::{PipelineConfig, PipelineBuilder, FrankenWhisperEngine};
use franken_whisper::model::{TranscribeRequest, BackendKind, TranscriptionResult};
use franken_whisper::storage::RunStore;
use franken_whisper::robot::robot_schema_value;
use franken_whisper::tty_audio::{encode_wav_to_frames, decode_frames_to_raw};
use franken_whisper::conformance::compare_segments_with_tolerance;
use franken_whisper::error::{FwError, FwResult};
Key types:
| Type | Module | Purpose |
|---|---|---|
TranscribeRequest |
model |
Fully-specified transcription request with all parameters |
TranscriptionResult |
model |
Backend output: transcript, segments, language, acceleration metadata |
TranscriptionSegment |
model |
Individual segment: start/end times, text, speaker, confidence |
RunReport |
model |
Complete run envelope: request + result + events + evidence + replay |
BackendKind |
model |
Enum: Auto, WhisperCpp, InsanelyFast, WhisperDiarization |
FrankenWhisperEngine |
orchestrator |
Main pipeline orchestrator |
PipelineConfig |
orchestrator |
Ordered list of stages to execute |
PipelineBuilder |
orchestrator |
Fluent constructor for pipeline configs |
CancellationToken |
orchestrator |
Cooperative cancellation handle |
RunStore |
storage |
SQLite persistence interface (open, persist, query) |
TtyAudioFrame |
tty_audio |
Protocol frame with seq, codec, payload, integrity hashes |
TtyControlFrame |
tty_audio |
Control messages (handshake, ack, retransmit, backpressure, transcript_*) |
DecodeReport |
tty_audio |
Decode telemetry: frames decoded, gaps, duplicates, failures |
ReplayEnvelope |
replay_pack |
SHA-256 hash summary for deterministic replay |
FwError |
error |
Error enum with 12 variants, each mapping to a stable FW-* code |
SegmentCompatibilityTolerance |
conformance |
Drift thresholds for cross-engine comparison |
Data Model
SQLite Schema
-- Core run record (one row per transcription). All columns NOT NULL.
CREATE TABLE runs (
id TEXT PRIMARY KEY, -- UUID run identifier
started_at TEXT NOT NULL, -- RFC-3339 timestamp
finished_at TEXT NOT NULL, -- RFC-3339 timestamp (set on completion or error)
backend TEXT NOT NULL, -- "whisper_cpp", "insanely_fast", "whisper_diarization"
input_path TEXT NOT NULL, -- Original input file path (or sentinel for stdin/mic)
normalized_wav_path TEXT NOT NULL, -- Path to 16 kHz mono WAV
request_json TEXT NOT NULL, -- Full TranscribeRequest as JSON
result_json TEXT NOT NULL, -- Full TranscriptionResult as JSON
warnings_json TEXT NOT NULL, -- Non-fatal warnings as JSON array
transcript TEXT NOT NULL, -- Plain text transcript
replay_json TEXT NOT NULL DEFAULT '{}', -- ReplayEnvelope as JSON
acceleration_json TEXT NOT NULL DEFAULT '{}' -- AccelerationReport as JSON
);
-- Timed transcript segments (N rows per run)
CREATE TABLE segments (
run_id TEXT NOT NULL, -- References runs(id)
idx INTEGER NOT NULL, -- Segment index within run
start_sec REAL, -- Start time in seconds (may be NULL)
end_sec REAL, -- End time in seconds (may be NULL)
speaker TEXT, -- Speaker label (if diarized)
text TEXT NOT NULL, -- Segment text
confidence REAL, -- Confidence score [0.0, 1.0]
PRIMARY KEY (run_id, idx)
);
-- Pipeline stage events (M rows per run)
CREATE TABLE events (
run_id TEXT NOT NULL, -- References runs(id)
seq INTEGER NOT NULL, -- Strictly increasing per run
ts_rfc3339 TEXT NOT NULL, -- Non-decreasing timestamp
stage TEXT NOT NULL, -- Pipeline stage name
code TEXT NOT NULL, -- Event code (e.g., "backend.ok")
message TEXT NOT NULL, -- Human-readable description
payload_json TEXT NOT NULL, -- Event-specific JSON payload
PRIMARY KEY (run_id, seq)
);
-- Key-value schema metadata
CREATE TABLE _meta (
key TEXT PRIMARY KEY, -- e.g. 'schema_version'
value TEXT NOT NULL -- 'schema_version' currently '6'
);
-- v3 migration adds indexes on hot query paths (recent-runs listing,
-- per-run segment + event lookup).
-- v4 adds derived diarization reports, turns, hint audits, and privacy-safe
-- profile summaries rebuilt from canonical runs JSON.
-- v5 adds typed speaker-count status/outcome JSON and privacy-safe per-hint
-- disposition JSON to the derived diarization report index.
-- v6 adds a bounded per-run mutation sequence and triggers for lossless
-- incremental export of run, segment, and event changes, plus a stable
-- sync database identity in _meta so cursors cannot cross database lineages.
NDJSON Export Format
JSONL snapshots mirror the database schema:
runs.jsonl (one JSON object per line):
{"id":"fw-run-abc","started_at":"2026-04-25T06:00:00Z","finished_at":"2026-04-25T06:00:05Z","backend":"whisper_cpp","transcript":"Hello world...","replay_json":"{...}"}
segments.jsonl:
{"run_id":"fw-run-abc","idx":0,"start_sec":0.0,"end_sec":2.5,"text":"Hello world","confidence":0.95}
events.jsonl:
{"run_id":"fw-run-abc","seq":0,"ts_rfc3339":"2026-04-25T06:00:00Z","stage":"ingest","code":"ingest.start","message":"materializing input","payload_json":"{}"}
manifest.json (integrity metadata):
{
"exported_at": "2026-04-25T06:30:00Z",
"run_count": 42,
"segment_count": 1847,
"event_count": 336,
"runs_sha256": "a1b2c3...",
"segments_sha256": "d4e5f6...",
"events_sha256": "g7h8i9..."
}
Key Data Types
TranscribeRequest (the full input specification):
| Field | Type | Description |
|---|---|---|
input |
InputSource |
Tagged enum: File { path } / Stdin { source_hint } / Microphone { seconds, device, ffmpeg_format, ffmpeg_source } |
backend |
BackendKind |
Auto, WhisperCpp, InsanelyFast, or WhisperDiarization |
model |
Option<String> |
Model name or path forwarded to backend |
language |
Option<String> |
Language hint (ISO 639-1) |
translate |
bool |
Translate to English |
diarize |
bool |
Enable speaker diarization |
persist |
bool |
Persist run to SQLite (inverse of --no-persist) |
db_path |
PathBuf |
SQLite database path |
timeout_ms |
Option<u64> |
Overall pipeline timeout in milliseconds |
backend_params |
BackendParams |
Aggregate of all backend-specific tunables — decoding params (beam / temperature / thresholds), VAD params, diarization config, speculative config, alignment overrides, word-timestamp params, audio windowing, output format selectors |
The BackendParams aggregate is the catch-all for every backend-specific tuning knob. The CLI marshals every transcribe flag into the corresponding field here, and downstream stages read what they need (VAD reads vad_params, the speculative path reads speculative, the bridge adapters read decoding params, and so on).
TranscriptionResult (what the backend produces):
| Field | Type | Description |
|---|---|---|
transcript |
String |
Full transcript text |
segments |
Vec<TranscriptionSegment> |
Timed segments with text, speaker, confidence |
language |
Option<String> |
Detected language |
acceleration |
Option<AccelerationReport> |
Confidence normalization metadata |
raw_backend_json |
Option<String> |
Preserved raw backend output for replay |
RunEvent (a single pipeline event):
| Field | Type | Description |
|---|---|---|
seq |
u64 |
Strictly increasing per run |
ts_rfc3339 |
String |
Non-decreasing RFC-3339 timestamp |
stage |
String |
Pipeline stage (e.g., "ingest", "backend", "speculation") |
code |
String |
Event code (e.g., "backend.routing.decision_contract") |
message |
String |
Human-readable description |
payload |
Value |
Event-specific JSON payload |
Performance Characteristics
Native Engine Speed (measured)
The competitive rows below come from live whisper-cli incumbent arms in
examples/incumbent_ab.rs: both binaries run side-by-side in the same
invocation at 32 requested threads and matched greedy decode settings
(whisper-cli -bs 1 -bo 1). They were measured with the int8 encoder, which
is now an opt-in (FW_ENC_ATTN_OUT_I8I32=1); the default encoder is f32
(DISC-010), and its incumbent ratios have
not been re-certified.
| Comparison (matched-greedy) | Model | Clip / mode | Result |
|---|---|---|---|
vs whisper.cpp (CPU) |
large-v3-turbo |
124.5 s, whole job, no timestamps | 2.99× faster |
vs whisper.cpp (CPU) |
tiny.en |
124.5 s, transcribe only, no timestamps | 1.52× faster |
vs whisper.cpp (CPU) |
tiny.en |
300 s, transcribe only, no timestamps | 1.51× faster |
Measurement contract.
- Campaign wins use the actual incumbent — a competitive result requires the legacy incumbent arm to run side-by-side with franken in the same harness invocation. A before/after comparison of franken against itself is recorded as a maintenance self-speedup, never as a competitive result.
- Paired null (A/A) control, same binary — every new wall-time A/B verdict must carry an identity null in the same invocation, with order-interleaved arms, so host contention and run-order bias cannot masquerade as a speedup. A counted-mechanism rejection may omit timing inference only when the unchanged count itself proves that no work was removed.
- Byte/ULP-exact where claimed — byte-exact levers are asserted bit-identical to the reference path; the sole numerics-affecting default (poly-exp) is held to WER-Δ 0.000 vs
whisper.cpp. - Negative-evidence ledger — new rejected levers record either a numerical same-invocation A/A null or a counted unchanged-work mechanism, plus a concrete retry predicate. The pre-commit gate rejects undecidable rows. See
docs/NEGATIVE_EVIDENCE.mdanddocs/LEDGER_RESURRECTION.md. - Gate. A result is decidable only when both same-invocation A/A null medians lie in
[0.98, 1.02]inclusive, its comparison CI95 excludes1.0, and its effect clears 2× the widest null-CI edge from1.0. A null CI need not straddle1.0; its widest edge calibrates the margin.cvis recorded as provenance and never decides a verdict.
Scope. These are greedy / temperature-0 comparisons with the reference
explicitly forced to the same decode mode (-bs 1 -bo 1). The turbo row is
whole-process wall time, including startup, model/audio I/O, inference,
serialization, and teardown; both arms also use max_context=0. The tiny.en
rows are transcribe-only and exclude one-time model load. All three use a
quiet Threadripper host at requested/configured width 32 with order-alternating
pairs and per-engine A/A controls. The full record lives in
docs/PERF_LEDGER.md and
docs/NEGATIVE_EVIDENCE.md.
Audio Normalization
| Input Format | Duration | Normalization Time | Method |
|---|---|---|---|
| MP3 (128 kbps, stereo) | 2 min | ~260 ms | Built-in (symphonia) |
| FLAC (16-bit, 44.1 kHz) | 2 min | ~180 ms | Built-in (symphonia) |
| WAV (16 kHz, mono) | 2 min | ~5 ms | Passthrough (already normalized) |
| MP4 (video, AAC audio) | 2 min | ~500 ms | ffmpeg fallback |
The built-in normalizer runs entirely in process without a backend executable. It decodes and resamples one packet at a time, retaining one interpolation sample and an 8,192-sample output batch instead of whole-recording waveform vectors. It publishes the completed PCM16 WAV from an adjacent temporary file after finalization and cancellation checks. The timing figures above predate this streaming change; no new latency measurement is claimed.
Pipeline Overhead
Typical overhead beyond the backend inference time:
| Component | Time | Notes |
|---|---|---|
| CLI parse | < 1 ms | clap argument parsing |
| Database open | ~5 ms | SQLite connection + schema check |
| Ingest | ~1 ms | File existence check, size read |
| Normalize (MP3) | ~260 ms | Built-in Rust decoder |
| Persistence | ~10 ms | SQLite transaction (8 retry budget) |
| Latency profiling | ~1 ms | Compute utilization ratios |
| Report assembly | ~2 ms | JSON serialization |
| Total overhead | ~280 ms | Everything except actual inference |
The backend inference stage dominates total runtime (typically 3–60 seconds depending on audio length, model size, and hardware).
Benchmark Suites
Five Criterion benchmark suites measure performance of critical paths:
| Benchmark | What it measures |
|---|---|
storage_bench |
SQLite persist / query throughput, concurrent access |
normalize_bench |
Audio normalization latency by format and duration |
pipeline_bench |
End-to-end pipeline overhead (mocked backend) |
tty_bench |
TTY encode / decode throughput, retransmit loop latency |
sync_bench |
JSONL export / import throughput, compression ratios |
Run with: cargo bench --bench <name>
The benchmark regression policy is documented in docs/benchmark_regression_policy.md.
Binary Size
With the release profile (opt-level = 3, full LTO, stripped):
| Build | Approximate Size |
|---|---|
| Debug | ~150 MB |
| Release (default) | ~20 MB |
| Release (optimized profile) | ~12 MB |
Release + --features tui |
~15 MB |
Testing
The repository has thousands of unit, integration, conformance, metamorphic,
and model-gated tests. The default suite deliberately ignores models found only
in implicit home-directory caches, keeping ordinary development checks bounded
and deterministic. Set an explicit FRANKEN_WHISPER_TEST_MODEL_DIR, or opt into
the complete local-model stress lane with FRANKEN_WHISPER_ULTRA_STRESS=1.
# normal development gate (no accidental multi-minute model inference)
cargo test
# opt-in ultra stress gate using models installed in the normal local caches
FRANKEN_WHISPER_ULTRA_STRESS=1 cargo test
# library tests only
cargo test --lib
# run specific test module
cargo test --lib -- backend::tests
cargo test --lib -- robot::tests
cargo test --lib -- tty_audio::tests
# run integration tests
cargo test --test tty_telemetry_tests
cargo test --test conformance_comparator_tests
cargo test --test conformance_harness
cargo test --test gpu_cancellation_tests
cargo test --test robot_contract_tests
cargo test --test e2e_pipeline_tests
# run metamorphic suites
cargo test --test metamorphic_audio_tests
cargo test --test metamorphic_accelerate_tests
cargo test --test metamorphic_speculation_tests
# run benchmarks
cargo bench --bench storage_bench
cargo bench --bench normalize_bench
cargo bench --bench pipeline_bench
cargo bench --bench tty_bench
cargo bench --bench sync_bench
# lint
cargo clippy --all-targets -- -D warnings
Test Categories
| Category | Description |
|---|---|
| Backend engine | Engine contracts, native execution, and bridge normalization |
| Robot contract | NDJSON schema, field presence, path safety, and panic handling |
| TTY audio | Handshake, integrity, retransmit, telemetry, and control frames |
| Conformance | Cross-engine tolerance, replay drift, segment invariants, and model-gated fixtures |
Differential oracle (fj-oracle) |
native_engine kernels (matmul, softmax, layer norm, conv1d) cross-checked against the frankenjax fj-lax interpreter on seeded random tensors, 1e-4 tolerance; feature-gated, see docs/conformance-contract.md |
| Storage and sync | SQLite round trips, concurrent writes, JSONL recovery, and lock ownership |
| Cancellation | Process-tree ownership, stage budgets, cleanup, and interruption |
| Speculation | Windowing, adaptive thresholds, correction drift, and retractions |
| Metamorphic | Audio, normalization, and string-distance invariants |
| CLI integration | End-to-end command behavior with controlled backend fixtures |
A clause-to-test traceability table lives in tests/COVERAGE.md.
Release Engineering
Doodlestein Self Releaser (DSR)
is the canonical release authority. Its local registration builds Linux x86_64
and ARM64, macOS Intel and Apple Silicon, and Windows x86_64 on native/SSH
hosts; packages both franken_whisper and fw; and syncs the exact pinned
frankensqlite, frankentorch, frankentui, and frankentts commits adjacent
to the source tree.
dsr build franken_whisper --version 0.9.2 --dry-run \
--targets darwin/arm64,darwin/amd64,linux/amd64,linux/arm64,windows/amd64
dsr build franken_whisper --version 0.9.2 \
--targets darwin/arm64,darwin/amd64,linux/amd64,linux/arm64,windows/amd64
No GitHub Actions workflow participates in the v0.9.2 release. DSR is the build and packaging authority; the tag and release assets are verified against its local receipts before publication.
Troubleshooting
FW-BACKEND-UNAVAILABLE: native Whisper package is missing
The all-native default requires the compiled-hash-pinned release package. Run
fw pull all to provision both default models, or fw pull whisper for a
transcript-only installation. An operator-supplied GGML model remains available
as an explicit override through --model PATH_OR_SHORT_NAME or
FRANKEN_WHISPER_NATIVE_DEFAULT_MODEL; arbitrary files in legacy search
directories never silently replace the packaged default. To deliberately use
the compatibility bridge instead, install its binary and opt into a bridge
rollout:
# whisper.cpp
brew install whisper-cpp # macOS
# or build from source: https://github.com/ggerganov/whisper.cpp
# or override the binary name
export FRANKEN_WHISPER_WHISPER_CPP_BIN=/path/to/whisper-cli
export FRANKEN_WHISPER_NATIVE_EXECUTION=0
franken_whisper transcribe --input audio.mp3 --backend whisper-cpp --no-diarize
FW-BACKEND-UNAVAILABLE: external diarization requires HF token
The optional pyannote backend needs a HuggingFace API token. The Rust acoustic engine does not:
export FRANKEN_WHISPER_HF_TOKEN="hf_your_token_here"
# or pass directly
franken_whisper transcribe --input audio.mp3 --diarize --hf-token "hf_..."
# or stay entirely in process
franken_whisper transcribe --input audio.mp3 --diarize \
--diarization-engine acoustic
The token is automatically redacted from command logs.
FW-CMD-TIMEOUT: backend exceeded timeout
The backend took longer than the allowed duration:
# increase the overall pipeline timeout (seconds)
franken_whisper transcribe --input long_audio.mp3 --timeout 600 --json
# or raise the per-stage backend budget
FRANKEN_WHISPER_STAGE_BUDGET_BACKEND_MS=1800000 \
franken_whisper transcribe --input long_audio.mp3 --json
Robot mode outputs nothing
Ensure you're using the robot run subcommand, not just robot:
franken_whisper robot run --input audio.mp3 --backend auto
SQLite database is locked
Another franken_whisper process is writing. The storage layer retries with linear backoff (5–40 ms across 8 attempts, ~180 ms total worst case), but simultaneous heavy writes may conflict. Use --no-persist to skip persistence, or use separate --db paths.
Built-in decoder fails on a file ffmpeg handles fine
Some formats or containers are outside symphonia's coverage. Force the ffmpeg path:
export FRANKEN_WHISPER_FORCE_FFMPEG_NORMALIZE=1
franken_whisper transcribe --input exotic_file.opus --json
Native engine produced different output than the bridge
Check the rollout stage:
echo "${FRANKEN_WHISPER_NATIVE_ROLLOUT_STAGE:-sole}"
echo "${FRANKEN_WHISPER_NATIVE_EXECUTION:-1}"
Roll back to fallback while the conformance harness investigates:
export FRANKEN_WHISPER_NATIVE_ROLLOUT_STAGE=fallback
Sync says "lock held by PID X but process gone"
The sync lock is age-gated when the owning PID is unknown. Wait the configured idle window or remove the lock file directly:
rm .franken_whisper/locks/sync.lock
Limitations
- Both default model packages are required for the default pipeline. The installer provisions them, or run
fw pull all.--no-diarizeremoves the Sortformer requirement for a transcript-only request. Explicit bridge modes remain available when their external tools are installed. - ffmpeg only needed for video / exotic formats / batch mic / live fallback. The built-in Rust decoder handles common audio formats natively. Batch
transcribe --micuses ffmpeg;fw robot listenprefers cpal and falls back to ffmpeg only when cpal cannot open the device. - Source checkouts need pinned siblings. The Git checkout intentionally uses versioned path dependencies for FrankenSQLite, FrankenTorch, and optional FrankenTUI development. Run
scripts/prepare_release_siblings.shbefore a source build. The crates.io package resolves the same version requirements from the registry and does not require sibling checkouts. - Native execution is the default, not a certification claim. The
solestage prevents silent bridge fallback. Sortformer remains development-uncertified and capped at four anonymous lanes despite being the product default. - One-way sync. JSONL export / import is one-way. There is no bidirectional merge beyond the explicit
--conflict-policyflag. - Single-machine. Designed for single-machine use with local SQLite. No distributed or multi-node support.
- ffmpeg auto-provisioning is Linux x86_64 only. On other platforms (
macOS, Windows, Linux ARM) install ffmpeg manually for formatssymphoniacannot decode, batch microphone capture, or live-capture fallback.
FAQ
Q: Do I need all three backends installed?
No. The default install needs no bridge backend: it provisions the native
Whisper and Sortformer packages and runs both stages in process. External tools
are explicit compatibility/evaluation choices. fw pull all repairs or
provisions the native cache if it is missing.
Q: What audio formats are supported? Common audio formats (MP3, AAC, FLAC, WAV, OGG, Vorbis, ALAC) are decoded in-process by the built-in Rust decoder without an external decoder. Video files and exotic codecs (AC3, DTS, Opus-in-MKV) fall back to ffmpeg automatically.
Q: Can I use this as a library?
Yes. franken_whisper is both a library crate and a binary. The public API exposes all modules: backend, orchestrator, robot, storage, tty_audio, conformance, speculation, etc.
Q: What's the "replay envelope"?
Each run produces a ReplayEnvelope containing SHA-256 hashes of the input content, backend identity, and output payload. This allows detecting drift when re-running the same input.
Q: What's the "replay pack"?
A four-file deterministic bundle (env.json, manifest.json, repro.lock, tolerance_manifest.json) that captures everything needed to reproduce a run on a different machine. The same report on the same runtime is byte-identical; env.json intentionally differs when OS or architecture differs.
Q: How does cancellation work?
Ctrl+C sets a global shutdown flag. The CancellationToken propagates through
pipeline stages, including inner word-timestamp loops. Each stage checks the
token at bounded work boundaries. SQLite work rolls back and owned subprocess
cleanup is verified; if cleanup cannot be certified, the command returns an
error that retains the original cancellation outcome.
Q: What's the TTY audio module for? It enables audio transport over constrained TTY/PTY links where binary data can't flow directly. Audio is compressed (mu-law + zlib), base64-encoded, and transmitted as NDJSON lines with sequence numbers, CRC32, and SHA-256 integrity hashes. Protocol v2 also defines transcript control frames (partial / retract / correct) with library emitters and parsers; wiring a live CLI producer onto the link is not done yet.
Q: How does the Bayesian router differ from a simple priority list? A priority list always tries backends in the same order. The Bayesian router learns from outcomes: if a backend starts failing, its posterior degrades and traffic shifts to alternatives. When the model is poorly calibrated (Brier > 0.35), it falls back to static priority automatically, but continues recording calibration observations so it can resume adaptive routing once the data improves.
Q: What happens if I Ctrl+C during a long transcription? The shutdown controller propagates cancellation through the pipeline. The active stage reaches a checkpoint, rolls back uncommitted transactions, terminates owned subprocess trees, and runs finalizers within the cleanup budget. A verified cancellation exits with code 130; cleanup-verification failure is surfaced as an error.
Q: What's speculative streaming?
Two models run simultaneously: a fast model produces low-latency partial transcripts while a quality model runs in parallel. When the quality model finishes each window, it either confirms or corrects the fast model's output. Use --speculative when you need both low latency and high accuracy.
Q: What's TinyDiarize?
--tiny-diarize enables speaker-turn tokens in a TinyDiarize-trained Whisper
checkpoint. Native inference and the whisper.cpp bridge both support it; use
an appropriate model such as a local ggml-small.en-tdrz.bin, rather than
expecting an ordinary Whisper checkpoint to acquire this capability.
The native result exposes ordered, source-relative turn hints in
raw_output.tiny_diarize.boundaries_ms. Only accepted text spans with an
actual closing timestamp supply a boundary. Untimed output, unfinished spans,
silence, and rejected decoding attempts cannot invent a turn time. The hints
can support the acoustic diarization stage when it runs, but they do not assign
speaker identities or replace the full diarization pipeline. Real-model turn
accuracy and calibration remain separate from this option's implementation.
Q: Why SQLite instead of Postgres / Redis / files?
SQLite fits a single-machine CLI tool: zero configuration, no daemon, ACID transactions, concurrent reads via WAL mode. The fsqlite crate provides a Rust-native interface without depending on system libsqlite3. JSONL export / import covers portability.
Q: Can franken_whisper transcribe video files?
Yes. Any video file ffmpeg can decode (MP4, MKV, AVI, MOV, WebM, …) is handled automatically. The ffmpeg fallback extracts the audio track using -vn.
Q: What's the "alien-artifact engineering contract"?
A design discipline for adaptive controllers. Every adaptive system in franken_whisper (the router, the bitrate controller, the budget tuner, the speculation window controller, the correction tracker, and the default-off live cadence/holdback controllers) must declare an explicit state space, action space, loss matrix, calibration metric, deterministic fallback trigger, and evidence ledger. This prevents adaptive systems from making unbounded bad decisions when their models are wrong.
Q: Will my HuggingFace token end up in log files?
No. Every command line is rendered through render_command_for_log() which redacts --hf-token values. The redaction applies to tracing output, error messages, and snapshot tests alike.
Q: How is native engine quality enforced?
The conformance harness compares native vs. bridge output on a fixture corpus at every rollout-stage promotion. A native engine that produces timestamps > 50 ms different from the bridge for the same audio is blocked from advancing past validated. Replay envelopes detect drift between runs, and the rollout stage is recorded in every backend.ok event and replay envelope for post-hoc analysis.
Anatomy of a Transcription Run
Step by step, when you run franken_whisper transcribe --input meeting.mp3 --json --backend auto:
1. CLI PARSE
Clap parses args -> TranscribeRequest { input: "meeting.mp3", backend: Auto, json: true, ... }
2. ENGINE CONSTRUCTION
FrankenWhisperEngine::new() opens SQLite database, initializes tracing
3. PIPELINE COMPOSITION
PipelineBuilder evaluates request flags:
- No --vad flag -> skip VAD stage
- No --diarize flag -> include native Sortformer diarization (default)
- Accelerate excluded -> skip confidence normalization
- --no-persist NOT set -> include Persist stage (default)
Pipeline: [Ingest, Normalize, Backend, Diarize, Persist]
4. TRACE ID GENERATION
TraceId::from_parts(1710000000000, random_u64) -> "1710000000000-a1b2c3d4e5f6"
5. INGEST STAGE (budget: 15s)
emit: stage { code: "ingest.start" }
Verify meeting.mp3 exists, get file size
emit: stage { code: "ingest.ok", payload: { size_bytes: 1234567 } }
6. NORMALIZE STAGE (budget: 180s)
emit: stage { code: "normalize.start" }
Try built-in Rust decoder (symphonia):
- Detect format: MP3
- Decode packets -> f32 samples
- Mix stereo -> mono (average channels using actual frame length)
- Resample 44.1 kHz -> 16 kHz (linear interpolation)
- Quantize f32 -> i16 PCM
- Write normalized_16k_mono.wav
emit: stage { code: "normalize.ok", payload: { method: "builtin", duration_ms: 260 } }
7. BACKEND STAGE (budget: 900s)
emit: stage { code: "backend.routing.decision_contract" }
Bayesian router evaluates:
- Probe availability: whisper_cpp=true, insanely_fast=false, diarization=false
- State: partial_available
- Compute loss matrix (latency*0.45 + quality*0.35 + failure*0.20)
- Best action: try_whisper_cpp (lowest expected loss)
- Calibration check: Brier=0.12, score=0.8 -> adaptive mode (no fallback)
- Record predicted_probability into the calibration sliding window
emit: stage { code: "backend.start", payload: { backend: "whisper_cpp" } }
Resolve and verify the pinned GGML model package
Run the Rust-native Whisper frontend, encoder, decoder, and DTW alignment
Assemble TranscriptionResult { transcript, segments, language }
emit: stage { code: "backend.ok",
payload: { segments: 42, language: "en",
implementation: "native",
native_rollout_stage: "sole" } }
8. CONFIDENCE NORMALIZATION (inline, no separate stage)
Replace missing confidences with ln(1 + char_count) + 1.0
Divide each positive finite value by their total mass
Record pre_mass=34.2, post_mass=1.0 in AccelerationReport
9. DIARIZE STAGE (budget: 900s)
Verify and load the pinned native Sortformer package
Infer anonymous activity lanes and overlap, then project turns onto segments
If the package or request is capacity-ineligible, use the explicit acoustic fallback
emit: stage { code: "diarize.ok", payload: { resolved_engine: "sortformer" } }
10. PERSIST STAGE (budget: 20s)
emit: stage { code: "persist.start" }
SAVEPOINT fw_persist_1
INSERT INTO runs (run_id, started_at, ...)
INSERT INTO segments (42 rows)
INSERT INTO events (8 rows)
token.checkpoint() -> Ok (not cancelled)
RELEASE SAVEPOINT fw_persist_1
emit: stage { code: "persist.ok" }
11. LATENCY PROFILING
emit: stage { code: "orchestration.latency_profile" }
Per-stage utilization: normalize=0.14% (decrease_budget_candidate),
backend=2.3% (decrease_budget_candidate),
persist=0.5% (decrease_budget_candidate)
12. REPLAY ENVELOPE
Compute SHA-256(normalized_16k_mono.wav) -> input_content_hash
Record backend_identity: "whisper.cpp-native", backend version and package identity
Compute SHA-256(raw_backend_json) -> output_payload_hash
Record native_rollout_stage: "sole"
13. CALIBRATION UPDATE
Record actual_outcome = 1.0 (success) against the predicted_probability from step 7
14. REPORT ASSEMBLY
RunReport { run_id, trace_id, request, result, events, evidence, replay, warnings }
15. OUTPUT
Serialize RunReport as JSON -> stdout
Exit code 0
Total wall time for a 2-minute MP3: typically 5–15 seconds depending on backend and hardware.
Integration Examples
Pipe Robot Output to jq
# Extract just the transcript from a robot run
franken_whisper robot run --input audio.mp3 --backend auto 2>/dev/null \
| jq -r 'select(.event == "run_complete") | .transcript'
# Monitor pipeline progress in real time
franken_whisper robot run --input audio.mp3 --backend auto 2>/dev/null \
| jq -r 'select(.event == "stage") | "\(.code): \(.message)"'
# Extract all segments with timestamps
franken_whisper robot run --input audio.mp3 --backend auto 2>/dev/null \
| jq -r 'select(.event == "run_complete") | .segments[] | "[\(.start_sec)s - \(.end_sec)s] \(.text)"'
Batch Transcription Script
#!/bin/bash
# Transcribe all audio files in a directory
for file in recordings/*.mp3; do
echo "Transcribing: $file"
franken_whisper transcribe --input "$file" --json --no-persist \
| jq -r '.result.transcript' > "${file%.mp3}.txt"
done
Health Check in CI/CD
# Verify all backends are available before running tests
status=$(franken_whisper robot health 2>/dev/null | jq -r '.overall_status')
if [ "$status" != "ok" ]; then
echo "Backend health check failed"
franken_whisper robot health 2>/dev/null | jq '.backends[] | select(.available == false)'
exit 1
fi
Export and Archive Run History
# Full export
franken_whisper sync export-jsonl --output ./backup
# Gzip the snapshot out-of-band (the import path auto-detects .gz)
gzip ./backup/*.jsonl
# Re-import into a scratch DB to verify the snapshot round-trips
franken_whisper sync import-jsonl --input ./backup --conflict-policy reject \
--db /tmp/verify.sqlite3
TTY Audio Over SSH
# On the remote machine (audio source):
franken_whisper tty-audio encode --input recording.wav \
| ssh user@local-machine 'franken_whisper tty-audio decode --output received.wav'
# With retransmit recovery for lossy links:
franken_whisper tty-audio encode --input recording.wav > frames.ndjson
cat frames.ndjson | ssh user@remote 'cat > /tmp/frames.ndjson'
# On remote, check for gaps:
ssh user@remote 'cat /tmp/frames.ndjson | franken_whisper tty-audio retransmit-plan'
Library Usage in Rust
use franken_whisper::model::{
BackendKind, BackendParams, InputSource, TranscribeRequest,
};
use franken_whisper::orchestrator::FrankenWhisperEngine;
use franken_whisper::storage::RunStore;
use std::path::{Path, PathBuf};
fn transcribe_file(path: &str) -> Result<String, Box<dyn std::error::Error>> {
let request = TranscribeRequest {
input: InputSource::File { path: PathBuf::from(path) },
backend: BackendKind::Auto,
model: None,
language: None,
translate: false,
diarize: false,
persist: true,
db_path: PathBuf::from(".franken_whisper/storage.sqlite3"),
timeout_ms: None,
backend_params: BackendParams::default(),
};
let engine = FrankenWhisperEngine::new()?;
let report = engine.transcribe(request)?;
Ok(report.result.transcript)
}
fn query_history(db_path: &str, limit: usize) -> Result<(), Box<dyn std::error::Error>> {
let store = RunStore::open(Path::new(db_path))?;
let runs = store.list_recent_runs(limit)?;
for run in &runs {
println!("{}: {} ({})", run.run_id, run.transcript_preview, run.backend);
}
Ok(())
}
Monitoring Routing Decisions
# See how the Bayesian router is performing (NDJSON: one routing_decision per
# line, then a routing_history.complete summary)
franken_whisper robot routing-history --limit 20 2>/dev/null \
| jq -c 'select(.event == "routing_decision")
| {decision_id, chosen_action, calibration_score, e_process, fallback_active}'
# Track correction rates in speculative mode
franken_whisper robot run --input audio.mp3 --speculative \
--fast-model tiny.en --quality-model large-v3 2>/dev/null \
| jq 'select(.event == "transcript.speculation_stats")'
What Makes This Different
Learned backend selection
WhisperS2T, transcribe-anything, and WhisperLive let you pick a backend. franken_whisper learns which backend to use based on observed outcomes. The Bayesian router maintains Beta-distribution posteriors per backend, tracks calibration via Brier scoring, and falls back to deterministic priority when uncertain, without losing calibration data while the fallback is active.
Cross-engine conformance validation
The conformance harness compares segment output across engines using a 50 ms canonical timestamp tolerance, text matching, speaker label matching, WER approximation, and replay envelope drift detection. The 5-stage native rollout governance prevents buggy engines from silently degrading quality.
End-to-end dual-model speculative streaming
A fast model and a quality model run in parallel on overlapping windows; partial transcripts emit immediately and corrections issue when the quality model disagrees. The CorrectionTracker adaptively adjusts confirmation thresholds. Speculation events stream into the robot NDJSON log as they are produced; the protocol v2 TTY transcript frames that could carry them over a TTY link exist at the library level only.
Full audit trail on every run
Every run is persisted to SQLite with the complete request, result, segments, pipeline events, evidence, and replay envelope. Full and incremental JSONL export with SHA-256 checksums and optional gzip compression.
Audio decoded without an external process
The built-in Rust decoder handles MP3, AAC, FLAC, WAV, OGG, Vorbis, and ALAC natively. No subprocess, no external binary, no PATH dependency. ffmpeg is only the fallback.
Agent consumption is the primary interface
The robot subcommand is the primary interface: sequenced NDJSON events with stable schema versioning (v1.1.0), 13 exact terminal error codes, health diagnostics, routing history, speculation events, and structured error envelopes even for argument-parsing failures.
Audited Rust safety boundaries
franken_whisper denies unsafe code by default. Explicitly annotated
native-engine kernels use runtime-gated SIMD or fully-overwritten preallocated
buffers and carry local safety arguments; unannotated unsafe code is rejected.
Cooperative cancellation, atomic transactions, bounded finalizers, and RAII
cleanup provide the operational safety boundary around inference.
Key Documentation
| Document | Description |
|---|---|
docs/tty-audio-protocol.md |
Complete TTY audio protocol specification |
docs/tty-replay-guarantees.md |
Deterministic replay/framing guarantees |
docs/native_engine_contract.md |
Native engine replacement interface contract |
docs/engine_compatibility_spec.md |
50 ms timestamp tolerance specification |
docs/conformance-contract.md |
Cross-engine conformance test contract |
docs/operational-playbook.md |
Deployment and monitoring guide |
docs/benchmark_regression_policy.md |
Performance regression thresholds |
tests/COVERAGE.md |
Spec clause → test traceability |
RECOVERY_RUNBOOK.md |
Disaster recovery procedures |
SYNC_STRATEGY.md |
One-way sync semantics |
docs/planning/PROPOSED_ARCHITECTURE.md |
System architecture design document |
FEATURE_PARITY.md |
Legacy feature parity matrix |
CHANGELOG.md |
Capability-wave changelog with live commit links |
DISCREPANCIES.md |
Known native-vs-bridge divergences under investigation |
Worked Examples
These examples walk through the actual math and bit-level operations of the most opaque algorithms in the system, using concrete inputs. They are intentionally arithmetic-heavy: the goal is to make the behavior of the algorithms verifiable by hand rather than treating the implementation as a black box.
Worked Example: A Single Bayesian Routing Decision
Suppose a user runs franken_whisper transcribe --input meeting.mp3 --backend auto --no-diarize on a 6-minute audio file. The user's PATH has whisper-cli and insanely-fast-whisper installed but no python3 for whisper-diarization. The Brier score from recent runs is 0.18 and the calibration sliding window holds 32 observations.
Step 1. Detect availability. The router probes via which:
whisper_cpp : available
insanely_fast : available
whisper_diarization: unavailable
state : partial_available
Step 2. Establish duration bucket. 6 minutes = 360 seconds. Bucket: long (≥ 60 s).
Step 3. Compute latency cost per backend. latency_cost = base + sqrt(360) × multiplier_normal:
whisper_cpp : 12.0 + sqrt(360) * 1.0 ≈ 12.0 + 18.97 = 30.97
insanely_fast : 8.0 + sqrt(360) * 1.0 ≈ 8.0 + 18.97 = 26.97
whisper_diarization: 18.0 + sqrt(360) * 1.0 ≈ 18.0 + 18.97 = 36.97
Step 4. Compute quality cost per backend. quality_cost = (1.0 - quality_score) × 100 with diarize=false:
whisper_cpp : (1.0 - 0.84) * 100 = 16.0
insanely_fast : (1.0 - 0.80) * 100 = 20.0
whisper_diarization: (1.0 - 0.63) * 100 = 37.0
Step 5. Compute posterior success probability per backend. Beta priors (α, β) updated with the current sliding window. Suppose recent empirical success rates are: whisper_cpp 0.93 (20 obs), insanely_fast 0.81 (12 obs), whisper_diarization no data:
whisper_cpp : α' = 7 + 0.93*20 = 25.6 β' = 3 + 0.07*20 = 4.4
p_success ≈ (25.6 + 0.84*2 + 0.3) / (25.6 + 4.4 + 1.68 + 0.3) ≈ 0.870
insanely_fast : α' = 6 + 0.81*12 = 15.72 β' = 4 + 0.19*12 = 6.28
p_success ≈ (15.72 + 0.80*2 + 0.3) / (15.72 + 6.28 + 1.6 + 0.3) ≈ 0.738
whisper_diarization: α = 5 β = 5 (prior only)
p_success = 0 (unavailable; availability penalty kicks in)
Step 6. Compute failure cost per backend.
whisper_cpp : (1.0 - 0.870) * 100 = 13.0
insanely_fast : (1.0 - 0.738) * 100 = 26.2
whisper_diarization: full availability penalty
Step 7. Combine into total cost (0.45 × latency + 0.35 × quality + 0.20 × failure):
whisper_cpp : 0.45*30.97 + 0.35*16.0 + 0.20*13.0
= 13.937 + 5.600 + 2.600 = 22.14
insanely_fast : 0.45*26.97 + 0.35*20.0 + 0.20*26.2
= 12.137 + 7.000 + 5.240 = 24.38
whisper_diarization: availability penalty (+1000) dominates → ≈ 1000+
Step 8. Calibration check. Brier = 0.18 (< 0.35 threshold) and observation count = 32 (≥ 5). Calibration is good, so the router stays in adaptive mode (no static fallback).
Step 9. Choose action. Lowest cost is try_whisper_cpp at 22.14. The router selects whisper_cpp.
Step 10. Record evidence and prediction. Push a RoutingEvidenceLedgerEntry (decision_id, trace_id, observed_state=partial_available, chosen_action=try_whisper_cpp, policy_id=backend-selection-v1.0, loss_matrix_hash) into the 200-entry circular buffer. Push the predicted probability (0.870) into the calibration sliding window. Emit the backend.routing.decision_contract event with full posterior snapshot for the agent.
Step 11. After the run. Once the backend finishes, record the actual outcome (1.0 = success or 0.0 = failure) against the prediction. The Brier score is recomputed. The Beta posterior for whisper_cpp updates: success bumps α, failure bumps β.
The same shape of calculation runs for every --backend auto decision. The math itself is microseconds; the audit trail is the expensive part, and it's worth it.
Worked Example: Mu-Law Encoding a Single Sample
In practice franken_whisper shells out to ffmpeg -f mulaw -ar 8000 -ac 1 for the actual transcoding. The bit-level math below is the codec definition, useful for debugging a captured wire trace or for understanding what ffmpeg is doing on your behalf.
Take a 16-bit signed PCM sample value s = 12_345 (positive). Encode to mu-law:
1. Clamp to ±32635:
s = min(max(12345, -32635), 32635) = 12345 ✓
2. Extract sign (0 = positive, 1 = negative):
sign = 0
3. Add bias:
magnitude = |12345| + 132 = 12477 (binary: 0011 0000 1011 1101)
4. Find segment = position of the highest set bit minus 7 (clamped to [0, 7]).
Highest set bit in 12477 is bit 13.
segment = 13 - 7 = 6.
5. Extract 4-bit mantissa = bits (segment+3 .. segment) shifted down:
shift the magnitude right by (segment + 3) = 9 bits:
12477 >> 9 = 24 = 0001 1000
mantissa = 24 & 0xF = 8.
6. Combine into 8 bits: (sign << 7) | (segment << 4) | mantissa
= (0 << 7) | (6 << 4) | 8
= 0110 1000 = 0x68 = 104
7. Invert all bits (wire format convention):
~0x68 = 0x97 = 151
Wire byte = 0x97
To decode 0x97 back to PCM:
1. Invert: ~0x97 = 0x68
2. sign = 0, segment = 6, mantissa = 8
3. Reconstruct magnitude:
m_raw = ((mantissa << 3) + 132) << (segment + 1) - 132
= ((8 << 3) + 132) << 7 - 132
= (64 + 132) << 7 - 132
= 196 << 7 - 132
= 25088 - 132 = 24956
4. Apply sign: +24956
The reconstructed value (24956) differs from the original (12345). Mu-law is lossy: it preserves dynamic range (loud sounds remain loud, quiet sounds remain quiet) but quantizes intermediate values. The compression ratio is exactly 2:1 (16 bits → 8 bits) and the error is logarithmically distributed, so perceived quality stays high for speech. Adding zlib compression on top of the mu-law byte stream typically achieves another 30–50% reduction, since mu-law-encoded speech has substantial statistical redundancy.
Worked Example: Brier Score Decomposition
The Brier score B = (1/N) Σ (p_i − o_i)² admits Murphy's three-component decomposition:
B = reliability − resolution + uncertainty
where, partitioning the N predictions into K bins by predicted probability p_k (with n_k observations per bin and observed mean outcome ō_k per bin):
- reliability =
(1/N) Σ_k n_k (p_k − ō_k)². How close predicted probabilities are to observed frequencies (smaller is better; perfect reliability = 0). - resolution =
(1/N) Σ_k n_k (ō_k − ō)². How much predictions vary around the base rateō(larger is better). - uncertainty =
ō (1 − ō). Irreducible noise in the outcome (a property of the data, not the predictor).
A backend router that always predicts the base rate has perfect reliability (0) but zero resolution → Brier score = uncertainty. A perfectly calibrated and confident router has zero reliability AND large resolution → Brier score much smaller than uncertainty.
This decomposition explains why franken_whisper falls back at Brier > 0.35: if reliability is bad (predicted probabilities don't match observed frequencies), the router is making systematically biased predictions and the safer play is the static priority list. Once the calibration sliding window accumulates enough corrective observations to bring reliability back down, adaptive routing automatically resumes. The fallback path's calibration recording is what makes this recovery possible.
Anatomy Series
Anatomy of a Routing Decision
0. backend.routing.decision_contract emit (event sequence #N)
payload includes: state, available[], duration_bucket, diarize, posteriors[], loss_matrix, chosen
1. probe_system_health()
for each backend kind:
- check FRANKEN_WHISPER_<KIND>_BIN override
- else `which <default_binary>` (e.g. `which whisper-cli`)
- record availability bool
2. derive observed_state:
if all 3 available → all_available
if 1-2 available → partial_available
if 0 available → none_available (will emit FW-BACKEND-UNAVAILABLE)
3. build action set: [try_whisper_cpp, try_insanely_fast, try_diarization, fallback_error]
reorder per diarize flag (diarization-first when --diarize is set)
4. for each (state, action) cell of the 3×4 loss matrix:
compute latency_cost = base + sqrt(duration_secs) * multiplier
compute quality_cost = (1 - quality_proxy(action, request)) * 100
compute failure_cost = (1 - p_success(action, posterior, request)) * 100
weighted = 0.45*latency + 0.35*quality + 0.20*failure
add availability penalty (+0 / +333 / +1000)
5. calibration check:
read sliding window (50 entries)
if observations < 5: use_static_priority = true
if calibration_score < 0.3: use_static_priority = true
if brier_score > 0.35: use_static_priority = true
6. select action:
if use_static_priority:
follow deterministic priority list (whisper_cpp > insanely_fast > whisper_diarization)
else:
argmin over cost cells
7. record:
- push RoutingEvidenceLedgerEntry into 200-entry circular buffer
- push (predicted_probability, observed_at) into 50-entry calibration sliding window
(recorded even when fallback path executes, so calibration keeps learning)
- emit `backend.routing.decision_contract` event with full posterior snapshot
8. dispatch to chosen backend (or return FW-BACKEND-UNAVAILABLE if action = fallback_error)
Anatomy of a TTY Audio Session
ENCODER DECODER
1. encode_wav_to_frames(input):
load WAV, verify 16 kHz mono
transcode PCM → mu-law (2:1 compression)
chunk into chunk_ms windows (default 200 ms = 3200 mu-law bytes)
2. emit Handshake frame:
min_version=1, max_version=2, codecs=[mulaw+zlib+b64]
3. receive Handshake:
select max compatible version
select first compatible codec
emit HandshakeAck
4. for each chunk:
payload = zlib_compress(mulaw_bytes)
crc32 = crc32(mulaw_bytes)
sha256 = sha256(mulaw_bytes)
payload_b64 = base64(payload)
emit AudioFrame { seq, codec, sample_rate_hz, channels, payload_b64, crc32, sha256 }
5. for each AudioFrame:
validate codec
if seq != expected: record gap
if seq == previous: record duplicate, skip
decode b64 → zlib_decompress → mulaw
verify crc32 and sha256 against raw mulaw
if mismatch: integrity_failure++, drop frame
mulaw → PCM, append to WAV buffer
6. emit SessionClose { reason=Complete, last_data_seq=N }
7. receive SessionClose:
if any seq <= N missing:
emit RetransmitRequest with missing sequences
else: emit Ack { up_to_seq=N }; finalize WAV
8. on RetransmitRequest:
look up requested sequences in send buffer
emit RetransmitResponse with payloads
if adaptive bitrate active and loss > 10%, escalate compression and FEC
9. retransmit_loop escalates across rounds:
Round 1 (Simple) : emit 1 copy per missing frame
Round 2 (Redundant): emit 2 copies
Round 3 (Escalate) : emit 4 copies
If link quality is poor (frame_loss_rate > 10%) the encoder pre-emptively duplicates critical control frames (Handshake, SessionClose, Ack) 3× so they survive independent loss probabilistically. The decoder dedupes by sequence number, so duplication never produces duplicate output.
Anatomy of a Conformance Check
1. load expected segments (golden fixture from tests/fixtures/conformance/...)
2. load observed segments (from bridge or native engine output)
3. validate segment invariants on each side:
for each segment:
assert start_sec, end_sec are finite (not NaN, not ±∞)
assert start_sec >= 0
assert end_sec >= start_sec
assert confidence ∈ [0.0, 1.0]
assert text is non-empty
for each adjacent pair:
assert segments[i].end_sec <= segments[i+1].start_sec + overlap_epsilon (1 µs default)
4. compare lengths:
N = expected.len(), M = observed.len()
if N != M: length_mismatch = true
5. for i in 0..min(N, M):
if require_text_exact and text differs: text_mismatches++
if require_speaker_exact and speaker differs: speaker_mismatches++
if |expected[i].start - observed[i].start| > 0.05: timestamp_violations++
if |expected[i].end - observed[i].end| > 0.05: timestamp_violations++
6. compute WER via Levenshtein on word sequences:
tokenize both transcripts by whitespace
edit_distance = levenshtein(expected_words, observed_words)
wer = edit_distance / max(reference_length, 1) clamped to [0, 1]
7. return SegmentComparisonReport {
length_mismatch, text_mismatches, speaker_mismatches,
timestamp_violations, segments_compared, wer_approx
}
8. at rollout-stage promotion:
conformance gate requires:
timestamp_violations == 0 (50 ms tolerance)
all segment invariants pass
replay envelope matches (input_hash + backend_version → output_hash)
if any check fails, promotion is blocked
Anatomy of a Speculative Window
1. WindowManager.next_window():
advance sliding window by (window_ms - overlap_ms)
compute sha256 of window audio content
allocate window_id
2. ConcurrentTwoLaneExecutor.spawn_lanes():
fast_lane: spawn fast_model on window with timeout budget
quality_lane: spawn quality_model on window with timeout budget
3. fast_lane returns first (by design):
build PartialTranscript { window_id, model_id=fast, segments, status=Pending }
emit transcript.partial event with monotonically increasing seq
4. quality_lane returns:
compute CorrectionDrift:
wer_approx = levenshtein(fast_words, quality_words) / max(...)
confidence_delta = |mean(fast_conf) - mean(quality_conf)|
segment_count_delta = quality.len() - fast.len()
text_edit_distance = levenshtein(fast_text, quality_text)
5. CorrectionTracker.evaluate(drift):
if all metrics within CorrectionTolerance:
emit transcript.confirm {
seq, window_id, quality_model_id, drift, latency_ms, ts
}
status = Confirmed
else:
emit transcript.retract {
retracted_seq, window_id, reason, quality_model_id, ts
}
emit transcript.correct {
correction_id, replaces_seq, window_id,
segments (from quality model), drift, latency_ms, ts
}
status = Retracted
6. SpeculationWindowController.update():
record outcome (correction or not) into observation buffer (size 20)
compute Brier score on corrections vs. predicted corrections
if brier > 0.25 and observations >= 10:
use deterministic fallback (fixed window_ms)
else:
adjust window_ms by ±step_ms based on correction rate pattern
7. periodic emit speculation.stats {
windows_processed, corrections_emitted, confirmations_emitted,
correction_rate, mean_fast_latency_ms, mean_quality_latency_ms,
current_window_size_ms, mean_drift_wer, ts
}
The whole flow is end-to-end safe to ship over TTY: every event has a wire-efficient TranscriptSegmentCompact representation (s / e / t / sp / c single-letter fields), and the controller's adaptive behavior is bounded by its alien-artifact contract.
Operational Topics
State Directory Layout
The state directory is $FRANKEN_WHISPER_STATE_DIR when set, otherwise .franken_whisper/ under the current directory. It is the default home of the run-history database (every --db defaults to <state dir>/storage.sqlite3; FRANKEN_WHISPER_DB overrides that default for all commands), of sync locks and the incremental cursor (sync --state-root), and of per-run work directories:
<state dir>/
├── storage.sqlite3 # run-history database (unless --db / FRANKEN_WHISPER_DB)
├── storage.sqlite3-wal # write-ahead log
├── storage.sqlite3-shm # shared memory file (transient)
├── locks/
│ ├── sync.lock # JSON lock file for sync export/import
│ │ # { "pid", "created_at_rfc3339", "operation" }
│ └── sync.lock.guard # advisory lock serializing lock acquisition
├── sync_cursor.json # incremental export cursor (--incremental)
└── tmp/
└── fw-run-{id}/ # per-run work directory (LIFO finalizers clean up)
├── normalized_16k_mono.wav
└── ... # backend / subprocess scratch files
Auto-provisioned ffmpeg/ffprobe live under tools/ffmpeg/bin/ of a separate tools root: $FRANKEN_WHISPER_STATE_DIR when set, else $XDG_STATE_HOME/franken_whisper, else ~/.local/state/franken_whisper, so multiple project trees share one download.
CLI Exit Codes
| Code | Meaning | Triggered by |
|---|---|---|
| 0 | Success | Pipeline completed and (if requested) JSON/NDJSON emitted |
| 1 | General error | Any FwError propagated to main() (FW-IO, FW-CMD-*, FW-STORAGE, FW-BACKEND-UNAVAILABLE, FW-INVALID-REQUEST, etc.) |
| 2 | Argument parse failure | clap's default exit code on invalid command-line syntax (occurs before the binary's own error handling runs) |
| 130 | Cancelled | Ctrl+C (POSIX convention: 128 + SIGINT=2) |
Process exits are deliberately coarse and published by fw capabilities --json: 0 for success, 1 for a parsed request that failed at runtime, 2 for invalid command syntax or values, and 130 for interruption. In robot mode, agents should inspect the final JSON/NDJSON event and its exact FW-* code; the process status classifies lifecycle, not root cause.
Logging
franken_whisper uses tracing for structured diagnostics. Set RUST_LOG to control verbosity.
Text format (default):
RUST_LOG=info franken_whisper transcribe --input audio.mp3 --json
# 2026-05-17T12:34:56Z INFO franken_whisper::orchestrator: stage=normalize started budget_ms=180000
# 2026-05-17T12:34:56Z INFO franken_whisper::audio: builtin decoder selected format=mp3
# 2026-05-17T12:35:00Z INFO franken_whisper::orchestrator: stage=normalize ok service_ms=257
JSON format (for log aggregation):
RUST_LOG=info RUST_LOG_FORMAT=json franken_whisper transcribe --input audio.mp3 --json
# {"timestamp":"2026-05-17T12:34:56.123Z","level":"INFO","target":"franken_whisper::orchestrator","fields":{"stage":"normalize","status":"started","budget_ms":180000}}
Filtering recipes:
# Backend routing only
RUST_LOG=franken_whisper::backend=debug franken_whisper transcribe --input audio.mp3 --json
# TTY audio decode telemetry
RUST_LOG=franken_whisper::tty_audio=trace franken_whisper tty-audio decode --output a.wav < frames.ndjson
# Sync internals
RUST_LOG=franken_whisper::sync=debug franken_whisper sync export-jsonl --output ./snapshot
# Everything verbose except hyper / clap noise
RUST_LOG=franken_whisper=debug,clap=warn franken_whisper transcribe --input audio.mp3 --json
Secret values (HuggingFace tokens, in particular) never enter the log stream; render_command_for_log() redacts them before any subprocess invocation is recorded.
Concurrent Agents Pattern
Multiple agents can persist into a single SQLite database safely:
// Agent A's session
let store = RunStore::open(&db_path)?;
let session = store.begin_concurrent_session("agent_alpha")?;
session.persist_report(&report_a)?;
session.commit()?; // RELEASE SAVEPOINT fw_session_agent_alpha
// Agent B can run concurrently against the same database:
let store_b = RunStore::open(&db_path)?;
let session_b = store_b.begin_concurrent_session("agent_beta")?;
session_b.persist_report(&report_b)?;
session_b.commit()?;
Concurrency guarantees:
- WAL mode allows multiple readers and one writer at any instant.
busy_timeout=5000lets writers wait up to 5 seconds on lock contention.- Each
begin_concurrent_sessionopens a named savepoint (fw_session_<name>); session names are validated to[A-Za-z0-9_]+so they cannot escape into SQL. - Persist transactions retry on
SQLITE_BUSYwith linear backoff (5 × (attempt + 1)ms, up to 8 attempts). - The cancellation token is checked before every
COMMITandRELEASE, so Ctrl+C never leaves the database in an inconsistent state.
Coordination via MCP Agent Mail. When the agents are coordinating work (not just sharing a database), the same project conventions used in this repository apply: each agent registers via register_agent, reserves file paths via file_reservation_paths with the issue ID in reason, and communicates via threaded messages keyed by br-NNN issue IDs. The database concurrency primitives above are necessary but not sufficient; the agent-coordination layer prevents two agents from trying to do the same work in the first place.
Database Maintenance
The SQLite database accumulates rows over time. For long-lived deployments:
-- Inspect WAL growth and freelist
.open .franken_whisper/storage.sqlite3
PRAGMA wal_checkpoint(TRUNCATE); -- force a full WAL checkpoint
PRAGMA freelist_count; -- how many unused pages
PRAGMA page_count; -- total pages
PRAGMA integrity_check; -- verify database integrity
-- Reclaim space after large deletes (run when no writers are active)
VACUUM;
robot health reports all of these in its database field. A reasonable monitoring rule: alert when wal_checkpoint.log_frames stays above a threshold across consecutive probes, which indicates a long-lived read transaction is preventing checkpointing.
Backup procedure (recommended):
# 1. Export the database state to portable JSONL
franken_whisper sync export-jsonl --output backup/$(date +%F)/
# 2. Gzip out-of-band (import reads .jsonl.gz transparently)
gzip backup/$(date +%F)/*.jsonl
# 3. Verify the export integrity against the live database
franken_whisper sync import-jsonl --input backup/$(date +%F)/ \
--conflict-policy skip
# 4. Copy the snapshot off-host
rsync -a backup/$(date +%F)/ user@host:/srv/franken_whisper/backups/
JSONL snapshots are the canonical recovery artifact. They are portable across machines and SQLite versions, deduplicate cleanly across incremental exports, and carry SHA-256 checksums in manifest.json for end-to-end integrity verification.
Recovery from Corruption
If PRAGMA integrity_check reports corruption or the database refuses to open:
- Don't run
VACUUMon a corrupted database; it can make things worse. - Try to dump what's salvageable by exporting recent runs from a different process:
franken_whisper sync export-jsonl --output recovery/ --db <corrupted>.sqlite3 - Move the corrupted database aside:
mv .franken_whisper/storage.sqlite3{,.corrupted-$(date +%F)} - Rebuild from the last good JSONL snapshot:
franken_whisper sync import-jsonl --input backup/latest/ --conflict-policy reject - Verify with
franken_whisper robot health→database.issues == [].
The export → reimport round-trip is deterministic: replay envelopes survive intact, evidence ledgers are preserved, and every persisted run remains addressable by its run_id after recovery.
Choosing a Backend (Decision Guide)
The auto router will normally pick the right backend, but explicit selection is sometimes useful. Quick decision tree:
Do you need speaker diarization?
├─ YES, waveform-derived and dependency-light → --diarization-engine acoustic
├─ YES, ECAPA identity only and model installed → --diarization-engine ecapa
├─ YES, authorize ECAPA plus usable channel evidence → --diarization-engine ecapa-fused
├─ YES, with an installed pyannote backend → --diarization-engine external
├─ YES, turn hints only → whisper_cpp + --tiny-diarize
└─ NO ──┐
Do you have a CUDA / MPS GPU?
├─ YES, batching long audio aggressively → insanely_fast
├─ YES, low-latency single-stream → whisper_cpp (--no-gpu false)
└─ NO → whisper_cpp (CPU + Metal/CUDA fallback inside whisper.cpp)
For mixed workloads, leave --backend auto and let the Bayesian router learn from outcomes. The static priority list (the fallback when calibration is poor) already encodes a reasonable default.
Audio Quality Considerations
Whisper models require 16 kHz mono audio. franken_whisper's normalization stage performs three operations whose tradeoffs matter:
| Operation | Method | Quality cost |
|---|---|---|
| Channel mixing | sample-by-sample average across channels (using actual frame length) | minimal for centered voice; spatial cues lost |
| Sample rate conversion | linear interpolation | introduces ~−40 dB aliasing above 8 kHz |
| Bit depth conversion | clamp-and-round 16-bit signed PCM | imperceptible for speech |
The linear resampler is intentional. A higher-quality polyphase resampler
would add an FFT or filter-bank implementation and more compute to the ingest
path. Whisper models tolerate this tradeoff for speech. For archival work,
pre-resample with ffmpeg -ar 16000 -ac 1 -filter:a "aresample=resampler=soxr" and pass the WAV via --input; normalization will
recognize an existing 16 kHz mono stream.
systemd Integration
# /etc/systemd/system/franken-whisper-watcher.service
[Unit]
Description=franken_whisper recording watcher
After=network.target
[Service]
Type=simple
User=transcribe
Environment=FRANKEN_WHISPER_HF_TOKEN=hf_...
Environment=FRANKEN_WHISPER_STATE_DIR=/var/lib/franken_whisper
Environment=RUST_LOG=info
ExecStart=/usr/local/bin/franken_whisper robot run --stdin --backend auto
Restart=on-failure
RestartSec=5s
StandardOutput=journal
StandardError=journal
# Hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/franken_whisper
PrivateTmp=true
[Install]
WantedBy=multi-user.target
For batch jobs, prefer a Type=oneshot unit and a *.timer for scheduling. Robot mode's NDJSON output lands cleanly in journalctl; pipe it through jq to extract specific events.
Cross-Compilation
| Target | Status | Notes |
|---|---|---|
x86_64-unknown-linux-gnu |
DSR release target | Auto-provisioned ffmpeg works |
aarch64-unknown-linux-gnu |
DSR release target | Install ffmpeg via package manager |
x86_64-apple-darwin |
DSR release target | brew install ffmpeg |
aarch64-apple-darwin |
DSR release target | brew install ffmpeg |
x86_64-pc-windows-msvc |
DSR release target | Install ffmpeg manually; dshow for mic; public-corpus artifact writers fail closed |
armv7-unknown-linux-musleabihf |
Best-effort | No auto-provisioned ffmpeg; cross-build via cross |
| WebAssembly | Not supported | Symphonia + clap pull in OS APIs |
Cross-builds typically use cross:
cargo install cross
cross build --release --target aarch64-unknown-linux-gnu
iOS (fw-ios C ABI + SwiftUI)
Shipped since v0.9.3: the native engine runs on-device through fw-ios, a
static library exposing a C ABI (fw-ios/include/fw_ios.h, 18 exported
functions: engine open/close/info, Sortformer + denoiser loading, staged
audio/PCM, full run, host-pushed AlignAtt live decode, progress +
live-transcript callbacks, cooperative cancellation, string release). The
staticlib mounts this repo's own
src/native_engine/ sources by path — one inference implementation, no FFI
into third parties, and the same unsafe_code = "deny" lint: unsafe appears
only in the audited pointer island in fw-ios/src/lib.rs, under explicit
#[allow(unsafe_code)] attributes.
A SwiftUI application under ios/Sources/ (xcodegen project in
ios/project.yml) wraps the handle in an actor and provides on-device
transcription, speaker naming, and JSON/Markdown export. It can also import a
playable video from Photos, Files, or the Share sheet, transcribe its locally
extracted audio, and burn a customizable word-level karaoke treatment back
into a shareable video using the decoder's real DTW alignment. Video, audio,
transcript, and rendered export remain on the device. Its bundled keyboard
uses a separate resident multilingual-tiny handle for low-latency text-only
dictation while the ordinary app path remains on large-v3-turbo. Because iOS
does not expose the microphone to custom keyboard extensions, one explicit
foreground activation starts a visible, time-bounded one-hour audio session;
subsequent keyboard Start/Finish commands remain in the current app through a
local App Group handoff, and standby samples are discarded. The session now
lasts up to one hour; the keyboard's compact animation displays real level and
frequency-band energy derived on-device rather than decorative motion.
- Contract details (return codes 0–6, ownership, threading, staging→run flow):
docs/fw_ios_contract.md - Header ↔ ABI lockstep is enforced by
tests/fw_ios_header_parity.rs; a symbol added on one side without the other fails the suite. - The iOS surface is a separate build product — it is not part of the CLI
binaries or the Homebrew/curl installs above. Agents can discover it via
the
ios_surfacekey offw capabilities --json.
Build Reproducibility
The release profile fixes optimization, LTO, codegen-unit, panic, and stripping
settings; rust-toolchain.toml pins the compiler and Cargo.lock pins resolved
dependencies. DSR records the source revision and artifact hashes. This is a
controlled build contract, not a claim of byte-for-byte reproducibility across
hosts.
Why Rust 2024 / Why Nightly
- Rust 2024 edition keeps the crate on the current language edition and its updated lifetime, pattern, and unsafe-operation rules.
- Stable Rust 1.95.0 is pinned in
rust-toolchain.tomlso local and DSR release builds use the same compiler. #![deny(unsafe_code)]rejects unannotated unsafe code. Explicit native-engine exceptions carry local safety arguments; dependency safety policies remain the responsibility of their respective crates.
Threat Model
franken_whisper is a CLI tool that runs on the user's own machine. Its threat model reflects that scope.
What it defends against
- Accidental secret leakage in logs.
render_command_for_log()redacts--hf-tokenvalues before any subprocess command is recorded in tracing output, error messages, snapshots, or test fixtures. The HuggingFace token never appears in any artifactfranken_whisperwrites. - Path-traversal via stdin input. When reading from stdin, the temporary file's extension is sanitized so a hostile content stream cannot smuggle a
../../../etc/passwd-style filename into ffmpeg. - SQL injection via session names. Concurrent session names are validated to
[A-Za-z0-9_]+before being interpolated intoSAVEPOINT fw_session_<name>/RELEASE SAVEPOINT fw_session_<name>statements. Table identifiers in sync imports are explicitly quoted. - Subprocess pipe deadlock. Subprocess stdout and stderr are drained on dedicated reader threads so a backend producing megabytes of output cannot wedge the orchestrator.
- Partial database writes on crash / cancellation. All persistence uses savepoints; the cancellation token is checked before
COMMIT/RELEASE. SQLite's journal recovery handles the death-during-COMMIT case. - Race conditions on the sync lock. The lock file is kept alive while the owning PID runs and age-gated when the PID is unknown. EPERM on
kill -0is treated as alive (the process exists but isn't ours). Windowstasklisterrors are treated as unknown. - Replay-envelope drift going undetected. The conformance harness compares replay envelopes (input hash + backend identity + backend version → output hash) at every run. The 5-stage native engine rollout blocks promotion of any native engine whose timestamps drift more than 50 ms from the bridge for the same audio.
What it does not defend against
- A hostile backend binary. If
whisper-cliorinsanely-fast-whisperis itself malicious,franken_whispercannot detect that. Use distribution-trusted binaries. - A hostile audio file (e.g., crafted to exploit a decoder vulnerability).
symphoniais a pure-Rust decoder with strong safety guarantees; the ffmpeg fallback path is constrained by-vn -ar 16000 -ac 1 -c:a pcm_s16leso options injection is hard, but a zero-day in the decoder itself is out of scope. - An explicitly configured hostile model file. Installer-provisioned Whisper and Sortformer packages are checked against compiled size/SHA-256 roots. An operator can still override the Whisper model with an arbitrary compatible local path; that override crosses a separate trust boundary.
- Side-channel leaks from inference timing. Latency profiling produces visible timing data; an attacker who can observe
orchestration.latency_profileevents could in theory infer audio properties. In the intended single-user threat model this is not a concern. - Network adversaries.
franken_whisperdoes no network I/O during transcription. Network access is confined to provisioning paths: installer-invoked or explicitfw pull all, the optional ffmpeg auto-provisioner (Linux x86_64), and model fetching by an explicit external diarization backend. Preseed the verified cache and use--no-pullfor air-gapped installation.
Trust boundaries
+--------------------------------------------------------------+
| USER PROCESS (franken_whisper) |
| - parses CLI |
| - reads/writes SQLite |
| - emits NDJSON on stdout |
+--------------------------------------------------------------+
|
(subprocess boundary; SIGKILL on cancellation)
|
+--------------------------------------------------------------+
| BACKEND SUBPROCESS (whisper-cli / insanely-fast-whisper / |
| python3+pyannote / ffmpeg) |
| - own user, own memory |
| - own stdin/stdout/stderr pipes (drained on dedicated |
| reader threads) |
| - timeout-bounded |
| - cleaned up by finalizers on cancel/panic |
+--------------------------------------------------------------+
The orchestrator treats backend output as untrusted JSON: it must parse correctly, segments must satisfy invariants, and replay envelopes must validate. Any failure is a structured FW-* error, not a panic.
Use Cases Gallery
| Use case | Configuration sketch |
|---|---|
| Meeting transcription with speakers | transcribe --input meeting.mp3 --json (native Whisper plus native Sortformer by default; explicit count hints remain optional) |
| Podcast batch processing | for f in podcasts/*.mp3; do franken_whisper transcribe --input "$f" --backend whisper-cpp --model large-v3 --json; done |
| Live transcription dashboard | fw robot listen --source stdin-pcm piped to a Server-Sent Events translator — true-live deltas, not batch stage events |
| Voicemail archival | transcribe --stdin --backend auto --json invoked from a mail-handler hook |
| Live event captioning over SSH | tty-audio encode --input mic.wav ➜ SSH ➜ tty-audio decode --output a.wav && franken_whisper transcribe --input a.wav --json |
| Multi-language conference transcription | transcribe --input session.mp4 --language ja --translate --json (transcribe Japanese, translate to English) |
| Compliance / QA scanning | transcribe --input call.wav --json piped to jq for regex matching on segments[].text |
| Voice-note search index | Persist all runs into a dedicated DB, sync export-jsonl nightly, ingest segments.jsonl into a full-text search index keyed by (run_id, idx) |
| Forensic transcription with audit trail | --json --output-srt --output-vtt plus a snapshot of the replay pack for chain-of-custody |
| Karaoke / lyrics alignment | transcribe --input song.mp3 --output-lrc --json then post-process with the word-level timestamps via library API |
| Real-time accessibility captioning | fw robot listen with committed transcript.delta text driving captions and the async quality lane's transcript.confirm / transcript.correct refining them after each utterance closes |
| Air-gapped sensitive recordings | Preseed and verify both release packages, install with --offline, and add --no-persist if local transcript storage is forbidden |
The common theme: franken_whisper is the same binary in every use case. The configuration changes; the integration story (NDJSON events, structured errors, deterministic replay) does not.
JSON Schema Reference
Run franken_whisper robot schema to dump the full machine-readable schema for every robot event. The required fields per event (as enforced by robot_contract_tests.rs against the *_REQUIRED_FIELDS constants in src/robot.rs) are:
run_start : event, schema_version, request
run_error : event, schema_version, code, message
stage : event, schema_version, run_id, seq, ts, stage, code, message, payload
run_complete : event, schema_version, run_id, trace_id, started_at, finished_at,
backend, language, transcript, segments, acceleration, diarization,
warnings, evidence
backends.discovery: event, schema_version, backends
routing_decision : event, schema_version, run_id, ts, code
transcript.partial: event, schema_version, run_id, seq, ts, text, start_sec, end_sec,
confidence, speaker
transcript.confirm: event, schema_version, run_id, seq, window_id, quality_model_id,
drift, latency_ms, ts
transcript.retract: event, schema_version, run_id, retracted_seq, window_id, reason,
quality_model_id, ts
transcript.correct: event, schema_version, run_id, correction_id, replaces_seq, window_id,
segments, drift, latency_ms, ts
health.report : event, schema_version, ts, backends, ffmpeg, audio_input, database,
resources, overall_status
transcript.speculation_stats: event, schema_version, run_id, windows_processed,
corrections_emitted, confirmations_emitted, correction_rate,
mean_fast_latency_ms, mean_quality_latency_ms,
current_window_size_ms, mean_drift_wer, ts
listen.session_start: event, schema_version, run_id, seq, ts, source, capture_backend,
device, sample_rate_hz, fast_model, quality_model, policy, step_ms,
partials, vad
speech_started : event, schema_version, run_id, seq, ts, utterance_id, t_session_sec
transcript.delta : event, schema_version, run_id, seq, ts, utterance_id, text, t0_sec,
t1_sec, tokens, confidence, stability
utterance_end : event, schema_version, run_id, seq, ts, utterance_id, reason, t0_sec,
t1_sec, text, text_truncated, delta_count
listen.warning : event, schema_version, run_id, seq, ts, reason, detail
listen.session_stats: event, schema_version, run_id, seq, ts, final, audio_sec, wall_sec,
deltas, utterances, capture_overruns, mean_step_latency_ms,
p95_step_latency_ms, ttft_ms, policy_holdbacks
Agents can assert these fields on every parsed event and abort early on contract violations rather than partially handling malformed input.
Live-mode note: in live sessions the shared transcript.confirm / transcript.correct events are keyed by utterance_id instead of window_id and follow their utterance_end; transcript.delta is the append-only committed-text stream (mutable previews ride transcript.partial, which carries the same required fields as the batch variant).
Embedding in Other Languages
Although franken_whisper is written in Rust, the robot interface makes it polyglot-friendly.
Python:
import json, subprocess
proc = subprocess.Popen(
["franken_whisper", "robot", "run", "--input", "audio.mp3", "--backend", "auto"],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
)
for line in proc.stdout:
event = json.loads(line)
if event["event"] == "run_complete":
print(event["transcript"])
break
Node.js:
import { spawn } from "node:child_process";
import readline from "node:readline";
const proc = spawn("franken_whisper", ["robot", "run", "--input", "audio.mp3", "--backend", "auto"]);
const rl = readline.createInterface({ input: proc.stdout });
for await (const line of rl) {
const event = JSON.parse(line);
if (event.event === "run_complete") {
console.log(event.transcript);
break;
}
}
Go:
package main
import (
"bufio"; "encoding/json"; "fmt"; "os/exec"
)
func main() {
cmd := exec.Command("franken_whisper", "robot", "run", "--input", "audio.mp3", "--backend", "auto")
out, _ := cmd.StdoutPipe()
cmd.Start()
scanner := bufio.NewScanner(out)
for scanner.Scan() {
var event map[string]any
json.Unmarshal(scanner.Bytes(), &event)
if event["event"] == "run_complete" {
fmt.Println(event["transcript"])
return
}
}
}
Each integration is essentially "spawn the binary, parse one JSON line at a time, dispatch on event." There is no FFI, no shared library, no per-language SDK to maintain. The contract is the NDJSON schema, and the schema is versioned.
Output Format Reference
The artifact exporter renders and syncs every requested format into temporary files before replacing any destination. A rendering failure leaves existing artifacts unchanged. Each completed file is then published atomically; if a later file cannot be published, the error reports how many files were already published. Those complete files remain in place, so a multi-format export is not a transaction across all output files. Existing symlink, directory, and other nonregular destinations are rejected. Duplicate formats produce one artifact. Full JSON records the new output paths and is published last.
During transcription, formats are exported independently so an unavailable destination does not prevent other requested formats from completing. The full JSON inventory includes only the successfully published artifacts.
franken_whisper transcribe can emit several text formats in parallel by combining flags. The same RunReport drives every formatter, so a single transcription can produce a .txt, a .vtt, an .srt, a .csv, an extended .json, and an .lrc together. Sample shapes:
--output-txt is a plain text dump, one segment per line (whisper.cpp side-output style). Diarized segments are prefixed with their speaker label; undiarized output is the bare text:
Hello, this is a test recording.
The system is working as expected.
[SPEAKER_01] All clear on my end.
--output-vtt is WebVTT subtitles (HTML5-native):
WEBVTT
00:00:00.000 --> 00:00:02.500
Hello, this is a test recording.
00:00:02.500 --> 00:00:05.100
The system is working as expected.
00:00:05.100 --> 00:00:07.300
<v SPEAKER_01>All clear on my end.</v>
--output-srt is SRT subtitles (de-facto industry standard):
1
00:00:00,000 --> 00:00:02,500
Hello, this is a test recording.
2
00:00:02,500 --> 00:00:05,100
The system is working as expected.
3
00:00:05,100 --> 00:00:07,300
[SPEAKER_01] All clear on my end.
--output-csv is a segment-per-row tabular form for spreadsheet ingestion:
start,end,speaker,text
0,2.5,"","Hello, this is a test recording."
2.5,5.1,"","The system is working as expected."
5.1,7.3,"SPEAKER_01","All clear on my end."
--output-json-full is extended JSON with full segment + acceleration + replay metadata (a superset of --json's default summary form).
--output-lrc is LRC karaoke format keyed to milliseconds:
[00:00.00] Hello, this is a test recording.
[00:02.50] The system is working as expected.
[00:05.10] [SPEAKER_01] All clear on my end.
Combining outputs. Output flags are additive; supply as many as you want. Each writes <stem>.<ext> in the current directory, where <stem> is the input file's name without its extension (transcript for stdin/mic input). The flags don't suppress JSON on stdout: --json --output-srt --output-vtt writes the full JSON report to stdout and drops two subtitle files on disk.
Health Report Field Reference
franken_whisper robot health emits a health.report event with this structure (real example, fields annotated):
{
"event": "health.report",
"schema_version": "1.1.0",
"ts": "2026-05-17T12:34:56Z",
"backends": [ // one entry per backend (bridge + native)
{
"name": "whisper.cpp", // bridge: external whisper-cli
"available": false,
"path": null, // not populated today (always null)
"version": null, // not populated today (always null)
"issues": ["whisper.cpp backend not available"]
},
{"name": "whisper.cpp-native", "available": true, "path": null, "version": null, "issues": []}
// ... insanely-fast-whisper / insanely-fast-native,
// whisper-diarization / whisper-diarization-native
],
"ffmpeg": { // single dependency, same shape
"name": "ffmpeg", "available": true,
"path": "/usr/bin/ffmpeg", // resolved via override, PATH, or provisioned bundle
"version": null, "issues": []
},
"audio_input": { // microphone capture readiness (not probed here)
"probed": false, "available": false, "default_device": null,
"device_count": 0, "backend": "cpal",
"issues": ["audio input not probed; use `fw robot listen --list-devices` to enumerate hardware"]
},
"database": { // store at --db: parent dir exists/writable, file writable
"name": "database", "available": true,
"path": ".franken_whisper/storage.sqlite3",
"version": null, // not populated today (always null)
"issues": []
},
"resources": { // host headroom
"disk_free_bytes": 50000000000, // filesystem holding the database (statvfs; Unix)
"disk_total_bytes": 250000000000,
"memory_available_bytes": 8000000000, // /proc/meminfo (Linux)
"memory_total_bytes": 16000000000
},
"overall_status": "ok" // "ok" / "degraded" / "unavailable"
}
overall_status derivation.
ok: at least one backend available, ffmpeg available, and the database check passes.degraded: otherwise, when at least one backend or ffmpeg is available.unavailable: no backend and no ffmpeg available.
Field stability. The schema is part of the 1.x contract (currently 1.1.0; the listen event family was an additive minor bump). New fields may be added but no existing fields will be renamed or removed within the 1.x line. Agents should ignore unknown fields rather than fail on them.
Failure Modes Catalog
Each FW-* error has a characteristic in-the-wild signature. Knowing what to look for cuts triage time substantially.
| Error code | Typical signature in run_error payload |
Most common cause | First triage step |
|---|---|---|---|
FW-IO |
"failed to open audio.mp3: No such file or directory" |
Path typo, deleted file, permission denied | ls -la <path> |
FW-JSON |
"invalid JSON at line N column M" |
Backend produced malformed output (rare) or a corrupted JSONL snapshot during sync import | cat <file> | jq . for the offending file |
FW-CMD-MISSING |
"whisper-cli not found on PATH" |
Backend binary not installed or shadowed | which whisper-cli; set FRANKEN_WHISPER_WHISPER_CPP_BIN |
FW-CMD-FAILED |
"command failed with exit status N: <stderr tail>" |
Backend crashed, bad model file, out-of-memory, hostile audio | Re-run the backend command directly with the rendered args |
FW-CMD-TIMEOUT |
"command exceeded timeout of N ms" |
Audio too long for budget, slow hardware, network model download mid-run | Raise --timeout or FRANKEN_WHISPER_STAGE_BUDGET_BACKEND_MS |
FW-BACKEND-UNAVAILABLE |
"no backend available for request (diarize=true, hf_token=missing)" |
No backend supports requested feature set | Install a diarization-capable backend or drop --diarize |
FW-INVALID-REQUEST |
"--input, --stdin, --mic are mutually exclusive" |
Contradictory CLI flags, malformed JSON request via library | Drop one of the conflicting flags |
FW-STORAGE |
"database is busy" or "PRAGMA integrity_check: out of order" |
Concurrent writer, corrupted DB, disk full | franken_whisper robot health; consider JSONL rebuild |
FW-UNSUPPORTED |
"backend X does not support diarization" |
Requested capability the chosen backend lacks | Switch backends or remove the capability flag |
FW-MISSING-ARTIFACT |
"backend completed but did not produce expected output file" |
Backend version skew, model didn't load | Inspect the per-run work dir under <state dir>/tmp/ |
FW-CANCELLED |
"cancelled at stage backend" |
Ctrl+C or deadline hit | Re-run with longer timeout if intended |
FW-STAGE-TIMEOUT |
"stage normalize exceeded budget of 180000 ms" |
Pathological input, contention | Raise the relevant FRANKEN_WHISPER_STAGE_BUDGET_*_MS |
In robot mode each of these arrives as a run_error event whose code is the FW-* code itself, with the human-readable detail in message.
Performance Tuning Guide
The default budgets and tunables are calibrated for a typical local workload (a few minutes of audio, a single backend, no heavy contention). Three tuning vectors matter most:
1. Stage budgets
Watch the orchestration.latency_profile event. Stages tagged decrease_budget_candidate (≤ 30% utilization) are over-budgeted; stages tagged increase_budget (≥ 90% utilization) are at risk of FW-STAGE-TIMEOUT. Adjust via FRANKEN_WHISPER_STAGE_BUDGET_<NAME>_MS. Common adjustments:
| Situation | Tuning |
|---|---|
| Long audio on a slow CPU | raise BACKEND_MS to 1800000 (30 min) |
| Microphone capture of 10+ minutes | raise INGEST_MS to 60000 |
| Cold-start with large models | raise BACKEND_MS to absorb model load time |
| Diarization whose processing time may exceed 15 minutes | raise DIARIZE_MS to 1800000 (30 min) |
| Container with strict CPU limits | raise everything except CLEANUP_MS 2–3× |
2. Backend selection
Force-pick when you know better than the router:
# Always use whisper.cpp on Apple Silicon (Metal is fast, batching doesn't help)
franken_whisper transcribe --input a.mp3 --backend whisper-cpp --model large-v3
# Always use insanely-fast-whisper on a CUDA box doing batch jobs
franken_whisper transcribe --input a.mp3 --backend insanely-fast --batch-size 24 --flash-attention
If you want adaptive behavior but want to seed the posteriors, run a small calibration corpus through --backend auto once. The router will absorb the empirical success rates into its Beta distributions and route accordingly going forward.
3. Audio preprocessing
If you control the audio pipeline upstream, pre-normalize to 16 kHz mono WAV. The Normalize stage detects this and becomes a passthrough, saving ~260 ms per run (significant when transcribing thousands of files). ffmpeg -ar 16000 -ac 1 -c:a pcm_s16le is the canonical incantation.
Speculative streaming
--speculative is a latency tool, not an accuracy tool. Use it when you need partial transcripts for a live UI; don't use it for batch processing (the dual-model overhead reduces throughput vs. running the quality model alone). Tune --speculative-window-ms based on your UI's update tolerance: smaller windows = lower partial latency but more corrections; larger windows = higher latency but fewer retractions.
When to disable persistence
--no-persist skips the Persist stage entirely (~10 ms saved per run). Use it when:
- The output stream is consumed downstream and the DB record would never be queried.
- You're benchmarking inference time.
- You're running on a filesystem where SQLite WAL files would land in an inconvenient place.
Disk Usage Growth Model
The SQLite database grows roughly linearly with transcribed audio. Rough estimates (your mileage varies with how chatty the audio is and how many events your pipeline emits):
| Workload | DB growth rate |
|---|---|
| Default pipeline, mostly-default flags, talky English audio | ~1–3 KB per transcript-minute |
| With diarization, multi-speaker | +20–40% (extra segments + speaker labels) |
With --word-threshold and word-level timestamps |
+50–100% (word-arrays in result_json) |
| With speculative streaming | +30–60% (extra transcript.* events) |
Per 1,000 hours of transcribed audio, expect the database to grow to roughly 100–250 MB in the default configuration, 200–500 MB with diarization and speculation. WAL files add transient overhead; run PRAGMA wal_checkpoint(TRUNCATE) periodically (or let SQLite checkpoint naturally between sessions) to keep them bounded.
JSONL snapshots are larger than the SQLite database (no compression by default, redundant text), roughly 2–3× the DB size. Pipe through gzip for ~5–10× compression ratio on JSONL (which is highly repetitive). The import path transparently handles .gz so gzipped snapshots are first-class.
Extension Guide: Adding a New Backend
To add a new backend (say, a Vosk or wav2vec2 bridge):
- Add a
BackendKindvariant insrc/model.rsand updateBackendKind::as_str()/parse_backend()/ serde derives. - Create
src/backend/<new>.rsimplementing theEnginetrait:pub trait Engine: Send + Sync { fn name(&self) -> &'static str; fn kind(&self) -> BackendKind; fn capabilities(&self) -> EngineCapabilities; fn is_available(&self) -> bool; fn run( &self, request: &TranscribeRequest, normalized_wav: &Path, work_dir: &Path, timeout: Duration, ) -> FwResult<TranscriptionResult>; } - Wire into
BackendRouterinsrc/backend/mod.rs:- Add to the engine enumeration.
- Add a prior
(α, β)toprior_for(). - Add a
quality_proxy(kind, request)entry for both diarize and non-diarize cases. - Add a
latency_proxybase cost. - Extend the loss matrix dimensions if you're adding a fourth action; otherwise reuse an existing action slot.
- Add an availability probe: set the appropriate
FRANKEN_WHISPER_*_BINenv var convention and updatecommand_exists()lookup. - Add capabilities: fill in
EngineCapabilities { supports_diarization, supports_translation, supports_word_timestamps, supports_gpu, supports_streaming }. - Update
robot healthandrobot backends: theBackendsReportbuilder enumerates known engines. - Add an
EngineCapabilitiesrow to the documentation table in this README. - Write tests in
tests/backend_mock_tests.rsand add a golden fixture undertests/fixtures/golden/<new>_native_output.json. - Add conformance fixtures under
tests/fixtures/conformance/corpus/for cross-engine comparison. - Decide on rollout stage: if you're shipping a native pilot, start at
Shadow. The conformance harness will gate promotion throughValidated → Fallback → Primary → Sole.
The Bayesian router will start with the prior you set, then learn empirical reliability across runs. You don't need to do anything special to teach it.
Extension Guide: Adding a New Pipeline Stage
To add a new stage (say, post-transcription summarization):
- Add a
PipelineStagevariant insrc/orchestrator.rsand updateas_str()/Display. - Add a budget knob: a field on
StageBudgetPolicy, aSTAGE_BUDGET_*_ENVconstant, and a default value. - Decide whether the stage is in
DEFAULT_STAGESor opt-in viaPipelineBuilder. - Implement the stage as a function that takes
(&mut PipelineCx, &mut RunReport, &TranscribeRequest, &CancellationToken)and returnsFwResult<()>. Use the established pattern:fn execute_stage_<name>(...) -> FwResult<()> { emit_event(cx, "<stage>.start", message, payload); cx.token.checkpoint()?; // ... do the work ... cx.token.checkpoint()?; emit_event(cx, "<stage>.ok", message, payload); Ok(()) } - Add ordering constraints to
PipelineConfig::validate()if your stage has dependencies (e.g., must run afterBackend). - Add
*.skiphandling: emit the skip event with a structured reason payload when the stage is configured but isn't needed for this run. - Add
*.cancelledand*.errorpaths: both must emit before propagating the error so the NDJSON contract is preserved. - Test: unit-test the stage in isolation, then add an integration test exercising the full pipeline with the stage enabled.
- Update the documentation tables in this README: Pipeline Stages diagram, Stage Budgets table, Stage Codes list, Dynamic Stage Composition table.
The orchestrator handles cancellation, finalizers, evidence accumulation, and latency profiling for you; your stage only needs to do its job and emit events.
The Cancellation Token Contract
Every stage in the pipeline interacts with CancellationToken. Authors writing new stages or backends should follow these invariants:
token.checkpoint()is cheap: it's just two atomic reads (Ctrl+C flag, deadline check). Call it liberally between unit chunks of work.- Subprocess invocations must use
run_command_cancellable(): the basicrun_command()andrun_command_with_timeout()don't honor the token. Long-running backends should use the cancellable variant. - Database writes must checkpoint before
COMMIT: never write to SQLite without one finaltoken.checkpoint()?immediately before theRELEASE SAVEPOINT. The savepoint mechanism guarantees rollback if the checkpoint fires. - Finalizers must respect the cleanup budget: register them via
cx.finalizers.push(...)and they'll run in LIFO order under a 5-second total budget. Don't do unbounded work in a finalizer (e.g., don't recurse a huge directory tree). - Drop checkpoint at stage boundaries: clear the
stage_starttimer when transitioning so elapsed time from a cancelled stage doesn't leak into the next stage's latency profile. - Emit
*.cancelledbefore returning: even on cancellation, the NDJSON contract requires a final event for the stage before pipeline termination.
Following these invariants gives cooperative cancellation a bounded cleanup path: owned subprocesses are terminated, transactions roll back, finalizers run within budget, and interruption maps to exit code 130. Cleanup failures remain errors rather than being reported as successful cancellation.
Debugging Recipes
| Scenario | Recipe |
|---|---|
| "Why did the router pick that backend?" | franken_whisper robot routing-history --limit 1 --run-id <RUN_ID> | jq — inspect the chosen action, calibration score, e-process, fallback state, and recommended order at decision time |
| "What did the backend actually output?" | RUST_LOG=franken_whisper::backend=trace franken_whisper transcribe ... and inspect the rendered subprocess command (with secrets redacted) |
| "Where did the time go?" | Look at the orchestration.latency_profile event; service_ms per stage and per-stage tuning recommendation |
| "Why is SQLite slow?" | franken_whisper robot health → database.wal_checkpoint.log_frames and database.freelist_count; if either is climbing, run PRAGMA wal_checkpoint(TRUNCATE); VACUUM; |
| "Why did the speculative model retract?" | Look at the transcript.retract event's reason and the transcript.correct event's drift payload; tune --correction-tolerance-wer if false retractions are too aggressive |
| "Why is TTY audio glitchy?" | Run tty-audio retransmit-plan on the captured stream; inspect the DecodeReport's gaps, duplicates, integrity_failures counts |
| "Why isn't auto-provisioning working?" | RUST_LOG=franken_whisper::audio=debug and watch for the ffmpeg auto-provision log lines; check FRANKEN_WHISPER_AUTO_PROVISION_FFMPEG is not 0; verify network access to johnvansickle.com |
| "Why does my native pilot disagree?" | franken_whisper robot routing-history → check native_rollout_stage per decision; run the conformance harness directly against the disagreeing fixture to see the violation report |
The general pattern: every adaptive behavior in franken_whisper is queryable. There is no "secret state". Every routing decision, every speculation correction, every retransmit round, every stage budget decision is recorded in events or evidence ledgers you can inspect post-hoc.
Multi-Run Routing Walk-through
Three sequential --backend auto runs against the same machine, showing how the Bayesian router learns:
Run 1: cold start. Empty calibration window, only priors:
posterior[whisper_cpp]: Beta(7, 3) → mean 0.700
posterior[insanely_fast]: Beta(6, 4) → mean 0.600
posterior[whisper_diarization]: Beta(5, 5) → mean 0.500
calibration: 0 observations → fall back to static priority
chosen: whisper_cpp (top of static priority for non-diarize)
outcome: success
Run 8: 7 successes so far. Calibration window fills slowly:
posterior[whisper_cpp]: Beta(7 + 0.86×7, 3 + 0.14×7) = Beta(13.0, 4.0) → mean 0.765
calibration: 7 observations → still using static priority (need ≥ 5, but also need calibration_score ≥ 0.3 and Brier ≤ 0.35)
chosen: whisper_cpp (still static)
outcome: success
Run 23: enough data, adaptive routing engages.
posterior[whisper_cpp]: Beta(25.6, 4.4) → mean 0.853
posterior[insanely_fast]: Beta(15.72, 6.28) → mean 0.715 (12 obs)
posterior[whisper_diarization]: Beta(5, 5) → mean 0.500 (still no data; was never picked)
calibration: 23 observations, Brier = 0.18, score = 0.82 → adaptive mode
loss matrix evaluation favors whisper_cpp by ~2 points
chosen: whisper_cpp (now via adaptive selection, not static fallback)
emit: routing_decision { calibration_score: 0.82, brier_score: 0.18, fallback_active: false }
outcome: success
Run 48: a transient whisper_cpp failure shifts the posterior.
posterior[whisper_cpp]: Beta(33.4, 11.6) → mean 0.742 (5 failures absorbed)
posterior[insanely_fast]: Beta(22.9, 9.1) → mean 0.716
calibration: 48 observations, Brier = 0.21, score = 0.79 → adaptive mode
loss matrix evaluation: whisper_cpp's failure cost now > insanely_fast's
chosen: insanely_fast (the router learned to shift)
outcome: success → posterior[insanely_fast] = Beta(23.7, 9.3) → mean 0.718
The router is doing nothing exotic: it blends priors with empirical data via Beta-conjugate updates, weights the result against the multi-factor loss matrix, and falls back when calibration degrades. The audit trail (routing_decision events plus the evidence ledger) makes every shift inspectable.
Speaker Diarization Paths
| Aspect | Native Sortformer | Rust acoustic | Rust ECAPA-only | Rust ECAPA-fused | External | TinyDiarize |
|---|---|---|---|---|---|---|
| Selection | auto default or --diarization-engine sortformer |
--diarization-engine acoustic |
--diarization-engine ecapa |
--diarization-engine ecapa-fused (JSON: ecapa_fused) |
--diarization-engine external |
--tiny-diarize |
| Speaker identity evidence | Learned anonymous activity lanes; no biometric identity claim | Hand-authored waveform voice features | Pinned ECAPA embeddings; no acoustic channel evidence in pair scoring | Pinned ECAPA embeddings plus bounded acoustic channel evidence when a selected consensus merge joins a compatible usable pair; otherwise generic consensus provenance | Backend-defined, normalized only after provenance checks | Decoder turn tokens |
| Dependencies | Built-in Rust + installer-provisioned, SHA-256-pinned Sortformer package | Built-in Rust + normalized PCM | Built-in Rust + user-installed, hash-pinned ECAPA safetensors | Same pinned local ECAPA package | Typically Python, model files, and possibly an HF token | whisper-cli |
| Output | Independent overlapping turns plus conservative projection to ASR segments | Independent turns plus conservative projection to ASR segments | The common turn/report/projection contract | The common turn/report/projection contract | Timed backend labels normalized to the common report | Inline turn hints |
| Known intervals | Identity enrollment routes to the acoustic fallback | Hard must-link and soft enrollment | Hard must-link and soft enrollment | Hard must-link and soft enrollment | Backend-specific | No |
| Speaker count | Inferred active lanes without a required count; hard capacity of four | Infer by default; optional soft range/prior or exact search constraint | Same bounded inference and constraint contract | Same bounded inference and constraint contract | Backend-specific | No |
| Unknown/overlap | Explicit independent overlap; unmatched evidence remains unknown | Explicit unknown and overlap suspicion | Same common handling | Same common handling | Backend-specific | No calibrated assignment |
| Accuracy authority | DevelopmentUncertified; selected by auto as the product default |
Public-development evidence exists; rollout remains uncertified | DevelopmentUncertified; outside auto |
DevelopmentUncertified; outside auto |
Depends on the installed backend and corpus | No project accuracy certification |
Native Sortformer is the default for anonymous calls with no more than four
active speakers. Use acoustic diarization for dependency-light waveform evidence,
recordings outside the four-lane capacity, and auditable known intervals. Use
explicit ecapa when the pinned model is installed and
speaker identity should come only from ECAPA; use ecapa-fused when bounded
channel evidence is also appropriate and may be available. The supported-profile
redecode experiment additionally requires complete neural tracklet coverage;
missing embeddings remain UNKNOWN except for immutable hard attribution. Both
are development-uncertified. Use an
external engine only when its model/deployment tradeoff is deliberate.
TinyDiarize is a turn hint, not a speaker-profile substitute.
Source Separation Tradeoffs (--no-stem)
The external diarization backend may run Demucs vocal isolation before clustering. The Rust acoustic engine does not invoke Demucs or Python.
Keep stemming on (default) when:
- Background music or significant ambient noise.
- Multiple overlapping speakers.
- Recordings with reverb / echo.
Disable with --no-stem when:
- Clean studio recordings (no benefit, just wasted compute).
- Real-time pipelines where the +5–15 s/min of Demucs latency is unacceptable.
- Memory-constrained environments (Demucs is the biggest single memory user in the pipeline).
The Source Separate stage has its own budget (FRANKEN_WHISPER_STAGE_BUDGET_SEPARATE_MS, default 30 s); raise it for long audio or lower it to fail fast on resource-constrained hosts.
Pre-Flight Production Checklist
Before deploying franken_whisper to a production workflow, walk through:
- Native packages installed.
fw doctor --jsonreturnsready=true, proving both compiled model trust roots pass. - HuggingFace token configured (only if using the external pyannote diarization backend). Set via
FRANKEN_WHISPER_HF_TOKEN. Verify redaction works by triggering an external diarization run withRUST_LOG=debugand confirming the token does not appear in logs. - Pinned ECAPA package installed (only if using
ecapaorecapa-fused). Verify the filename, auxiliary-model directory, and SHA-256 from Prerequisites; no HF token is needed. - ffmpeg accessible (if you'll transcribe video or use mic capture). Either system-installed, manually placed, or auto-provisioned. Verify with
franken_whisper robot health→ffmpeg.available=true. - State directory writable.
FRANKEN_WHISPER_STATE_DIR(or default.franken_whisper/) is on a partition with enough free space for your expected DB growth. - Stage budgets sized. The limits apply to processing wall time, not audio duration. Raise
FRANKEN_WHISPER_STAGE_BUDGET_BACKEND_MSorFRANKEN_WHISPER_STAGE_BUDGET_DIARIZE_MSonly when the target host may need more than the configured stage budget. - Backup strategy. Schedule periodic
sync export-jsonl+ off-host copy. Test the restore path at least once. - Concurrent agent expectations documented. If multiple processes will write to the same DB, all must use
RunStore::begin_concurrent_session()(or accept SQLITE_BUSY retries on conflict). - Native rollout stage chosen. Default
soleis the all-native product path. Set another stage only when you deliberately want bridge compatibility behavior. - Error handling integrated. Your downstream consumer differentiates
run_completefromrun_errorevents in robot mode, and handles eachrun_error.code(FW-*) appropriately. - Disk monitoring in place. Alert on
disk_free_bytes / disk_total_bytes < 0.10and onwal_checkpoint.log_framesclimbing across consecutiverobot healthprobes. - Live sessions sized (
fw robot listen). Plan RAM for the resident fast model, the optional quality model, and Sortformer when--diarizeis enabled.--quality-model noneremoves the quality model. Grant microphone access before headless/SSH deployment;fw robot listen --list-deviceschecks capture. Each active lane uses its own reusable compute pool. With speaker activity enabled, Sortformer receives one third of the configured width when quality confirmation is enabled, or one half otherwise; the remaining width is divided between fast and quality ASR, with the fast lane receiving the larger half. Every active lane needs at least one thread, so a width smaller than the active lane count cannot avoid oversubscription. Without speakers or quality confirmation, the fast lane keeps the full width. SetRAYON_NUM_THREADSexplicitly when sizing a dedicated host.
Robot Schema Dump (robot schema)
franken_whisper robot schema emits a single JSON document describing every event type, every required field, every optional field, every payload sub-schema, and the canonical timestamp tolerance. Use it to drive client codegen, JSON-Schema validators, or auto-generated documentation.
For a ready-made validator input, tests/fixtures/schemas/robot_event_schema.json is a draft 2020-12 JSON Schema generated from the same catalog (robot::robot_event_json_schema). Each stdout line is one of its oneOf events; run_start, stage, run_complete, run_error and batch.complete are fully typed (including the optional batch object, raw_confidences, and the FW-* code family), and the other events are checked for their required fields. transcript.confirm and transcript.correct accept either the speculative-window form or the utterance-keyed form that fw robot listen writes (the catalog's live_variant). tests/cli_integration.rs keeps the file in sync with the code and validates real fw robot run streams (single input, batch, error) against it:
franken_whisper robot schema | jq '.events | keys'
# [
# "backends.discovery",
# "batch.complete",
# "health.report",
# "listen.controller",
# "listen.device",
# "listen.session_start",
# "listen.session_stats",
# "listen.warning",
# "routing_decision",
# "routing_history.complete",
# "run_complete",
# "run_error",
# "run_start",
# "speech_started",
# "stage",
# "transcript.confirm",
# "transcript.correct",
# "transcript.delta",
# "transcript.partial",
# "transcript.retract",
# "transcript.speculation_stats",
# "utterance_end",
# "youtube.discovered", "youtube.done", "youtube.downloaded",
# "youtube.downloading", "youtube.failed", "youtube.run_complete",
# "youtube.run_start", "youtube.skipped", "youtube.transcribing"
# ]
franken_whisper robot schema | jq '.events["run_complete"].required'
# ["event", "schema_version", "run_id", "trace_id", "started_at",
# "finished_at", "backend", "language", "transcript", "segments",
# "acceleration", "diarization", "warnings", "evidence"]
franken_whisper robot schema | jq '.events["routing_decision"]'
# {"required": ["event", "schema_version", "run_id", "ts", "code"],
# "example": { ... decision_id, chosen_action, calibration_score,
# e_process, fallback_active, recommended_order, mode ... }}
The schema document is part of the 1.x contract (currently 1.1.0): adding new event types requires a minor-version bump, and renaming or removing required fields requires a major-version bump. Schema version is reported on every event so agents can detect mismatch instantly.
Recipe Cookbook
Idiomatic patterns for common one-off tasks.
Generate SRT subtitles for a folder of videos
for f in videos/*.mp4; do
franken_whisper transcribe --input "$f" --backend whisper-cpp --model large-v3 \
--output-srt --json > /dev/null
done
# Artifacts land in the current directory, named after each input's stem
# (videos/talk.mp4 -> ./talk.srt).
Build a searchable transcript archive
franken_whisper sync export-jsonl --output ./archive
jq -r '.id + "\t" + .transcript' ./archive/runs.jsonl > transcripts.tsv
# Now feed transcripts.tsv into any full-text index.
Tail the live pipeline as a continuous status line
franken_whisper robot run --input meeting.mp3 --backend auto 2>/dev/null \
| jq -r 'select(.event == "stage") | "[2K\r[\(.stage)] \(.code)"' \
| tr -d '\n'
Filter routing decisions where the router fell back to static
franken_whisper robot routing-history --limit 100 \
| jq -c 'select(.event == "routing_decision" and .fallback_active == true)
| {run_id, decision_id, calibration_score, e_process, mode}'
Validate all replay packs in a directory
for d in replay_packs/*/; do
for f in env.json manifest.json repro.lock tolerance_manifest.json; do
[ -f "$d/$f" ] || echo "MISSING: $d/$f"
done
done
# Cross-check: re-running the same input should produce byte-identical packs
Confirm a backend version drift
franken_whisper transcribe --input fixtures/canary.wav --backend whisper-cpp --json \
| jq '.replay.backend_version'
# Compare against the version recorded in your last known-good replay envelope.
# Any difference is a backend upgrade; trigger conformance re-validation.
Bulk-set stage budgets via env-file
cat > /etc/franken_whisper.env <<EOF
FRANKEN_WHISPER_STAGE_BUDGET_BACKEND_MS=1800000
FRANKEN_WHISPER_STAGE_BUDGET_DIARIZE_MS=1800000
FRANKEN_WHISPER_STAGE_BUDGET_NORMALIZE_MS=300000
EOF
env $(cat /etc/franken_whisper.env | xargs) franken_whisper transcribe --input long.mp3 --json
Cap memory by routing diarization to a separate process
# Process A: do the transcription only
franken_whisper transcribe --input meeting.mp3 --backend whisper-cpp --no-stem \
--db /tmp/runs.sqlite3 --json
# Process B: post-process for speakers in a memory-isolated context
# (run later, on different hardware, or in a smaller resource envelope)
About Contributions
Bug reports and proposed fixes are welcome. Pull requests may be used as design references, but are not merged directly; changes are independently reviewed and reimplemented where appropriate.
License
MIT License with OpenAI/Anthropic Rider. See LICENSE for the full text.
In short: standard MIT terms apply, with an additional restriction that no rights are granted to OpenAI, Anthropic, or their affiliates without express prior written permission from the author. This rider must be preserved in all copies and derivative works.
Explore related projects
Loading…