"""Transcribe Persian audio of any length with Nava. pip install torch transformers python transcribe.py audio.mp3 python transcribe.py audio.mp3 --digits fa # numbers, times and dates in Persian digits python transcribe.py audio.mp3 --digits ascii # ... in 0-9 python transcribe.py audio.mp3 --beams 5 # slightly more accurate, about half the speed Audio is decoded with ffmpeg if it is installed, otherwise with librosa (`pip install librosa`). Nava transcribes one window of up to 30 seconds at a time and does not produce timestamps, so Whisper's built-in long-form mode must not be used with it. This script cuts longer audio at quiet points into pieces of at most 29 seconds and joins the text. """ from __future__ import annotations import argparse import shutil import subprocess import numpy as np import torch SR = 16000 def load_audio(path: str) -> np.ndarray: """Any audio file -> mono float32 at 16 kHz.""" if shutil.which("ffmpeg"): raw = subprocess.run( ["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "1", "-ar", str(SR), "pipe:1"], capture_output=True, check=True, ).stdout return np.frombuffer(raw, dtype=np.float32).copy() import librosa return librosa.load(path, sr=SR, mono=True)[0].astype(np.float32) def split_long(wav: np.ndarray, max_s: float = 29.0, min_s: float = 12.0) -> list[np.ndarray]: """Pieces of at most `max_s` seconds, each cut at the quietest 0.3 s between `min_s` and `max_s` after the previous cut.""" if len(wav) <= int(30.0 * SR): return [wav] hop, win = int(0.02 * SR), int(0.3 * SR) energy = np.convolve(wav.astype(np.float32) ** 2, np.ones(win, dtype=np.float32) / win, mode="same")[::hop] pieces, start = [], 0 while len(wav) - start > int(max_s * SR): lo, hi = (start + int(min_s * SR)) // hop, (start + int(max_s * SR)) // hop cut = (lo + int(np.argmin(energy[lo:hi]))) * hop pieces.append(wav[start:cut]) start = cut pieces.append(wav[start:]) return pieces @torch.inference_mode() def transcribe(wav: np.ndarray, model, processor, beams: int = 1, batch_size: int = 8) -> str: pieces = [p for p in split_long(wav) if len(p) > 0.1 * SR] texts = [] for i in range(0, len(pieces), batch_size): feats = processor.feature_extractor(pieces[i : i + batch_size], sampling_rate=SR, return_tensors="pt").input_features ids = model.generate(feats.to(model.device, model.dtype), language="fa", task="transcribe", num_beams=beams, max_new_tokens=440) texts += [t.strip() for t in processor.batch_decode(ids, skip_special_tokens=True)] return " ".join(t for t in texts if t) def main(): from transformers import WhisperForConditionalGeneration, WhisperProcessor ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("audio", nargs="+") ap.add_argument("--model", default="Nimruz/Nava") ap.add_argument("--digits", choices=["none", "fa", "ascii"], default="none", help="rewrite spoken numbers, times and dates in digits") ap.add_argument("--beams", type=int, default=1) args = ap.parse_args() device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" dtype = torch.float16 if device == "cuda" else torch.float32 processor = WhisperProcessor.from_pretrained(args.model) model = WhisperForConditionalGeneration.from_pretrained(args.model).to(device=device, dtype=dtype).eval() for path in args.audio: text = transcribe(load_audio(path), model, processor, beams=args.beams) if args.digits != "none": from nimruz.itn import itn # the nimruz/ folder next to this script text = itn(text, digits=args.digits) print(text) if __name__ == "__main__": main()