| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- # ASR 语音识别模块
- from openai import OpenAI
- from config import Config
- def transcribe(audio_data: bytes) -> str:
- """
- 把音频转为文字
- 输入:WAV 格式音频 bytes
- 输出:识别出的文字
- """
- if Config.ASR_PROVIDER == 'openai_whisper':
- return transcribe_whisper(audio_data)
- else:
- raise ValueError(f'不支持的 ASR 提供商: {Config.ASR_PROVIDER}')
- def transcribe_whisper(audio_data: bytes) -> str:
- """使用 OpenAI Whisper API"""
- client = OpenAI(
- api_key=Config.OPENAI_API_KEY,
- base_url=Config.OPENAI_BASE_URL,
- )
- # 构造文件对象
- audio_file = ('audio.wav', audio_data, 'audio/wav')
- print('正在识别...')
- response = client.audio.transcriptions.create(
- model='whisper-1',
- file=audio_file,
- language='zh',
- )
- text = response.text.strip()
- print(f'识别结果: {text}')
- return text
- if __name__ == '__main__':
- from recorder import record_until_silence
- audio = record_until_silence()
- text = transcribe(audio)
- print(f'\n你说的是: {text}')
|