eaglelandsonce commited on
Commit
0239bce
·
verified ·
1 Parent(s): 9775a54

Upload 2 files

Browse files
Files changed (2) hide show
  1. app (4).py +134 -0
  2. requirements (8).txt +2 -0
app (4).py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ import pandas as pd
4
+
5
+ # ---------- Inventory ----------
6
+ # ID -> (Name, Price per KG)
7
+ INVENTORY = {
8
+ 1: ("Apples", 250),
9
+ 2: ("Cherry", 650),
10
+ 3: ("Chickoo", 50),
11
+ 4: ("Grapes", 90),
12
+ 5: ("Mangoes", 150),
13
+ }
14
+
15
+ def inventory_markdown():
16
+ items = "\n".join([f"({pid}) **{name}**, {price}"
17
+ for pid, (name, price) in INVENTORY.items()])
18
+ return f"### Inventory\n{items}"
19
+
20
+ # ---------- Cart helpers ----------
21
+ def summarize_cart(cart):
22
+ """Return (DataFrame, total_cost) for the cart.
23
+ Cart structure: list of dicts with keys: id, name, unit_price, qty
24
+ """
25
+ if not cart:
26
+ return pd.DataFrame(columns=["Index","Name","Quantity","Price Per KG"]), 0
27
+ rows = []
28
+ total = 0
29
+ for idx, item in enumerate(cart):
30
+ rows.append({
31
+ "Index": idx,
32
+ "Name": item["name"],
33
+ "Quantity": item["qty"],
34
+ "Price Per KG": f"${item['unit_price']:.2f}",
35
+ })
36
+ total += item["qty"] * item["unit_price"]
37
+ df = pd.DataFrame(rows)
38
+ return df, total
39
+
40
+ def add_item_to_cart(pid, cart):
41
+ add_msg = ""
42
+ if pid is None:
43
+ return *summarize_cart(cart), add_msg, ""
44
+ if pid not in INVENTORY:
45
+ add_msg = f":warning: Invalid ID {pid}. Please use one of: {list(INVENTORY.keys())}"
46
+ return *summarize_cart(cart), add_msg, ""
47
+ name, price = INVENTORY[pid]
48
+ # Check if already in cart -> increment quantity
49
+ for item in cart:
50
+ if item["id"] == pid:
51
+ item["qty"] += 1
52
+ df, total = summarize_cart(cart)
53
+ add_msg = f">>>>>>>>>> The item '{name}' has been added to the cart. <<<<<<<<<<"
54
+ return df, total, add_msg, ""
55
+ # Otherwise append new
56
+ cart.append({"id": pid, "name": name, "unit_price": float(price), "qty": 1})
57
+ df, total = summarize_cart(cart)
58
+ add_msg = f">>>>>>>>>> The item '{name}' has been added to the cart. <<<<<<<<<<"
59
+ return df, total, add_msg, ""
60
+
61
+ def remove_item_from_cart(index, cart):
62
+ rm_msg = ""
63
+ if index is None:
64
+ return *summarize_cart(cart), "", rm_msg
65
+ if not cart:
66
+ rm_msg = ":warning: Cart is empty."
67
+ return *summarize_cart(cart), "", rm_msg
68
+ if index < 0 or index >= len(cart):
69
+ rm_msg = f":warning: Invalid index {index}. Must be 0..{max(0,len(cart)-1)}"
70
+ return *summarize_cart(cart), "", rm_msg
71
+ removed = cart.pop(index)
72
+ df, total = summarize_cart(cart)
73
+ rm_msg = f"Removed '{removed['name']}' from the cart."
74
+ return df, total, "", rm_msg
75
+
76
+ with gr.Blocks(title="Fruit Shopping Cart System") as demo:
77
+ gr.Markdown("## Fruit Shopping Cart System")
78
+
79
+ # App state: the cart
80
+ cart_state = gr.State([])
81
+
82
+ with gr.Row():
83
+ with gr.Column(scale=2):
84
+ pid_in = gr.Number(label="Enter Product ID to Add to Cart", value=2, precision=0)
85
+ with gr.Column(scale=2):
86
+ rm_index_in = gr.Number(label="Enter Index ID to Remove from Cart", value=0, precision=0)
87
+ with gr.Column(scale=1):
88
+ add_btn = gr.Button("Add to Cart", variant="primary")
89
+ with gr.Column(scale=1):
90
+ rm_btn = gr.Button("Remove from Cart", variant="secondary")
91
+
92
+ with gr.Row():
93
+ with gr.Column(scale=3):
94
+ gr.Markdown("### Your Cart\n_Use 0-based index for removal_ :shopping_trolley:")
95
+ cart_df = gr.Dataframe(headers=["Index","Name","Quantity","Price Per KG"],
96
+ interactive=False,
97
+ wrap=True,
98
+ height=220)
99
+ add_msg_out = gr.Textbox(label="Add Item Message", interactive=False)
100
+ rm_msg_out = gr.Textbox(label="Remove Item Message", interactive=False)
101
+ total_cost_out = gr.Textbox(label="Total Cost", interactive=False)
102
+ with gr.Column(scale=2):
103
+ inv_md = gr.Markdown(inventory_markdown())
104
+ gr.Markdown("""
105
+ ### Business Requirements
106
+ 1. **Add Products to the Shopping Cart**: Add by ID from the inventory; quantities aggregate automatically.
107
+ 2. **Remove Unwanted Items**: Remove by 0-based index shown in the cart table.
108
+ 3. **Calculate the Total Bill**: Total updates automatically after each action.
109
+ """)
110
+
111
+ def handle_add(pid, cart):
112
+ df, total, add_msg, rm_msg = add_item_to_cart(int(pid), cart)
113
+ total_str = f"$ {total:,.2f}"
114
+ return df, add_msg, rm_msg, total_str, cart
115
+
116
+ def handle_remove(index, cart):
117
+ df, total, add_msg, rm_msg = remove_item_from_cart(int(index), cart)
118
+ total_str = f"$ {total:,.2f}"
119
+ return df, add_msg, rm_msg, total_str, cart
120
+
121
+ add_btn.click(
122
+ handle_add,
123
+ inputs=[pid_in, cart_state],
124
+ outputs=[cart_df, add_msg_out, rm_msg_out, total_cost_out, cart_state]
125
+ )
126
+
127
+ rm_btn.click(
128
+ handle_remove,
129
+ inputs=[rm_index_in, cart_state],
130
+ outputs=[cart_df, add_msg_out, rm_msg_out, total_cost_out, cart_state]
131
+ )
132
+
133
+ if __name__ == "__main__":
134
+ demo.launch()
requirements (8).txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gradio>=4.31.0
2
+ pandas>=2.0.0