Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

57 lines
2.0KB

  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. url = 'https://api.openai.com/v1/audio/speech'
  31. headers = {
  32. 'Authorization': 'Bearer ' + conf().get("open_ai_api_key"),
  33. 'Content-Type': 'application/json'
  34. }
  35. data = {
  36. 'model': conf().get("text_to_voice_model") or const.TTS_1,
  37. 'input': text,
  38. 'voice': conf().get("tts_voice_id") or "alloy"
  39. }
  40. response = requests.post(url, headers=headers, json=data)
  41. file_name = "tmp/" + datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(0, 1000)) + ".mp3"
  42. logger.debug(f"[OPENAI] text_to_Voice file_name={file_name}, input={text}")
  43. with open(file_name, 'wb') as f:
  44. f.write(response.content)
  45. logger.info(f"[OPENAI] text_to_Voice success")
  46. reply = Reply(ReplyType.VOICE, file_name)
  47. except Exception as e:
  48. logger.error(e)
  49. reply = Reply(ReplyType.ERROR, "遇到了一点小问题,请稍后再问我吧")
  50. return reply