cart_test / app.py
eaglelandsonce's picture
Rename app (4).py to app.py
d41491a verified
raw
history blame
5.02 kB
import gradio as gr
import pandas as pd
# ---------- Inventory ----------
# ID -> (Name, Price per KG)
INVENTORY = {
1: ("Apples", 250),
2: ("Cherry", 650),
3: ("Chickoo", 50),
4: ("Grapes", 90),
5: ("Mangoes", 150),
}
def inventory_markdown():
items = "\n".join([f"({pid}) **{name}**, {price}"
for pid, (name, price) in INVENTORY.items()])
return f"### Inventory\n{items}"
# ---------- Cart helpers ----------
def summarize_cart(cart):
"""Return (DataFrame, total_cost) for the cart.
Cart structure: list of dicts with keys: id, name, unit_price, qty
"""
if not cart:
return pd.DataFrame(columns=["Index","Name","Quantity","Price Per KG"]), 0
rows = []
total = 0
for idx, item in enumerate(cart):
rows.append({
"Index": idx,
"Name": item["name"],
"Quantity": item["qty"],
"Price Per KG": f"${item['unit_price']:.2f}",
})
total += item["qty"] * item["unit_price"]
df = pd.DataFrame(rows)
return df, total
def add_item_to_cart(pid, cart):
add_msg = ""
if pid is None:
return *summarize_cart(cart), add_msg, ""
if pid not in INVENTORY:
add_msg = f":warning: Invalid ID {pid}. Please use one of: {list(INVENTORY.keys())}"
return *summarize_cart(cart), add_msg, ""
name, price = INVENTORY[pid]
# Check if already in cart -> increment quantity
for item in cart:
if item["id"] == pid:
item["qty"] += 1
df, total = summarize_cart(cart)
add_msg = f">>>>>>>>>> The item '{name}' has been added to the cart. <<<<<<<<<<"
return df, total, add_msg, ""
# Otherwise append new
cart.append({"id": pid, "name": name, "unit_price": float(price), "qty": 1})
df, total = summarize_cart(cart)
add_msg = f">>>>>>>>>> The item '{name}' has been added to the cart. <<<<<<<<<<"
return df, total, add_msg, ""
def remove_item_from_cart(index, cart):
rm_msg = ""
if index is None:
return *summarize_cart(cart), "", rm_msg
if not cart:
rm_msg = ":warning: Cart is empty."
return *summarize_cart(cart), "", rm_msg
if index < 0 or index >= len(cart):
rm_msg = f":warning: Invalid index {index}. Must be 0..{max(0,len(cart)-1)}"
return *summarize_cart(cart), "", rm_msg
removed = cart.pop(index)
df, total = summarize_cart(cart)
rm_msg = f"Removed '{removed['name']}' from the cart."
return df, total, "", rm_msg
with gr.Blocks(title="Fruit Shopping Cart System") as demo:
gr.Markdown("## Fruit Shopping Cart System")
# App state: the cart
cart_state = gr.State([])
with gr.Row():
with gr.Column(scale=2):
pid_in = gr.Number(label="Enter Product ID to Add to Cart", value=2, precision=0)
with gr.Column(scale=2):
rm_index_in = gr.Number(label="Enter Index ID to Remove from Cart", value=0, precision=0)
with gr.Column(scale=1):
add_btn = gr.Button("Add to Cart", variant="primary")
with gr.Column(scale=1):
rm_btn = gr.Button("Remove from Cart", variant="secondary")
with gr.Row():
with gr.Column(scale=3):
gr.Markdown("### Your Cart\n_Use 0-based index for removal_ :shopping_trolley:")
cart_df = gr.Dataframe(headers=["Index","Name","Quantity","Price Per KG"],
interactive=False,
wrap=True,
height=220)
add_msg_out = gr.Textbox(label="Add Item Message", interactive=False)
rm_msg_out = gr.Textbox(label="Remove Item Message", interactive=False)
total_cost_out = gr.Textbox(label="Total Cost", interactive=False)
with gr.Column(scale=2):
inv_md = gr.Markdown(inventory_markdown())
gr.Markdown("""
### Business Requirements
1. **Add Products to the Shopping Cart**: Add by ID from the inventory; quantities aggregate automatically.
2. **Remove Unwanted Items**: Remove by 0-based index shown in the cart table.
3. **Calculate the Total Bill**: Total updates automatically after each action.
""")
def handle_add(pid, cart):
df, total, add_msg, rm_msg = add_item_to_cart(int(pid), cart)
total_str = f"$ {total:,.2f}"
return df, add_msg, rm_msg, total_str, cart
def handle_remove(index, cart):
df, total, add_msg, rm_msg = remove_item_from_cart(int(index), cart)
total_str = f"$ {total:,.2f}"
return df, add_msg, rm_msg, total_str, cart
add_btn.click(
handle_add,
inputs=[pid_in, cart_state],
outputs=[cart_df, add_msg_out, rm_msg_out, total_cost_out, cart_state]
)
rm_btn.click(
handle_remove,
inputs=[rm_index_in, cart_state],
outputs=[cart_df, add_msg_out, rm_msg_out, total_cost_out, cart_state]
)
if __name__ == "__main__":
demo.launch()