speech_recognition.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. MODELS = ["tiny.en", "tiny", "base.en", "base", "small.en", "small", "medium.en", "medium", "large"]
  19. class ASR():
  20. def __init__(self, model = "tiny"):
  21. if model not in MODELS:
  22. raise ValueError(f"Invalid model: {model}. Must be one of {MODELS}")
  23. self.model = model
  24. if not os.path.exists("/data/models"):
  25. os.mkdir("/data/models")
  26. self.model_path = f"/data/models/ggml-{model}.bin"
  27. self.model_url = f"https://ggml.ggerganov.com/ggml-model-whisper-{self.model}.bin"
  28. def load_model(self):
  29. if not os.path.exists(self.model_path):
  30. print("Downloading model...")
  31. subprocess.run(["wget", self.model_url, "-O", self.model_path], check=True)
  32. print("Done.")
  33. def transcribe(self, audio: bytes) -> str:
  34. convert_audio(audio)
  35. stdout, stderr = subprocess.Popen(
  36. ["./main", "-m", self.model_path, "-f", "audio.wav", "--no_timestamps"],
  37. stdout=subprocess.PIPE
  38. ).communicate()
  39. os.remove("audio.wav")
  40. if stderr:
  41. print(stderr.decode())
  42. lines = stdout.decode().splitlines()[23:]
  43. print('\n'.join(lines))
  44. text = takewhile(lambda x: x, lines)
  45. return '\n'.join(text)