jhu_week_3 / app.py
rajendrr's picture
renamed shopping_cart_app to app.py
874344c verified
import gradio as gr
# Inventory and cart
Inventory = [
(1, "Apples", 250),
(2, "Cherry", 650),
(3, "Chickoo", 50),
(4, "Grapes", 90),
(5, "Mangoes", 150),
]
cart = []
# Helper functions
def get_inventory_dict():
return {f"{item[1]} - ₹{item[2]}": item for item in Inventory}
def add_to_cart(product):
item = get_inventory_dict().get(product)
if item:
cart.append(item)
return show_cart(), calculate_total()
return "Item not found.", calculate_total()
def remove_from_cart(product):
item = get_inventory_dict().get(product)
if item in cart:
cart.remove(item)
return show_cart(), calculate_total()
return "Item not in cart.", calculate_total()
def show_cart():
if not cart:
return "Cart is empty."
return "\n".join([f"{item[1]} - ₹{item[2]}" for item in cart])
def calculate_total():
return f"₹{sum(item[2] for item in cart)}"
# Gradio interface to use to make it work
product_choices = list(get_inventory_dict().keys())
with gr.Blocks() as app:
gr.Markdown("## 🛒 Shopping Cart App")
with gr.Row():
product_dropdown = gr.Dropdown(label="Select Product", choices=product_choices)
with gr.Row():
add_button = gr.Button("Add to Cart")
remove_button = gr.Button("Remove from Cart")
cart_display = gr.Textbox(label="Your Cart", interactive=False, lines=10)
total_display = gr.Textbox(label="Total Bill", interactive=False)
add_button.click(fn=add_to_cart, inputs=product_dropdown, outputs=[cart_display, total_display])
remove_button.click(fn=remove_from_cart, inputs=product_dropdown, outputs=[cart_display, total_display])
app.launch()