#!/usr/bin/env python3 """Standalone Griot batch engine and one-shot CLI; no server is required.""" from __future__ import annotations import argparse import importlib.util import json import math import sys import threading import time from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from pathlib import Path from typing import Any import numpy as np import soundfile as sf import torch from torch.nn.utils.rnn import pad_sequence from chunking import AudioChunk, chunk_audio_vad, stitch_transcripts from ctc_alignment import align_text_to_words @dataclass class AudioInput: id: str audio: np.ndarray sample_rate: int @dataclass(frozen=True) class Chunk: recording: int index: int start: int end: int keep_start: int keep_end: int audio_chunk: Any | None = None @property def frames(self) -> int: return self.end - self.start @dataclass class Prepared: id: str seconds: float features: torch.Tensor | None chunks: list[Chunk] audio_chunks: list[AudioChunk] | None = None chunk_features: list[torch.Tensor] | None = None def load_module(name: str, path: Path): spec = importlib.util.spec_from_file_location(name, path) if spec is None or spec.loader is None: raise ValueError(f"Cannot import {path}") module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) return module def plan_chunks(total: int, window: int, overlap: int, stride: int = 4) -> list[Chunk]: """Assign every global output frame to exactly one acoustic window.""" if total < 1 or stride < 1 or window < stride or not 0 <= overlap < window: raise ValueError("Invalid chunk geometry") if window % stride or overlap % stride: raise ValueError("Window and overlap must align to the subsampling stride") starts = [0] while starts[-1] + window < total: starts.append(starts[-1] + window - overlap) plans = [] for index, start in enumerate(starts): end = min(start + window, total) offset = start // stride first = ( 0 if index == 0 else ((starts[index - 1] + window + start) // (2 * stride) - offset) ) last = ( (end - start + stride - 1) // stride if index == len(starts) - 1 else ((end + starts[index + 1]) // (2 * stride) - offset) ) plans.append(Chunk(0, index, start, end, first, last)) return plans def schedule_batches( chunks: list[Chunk], batch_size: int, max_frames: int, max_padding_fraction: float = 0.15, ): """Bucket by duration and bound padded frames, including all batch rows.""" if batch_size < 1 or max_frames < 1 or not 0 <= max_padding_fraction < 1: raise ValueError("Batch size and frame budget must be positive") current: list[Chunk] = [] for chunk in sorted(chunks, key=lambda c: (-c.frames, c.recording, c.index)): if chunk.frames > max_frames: raise ValueError("A chunk exceeds the batch frame budget") padded = current[0].frames * (len(current) + 1) if current else chunk.frames valid = sum(c.frames for c in current) + chunk.frames if current and ( len(current) == batch_size or padded > max_frames or 1 - valid / padded > max_padding_fraction ): yield current current = [] current.append(chunk) if current: yield current class BatchEngine: """One resident acoustic model. Chunk batching works across input files. GPU work is serialized per engine. CPU decoding can use shared-LM threads. CPU audio, features, and scores scale with total submitted audio duration; device input/activation memory is limited by the batch frame budget. """ def __init__( self, model_dir: str | Path, *, device: str = "auto", dtype: str = "auto", batch_size: int = 8, max_batch_frames: int | None = None, chunk_seconds: float = 30, overlap_seconds: float = 5, lookahead_frames: int | None = None, greedy: bool = False, beam_width: int = 25, decode_workers: int = 1, cpu_threads: int | None = None, max_padding_fraction: float = 0.15, decoder_backend: str = "pyctcdecode", flashlight_beam_threshold: float = 10.0, flashlight_token_beam_size: int | None = 8, beam_prune_logp: float = -10.0, token_min_logp: float = -5.0, kenlm: str | Path | None = None, unigrams: str | Path | None = None, lm_alpha: float | None = None, lm_beta: float | None = None, chunk_mode: str = "vad", min_chunk_seconds: float = 20.0, max_chunk_seconds: float = 28.0, vad_threshold: float = 0.015, vad_min_silence_seconds: float = 0.3, ): started = time.perf_counter() self.model_dir = Path(model_dir).expanduser().resolve() if cpu_threads is not None: if cpu_threads < 1: raise ValueError("cpu_threads must be positive") torch.set_num_threads(cpu_threads) if batch_size < 1 or decode_workers < 1 or beam_width < 1: raise ValueError( "Batch size, decode workers, and beam width must be positive" ) if ( not math.isfinite(chunk_seconds) or not math.isfinite(overlap_seconds) or not 0 < chunk_seconds <= 30 or not 0 <= overlap_seconds < chunk_seconds ): raise ValueError( "Use 0 < chunk_seconds <= 30 and 0 <= overlap < chunk_seconds" ) if chunk_mode not in {"vad", "fixed"}: raise ValueError("chunk_mode must be 'vad' or 'fixed'") if ( min_chunk_seconds <= 0 or max_chunk_seconds <= min_chunk_seconds or max_chunk_seconds > 30.0 ): raise ValueError( "min_chunk_seconds and max_chunk_seconds must satisfy 0 < min < max <= 30" ) if vad_threshold <= 0: raise ValueError("vad_threshold must be positive") if vad_min_silence_seconds <= 0: raise ValueError("vad_min_silence_seconds must be positive") self.chunk_mode = chunk_mode self.min_chunk_seconds = min_chunk_seconds self.max_chunk_seconds = max_chunk_seconds self.vad_threshold = vad_threshold self.vad_min_silence_s = vad_min_silence_seconds sys.path.insert(0, str(self.model_dir)) self.hub = load_module("_griot_batch_hub", self.model_dir / "inference.py") self.device = self.hub.resolve_device(device) if dtype == "auto" and self.device.type == "mps": # Modern Metal supports BF16; explicit --dtype bf16 never falls # back. Auto remains usable on older Macs without BF16 support. try: torch.empty(1, device=self.device, dtype=torch.bfloat16) self.dtype = torch.bfloat16 except (TypeError, RuntimeError): self.dtype = torch.float32 else: self.dtype = self.hub.resolve_dtype(dtype, self.device) self.model, self.vocab, self.id_to_token = self.hub.load_model( self.model_dir, self.device, self.dtype, ) self.runtime = sys.modules["runtime"] self.live = load_module("_griot_batch_audio", self.model_dir / "_live.py") self.ctc = load_module("_griot_batch_ctc", self.model_dir / "ctc_decode.py") self.feature_config = self.runtime.FeatureConfig( sample_rate=16000, n_mels=self.model.config.n_mels, ) self.stride = int(self.model.config.subsampling_factor) fps = self.feature_config.sample_rate / self.feature_config.hop_length self.window = int(chunk_seconds * fps / self.stride) * self.stride self.chunk_seconds = chunk_seconds self.overlap_seconds = overlap_seconds self.vad_overlap_seconds = 1.5 self.overlap = int(overlap_seconds * fps / self.stride) * self.stride if self.window < self.stride or self.window - self.overlap < self.stride: raise ValueError( "Chunk duration/overlap leaves less than one encoder frame" ) self.batch_size = batch_size if not 0 <= max_padding_fraction < 1: raise ValueError("max_padding_fraction must be in [0, 1)") self.max_padding_fraction = max_padding_fraction self.max_batch_frames = ( batch_size * (self.window + 1) if max_batch_frames is None else max_batch_frames ) if self.max_batch_frames < self.window: raise ValueError("max_batch_frames must fit one complete acoustic window") release_path = self.model_dir / "release_config.json" release = json.loads(release_path.read_text()) if release_path.exists() else {} self.lookahead = ( release.get("default_lookahead_frames", 13) if lookahead_frames is None else lookahead_frames ) self.beam_width = beam_width self.beam_prune_logp = beam_prune_logp self.token_min_logp = token_min_logp if ( not math.isfinite(beam_prune_logp) or beam_prune_logp > 0 or not math.isfinite(token_min_logp) or token_min_logp > 0 ): raise ValueError("Pruning thresholds must be finite and nonpositive") self.decode_workers = decode_workers self.decoder = None if decoder_backend not in {"pyctcdecode", "flashlight"}: raise ValueError("Unknown decoder backend") self.decoder_backend = decoder_backend if not greedy: lm = kenlm or release.get("bundled_kenlm") if not lm: raise ValueError("No bundled KenLM configured; choose --greedy") model_path = Path(lm) if kenlm else self.model_dir / lm alpha = release.get("lm_alpha", 0.5) if lm_alpha is None else lm_alpha beta = release.get("lm_beta", 1) if lm_beta is None else lm_beta if not math.isfinite(alpha) or not math.isfinite(beta): raise ValueError("LM weights must be finite") if decoder_backend == "flashlight": from flashlight_decode import FlashlightDecoder self.decoder = FlashlightDecoder( self.vocab, model_path, alpha=alpha, beta=beta, beam_width=beam_width, beam_threshold=flashlight_beam_threshold, token_beam_size=flashlight_token_beam_size, unigrams_path=unigrams, ) else: self.decoder = self.ctc.build_kenlm_decoder( self.vocab, model_path, alpha=alpha, beta=beta, unigrams_path=unigrams, ) self.lock = threading.Lock() self.load_seconds = time.perf_counter() - started def synchronize(self): if self.device.type == "mps": torch.mps.synchronize() elif self.device.type == "cuda": torch.cuda.synchronize(self.device) def prepare(self, inputs: list[AudioInput]) -> list[Prepared]: if len({entry.id for entry in inputs}) != len(inputs): raise ValueError("Input IDs must be unique") prepared = [] for index, entry in enumerate(inputs): audio = np.asarray(entry.audio) if ( entry.sample_rate <= 0 or audio.ndim not in (1, 2) or audio.size == 0 or not np.isfinite(audio).all() ): raise ValueError(f"Invalid or empty audio for {entry.id}") seconds = len(audio) / entry.sample_rate audio = self.live.prepare_audio(audio, entry.sample_rate) # Centered STFT reflection requires more than n_fft/2 samples. if len(audio) <= self.feature_config.n_fft // 2: raise ValueError(f"Audio too short for feature extraction: {entry.id}") if self.chunk_mode == "vad": if seconds <= self.chunk_seconds: features = self.runtime.audio_to_log_mel( audio, 16000, self.feature_config ) n_feat = len(features) n_out = (n_feat + self.stride - 1) // self.stride ac = AudioChunk( 0, audio, 0.0, seconds, is_silence_cut=True, overlap_start=0.0, overlap_end=0.0, ) chunks = [Chunk(index, 0, 0, n_feat, 0, n_out, audio_chunk=ac)] prepared.append( Prepared( entry.id, seconds, features, chunks, audio_chunks=[ac], chunk_features=[features], ) ) else: audio_chunks = chunk_audio_vad( audio, sample_rate=16000, max_chunk_s=self.max_chunk_seconds, min_chunk_s=self.min_chunk_seconds, overlap_s=self.vad_overlap_seconds, vad_threshold=self.vad_threshold, min_silence_s=self.vad_min_silence_s, ) chunks = [] chunk_features = [] for ac in audio_chunks: feat = self.runtime.audio_to_log_mel( ac.audio, 16000, self.feature_config ) n_feat = len(feat) n_out = (n_feat + self.stride - 1) // self.stride chunks.append( Chunk(index, ac.index, 0, n_feat, 0, n_out, audio_chunk=ac) ) chunk_features.append(feat) prepared.append( Prepared( entry.id, seconds, None, chunks, audio_chunks=audio_chunks, chunk_features=chunk_features, ) ) else: features = self.runtime.audio_to_log_mel( audio, 16000, self.feature_config ) # Centered STFT adds an endpoint frame: exactly 30 seconds has 3001 # feature frames. Do not create a second overlap window just for it. if ( seconds <= self.chunk_seconds and len(features) <= self.window + 1 and len(features) <= self.max_batch_frames ): plans = [ Chunk( 0, 0, 0, len(features), 0, (len(features) + self.stride - 1) // self.stride, ) ] else: plans = plan_chunks( len(features), self.window, self.overlap, self.stride ) chunks = [ Chunk(index, p.index, p.start, p.end, p.keep_start, p.keep_end) for p in plans ] prepared.append(Prepared(entry.id, seconds, features, chunks)) return prepared def _decode(self, scores: torch.Tensor) -> str: if self.decoder is not None: if self.decoder_backend == "flashlight": return self.decoder.decode(scores.numpy()) text = str( self.decoder.decode( scores.numpy(), beam_width=self.beam_width, beam_prune_logp=self.beam_prune_logp, token_min_logp=self.token_min_logp, ) ) for placeholder in self.ctc._NON_EMITTING_LABELS.values(): text = text.replace(placeholder, "") return text return self.runtime.greedy_decode( scores[None], torch.tensor([len(scores)]), self.id_to_token, blank_id=self.model.config.blank_id, pad_id=self.model.config.pad_id, )[0] def transcribe_prepared( self, prepared: list[Prepared], *, batch_size: int | None = None, max_batch_frames: int | None = None, ) -> dict: if batch_size is not None and batch_size < 1: raise ValueError("batch_size must be positive") if max_batch_frames is not None and max_batch_frames < 1: raise ValueError("max_batch_frames must be positive") with self.lock: return self._run(prepared, batch_size, max_batch_frames) def _run(self, prepared, batch_size, max_batch_frames): started = time.perf_counter() all_chunks = [c for r in prepared for c in r.chunks] output_scores = [[None] * len(r.chunks) for r in prepared] padded_frames = 0 batch_sizes = [] self.synchronize() acoustic_start = time.perf_counter() for chunks in schedule_batches( all_chunks, batch_size or self.batch_size, max_batch_frames or self.max_batch_frames, self.max_padding_fraction, ): features = [] for c in chunks: r = prepared[c.recording] if r.chunk_features is not None: features.append(r.chunk_features[c.index]) else: features.append(r.features[c.start : c.end]) inputs = pad_sequence(features, batch_first=True) lengths = torch.tensor([c.frames for c in chunks], dtype=torch.long) padded_frames += len(chunks) * inputs.shape[1] batch_sizes.append(len(chunks)) if self.device.type == "cuda": inputs = inputs.pin_memory() lengths = lengths.pin_memory() inputs = inputs.to(self.device, dtype=self.dtype, non_blocking=True) lengths = lengths.to(self.device, non_blocking=True) with torch.inference_mode(): output = self.model(inputs, lengths, lookahead_frames=self.lookahead) scores = output.log_probs.float().cpu() output_lengths = output.output_lengths.cpu().tolist() for row, chunk in enumerate(chunks): if ( output_lengths[row] != (chunk.frames + self.stride - 1) // self.stride ): raise RuntimeError("Unexpected frontend output geometry") output_scores[chunk.recording][chunk.index] = scores[ row, chunk.keep_start : chunk.keep_end, ].clone() del inputs, lengths, output, scores self.synchronize() acoustic_seconds = time.perf_counter() - acoustic_start decode_start = time.perf_counter() if self.chunk_mode == "fixed": stitched = [] for recording, pieces in zip(prepared, output_scores, strict=True): scores = torch.cat(pieces) expected = (len(recording.features) + self.stride - 1) // self.stride if len(scores) != expected: raise RuntimeError("Missing or duplicated CTC frames after stitching") stitched.append(scores) del output_scores if self.decode_workers > 1 and len(stitched) > 1: with ThreadPoolExecutor(max_workers=self.decode_workers) as pool: texts = list(pool.map(self._decode, stitched)) else: texts = [self._decode(scores) for scores in stitched] final_texts = texts else: all_scores = [score for pieces in output_scores for score in pieces] if self.decode_workers > 1 and len(all_scores) > 1: with ThreadPoolExecutor(max_workers=self.decode_workers) as pool: all_texts = list(pool.map(self._decode, all_scores)) else: all_texts = [self._decode(score) for score in all_scores] idx = 0 final_texts = [] for r, pieces in zip(prepared, output_scores, strict=True): n_p = len(pieces) chunk_texts = all_texts[idx : idx + n_p] chunk_scores = pieces idx += n_p if r.audio_chunks is not None and len(r.audio_chunks) > 1: chunk_transcripts = [] for ac, c_text, c_score in zip( r.audio_chunks, chunk_texts, chunk_scores ): words = [] align_res = None if c_text.strip(): align_res = align_text_to_words( c_score.numpy(), c_text, self.vocab, blank_id=self.model.config.blank_id, pad_id=self.model.config.pad_id, frame_duration_seconds=0.040, audio_duration_seconds=ac.duration, ) if align_res: words = align_res.get("words", []) chunk_transcripts.append( { "text": c_text, "words": words, "confidence_score": ( align_res.get("confidence_score") if align_res else None ), } ) stitched_result = stitch_transcripts( r.audio_chunks, chunk_transcripts ) final_texts.append(stitched_result["text"]) else: final_texts.append(chunk_texts[0]) del output_scores decode_seconds = time.perf_counter() - decode_start result = [ { "id": r.id, "text": text, "audio_seconds": r.seconds, "chunks": len(r.chunks), } for r, text in zip(prepared, final_texts, strict=True) ] return { "results": result, "stats": { "device": str(self.device), "dtype": str(self.dtype), "decoder_backend": self.decoder_backend if self.decoder else "greedy", "recordings": len(prepared), "chunks": len(all_chunks), "batch_sizes": batch_sizes, "audio_seconds": sum(r.seconds for r in prepared), "processed_feature_frames": sum(c.frames for c in all_chunks), "padded_feature_frames": padded_frames, "padding_fraction": ( 1 - sum(c.frames for c in all_chunks) / padded_frames if padded_frames else 0 ), "acoustic_seconds": acoustic_seconds, "decode_seconds": decode_seconds, "run_seconds": time.perf_counter() - started, }, } def transcribe(self, inputs: list[AudioInput], **kwargs) -> dict: started = time.perf_counter() prepared = self.prepare(inputs) preprocessing_seconds = time.perf_counter() - started result = self.transcribe_prepared(prepared, **kwargs) result["stats"]["preprocessing_seconds"] = preprocessing_seconds result["stats"]["total_seconds"] = time.perf_counter() - started return result def add_engine_arguments(parser): parser.add_argument("--model-dir", required=True) parser.add_argument( "--device", choices=["auto", "cpu", "mps", "cuda"], default="auto" ) parser.add_argument("--dtype", choices=["auto", "fp32", "bf16"], default="auto") parser.add_argument("--batch-size", type=int, default=8) parser.add_argument("--max-batch-frames", type=int) parser.add_argument("--max-padding-fraction", type=float, default=0.15) parser.add_argument("--chunk-seconds", type=float, default=30) parser.add_argument("--overlap-seconds", type=float, default=5) parser.add_argument("--lookahead-frames", type=int) parser.add_argument("--greedy", action="store_true") parser.add_argument("--beam-width", type=int, default=25) parser.add_argument( "--decoder-backend", choices=["pyctcdecode", "flashlight"], default="pyctcdecode", ) parser.add_argument("--flashlight-beam-threshold", type=float, default=10.0) parser.add_argument("--flashlight-token-beam-size", type=int, default=8) parser.add_argument("--beam-prune-logp", type=float, default=-10.0) parser.add_argument("--token-min-logp", type=float, default=-5.0) parser.add_argument("--kenlm") parser.add_argument("--unigrams") parser.add_argument("--lm-alpha", type=float) parser.add_argument("--lm-beta", type=float) parser.add_argument("--decode-workers", type=int, default=1) parser.add_argument("--cpu-threads", type=int) parser.add_argument( "--chunk-mode", choices=["vad", "fixed"], default="vad" ) parser.add_argument("--min-chunk-seconds", type=float, default=20.0) parser.add_argument("--max-chunk-seconds", type=float, default=28.0) parser.add_argument("--vad-threshold", type=float, default=0.015) parser.add_argument("--vad-min-silence-seconds", type=float, default=0.3) def engine_from_args(args): return BatchEngine( args.model_dir, device=args.device, dtype=args.dtype, batch_size=args.batch_size, max_batch_frames=args.max_batch_frames, chunk_seconds=args.chunk_seconds, overlap_seconds=args.overlap_seconds, lookahead_frames=args.lookahead_frames, greedy=args.greedy, beam_width=args.beam_width, decode_workers=args.decode_workers, cpu_threads=args.cpu_threads, max_padding_fraction=args.max_padding_fraction, decoder_backend=args.decoder_backend, flashlight_beam_threshold=args.flashlight_beam_threshold, flashlight_token_beam_size=args.flashlight_token_beam_size, beam_prune_logp=args.beam_prune_logp, token_min_logp=args.token_min_logp, kenlm=args.kenlm, unigrams=args.unigrams, lm_alpha=args.lm_alpha, lm_beta=args.lm_beta, chunk_mode=getattr(args, "chunk_mode", "vad"), min_chunk_seconds=getattr(args, "min_chunk_seconds", 20.0), max_chunk_seconds=getattr(args, "max_chunk_seconds", 28.0), vad_threshold=getattr(args, "vad_threshold", 0.015), vad_min_silence_seconds=getattr(args, "vad_min_silence_seconds", 0.3), ) def read_inputs(args) -> list[AudioInput]: entries = ( [{"id": str(i), "audio": path} for i, path in enumerate(args.audio)] if args.audio else json.loads(Path(args.manifest).read_text()) ) inputs = [] for entry in entries: audio, rate = sf.read(Path(entry["audio"]).expanduser(), dtype="float32") inputs.append(AudioInput(str(entry["id"]), audio, rate)) return inputs def main(): parser = argparse.ArgumentParser(description=__doc__) add_engine_arguments(parser) source = parser.add_mutually_exclusive_group(required=True) source.add_argument("--audio", nargs="+") source.add_argument("--manifest", help="JSON list of {id, audio: local_path}") parser.add_argument("--output", help="Output JSON file; default: stdout") args = parser.parse_args() inputs = read_inputs(args) if not inputs: parser.error("At least one input is required") engine = engine_from_args(args) result = engine.transcribe(inputs) result["stats"]["model_load_seconds"] = engine.load_seconds text = json.dumps(result, ensure_ascii=False, indent=2) + "\n" if args.output: Path(args.output).write_text(text) else: print(text, end="") if __name__ == "__main__": main()