Spaces:
Runtime error
Runtime error
File size: 1,968 Bytes
e61a4ec 482bba4 ffcf1f4 482bba4 ffcf1f4 e61a4ec 482bba4 ffcf1f4 e61a4ec 482bba4 e61a4ec ffcf1f4 e61a4ec 32f82e6 e61a4ec f094adb e61a4ec f1fd01a e61a4ec fab5430 e61a4ec 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 70 71 72 73 74 75 76 77 78 79 80 81 |
import os
import time
import openai
import gradio as gr
from gtts import gTTS
from io import BytesIO
from IPython.display import Audio, display
# Set OpenAI API key
openai.api_key = os.environ.get("OPENAI_API_KEY")
# Set OpenAI GPT-3 model
MODEL = "text-davinci-002"
# Initialize chat history as an empty list
chat_history = []
# Define function to generate speech from text using Google Text-to-Speech (gTTS)
def text_to_speech(text):
tts = gTTS(text=text)
mp3 = BytesIO()
tts.write_to_fp(mp3)
mp3.seek(0)
display(Audio(mp3, autoplay=True))
# Define function to get chatbot response
def chat(text):
# Append user input to chat history
chat_history.append(f"User: {text}")
# Use OpenAI's GPT-3.5 model to generate chatbot response
response = openai.Completion.create(
model=MODEL,
prompt = r"Conversation with user:\n" + "\n".join(chat_history) + r"\nChatbot:",
temperature=0.5,
max_tokens=1024,
n=1,
stop=None,
frequency_penalty=0,
presence_penalty=0
).choices[0].text.strip()
# Append chatbot response to chat history
chat_history.append(f"Chatbot: {response}")
# Generate speech from chatbot response
text_to_speech(response)
return response
# Define function to clear chat history
def clear_chat():
global chat_history
chat_history = []
# Define interface
interface = gr.Interface(
chat,
inputs=["text",
gr.Audio(source="microphone", type="numpy"),
],
outputs=["text", gr.outputs.Voice()],
title="Chatbot with OpenAI's GPT-3.5 Model",
description="An interactive chatbot using OpenAI's GPT-3.5 model with chat persistence and voice inputs/outputs.",
theme="default",
layout="vertical",
allow_flagging=False,
allow_screenshot=False,
allow_download=False,
show_input=True,
show_output=True
)
# Run interface
interface.launch()
|