Spaces:
Running
Running
| import os | |
| import gradio as gr | |
| import openai | |
| openai.api_key = os.environ['OPENAI_API_KEY'] | |
| user_db = {os.environ['username']: os.environ['password']} | |
| messages = [{"role": "system", "content": 'You are a helpful technology assistant.'}] | |
| def audioGPT(audio): | |
| global messages | |
| audio_file = open(audio, "rb") | |
| transcript = openai.Audio.transcribe("whisper-1", audio_file) | |
| messages.append({"role": "user", "content": transcript["text"]}) | |
| response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages) | |
| system_message = response["choices"][0]["message"] | |
| messages.append(system_message) | |
| chats = "" | |
| for msg in messages: | |
| if msg['role'] != 'system': | |
| chats += msg['role'] + ": " + msg['content'] + "\n\n" | |
| return chats | |
| def textGPT(text): | |
| global messages | |
| messages.append({"role": "user", "content": text}) | |
| response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages) | |
| system_message = response["choices"][0]["message"] | |
| messages.append(system_message) | |
| chats = "" | |
| for msg in messages: | |
| if msg['role'] != 'system': | |
| chats += msg['role'] + ": " + msg['content'] + "\n\n" | |
| return chats | |
| def clear(): | |
| global messages | |
| messages = [{"role": "system", "content": 'You are a helpful technology assistant.'}] | |
| return | |
| def show(): | |
| global messages | |
| chats = "" | |
| for msg in messages: | |
| if msg['role'] != 'system': | |
| chats += msg['role'] + ": " + msg['content'] + "\n\n" | |
| return chats | |
| with gr.Blocks() as chatHistory: | |
| gr.Markdown("Click the Clear button below to remove all the chat history.") | |
| clear_btn = gr.Button("Clear") | |
| clear_btn.click(fn=clear, inputs=None, outputs=None, queue=False) | |
| gr.Markdown("Click the Display button below to show all the chat history.") | |
| clear_btn = gr.Button("Display") | |
| clear_btn.click(fn=show, inputs=None, outputs="text", queue=False) | |
| text = gr.Interface(fn=textGPT, inputs="text", outputs="text") | |
| audio = gr.Interface(fn=audioGPT, inputs=gr.Audio(source="microphone", type="filepath"), outputs="text") | |
| demo = gr.TabbedInterface([text, audio, chatHistory], [ "chatGPT", "audioGPT", "ChatHistory"]) | |
| if __name__ == "__main__": | |
| demo.launch(enable_queue=False, auth=lambda u, p: user_db.get(u) == p, | |
| auth_message="Welcome to Yichuan GPT!") | |
| #demo.launch() | |