TalkGPT / app.py
Aniquel's picture
Update app.py
f1fd01a
raw
history blame
2.13 kB
import openai
import gradio as gr
from gtts import gTTS
from io import BytesIO
from IPython.display import Audio, display
import os
# Set OpenAI API key
openai.api_key = os.environ.get("OPENAI_API_KEY")
# Set OpenAI GPT-3 model
MODEL = "gpt-3.5-turbo"
# Load chat history from file
with open("chat_history.txt", "r") as f:
chat_history = f.read().strip()
# Define chatbot response function
def chatbot_response(text_input, voice_input):
# Concatenate text and voice input
input_text = text_input + " " + voice_input
# Concatenate input text with chat history
input_text_with_history = input_text + "\n\n" + chat_history
# Use OpenAI API to generate response
response = openai.Completion.create(
model=MODEL,
prompt=input_text_with_history,
max_tokens=3000,
n=1,
stop=None,
temperature=0.5
)
# Extract response text from OpenAI API output
response_text = response.choices[0].text.strip()
# Convert response text to speech
tts = gTTS(text=response_text)
audio_bytes = BytesIO()
tts.write_to_fp(audio_bytes)
audio_bytes.seek(0)
response_audio = Audio(audio_bytes, autoplay=True)
# Update chat history with input and response text
chat_history += f"\n\nUser: {text_input}\nChatbot: {response_text}"
# Save chat history to file
with open("chat_history.txt", "w") as f:
f.write(chat_history)
# Return response text and audio for display in interface
return response_text, response_audio
def run():
global chat_history
chat_history = ""
interface = gr.Interface(
fn=chat,
inputs=["text", gr.inputs.Dropdown(["en-US-Wavenet-A", "en-US-Wavenet-B", "en-US-Wavenet-C", "en-US-Wavenet-D"])],
outputs=["text", "audio"],
layout="vertical",
title="OpenAI Chatbot with Speech Output",
description="Chat with the OpenAI GPT-3 chatbot and get speech output of the bot's response."
)
interface.launch()
while True:
time.sleep(0.1)
with open("chat_history.txt", "w") as f:
f.write(chat_history)