Spaces:
Runtime error
Runtime error
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 | |
# Define chatbot interface | |
chatbot_interface = gr.Interface( | |
fn=chatbot_response, | |
inputs=["text", gr.inputs.Microphone(type="live", duration=10)], | |
outputs=["text", "audio"], | |
title="Chatbot", | |
description="Talk to the chatbot using text and speech inputs." | |
) | |
# Launch chatbot interface | |
chatbot_interface.launch() | |