speech_recognition.py 2.4 KB

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