SPB Git

Repository Public

transcribe.py 2.1 KB 52 lines python

1"""Transcribes one audio file with word-level timestamps (mlx-whisper, runs locally on Apple Silicon).23    python transcribe.py <audio file> <model repo> <language | auto>45Prints one JSON object on stdout: {"language": "fr", "segments": [{start, end, text, no_speech_prob, avg_logprob,6compression_ratio, words: [{start, end, word}]}]}. Called by the worker with an argument vector (no shell).7"""8import json9import math10import sys111213def num(value, fallback: float) -> float:14    """Whisper yields NaN for a segment with no tokens (silence, pure instrumental); NaN is not valid JSON."""15    try:16        f = float(value)17    except (TypeError, ValueError):18        return fallback19    return f if math.isfinite(f) else fallback202122def main() -> None:23    path, model, language = sys.argv[1], sys.argv[2], sys.argv[3]24    import mlx_whisper  # imported late so a missing install gives a clear error line2526    result = mlx_whisper.transcribe(27        path,28        path_or_hf_repo=model,29        word_timestamps=True,30        # Songs repeat themselves: feeding the previous window back makes the model loop on a chorus.31        condition_on_previous_text=False,32        language=None if language == "auto" else language,33        verbose=None,34    )35    out = {"language": result.get("language"), "segments": []}36    for s in result.get("segments", []):37        out["segments"].append({38            "start": float(s["start"]), "end": float(s["end"]), "text": s["text"],39            "no_speech_prob": num(s.get("no_speech_prob"), 0.0), "avg_logprob": num(s.get("avg_logprob"), -5.0),40            "compression_ratio": num(s.get("compression_ratio"), 0.0),41            "words": [{"start": float(w["start"]), "end": float(w["end"]), "word": w["word"]} for w in s.get("words", [])],42        })43    json.dump(out, sys.stdout, ensure_ascii=False, allow_nan=False)444546if __name__ == "__main__":47    try:48        main()49    except Exception as e:  # noqa: BLE001 — one line for the worker's log, no traceback with paths50        print(f"transcribe failed: {type(e).__name__}: {str(e)[:200]}", file=sys.stderr)51        sys.exit(1)52
Files main
Menu

Theme