speech_recognition.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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", language = "en"):
  21. if model not in MODELS:
  22. raise ValueError(f"Invalid model: {model}. Must be one of {MODELS}")
  23. self.model = model
  24. self.language = language
  25. if not os.path.exists("/data/models"):
  26. os.mkdir("/data/models")
  27. self.model_path = f"/data/models/ggml-{model}.bin"
  28. self.model_url = f"https://ggml.ggerganov.com/ggml-model-whisper-{self.model}.bin"
  29. self.lock = asyncio.Lock()
  30. def load_model(self):
  31. if not os.path.exists(self.model_path):
  32. print("Downloading model...")
  33. subprocess.run(["wget", self.model_url, "-O", self.model_path], check=True)
  34. print("Done.")
  35. async def transcribe(self, audio: bytes) -> str:
  36. async with self.lock:
  37. convert_audio(audio)
  38. proc = await asyncio.create_subprocess_exec(
  39. "./main",
  40. "-m", self.model_path,
  41. "-l", self.language,
  42. "-f", "audio.wav",
  43. "--no_timestamps",
  44. stdout=asyncio.subprocess.PIPE,
  45. stderr=asyncio.subprocess.PIPE
  46. )
  47. stdout, stderr = await proc.communicate()
  48. os.remove("audio.wav")
  49. if stderr:
  50. print(stderr.decode())
  51. text = stdout.decode()
  52. print(text)
  53. return text