speech_recognition.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. os.mkdir("/data/models")
  25. self.model_path = f"/data/models/ggml-{model}.bin"
  26. self.model_url = f"https://ggml.ggerganov.com/ggml-model-whisper-{self.model}.bin"
  27. def load_model(self):
  28. if not os.path.exists(self.model_path):
  29. print("Downloading model...")
  30. subprocess.run(["wget", self.model_url, "-O", self.model_path], check=True)
  31. print("Done.")
  32. def transcribe(self, audio: bytes) -> str:
  33. convert_audio(audio)
  34. stdout, stderr = subprocess.Popen(
  35. ["./main", "-m", self.model_path, "-f", "audio.wav", "--no_timestamps"],
  36. stdout=subprocess.PIPE
  37. ).communicate()
  38. os.remove("audio.wav")
  39. if stderr:
  40. print(stderr.decode())
  41. lines = stdout.decode().splitlines()[23:]
  42. print('\n'.join(lines))
  43. text = takewhile(lambda x: x, lines)
  44. return '\n'.join(text)