speech_recognition.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import ffmpeg
  2. import asyncio
  3. import subprocess
  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. self.lock = asyncio.Lock()
  29. def load_model(self):
  30. if not os.path.exists(self.model_path):
  31. print("Downloading model...")
  32. subprocess.run(["wget", self.model_url, "-O", self.model_path], check=True)
  33. print("Done.")
  34. async def transcribe(self, audio: bytes) -> str:
  35. async with self.lock:
  36. convert_audio(audio)
  37. proc = await asyncio.create_subprocess_exec(
  38. "./main", "-m", self.model_path, "-f", "audio.wav", "--no_timestamps",
  39. stdout=asyncio.subprocess.PIPE,
  40. stderr=asyncio.subprocess.PIPE
  41. )
  42. stdout, stderr = await proc.communicate()
  43. os.remove("audio.wav")
  44. if stderr:
  45. print(stderr.decode())
  46. text = stdout.decode()
  47. print(text)
  48. return text