DynamicMenuApp3 / app.py
nagasurendra's picture
Update app.py
c6f513e verified
raw
history blame
5.22 kB
import gradio as gr
import pandas as pd
# Function to load the menu data from Excel
def load_menu():
try:
return pd.read_excel("menu.xlsx") # Ensure menu.xlsx is in the same directory
except Exception as e:
raise ValueError(f"Error loading menu file: {e}")
# Function to filter menu items based on preference
def filter_menu(preference):
menu_data = load_menu()
if preference == "Halal/Non-Veg":
filtered_data = menu_data[menu_data["Ingredients"].str.contains("Chicken|Mutton|Fish|Prawns|Goat", case=False, na=False)]
elif preference == "Vegetarian":
filtered_data = menu_data[~menu_data["Ingredients"].str.contains("Chicken|Mutton|Fish|Prawns|Goat", case=False, na=False)]
elif preference == "Guilt-Free":
filtered_data = menu_data[menu_data["Description"].str.contains(r"Fat: ([0-9]|10)g", case=False, na=False)]
else: # Default to "All"
filtered_data = menu_data
# Generate HTML for the menu
html_content = ""
for _, item in filtered_data.iterrows():
html_content += f"""
<div class="menu-item">
<img src="{item['Image URL']}" alt="{item['Dish Name']}">
<h3>{item['Dish Name']}</h3>
<p>{item['Description']}</p>
<p><strong>${item['Price ($)']}</strong></p>
<button value="{item['Dish Name']}" onclick="showModal('{item['Dish Name']}')">Add</button>
</div>
"""
return html_content
# Function to render detailed view of a dish
def render_dish_details(dish_name):
menu_data = load_menu()
try:
dish = menu_data[menu_data["Dish Name"] == dish_name].iloc[0]
return (
dish["Image URL"],
dish_name,
dish["Description"],
f"${dish['Price ($)']}"
)
except IndexError:
raise ValueError(f"Dish '{dish_name}' not found!")
# Main Gradio app
def app():
with gr.Blocks(css="style.css") as demo:
gr.Markdown("## Dynamic Menu with Modal Window")
# Menu page
preference_selector = gr.Radio(
choices=["All", "Vegetarian", "Halal/Non-Veg", "Guilt-Free"],
value="All",
label="Filter Menu"
)
menu_output = gr.HTML(value=filter_menu("All"))
# Modal window (hidden by default)
modal_window = gr.Column(visible=False, elem_classes=["popup"])
modal_image = gr.Image(label="Dish Image")
modal_name = gr.Markdown()
modal_description = gr.Markdown()
modal_price = gr.Markdown()
spice_level = gr.Radio(choices=["Mild", "Medium", "Spicy"], label="Choose Spice Level")
extras = gr.CheckboxGroup(choices=["Extra Raita", "Extra Salan", "Extra Fried Onion"], label="Choose Extras")
quantity = gr.Number(value=1, label="Quantity", interactive=True)
special_instructions = gr.Textbox(label="Special Instructions", placeholder="Add any requests...")
add_to_cart_button = gr.Button("Add to Bag")
close_modal_button = gr.Button("Close")
# Cart
cart_state = gr.State([])
cart_output = gr.HTML(value="Your cart is empty.")
# Handlers
def update_menu(preference):
return filter_menu(preference)
def show_modal(dish_name):
try:
img, name, desc, price = render_dish_details(dish_name)
return (
gr.update(visible=True),
img, name, desc, price
)
except ValueError as e:
return gr.update(value=f"Error: {str(e)}")
def close_modal():
return gr.update(visible=False)
def add_to_cart(dish_name, spice_level, extras, quantity, instructions, cart):
cart.append({
"name": dish_name,
"spice_level": spice_level,
"extras": extras,
"quantity": quantity,
"instructions": instructions
})
cart_html = "<br>".join(
[f"{item['quantity']}x {item['name']} - {item['spice_level']} (Extras: {', '.join(item['extras'])})"
for item in cart]
)
return cart, cart_html
# Events
preference_selector.change(update_menu, inputs=[preference_selector], outputs=[menu_output])
menu_output.change(show_modal, inputs=[menu_output], outputs=[modal_window, modal_image, modal_name, modal_description, modal_price])
close_modal_button.click(close_modal, outputs=[modal_window])
add_to_cart_button.click(add_to_cart, inputs=[modal_name, spice_level, extras, quantity, special_instructions, cart_state], outputs=[cart_state, cart_output])
# Layout
with gr.Row():
menu_output
with modal_window:
modal_image
modal_name
modal_description
modal_price
spice_level
extras
quantity
special_instructions
add_to_cart_button
close_modal_button
with gr.Row():
cart_output
return demo
if __name__ == "__main__":
app().launch()