#!/usr/bin/env python3
"""
transcribe.py - minimal Arabic speech-to-text test using Whisper (via sherpa-onnx)

Setup (see README.md for full instructions):
    pip install sherpa-onnx soundfile --break-system-packages
    wget https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-whisper-small.tar.bz2
    tar xf sherpa-onnx-whisper-small.tar.bz2

Usage:
    python3 transcribe.py path/to/audio.wav
"""
import sys
import time
import soundfile as sf
import sherpa_onnx

MODEL_DIR = "sherpa-onnx-whisper-small"
MODEL_SIZE = "small"  # must match the downloaded model files' prefix


def main():
    if len(sys.argv) < 2:
        print("Usage: python3 transcribe.py path/to/audio.wav")
        sys.exit(1)

    audio_path = sys.argv[1]

    recognizer = sherpa_onnx.OfflineRecognizer.from_whisper(
        encoder=f"{MODEL_DIR}/{MODEL_SIZE}-encoder.int8.onnx",
        decoder=f"{MODEL_DIR}/{MODEL_SIZE}-decoder.int8.onnx",
        tokens=f"{MODEL_DIR}/{MODEL_SIZE}-tokens.txt",
        language="ar",  # change to "en" for English, or omit for auto-detect
        task="transcribe",
        num_threads=2,
    )

    audio, sample_rate = sf.read(audio_path, dtype="float32")

    stream = recognizer.create_stream()
    stream.accept_waveform(sample_rate, audio)

    t0 = time.time()
    recognizer.decode_stream(stream)
    elapsed = time.time() - t0

    print(f"Transcribed ({elapsed:.2f}s): {stream.result.text}")


if __name__ == "__main__":
    main()
