speech_recognition.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 = [
  26. "tiny.en",
  27. "tiny.en-q5_1",
  28. "tiny",
  29. "tiny-q5_1",
  30. "base.en",
  31. "base.en-q5_1",
  32. "base",
  33. "base-q5_1",
  34. "small.en",
  35. "small.en-q5_1",
  36. "small",
  37. "small-q5_1",
  38. "medium.en-q5_0",
  39. "medium-q5_0",
  40. "large-q5_0"
  41. ]
  42. class ASR():
  43. def __init__(self, model = "tiny", language = "en"):
  44. if model not in MODELS:
  45. raise ValueError(f"Invalid model: {model}. Must be one of {MODELS}")
  46. self.model = model
  47. self.language = language
  48. if os.path.exists(f"/app/ggml-model-whisper-{model}.bin"):
  49. self.model_path = f"/app/ggml-model-whisper-{model}.bin"
  50. else:
  51. self.model_path = f"/data/models/ggml-{model}.bin"
  52. if not os.path.exists("/data/models"):
  53. os.mkdir("/data/models")
  54. self.model_url = f"https://ggml.ggerganov.com/ggml-model-whisper-{self.model}.bin"
  55. self.lock = asyncio.Lock()
  56. def load_model(self):
  57. if not os.path.exists(self.model_path) or os.path.getsize(self.model_path) == 0:
  58. print("Downloading model...")
  59. subprocess.run(["wget", "-nv", self.model_url, "-O", self.model_path], check=True)
  60. print("Done.")
  61. async def transcribe(self, audio: bytes) -> str:
  62. filename = tempfile.mktemp(suffix=".wav")
  63. convert_audio(audio, filename)
  64. async with self.lock:
  65. proc = await asyncio.create_subprocess_exec(
  66. "./main",
  67. "-m", self.model_path,
  68. "-l", self.language,
  69. "-f", filename,
  70. "-nt",
  71. stdout=asyncio.subprocess.PIPE,
  72. stderr=asyncio.subprocess.PIPE
  73. )
  74. stdout, stderr = await proc.communicate()
  75. os.remove(filename)
  76. if stderr:
  77. print(stderr.decode())
  78. text = stdout.decode().strip()
  79. print(text)
  80. return text