forked from Blendman974/faceclaw
53 lines
2.2 KiB
Python
53 lines
2.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Verify released hashes and decode a public/test WAV with sherpa-onnx CPU."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import time
|
|
import wave
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--model-dir', type=Path, required=True)
|
|
parser.add_argument('--wav', type=Path, required=True)
|
|
parser.add_argument('--expected', help='Optional expected transcription substring')
|
|
args = parser.parse_args()
|
|
model_dir = args.model_dir
|
|
manifest = json.loads((model_dir / 'manifest.json').read_text())
|
|
for entry in manifest['files']:
|
|
path = model_dir / entry['name']
|
|
with path.open('rb') as stream:
|
|
actual = hashlib.file_digest(stream, 'sha256').hexdigest()
|
|
if actual != entry['sha256'] or path.stat().st_size != entry['sizeBytes']:
|
|
raise ValueError(f'Model file integrity check failed: {path.name}')
|
|
|
|
import numpy as np
|
|
import sherpa_onnx
|
|
with wave.open(str(args.wav)) as audio:
|
|
if audio.getnchannels() != 1 or audio.getsampwidth() != 2:
|
|
raise ValueError('Provide a mono PCM16 WAV')
|
|
sample_rate = audio.getframerate()
|
|
samples = np.frombuffer(audio.readframes(audio.getnframes()), dtype='<i2').astype(np.float32) / 32768
|
|
recognizer = sherpa_onnx.OfflineRecognizer.from_whisper(
|
|
encoder=str(model_dir / 'small-fr-encoder.int8.onnx'),
|
|
decoder=str(model_dir / 'small-fr-decoder.int8.onnx'),
|
|
tokens=str(model_dir / 'small-fr-tokens.txt'), num_threads=1,
|
|
language='fr', task='transcribe',
|
|
)
|
|
stream = recognizer.create_stream()
|
|
stream.accept_waveform(sample_rate, samples)
|
|
start = time.monotonic()
|
|
recognizer.decode_stream(stream)
|
|
text = stream.result.text.strip()
|
|
if not text or (args.expected and args.expected.casefold() not in text.casefold()):
|
|
raise ValueError(f'Unexpected transcription: {text!r}')
|
|
print(json.dumps({'sherpaVersion': sherpa_onnx.__version__, 'text': text,
|
|
'audioSeconds': len(samples) / sample_rate,
|
|
'decodeSeconds': time.monotonic() - start}, ensure_ascii=False, indent=2))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|