Gnib commited on
Commit
cbd4ad8
1 Parent(s): c066311

Upload 4 files

Browse files
Files changed (4) hide show
  1. env.py +4 -0
  2. gpt_log/admin/chat_secrets.log +0 -0
  3. output.wav +0 -0
  4. test2.py +117 -0
env.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import os
2
+
3
+ os.environ["OPENAI_APIKEY"]="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"
4
+ os.environ["PATH_LOGGING"]="gpt_log"
gpt_log/admin/chat_secrets.log ADDED
File without changes
output.wav ADDED
Binary file (235 kB). View file
 
test2.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- encoding: utf-8 -*-
3
+ '''
4
+ @Time : 2023/09/22 17:43:35
5
+ @Author : zoeyxiong
6
+ @File : chatgpt_bot.py
7
+ @Desc : 调用chatGPT类
8
+ '''
9
+ import os
10
+ import json
11
+ import openai
12
+ import gradio as gr
13
+ import azure.cognitiveservices.speech as speechsdk
14
+ import logging
15
+ from openai import OpenAI
16
+ import env
17
+ API_URL_REDIRECT = {"https://api.openai.com/v1/chat/completions": "https://gnib.shop/v1/chat/completions"}
18
+
19
+ MODEL_NAME = 'gpt-3.5-turbo'
20
+ openai.api_key = os.environ.get("OPENAI_APIKEY")
21
+ # 设置端口号,默认7560,遇冲突可自定义
22
+ SERVER_PORT = 7560
23
+
24
+ def enable_log(PATH_LOGGING):
25
+ admin_log_path = os.path.join(PATH_LOGGING, "admin")
26
+ os.makedirs(admin_log_path, exist_ok=True)
27
+ log_dir = os.path.join(admin_log_path, "chat_secrets.log")
28
+ 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")
29
+ except:logging.basicConfig(filename=log_dir, level=logging.INFO, format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
30
+ # Disable logging output from the 'httpx' logger
31
+ logging.getLogger("httpx").setLevel(logging.WARNING)
32
+ print(f"所有对话记录将自动保存在本地目录{log_dir}, 请注意自我隐私保护哦!")
33
+
34
+
35
+ class ChatGPT:
36
+ def __init__(self, save_message=False, ):
37
+ self.message=[]
38
+ self.model = MODEL_NAME
39
+ # 开启此项,须告知用户
40
+ self.save_message = save_message
41
+ self.filename = "./user_messages.json"
42
+
43
+
44
+ def get_response(self,question):
45
+ """ 调用openai接口, 获取回答
46
+ """
47
+ # 用户的问题加入到message
48
+ self.message.append({"role": "user", "content": "你是一个AI助手(回答不要加表情),%s"%question})
49
+ # 问chatgpt问题的答案
50
+ rsp = openai.chat.completions.create(
51
+ model=self.model,
52
+ messages=self.message,
53
+ )
54
+ answer = rsp.choices[0].message.content
55
+ logging.warning('Q:%s'+'A:%s',self.message,answer)
56
+ # 得到的答案加入message,多轮对话的历史信息
57
+ self.message.append({"role": "assistant", "content": str(answer)})
58
+ # return [["",answer]]
59
+ return respond(answer,'')
60
+
61
+ def clean_history(self):
62
+ """ 清空历史信息
63
+ """
64
+ self.message.clear()
65
+
66
+ def respond(text,audio):
67
+ speech_config = speechsdk.SpeechConfig(subscription="2aaf11299e2a44238d678cf77185e694",
68
+ region="eastus")
69
+ audio_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=True)
70
+
71
+ # The neural multilingual voice can speak different languages based on the input text.
72
+ speech_config.speech_synthesis_voice_name = 'en-US-AvaMultilingualNeural'
73
+ # # 由于TTS无法很好地处理回车符和空格,需要对text里的回车符进行替换
74
+ text = text.replace("\n", ",")
75
+ text = text.replace(" ", "")
76
+
77
+ speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)
78
+
79
+ # Get text from the console and synthesize to the default speaker.
80
+ # print("Enter some text that you want to speak >")
81
+ # text = input()
82
+
83
+ speech_synthesis_result = speech_synthesizer.speak_text_async(text).get()
84
+
85
+ file_path = 'output.wav'
86
+ with open(file_path, 'wb') as audio_file:
87
+ audio_file.write(speech_synthesis_result.audio_data)
88
+
89
+ return file_path
90
+
91
+
92
+ def main():
93
+ chatgpt=ChatGPT()
94
+ with gr.Blocks() as demo:
95
+ gr.HTML("""<h1 align="center">{}</h1>""".format(MODEL_NAME))
96
+ outputs = gr.Audio(label="Output")
97
+ # gradio的chatbot
98
+ # chatbot = gr.Chatbot()
99
+ with gr.Row():
100
+ with gr.Column(scale=4):
101
+ with gr.Column(scale=50):
102
+ user_input = gr.Textbox(show_label=False, placeholder="Input...", lines=10)
103
+ with gr.Column(min_width=32, scale=1):
104
+ submitBtn = gr.Button("Submit", variant="primary")
105
+ # with gr.Column(scale=1):
106
+ # emptyBtn = gr.ClearButton([chatbot])
107
+ # 提交问题
108
+ submitBtn.click(chatgpt.get_response,[user_input],outputs)
109
+ # submitBtn.click(reset_user_input, [], [user_input])
110
+ # # 清空历史对话
111
+ # emptyBtn.click(reset_state, outputs=[chatbot], show_progress=True)
112
+
113
+
114
+ demo.launch(share=False, inbrowser=True, server_port=SERVER_PORT)
115
+
116
+ if __name__ == '__main__':
117
+ main()