Joey / app.py
LucidMinds3ye's picture
Update app.py
be0447d verified
raw
history blame
10.3 kB
import gradio as gr
import random
import time
# Business information - customize this for your business
BUSINESS_INFO = {
"name": "TechGadget Store",
"hours": "9AM-6PM Monday to Saturday",
"products": "smartphones, laptops, tablets, and accessories",
"address": "123 Main Street, Tech City",
"phone": "(555) 123-4567",
"email": "[email protected]",
"return_policy": "30-day money-back guarantee on all products",
"shipping": "Free shipping on orders over $50"
}
# Sample product database
PRODUCTS = {
"smartphone": {
"basic": {"name": "BasicPhone", "price": "$199", "features": "6.1\" display, 128GB storage"},
"pro": {"name": "ProPhone X", "price": "$899", "features": "6.7\" OLED, 512GB, 5G"}
},
"laptop": {
"standard": {"name": "WorkBook Lite", "price": "$699", "features": "15\" display, 8GB RAM, 256GB SSD"},
"premium": {"name": "WorkBook Pro", "price": "$1499", "features": "16\" display, 16GB RAM, 1TB SSD"}
}
}
# Predefined responses for common queries
def get_business_response(intent):
responses = {
"hours": f"Our store hours are {BUSINESS_INFO['hours']}.",
"location": f"We're located at {BUSINESS_INFO['address']}. Come visit us!",
"contact": f"You can reach us at {BUSINESS_INFO['phone']} or email {BUSINESS_INFO['email']}.",
"products": f"We offer a wide range of {BUSINESS_INFO['products']}. What specifically are you interested in?",
"returns": f"Our return policy: {BUSINESS_INFO['return_policy']}.",
"shipping": f"Shipping info: {BUSINESS_INFO['shipping']}. We offer free shipping on orders over $50!",
"greeting": "Hello! Welcome to TechGadget Store. How can I help you today?",
"thanks": "You're welcome! Is there anything else I can help you with?",
"goodbye": "Thank you for contacting TechGadget Store. Have a great day!",
"help": "I can help you with: \n• Store hours and location \n• Product information and pricing \n• Return and shipping policies \n• Technical comparisons between products \n• And much more! What do you need help with today?",
"capabilities": "I'm your virtual assistant for TechGadget Store! I can: \n• Answer questions about our products \n• Provide store information and hours \n• Explain our shipping and return policies \n• Help you compare different tech products \n• Assist with basic technical advice \n\nWhat would you like to know?"
}
return responses.get(intent, "I'm not sure how to help with that. Can you please rephrase?")
# Function to handle product inquiries
def handle_product_inquiry(product_type, model=None):
if product_type not in PRODUCTS:
return f"We don't carry that product. We mainly offer {', '.join(PRODUCTS.keys())}."
if model:
if model in PRODUCTS[product_type]:
product = PRODUCTS[product_type][model]
return f"Our {model} {product_type} is the {product['name']}, priced at {product['price']}. Features: {product['features']}"
else:
return f"We don't have a {model} model for {product_type}. We have {', '.join(PRODUCTS[product_type].keys())}."
else:
models = PRODUCTS[product_type]
response = f"For {product_type}, we have: "
for model_name, details in models.items():
response += f"\n- {model_name}: {details['name']} ({details['price']})"
return response
# Main chat function - updated for gr.Messages format
def chat_with_bot(message, chat_history):
user_message = message.lower()
bot_response = ""
# Check for greetings
if any(word in user_message for word in ["hi", "hello", "hey", "greetings"]):
bot_response = get_business_response("greeting")
# Check for thanks
elif any(word in user_message for word in ["thank", "appreciate", "thanks"]):
bot_response = get_business_response("thanks")
# Check for goodbye
elif any(word in user_message for word in ["bye", "goodbye", "see you"]):
bot_response = get_business_response("goodbye")
# Check for business hours
elif any(word in user_message for word in ["hour", "time", "open", "close"]):
bot_response = get_business_response("hours")
# Check for location
elif any(word in user_message for word in ["where", "location", "address", "find"]):
bot_response = get_business_response("location")
# Check for contact info
elif any(word in user_message for word in ["contact", "phone", "call", "email"]):
bot_response = get_business_response("contact")
# Check for products
elif any(word in user_message for word in ["product", "sell", "offer", "item"]):
bot_response = get_business_response("products")
# Check for returns
elif any(word in user_message for word in ["return", "exchange", "refund"]):
bot_response = get_business_response("returns")
# Check for shipping
elif any(word in user_message for word in ["ship", "delivery", "deliver", "shipping", "free shipping"]):
bot_response = get_business_response("shipping")
# Check for help or capabilities
elif any(word in user_message for word in ["help", "what can you do", "how can you help", "capabilities", "what do you know"]):
bot_response = get_business_response("capabilities")
# Handle product inquiries
elif any(word in user_message for word in ["smartphone", "phone"]):
if "pro" in user_message or "premium" in user_message:
bot_response = handle_product_inquiry("smartphone", "pro")
elif "basic" in user_message or "cheap" in user_message:
bot_response = handle_product_inquiry("smartphone", "basic")
else:
bot_response = handle_product_inquiry("smartphone")
elif any(word in user_message for word in ["laptop", "computer"]):
if "pro" in user_message or "premium" in user_message:
bot_response = handle_product_inquiry("laptop", "premium")
elif "standard" in user_message or "basic" in user_message:
bot_response = handle_product_inquiry("laptop", "standard")
else:
bot_response = handle_product_inquiry("laptop")
# Default response for unrecognized queries
else:
bot_response = "I'm here to help with information about our products, store hours, location, and policies. How can I assist you today?"
# Add a small delay to make it feel more natural
time.sleep(0.5)
# Append to chat history using the new Messages format
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": bot_response})
return "", chat_history
# Custom CSS for styling
custom_css = """
#chatbot {
font-family: 'Arial', sans-serif;
height: 400px;
overflow-y: auto;
}
.gr-button {
background-color: #4CAF50 !important;
color: white !important;
}
.gr-button:hover {
background-color: #45a049 !important;
}
.send-button {
background-color: #2196F3 !important;
}
.send-button:hover {
background-color: #0b7dda !important;
}
.clear-button {
background-color: #f44336 !important;
}
.clear-button:hover {
background-color: #d32f2f !important;
}
h1 {
color: #2C3E50;
text-align: center;
}
.container {
max-width: 1000px;
margin: auto;
padding: 20px;
}
.example-btn {
margin: 5px;
padding: 8px 12px;
border-radius: 5px;
background-color: #f0f0f0;
border: 1px solid #ddd;
cursor: pointer;
}
.example-btn:hover {
background-color: #e0e0e0;
}
"""
# Create the Gradio interface
with gr.Blocks(css=custom_css, title="TechGadget Store Support") as demo:
with gr.Column(elem_id="container"):
gr.Markdown("# 🤖 TechGadget Store Support Chat")
gr.Markdown("### How can I help you with our products and services today?")
with gr.Row():
with gr.Column(scale=2):
# Updated to use the new Messages format
chatbot = gr.Chatbot(
label="Conversation",
elem_id="chatbot",
type="messages",
show_copy_button=True
)
with gr.Row():
msg = gr.Textbox(
label="Type your message here...",
placeholder="What are your store hours? Or ask me about technology!",
lines=1,
scale=4
)
send_btn = gr.Button("Send", variant="primary", elem_classes="send-button", scale=1)
clear = gr.Button("Clear Conversation", variant="stop", elem_classes="clear-button")
with gr.Column(scale=1):
gr.Markdown("### 💡 Common Questions")
# Create example buttons with correct parameters
examples = gr.Examples(
examples=[
["What are your store hours?"],
["Where are you located?"],
["What smartphones do you sell?"],
["What is your return policy?"],
["Do you offer free shipping?"],
["What can you help with?"],
["Tell me about your laptops"]
],
inputs=msg,
label="Click any question to try it!"
)
gr.Markdown("### 🏪 Store Information")
gr.Markdown(f"""
- **Hours**: {BUSINESS_INFO['hours']}
- **Address**: {BUSINESS_INFO['address']}
- **Phone**: {BUSINESS_INFO['phone']}
- **Email**: {BUSINESS_INFO['email']}
- **Shipping**: {BUSINESS_INFO['shipping']}
""")
# Event handlers
msg.submit(chat_with_bot, [msg, chatbot], [msg, chatbot])
send_btn.click(chat_with_bot, [msg, chatbot], [msg, chatbot])
clear.click(lambda: None, None, chatbot, queue=False)
# Launch the application
if __name__ == "__main__":
demo.launch(share=True)