speech_recognition.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 os.path.exists(f"/app/ggml-model-whisper-{model}.bin"):
  33. self.model_path = f"/app/ggml-model-whisper-{model}.bin"
  34. else:
  35. self.model_path = f"/data/models/ggml-{model}.bin"
  36. if not os.path.exists("/data/models"):
  37. os.mkdir("/data/models")
  38. self.model_url = f"https://ggml.ggerganov.com/ggml-model-whisper-{self.model}.bin"
  39. self.lock = asyncio.Lock()
  40. def load_model(self):
  41. if not os.path.exists(self.model_path) or os.path.getsize(self.model_path) == 0:
  42. print("Downloading model...")
  43. subprocess.run(["wget", self.model_url, "-O", self.model_path], check=True)
  44. print("Done.")
  45. async def transcribe(self, audio: bytes) -> str:
  46. filename = tempfile.mktemp(suffix=".wav")
  47. convert_audio(audio, filename)
  48. async with self.lock:
  49. proc = await asyncio.create_subprocess_exec(
  50. "./main",
  51. "-m", self.model_path,
  52. "-l", self.language,
  53. "-f", filename,
  54. "--no_timestamps",
  55. stdout=asyncio.subprocess.PIPE,
  56. stderr=asyncio.subprocess.PIPE
  57. )
  58. stdout, stderr = await proc.communicate()
  59. os.remove(filename)
  60. if stderr:
  61. print(stderr.decode())
  62. text = stdout.decode().strip()
  63. print(text)
  64. return text