Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

openai_voice.py 2.1KB

11 miesięcy temu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """
  2. google voice service
  3. """
  4. import json
  5. import openai
  6. from bridge.reply import Reply, ReplyType
  7. from common.log import logger
  8. from config import conf
  9. from voice.voice import Voice
  10. import requests
  11. from common import const
  12. import datetime, random
  13. class OpenaiVoice(Voice):
  14. def __init__(self):
  15. openai.api_key = conf().get("open_ai_api_key")
  16. def voiceToText(self, voice_file):
  17. logger.debug("[Openai] voice file name={}".format(voice_file))
  18. try:
  19. file = open(voice_file, "rb")
  20. result = openai.Audio.transcribe("whisper-1", file)
  21. text = result["text"]
  22. reply = Reply(ReplyType.TEXT, text)
  23. logger.info("[Openai] voiceToText text={} voice file name={}".format(text, voice_file))
  24. except Exception as e:
  25. reply = Reply(ReplyType.ERROR, "我暂时还无法听清您的语音,请稍后再试吧~")
  26. finally:
  27. return reply
  28. def textToVoice(self, text):
  29. try:
  30. api_base = conf().get("open_ai_api_base") or "https://api.openai.com/v1"
  31. url = f'{api_base}/audio/speech'
  32. headers = {
  33. 'Authorization': 'Bearer ' + conf().get("open_ai_api_key"),
  34. 'Content-Type': 'application/json'
  35. }
  36. data = {
  37. 'model': conf().get("text_to_voice_model") or const.TTS_1,
  38. 'input': text,
  39. 'voice': conf().get("tts_voice_id") or "alloy"
  40. }
  41. response = requests.post(url, headers=headers, json=data)
  42. file_name = "tmp/" + datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(0, 1000)) + ".mp3"
  43. logger.debug(f"[OPENAI] text_to_Voice file_name={file_name}, input={text}")
  44. with open(file_name, 'wb') as f:
  45. f.write(response.content)
  46. logger.info(f"[OPENAI] text_to_Voice success")
  47. reply = Reply(ReplyType.VOICE, file_name)
  48. except Exception as e:
  49. logger.error(e)
  50. reply = Reply(ReplyType.ERROR, "遇到了一点小问题,请稍后再问我吧")
  51. return reply