speech_recognition.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import tempfile
  2. import ffmpeg
  3. import asyncio
  4. import subprocess
  5. import os
  6. SAMPLE_RATE = 16000
  7. def convert_audio(data: bytes, out_filename: str):
  8. try:
  9. with tempfile.NamedTemporaryFile("w+b") as file:
  10. file.write(data)
  11. file.flush()
  12. print(f"Converting media {file.name} to {out_filename}")
  13. out, err = (
  14. ffmpeg.input(file.name, threads=0)
  15. .output(out_filename, format="wav", acodec="pcm_s16le", ac=1, ar=SAMPLE_RATE)
  16. .overwrite_output()
  17. .run(cmd="ffmpeg", capture_stdout=True, capture_stderr=True, input=data)
  18. )
  19. if os.path.getsize(out_filename) == 0:
  20. print(str(err, "utf-8"))
  21. raise Exception("Converted file is empty")
  22. except ffmpeg.Error as e:
  23. raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e
  24. return out
  25. MODELS = ["tiny.en", "tiny", "base.en", "base", "small.en", "small", "medium.en", "medium", "large"]
  26. class ASR():
  27. def __init__(self, model = "tiny", language = "en"):
  28. if model not in MODELS:
  29. raise ValueError(f"Invalid model: {model}. Must be one of {MODELS}")
  30. self.model = model
  31. self.language = language
  32. if not os.path.exists("/data/models"):
  33. os.mkdir("/data/models")
  34. self.model_path = f"/data/models/ggml-{model}.bin"
  35. self.model_url = f"https://ggml.ggerganov.com/ggml-model-whisper-{self.model}.bin"
  36. self.lock = asyncio.Lock()
  37. def load_model(self):
  38. if not os.path.exists(self.model_path):
  39. print("Downloading model...")
  40. subprocess.run(["wget", self.model_url, "-O", self.model_path], check=True)
  41. print("Done.")
  42. async def transcribe(self, audio: bytes) -> str:
  43. filename = tempfile.mktemp(suffix=".wav")
  44. convert_audio(audio, filename)
  45. async with self.lock:
  46. proc = await asyncio.create_subprocess_exec(
  47. "./main",
  48. "-m", self.model_path,
  49. "-l", self.language,
  50. "-f", filename,
  51. "--no_timestamps",
  52. stdout=asyncio.subprocess.PIPE,
  53. stderr=asyncio.subprocess.PIPE
  54. )
  55. stdout, stderr = await proc.communicate()
  56. os.remove(filename)
  57. if stderr:
  58. print(stderr.decode())
  59. text = stdout.decode().strip()
  60. print(text)
  61. return text