TalkGPT / app.py
Aniquel's picture
Update app.py
d400b93
raw
history blame contribute delete
No virus
2.11 kB
import os
import time
import openai
import gradio as gr
from gtts import gTTS
from io import BytesIO
from IPython.display import Audio, display
from transformers import pipeline
# 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
async def chat(input_text, state):
# 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.inputs.Audio(source="microphone", type="filepath"),
],
outputs=["text",
],
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()
save_chat_history() # save the chat history to a file