Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| # ---- Inventory (ID, Name, PricePerUnit) ---- | |
| INVENTORY = [ | |
| (1, "Apples", 250), | |
| (2, "Cherry", 650), | |
| (3, "Chickoo", 50), | |
| (4, "Grapes", 90), | |
| (5, "Mangoes", 150), | |
| ] | |
| INV_MAP = {pid: (name, price) for pid, name, price in INVENTORY} | |
| def add_item(cart, item_id): | |
| """ | |
| Add one unit of item_id to the cart. | |
| cart: dict {product_id: quantity} | |
| """ | |
| # Validate item_id | |
| if item_id is None: | |
| return cart, "Please enter a Product ID to add.", "" | |
| try: | |
| item_id = int(item_id) | |
| except (TypeError, ValueError): | |
| return cart, "Product ID must be an integer.", "" | |
| if item_id not in INV_MAP: | |
| return cart, f"Invalid Product ID: {item_id}", "" | |
| new_cart = dict(cart) if cart else {} | |
| new_cart[item_id] = new_cart.get(item_id, 0) + 1 | |
| name, _ = INV_MAP[item_id] | |
| return new_cart, f">>>>> '{name}' added to cart. <<<<<\n", "" | |
| def remove_item(cart, item_id): | |
| """ | |
| Remove one unit of item_id from the cart (if present). | |
| """ | |
| if not cart: | |
| return cart, "", "Cart is empty." | |
| if item_id is None: | |
| return cart, "", "Please enter a Product ID to remove." | |
| try: | |
| item_id = int(item_id) | |
| except (TypeError, ValueError): | |
| return cart, "", "Product ID must be an integer." | |
| if item_id not in cart or cart[item_id] <= 0: | |
| return cart, "", f"Item ID {item_id} is not in the cart." | |
| new_cart = dict(cart) | |
| new_cart[item_id] -= 1 | |
| if new_cart[item_id] <= 0: | |
| del new_cart[item_id] | |
| name, _ = INV_MAP[item_id] | |
| return new_cart, "", f">>>>> One '{name}' removed. <<<<<\n" | |
| def render_cart(cart): | |
| """ | |
| Pretty-print the cart and compute total. | |
| cart: dict {product_id: quantity} | |
| """ | |
| if not cart: | |
| return ">>>>>>>> Your cart is empty! Why not buy fruits from us? <<<<<<<<\n", "Total cost: $0.00" | |
| lines = [] | |
| lines.append("+" * 62) | |
| lines.append(f"{'Your Cart':^62}") | |
| lines.append("+" * 62) | |
| lines.append(f"{'ProdID':<8} {'Name':<20} {'Qty':<6} {'Price/Unit':<12} {'Line Total':<12}") | |
| lines.append("-" * 62) | |
| grand = 0 | |
| # Stable order by product id | |
| for pid in sorted(cart.keys()): | |
| qty = cart[pid] | |
| name, price = INV_MAP[pid] | |
| line_total = price * qty | |
| grand += line_total | |
| lines.append(f"{pid:<8} {name:<20} {qty:<6} ${price/100:>10.2f} ${line_total/100:>10.2f}") | |
| lines.append("-" * 62) | |
| lines.append(f"{'Grand Total':<48} ${grand/100:>10.2f}") | |
| return "\n".join(lines), f"Total cost: ${grand/100:.2f}" | |
| def add_handler(cart_state, item_id): | |
| cart, add_msg, _ = add_item(cart_state, item_id) | |
| cart_txt, total_txt = render_cart(cart) | |
| return cart, cart_txt, add_msg, "" , total_txt | |
| def remove_handler(cart_state, item_id): | |
| cart, _, remove_msg = remove_item(cart_state, item_id) | |
| cart_txt, total_txt = render_cart(cart) | |
| return cart, cart_txt, "" , remove_msg, total_txt | |
| def clear_cart(): | |
| cart = {} | |
| cart_txt, total_txt = render_cart(cart) | |
| return cart, cart_txt, "", "", total_txt | |
| def launch_gradio(): | |
| with gr.Blocks() as demo: | |
| gr.Markdown("### Fruit Shopping Cart System") | |
| # Persist cart per user session | |
| cart_state = gr.State({}) | |
| with gr.Row(): | |
| add_id = gr.Number(label="Product ID to Add", precision=0) | |
| rem_id = gr.Number(label="Product ID to Remove", precision=0) | |
| with gr.Row(): | |
| add_btn = gr.Button("Add to Cart") | |
| rem_btn = gr.Button("Remove from Cart") | |
| clr_btn = gr.Button("Clear Cart") | |
| cart_display = gr.Textbox(label="Your Cart", interactive=False, lines=12) | |
| add_msg_box = gr.Textbox(label="Add Item Message", interactive=False) | |
| rem_msg_box = gr.Textbox(label="Remove Item Message", interactive=False) | |
| total_box = gr.Textbox(label="Total Cost", interactive=False) | |
| # Show inventory reference | |
| inv_md = "#### Inventory\n" | |
| inv_md += "| ID | Name | Price (USD) |\n|---:|---------|-------------:|\n" | |
| for pid, name, price in INVENTORY: | |
| inv_md += f"| {pid} | {name} | ${price/100:.2f} |\n" | |
| gr.Markdown(inv_md) | |
| # Wire up events | |
| add_btn.click( | |
| add_handler, | |
| inputs=[cart_state, add_id], | |
| outputs=[cart_state, cart_display, add_msg_box, rem_msg_box, total_box], | |
| ) | |
| rem_btn.click( | |
| remove_handler, | |
| inputs=[cart_state, rem_id], | |
| outputs=[cart_state, cart_display, add_msg_box, rem_msg_box, total_box], | |
| ) | |
| clr_btn.click( | |
| clear_cart, | |
| inputs=[], | |
| outputs=[cart_state, cart_display, add_msg_box, rem_msg_box, total_box], | |
| ) | |
| # Initial render | |
| demo.load(lambda: render_cart({}), inputs=None, outputs=[cart_display, total_box]) | |
| demo.launch() | |
| if __name__ == "__main__": | |
| launch_gradio() | |