Papori_MVP_01 / app.py
RLealz's picture
Update app.py
8d6dc6e verified
raw
history blame
6.55 kB
import gradio as gr
import random
import os
# Attempt to import required libraries
try:
from diffusers import StableDiffusionPipeline
import torch
STABLE_DIFFUSION_AVAILABLE = True
except ImportError as e:
print(f"Error importing Stable Diffusion dependencies: {e}")
STABLE_DIFFUSION_AVAILABLE = False
try:
import openai
openai.api_key = os.environ.get("OPENAI_API_KEY")
USE_GPT = True
except ImportError:
print("OpenAI library not found. Falling back to basic responses.")
USE_GPT = False
# Quiz questions and answers
christmas_quiz = [
{
"question": "What is the traditional Christmas flower?",
"options": ["Rose", "Poinsettia", "Tulip", "Daisy"],
"answer": "Poinsettia"
},
{
"question": "In which country did the tradition of putting up a Christmas tree originate?",
"options": ["USA", "England", "Germany", "France"],
"answer": "Germany"
},
{
"question": "What is the name of the ballet often performed at Christmas?",
"options": ["Swan Lake", "The Nutcracker", "Sleeping Beauty", "Giselle"],
"answer": "The Nutcracker"
},
{
"question": "Which company was the first to use Santa Claus in advertising?",
"options": ["Pepsi", "Coca-Cola", "McDonald's", "Walmart"],
"answer": "Coca-Cola"
},
{
"question": "What is the most popular Christmas dinner in Japan?",
"options": ["Turkey", "Ham", "KFC Chicken", "Roast Beef"],
"answer": "KFC Chicken"
}
]
# Initialize the Stable Diffusion pipeline if available
if STABLE_DIFFUSION_AVAILABLE:
model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float32)
def generate_image(prompt):
if not STABLE_DIFFUSION_AVAILABLE:
return None
with torch.no_grad():
image = pipe(prompt, num_inference_steps=50).images[0]
return image
def get_gpt_response(prompt, history):
if not USE_GPT:
return "I'm sorry, but I'm currently operating with limited capabilities. I can still help with the Christmas quiz and card generation!"
messages = [
{"role": "system", "content": "You are a helpful Christmas-themed chatbot named Holly. You can answer questions about Christmas, offer holiday tips, and engage in festive conversation. You also know about the Christmas quiz and card generation features of this application."},
]
for h in history:
messages.append({"role": "user", "content": h[0]})
messages.append({"role": "assistant", "content": h[1]})
messages.append({"role": "user", "content": prompt})
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
max_tokens=150,
n=1,
stop=None,
temperature=0.7,
)
return response.choices[0].message['content'].strip()
except Exception as e:
print(f"Error in GPT response: {e}")
return "I'm having trouble connecting to my knowledge base right now. Can I help you with the Christmas quiz or card generation instead?"
def chatbot(message, history):
if not history:
return "Ho ho ho! Merry Christmas! I'm Holly, your Christmas helper. Would you like to take a Christmas quiz, create a Christmas card, or chat about the holidays?"
last_response = history[-1][1].lower()
if "quiz" in message.lower():
question = random.choice(christmas_quiz)
options_text = "\n".join([f"{i+1}. {opt}" for i, opt in enumerate(question['options'])])
return f"Great! Here's your Christmas quiz question:\n\n{question['question']}\n\n{options_text}\n\nPlease enter the number of your answer."
elif "card" in message.lower():
if STABLE_DIFFUSION_AVAILABLE:
return "Wonderful! Let's create a Christmas card. Please describe the scene you'd like on your card, and I'll generate it for you using AI."
else:
return "I'm sorry, but the card generation feature is currently unavailable. Would you like to take a Christmas quiz instead?"
elif any(str(i) in message for i in range(1, 5)): # Check if the message is a quiz answer
for q in christmas_quiz:
if q['question'] in history[-2][1]: # Find the question in the history
user_answer = q['options'][int(message) - 1]
if user_answer == q['answer']:
return f"Correct! {q['answer']} is the right answer. Would you like another question, to create a Christmas card, or to chat about something else?"
else:
return f"Sorry, that's not correct. The right answer is {q['answer']}. Would you like another question, to create a Christmas card, or to chat about something else?"
elif "card" in last_response and STABLE_DIFFUSION_AVAILABLE:
image = generate_image(f"Christmas card scene: {message}")
if image:
return (f"I've created a Christmas card based on your description: '{message}'. You can see it in the image box below. "
f"Would you like to create another card, take a quiz, or chat about something else?", image)
else:
return "I'm sorry, I couldn't generate the image. Would you like to try again, take a quiz, or chat about something else?"
else:
# Use GPT-3.5 for general conversation
return get_gpt_response(message, history)
# Gradio interface
with gr.Blocks() as demo:
gr.Markdown("# Christmas Quiz and Card Generator Chatbot")
gr.Markdown("""
Welcome to the Christmas Quiz and Card Generator Chatbot!
- Type 'quiz' to start a Christmas quiz.
- Type 'card' to create a custom Christmas card.
- Or just chat about anything Christmas-related!
""")
chatbot = gr.Chatbot()
msg = gr.Textbox(label="Type your message here")
clear = gr.Button("Clear")
def user(user_message, history):
return "", history + [[user_message, None]]
def bot(history):
bot_message = chatbot(history[-1][0], history[:-1])
history[-1][1] = bot_message
if isinstance(bot_message, tuple):
return history, bot_message[1]
return history, None
image_output = gr.Image()
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
bot, chatbot, [chatbot, image_output]
)
clear.click(lambda: None, None, chatbot, queue=False)
demo.launch()