asr.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # ASR 语音识别模块
  2. from openai import OpenAI
  3. from config import Config
  4. def transcribe(audio_data: bytes) -> str:
  5. """
  6. 把音频转为文字
  7. 输入:WAV 格式音频 bytes
  8. 输出:识别出的文字
  9. """
  10. if Config.ASR_PROVIDER == 'openai_whisper':
  11. return transcribe_whisper(audio_data)
  12. else:
  13. raise ValueError(f'不支持的 ASR 提供商: {Config.ASR_PROVIDER}')
  14. def transcribe_whisper(audio_data: bytes) -> str:
  15. """使用 OpenAI Whisper API"""
  16. client = OpenAI(
  17. api_key=Config.OPENAI_API_KEY,
  18. base_url=Config.OPENAI_BASE_URL,
  19. )
  20. # 构造文件对象
  21. audio_file = ('audio.wav', audio_data, 'audio/wav')
  22. print('正在识别...')
  23. response = client.audio.transcriptions.create(
  24. model='whisper-1',
  25. file=audio_file,
  26. language='zh',
  27. )
  28. text = response.text.strip()
  29. print(f'识别结果: {text}')
  30. return text
  31. if __name__ == '__main__':
  32. from recorder import record_until_silence
  33. audio = record_until_silence()
  34. text = transcribe(audio)
  35. print(f'\n你说的是: {text}')