Spaces:
Runtime error
Runtime error
File size: 1,871 Bytes
482bba4 ffcf1f4 482bba4 ffcf1f4 482bba4 ffcf1f4 482bba4 ffcf1f4 482bba4 ffcf1f4 482bba4 ffcf1f4 482bba4 ffcf1f4 482bba4 ffcf1f4 482bba4 ffcf1f4 482bba4 ffcf1f4 482bba4 ffcf1f4 482bba4 ffcf1f4 482bba4 ffcf1f4 482bba4 ffcf1f4 482bba4 f81f0bf |
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 |
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()
|