speech_recognition.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import ffmpeg
  2. import subprocess
  3. from itertools import takewhile
  4. import os
  5. SAMPLE_RATE = 16000
  6. def convert_audio(data: bytes) -> bytes:
  7. try:
  8. # This launches a subprocess to decode audio while down-mixing and resampling as necessary.
  9. # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
  10. out, _ = (
  11. ffmpeg.input("pipe:", threads=0)
  12. .output("audio.wav", format="wav", acodec="pcm_s16le", ac=1, ar=SAMPLE_RATE)
  13. .run(cmd="ffmpeg", capture_stdout=True, capture_stderr=True, input=data)
  14. )
  15. except ffmpeg.Error as e:
  16. raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e
  17. return out
  18. class ASR():
  19. def __init__(self, model = "tiny"):
  20. self.model = model
  21. def transcribe(self, audio: bytes) -> str:
  22. convert_audio(audio)
  23. stdout, stderr = subprocess.Popen(
  24. ["./main", "-m", f"models/ggml-{self.model}.bin", "-f", "audio.wav", "--no_timestamps"],
  25. stdout=subprocess.PIPE
  26. ).communicate()
  27. os.remove("audio.wav")
  28. if stderr:
  29. print(stderr.decode())
  30. lines = stdout.decode().splitlines()[23:]
  31. print('\n'.join(lines))
  32. text = takewhile(lambda x: x, lines)
  33. return '\n'.join(text)