import gradio as gr # ----------------------------- # Module 1: Data Structures (USD) # ----------------------------- Inventory = [ (101, "Hammer", 1.20), (102, "Screwdriver Set", 3.50), (103, "Drill Machine", 25.00), (104, "Pliers", 1.80), (105, "Wrench", 2.20), ] # Lookup dictionary for fast access inventory_lookup = {item[0]: {"name": item[1], "price": item[2]} for item in Inventory} # Cart holds item IDs My_Cart = [] # ----------------------------- # Module 2: Business Logic # ----------------------------- def add_to_cart(item_id): if item_id in inventory_lookup: My_Cart.append(item_id) return f"Added: {inventory_lookup[item_id]['name']}" return "Invalid item ID." def remove_from_cart(item_id): if item_id in My_Cart: My_Cart.remove(item_id) return f"Removed: {inventory_lookup[item_id]['name']}" return "Item not in cart." def get_cart_contents(): if not My_Cart: return "Cart is empty." lines = [] for item_id in My_Cart: item = inventory_lookup[item_id] lines.append(f"{item_id} - {item['name']} - ${item['price']:.2f}") return "\n".join(lines) def calculate_total(): total = sum(inventory_lookup[item_id]["price"] for item_id in My_Cart) return f"Total Amount: ${total:.2f}" # ----------------------------- # Module 3: Helpers for Dropdown Text # ----------------------------- def extract_id(choice_text): # Dropdown text looks like: "101 - Hammer - $1.20" return int(choice_text.split(" - ")[0]) # ----------------------------- # Module 4: Gradio Callbacks # ----------------------------- def handle_add(selected_text): item_id = extract_id(selected_text) msg = add_to_cart(item_id) return get_cart_contents(), msg def handle_remove(selected_text): item_id = extract_id(selected_text) msg = remove_from_cart(item_id) return get_cart_contents(), msg def handle_total(): return calculate_total() # ----------------------------- # Module 5: Gradio Interface # ----------------------------- with gr.Blocks(title="Hardware Store Billing System (USD)") as demo: gr.Markdown("## 🧰 Hardware Store Billing System (USD)") # Dropdowns show: "101 - Hammer - $1.20" formatted_choices = [ f"{item[0]} - {item[1]} - ${item[2]:.2f}" for item in Inventory ] with gr.Row(): add_dropdown = gr.Dropdown( choices=formatted_choices, label="Select Item to Add" ) add_button = gr.Button("Add Tool") with gr.Row(): remove_dropdown = gr.Dropdown( choices=formatted_choices, label="Select Item to Remove" ) remove_button = gr.Button("Remove Tool") cart_display = gr.Textbox(label="Cart Contents", lines=8) message_display = gr.Textbox(label="Status Message") total_button = gr.Button("Calculate Total") total_output = gr.Textbox(label="Total Amount") # Bind callbacks add_button.click(handle_add, inputs=add_dropdown, outputs=[cart_display, message_display]) remove_button.click(handle_remove, inputs=remove_dropdown, outputs=[cart_display, message_display]) total_button.click(handle_total, outputs=total_output) if __name__ == "__main__": demo.launch()