Spaces:
Sleeping
Sleeping
File size: 2,880 Bytes
86679b0 86db9f1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | import gradio as gr
# -----------------------------
# Inventory Data
# -----------------------------
inventory = [
(101, "Hammer", 120),
(102, "Screwdriver Set", 350),
(103, "Drill Machine", 2500),
(104, "Pliers", 180),
(105, "Wrench", 220)
]
# Convert inventory into dictionary for quick lookup
inventory_dict = {item[0]: {"name": item[1], "price": item[2]} for item in inventory}
# Cart
my_cart = []
# -----------------------------
# Functions
# -----------------------------
def add_to_cart(item_id):
if item_id is None:
return my_cart, "Please select an item"
item = inventory_dict[item_id]
my_cart.append(item)
return my_cart, f"{item['name']} added to cart"
def remove_from_cart(index):
if index is None or index >= len(my_cart):
return my_cart, "Invalid selection"
removed_item = my_cart.pop(index)
return my_cart, f"{removed_item['name']} removed from cart"
def display_cart():
if not my_cart:
return "Cart is empty"
cart_text = ""
for i, item in enumerate(my_cart):
cart_text += f"{i}. {item['name']} - ${item['price']}\n"
return cart_text
def calculate_total():
total = sum(item["price"] for item in my_cart)
return f"Total Bill: ${total}"
# -----------------------------
# Gradio Interface
# -----------------------------
with gr.Blocks() as demo:
gr.Markdown("# 🧾 Hardware Store Billing System")
# Dropdown to select inventory item
item_dropdown = gr.Dropdown(
choices=[(f"{item[1]} (${item[2]})", item[0]) for item in inventory],
label="Select Item from Inventory"
)
add_button = gr.Button("Add to Cart")
# Dropdown for cart items (by index)
remove_dropdown = gr.Dropdown(label="Select Cart Item Index to Remove")
remove_button = gr.Button("Remove from Cart")
cart_display = gr.Textbox(label="Cart Contents", lines=8)
total_output = gr.Textbox(label="Total Bill")
status_output = gr.Textbox(label="Status")
# -----------------------------
# Event Handlers
# -----------------------------
def update_remove_dropdown(cart):
return gr.Dropdown(
choices=[(f"{i}: {item['name']}", i) for i, item in enumerate(cart)]
)
add_button.click(
add_to_cart,
inputs=item_dropdown,
outputs=[remove_dropdown, status_output]
).then(display_cart, outputs=cart_display).then(update_remove_dropdown, inputs=remove_dropdown, outputs=remove_dropdown)
remove_button.click(
remove_from_cart,
inputs=remove_dropdown,
outputs=[remove_dropdown, status_output]
).then(display_cart, outputs=cart_display).then(update_remove_dropdown, inputs=remove_dropdown, outputs=remove_dropdown)
gr.Button("Calculate Total").click(
calculate_total,
outputs=total_output
)
demo.launch()
|