eaglelandsonce commited on
Commit
2c7ce16
·
verified ·
1 Parent(s): b271788

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -47
app.py CHANGED
@@ -1,4 +1,4 @@
1
- import streamlit as st
2
 
3
  # --- Data Structures ---
4
  Inventory = [
@@ -9,49 +9,112 @@ Inventory = [
9
  ("Mangoes", 150),
10
  ]
11
 
12
- # Convert Inventory into a dictionary for easier lookup: {"Apples": 250, "Cherry": 650, ...}
13
- price_dict = {item[0]: item[1] for item in Inventory}
14
-
15
- # Initialize the cart in session state if not already present
16
- if "cart" not in st.session_state:
17
- st.session_state.cart = [] # Each element will be a tuple (product_name, quantity)
18
-
19
- # --- Streamlit Layout ---
20
- st.title("Shopping Cart Management System")
21
-
22
- # 1. Add Products to the Shopping Cart
23
- st.subheader("Add Items to Your Cart")
24
- product_list = [item[0] for item in Inventory] # ["Apples", "Cherry", "Chickoo", "Oranges", "Mangoes"]
25
- selected_product = st.selectbox("Select a product", product_list)
26
- selected_quantity = st.number_input("Quantity", min_value=1, value=1, step=1)
27
-
28
- if st.button("Add to Cart"):
29
- # Append (product, quantity) to the cart
30
- st.session_state.cart.append((selected_product, selected_quantity))
31
- st.success(f"Added {selected_quantity} {selected_product}(s) to your cart!")
32
-
33
- st.write("---")
34
-
35
- # 2. Display and Remove Items from the Shopping Cart
36
- st.subheader("Items in Your Cart")
37
- if len(st.session_state.cart) == 0:
38
- st.info("Your cart is empty. Add some items!")
39
- else:
40
- # List each item along with remove button
41
- for i, (product, quantity) in enumerate(st.session_state.cart):
42
- col1, col2, col3 = st.columns([3, 2, 1])
43
- with col1:
44
- st.write(f"**{product}** x {quantity} @ {price_dict[product]} each")
45
- with col2:
46
- st.write(f"Subtotal: {price_dict[product] * quantity}")
47
- with col3:
48
- # Create a dynamic remove button
49
- remove_button_label = f"Remove-{i}"
50
- if st.button("Remove", key=remove_button_label):
51
- st.session_state.cart.pop(i)
52
- st.experimental_rerun() # Refresh the app so the item disappears immediately
53
-
54
- # 3. Calculate the Total Bill
55
- total_bill = sum(price_dict[p] * q for p, q in st.session_state.cart)
56
- st.write("---")
57
- st.subheader(f"**Total Bill: {total_bill}**")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
 
3
  # --- Data Structures ---
4
  Inventory = [
 
9
  ("Mangoes", 150),
10
  ]
11
 
12
+ # Create a price lookup dictionary for convenience.
13
+ price_dict = {name: price for name, price in Inventory}
14
+
15
+ def format_cart(cart):
16
+ """Return a formatted string of the cart contents and total bill."""
17
+ if not cart:
18
+ return "Your cart is empty."
19
+ summary = ""
20
+ total = 0
21
+ for i, (product, quantity) in enumerate(cart):
22
+ price = price_dict[product]
23
+ subtotal = price * quantity
24
+ summary += f"{i+1}. **{product}** x {quantity} @ {price} each = {subtotal}\n"
25
+ total += subtotal
26
+ summary += f"\n**Total Bill:** {total}"
27
+ return summary
28
+
29
+ def generate_remove_options(cart):
30
+ """Generate options for the removal dropdown from the cart list."""
31
+ options = []
32
+ for i, (product, quantity) in enumerate(cart):
33
+ price = price_dict[product]
34
+ subtotal = price * quantity
35
+ options.append(f"{i}: {product} x {quantity} (Subtotal: {subtotal})")
36
+ return options
37
+
38
+ def add_to_cart(product, quantity, cart):
39
+ """
40
+ Add the selected product and quantity to the cart.
41
+ Returns the updated cart state, a message, the cart summary,
42
+ and updated removal dropdown options.
43
+ """
44
+ # Ensure the cart exists.
45
+ if cart is None:
46
+ cart = []
47
+ cart.append((product, int(quantity)))
48
+ message = f"Added {int(quantity)} **{product}**(s) to your cart!"
49
+ summary = format_cart(cart)
50
+ remove_options = generate_remove_options(cart)
51
+ # Use gr.Dropdown.update to update the choices for removal.
52
+ return cart, message, summary, gr.Dropdown.update(choices=remove_options)
53
+
54
+ def remove_from_cart(selected_option, cart):
55
+ """
56
+ Remove the selected item from the cart.
57
+ Returns the updated cart state, a message, the cart summary,
58
+ and updated removal dropdown options.
59
+ """
60
+ if not cart:
61
+ message = "Cart is empty."
62
+ return cart, message, format_cart(cart), gr.Dropdown.update(choices=[])
63
+ # Extract the index from the selected option.
64
+ index = int(selected_option.split(":")[0])
65
+ removed_item = cart.pop(index)
66
+ message = f"Removed {removed_item[1]} **{removed_item[0]}**(s) from your cart."
67
+ summary = format_cart(cart)
68
+ remove_options = generate_remove_options(cart)
69
+ return cart, message, summary, gr.Dropdown.update(choices=remove_options)
70
+
71
+ # --- Build the Gradio Interface ---
72
+ with gr.Blocks() as demo:
73
+ # Initialize an empty cart in state.
74
+ cart_state = gr.State([])
75
+
76
+ gr.Markdown("# Gradio Shopping Cart")
77
+
78
+ with gr.Row():
79
+ product_input = gr.Dropdown(
80
+ label="Select Product",
81
+ choices=[name for name, _ in Inventory],
82
+ value=Inventory[0][0]
83
+ )
84
+ quantity_input = gr.Number(
85
+ label="Quantity",
86
+ value=1,
87
+ precision=0
88
+ )
89
+ add_button = gr.Button("Add to Cart")
90
+
91
+ add_message = gr.Markdown("") # To display add-to-cart messages.
92
+ cart_display = gr.Textbox(
93
+ label="Cart Summary",
94
+ interactive=False,
95
+ lines=10,
96
+ value="Your cart is empty."
97
+ )
98
+
99
+ gr.Markdown("## Remove Items from Cart")
100
+ with gr.Row():
101
+ remove_dropdown = gr.Dropdown(
102
+ label="Select Item to Remove",
103
+ choices=[] # Updated dynamically after adding items.
104
+ )
105
+ remove_button = gr.Button("Remove Selected Item")
106
+ remove_message = gr.Markdown("") # To display removal messages.
107
+
108
+ # Set up interactions:
109
+ add_button.click(
110
+ fn=add_to_cart,
111
+ inputs=[product_input, quantity_input, cart_state],
112
+ outputs=[cart_state, add_message, cart_display, remove_dropdown]
113
+ )
114
+ remove_button.click(
115
+ fn=remove_from_cart,
116
+ inputs=[remove_dropdown, cart_state],
117
+ outputs=[cart_state, remove_message, cart_display, remove_dropdown]
118
+ )
119
+
120
+ demo.launch()