SCMS_v1 / app.py
walepavan's picture
Create app.py
6fb377b verified
Raw
History Blame Contribute Delete
2.88 kB
import gradio as gr
# Sample inventory (can be extended later)
inventory = {
1: {"name": "Apple", "price": 2.0},
2: {"name": "Banana", "price": 1.0},
3: {"name": "Orange", "price": 1.5},
4: {"name": "Mango", "price": 3.0},
5: {"name": "Grapes", "price": 2.5},
}
# Cart stored as {item_id: quantity}
cart = {}
def get_inventory_display():
return "\n".join(
[f"{item_id}: {item['name']}{item['price']})" for item_id, item in inventory.items()]
)
def view_cart():
if not cart:
return "Cart is empty.", "Total: £0.00"
lines = []
total = 0
for item_id, qty in cart.items():
item = inventory[item_id]
cost = item["price"] * qty
total += cost
lines.append(f"{item['name']} x {qty} = £{cost:.2f}")
return "\n".join(lines), f"Total: £{total:.2f}"
def add_to_cart(item_id, quantity):
try:
item_id = int(item_id)
quantity = float(quantity)
if item_id not in inventory:
return "Invalid product ID.", *view_cart()
if quantity <= 0:
return "Quantity must be positive.", *view_cart()
cart[item_id] = cart.get(item_id, 0) + quantity
return f"Added {quantity} {inventory[item_id]['name']}(s).", *view_cart()
except:
return "Invalid input.", *view_cart()
def remove_from_cart(item_id, quantity):
try:
item_id = int(item_id)
quantity = float(quantity)
if item_id not in cart:
return "Item not in cart.", *view_cart()
if quantity <= 0:
return "Quantity must be positive.", *view_cart()
cart[item_id] -= quantity
if cart[item_id] <= 0:
del cart[item_id]
return f"Removed {quantity} item(s).", *view_cart()
except:
return "Invalid input.", *view_cart()
with gr.Blocks() as app:
gr.Markdown("# 🛒 Fruit Seller Shopping Cart")
gr.Markdown("## 📦 Available Inventory")
inventory_box = gr.Textbox(value=get_inventory_display(), lines=6, interactive=False)
with gr.Row():
item_id_input = gr.Number(label="Product ID")
quantity_input = gr.Number(label="Quantity")
with gr.Row():
add_btn = gr.Button("Add to Cart")
remove_btn = gr.Button("Remove from Cart")
status = gr.Textbox(label="Status")
cart_display = gr.Textbox(label="Cart Details", lines=8)
total_display = gr.Textbox(label="Total Bill")
add_btn.click(
add_to_cart,
inputs=[item_id_input, quantity_input],
outputs=[status, cart_display, total_display],
)
remove_btn.click(
remove_from_cart,
inputs=[item_id_input, quantity_input],
outputs=[status, cart_display, total_display],
)
# Initialize cart view
app.load(fn=view_cart, outputs=[cart_display, total_display])
app.launch()