test / test2.py
Gnib's picture
Update test2.py
ce7bf73 verified
raw
history blame contribute delete
No virus
4.38 kB
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
pip install --upgrade pip
'''
import os
import json
import openai
import gradio as gr
import azure.cognitiveservices.speech as speechsdk
import logging
from openai import OpenAI
API_URL_REDIRECT = {"https://api.openai.com/v1/chat/completions": "https://gnib.shop/v1/chat/completions"}
MODEL_NAME = 'gpt-3.5-turbo'
openai.api_key = os.getenv("OPENAI_APIKEY")
# 设置端口号,默认7560,遇冲突可自定义
SERVER_PORT = 7560
def enable_log(PATH_LOGGING):
admin_log_path = os.path.join(PATH_LOGGING, "admin")
os.makedirs(admin_log_path, exist_ok=True)
log_dir = os.path.join(admin_log_path, "chat_secrets.log")
try:logging.basicConfig(filename=log_dir, level=logging.INFO, encoding="utf-8", format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
except:logging.basicConfig(filename=log_dir, level=logging.INFO, format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
# Disable logging output from the 'httpx' logger
logging.getLogger("httpx").setLevel(logging.WARNING)
print(f"所有对话记录将自动保存在本地目录{log_dir}, 请注意自我隐私保护哦!")
class ChatGPT:
def __init__(self, save_message=False, ):
self.message=[]
self.model = MODEL_NAME
# 开启此项,须告知用户
self.save_message = save_message
self.filename = "./user_messages.json"
def get_response(self,question):
""" 调用openai接口, 获取回答
"""
# 用户的问题加入到message
self.message.append({"role": "user", "content": "你是一个AI助手(回答不要加表情),%s"%question})
# 问chatgpt问题的答案
rsp = openai.chat.completions.create(
model=self.model,
messages=self.message,
)
answer = rsp.choices[0].message.content
logging.warning('Q:%s'+'A:%s',self.message,answer)
# 得到的答案加入message,多轮对话的历史信息
self.message.append({"role": "assistant", "content": str(answer)})
# return [["",answer]]
return respond(answer,'')
def clean_history(self):
""" 清空历史信息
"""
self.message.clear()
def respond(text,audio):
speech_config = speechsdk.SpeechConfig(subscription="2aaf11299e2a44238d678cf77185e694",
region="eastus")
audio_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=True)
# The neural multilingual voice can speak different languages based on the input text.
speech_config.speech_synthesis_voice_name = 'en-US-AvaMultilingualNeural'
# # 由于TTS无法很好地处理回车符和空格,需要对text里的回车符进行替换
text = text.replace("\n", ",")
text = text.replace(" ", "")
speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)
# Get text from the console and synthesize to the default speaker.
# print("Enter some text that you want to speak >")
# text = input()
speech_synthesis_result = speech_synthesizer.speak_text_async(text).get()
file_path = 'output.wav'
with open(file_path, 'wb') as audio_file:
audio_file.write(speech_synthesis_result.audio_data)
return file_path
def main():
chatgpt=ChatGPT()
with gr.Blocks() as demo:
gr.HTML("""<h1 align="center">{}</h1>""".format(MODEL_NAME))
outputs = gr.Audio(label="Output")
# gradio的chatbot
# chatbot = gr.Chatbot()
with gr.Row():
with gr.Column(scale=4):
with gr.Column(scale=50):
user_input = gr.Textbox(show_label=False, placeholder="Input...", lines=10)
with gr.Column(min_width=32, scale=1):
submitBtn = gr.Button("Submit", variant="primary")
# with gr.Column(scale=1):
# emptyBtn = gr.ClearButton([chatbot])
# 提交问题
submitBtn.click(chatgpt.get_response,[user_input],outputs)
# submitBtn.click(reset_user_input, [], [user_input])
# # 清空历史对话
# emptyBtn.click(reset_state, outputs=[chatbot], show_progress=True)
demo.launch(server_port=SERVER_PORT)
if __name__ == '__main__':
main()