当前位置:   article > 正文

Python40行代码实现语音和ChatGPT聊天_os.environ.get("openai_api_key")

os.environ.get("openai_api_key")

首先需要安装依赖包

pip install -r requirements.txt

1. 导入相关的包

  1. from Dxr_Chat.ChatGPT import Chatbot
  2. import os, subprocess
  3. from Dxr_voice.dxr_tts import text_to_speech_sync

2. 初始化

  1. # 初始化
  2. bot = Chatbot(os.environ.get('OPENAI_API_KEY'))

需要在环境变量中设置OPENAI_API_KEY

3. 生成对话

  1. # 生成对话
  2. response = bot.ask_stream("你好")
  3. for i in response:
  4. print(i, end='', flush=True)

4. 语音合成

  1. def say(text):
  2. rate = '+50%'
  3. out_file = text_to_speech_sync(text, rate=rate)
  4. # 使用sox来播放音频,如果没有安装sox,可以使用其他播放器
  5. subprocess.call(f"play {out_file}", shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

5. 语音识别

  1. # 语音识别
  2. def get_voice():
  3. print("请说话...")
  4. # 使用sox来录制音频
  5. subprocess.call("sox -d -r 16000 -c 1 -b 16 test.wav silence 1 0.1 1% 1 1.0 1%", shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  6. print("录音结束")
  7. return open("test.wav", "rb")
  8. # 调用语音识别获取语音文本
  9. voice_text = bot.voice_2_text(get_voice())

6. 语音对话

  1. # 语音对话
  2. while True:
  3. voice_text = bot.voice_2_text(get_voice())
  4. print(f'你说:{voice_text}')
  5. response = bot.ask_stream(voice_text)
  6. print(f'ChatGPT:', end='')
  7. final_str = ''
  8. for i in response:
  9. print(i, end='', flush=True)
  10. final_str += i
  11. print()
  12. say(final_str)

相关开源项目详见GitHub - boyueluzhipeng/MyChatGPT

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/201537?site
推荐阅读
相关标签
  

闽ICP备14008679号