File size: 4,516 Bytes
cbd4ad8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Time    :   2023/09/22 17:43:35
@Author  :   zoeyxiong
@File    :   chatgpt_bot.py
@Desc    :   调用chatGPT类
'''
import os
import json
import openai
import gradio as gr
import azure.cognitiveservices.speech as speechsdk
import logging
from openai import OpenAI
import env
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.environ.get("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(share=False, inbrowser=True, server_port=SERVER_PORT)

if __name__ == '__main__':
    main()