olivebot/ai_module/openai_tts.py
xszyou d68e759873 紧急修复
1、修复agent run的结果文字显示、保存DB✓
2、区分文字输入和语音输入✓
3、修复Speech.close bug✓
4、增加个人信息存入向量库✓
5、修复处理时间计算不准确✓
6、修复gpt key出错✓
2023-12-12 18:23:43 +08:00

59 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import requests
import json
import time
from utils import util, config_util
class Speech:
def __init__(self):
self.api_key = config_util.key_gpt_api_key
self.history_data = []
def __get_history(self, text):
for data in self.history_data:
if data[0] == text:
return data[1]
return None
def connect(self):
pass
def close(self):
pass
def to_sample(self, text, voice="nova", response_format="mp3", speed=1):
history = self.__get_history(text)
if history is not None:
return history
headers = {
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json'
}
url = "https://api.openai.com/v1/audio/speech"
query = {
"model": "tts-1-hd",#tts-1、tts-1-hd
"input": text,
"voice": voice,
"response_format": response_format,
"speed": speed
}
try:
response = requests.post(url=url, data=json.dumps(query), headers=headers)
file_url = './samples/sample-' + str(int(time.time() * 1000)) + '.mp3'
with open(file_url, "wb") as audio_file:
audio_file.write(response.content)
self.history_data.append((text, file_url))
except Exception as e :
util.log(1, "[x] 语音转换失败!")
util.log(1, "[x] 原因: " + str(str(e)))
file_url = None
return file_url
if __name__ == '__main__':
openai_tts = Speech(api_key='') # 替换为您的 OpenAI API Key
text = "你好我是FAY今天天气真好"
audio_file_url = openai_tts.to_sample(text)
print("音频文件已保存:", audio_file_url)