eaglelandsonce commited on
Commit
b8563e8
·
verified ·
1 Parent(s): f33b324

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -34
app.py CHANGED
@@ -1,9 +1,7 @@
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),
@@ -17,15 +15,10 @@ def inventory_markdown():
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,
@@ -34,28 +27,25 @@ def summarize_cart(cart):
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):
@@ -75,8 +65,6 @@ def remove_item_from_cart(index, cart):
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():
@@ -91,16 +79,14 @@ with gr.Blocks(title="Fruit Shopping Cart System") as demo:
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.
@@ -118,17 +104,10 @@ with gr.Blocks(title="Fruit Shopping Cart System") as demo:
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()
 
 
1
  import gradio as gr
2
  import pandas as pd
3
 
4
  # ---------- Inventory ----------
 
5
  INVENTORY = {
6
  1: ("Apples", 250),
7
  2: ("Cherry", 650),
 
15
  for pid, (name, price) in INVENTORY.items()])
16
  return f"### Inventory\n{items}"
17
 
 
18
  def summarize_cart(cart):
 
 
 
19
  if not cart:
20
  return pd.DataFrame(columns=["Index","Name","Quantity","Price Per KG"]), 0
21
+ rows, total = [], 0
 
22
  for idx, item in enumerate(cart):
23
  rows.append({
24
  "Index": idx,
 
27
  "Price Per KG": f"${item['unit_price']:.2f}",
28
  })
29
  total += item["qty"] * item["unit_price"]
30
+ return pd.DataFrame(rows), total
 
31
 
32
  def add_item_to_cart(pid, cart):
33
  add_msg = ""
34
  if pid is None:
35
  return *summarize_cart(cart), add_msg, ""
36
  if pid not in INVENTORY:
37
+ add_msg = f":warning: Invalid ID {pid}. Use: {list(INVENTORY.keys())}"
38
  return *summarize_cart(cart), add_msg, ""
39
  name, price = INVENTORY[pid]
 
40
  for item in cart:
41
  if item["id"] == pid:
42
  item["qty"] += 1
43
  df, total = summarize_cart(cart)
44
+ add_msg = f">>>>>>>>>>> The item '{name}' has been added to the cart. <<<<<<<<<<"
45
  return df, total, add_msg, ""
 
46
  cart.append({"id": pid, "name": name, "unit_price": float(price), "qty": 1})
47
  df, total = summarize_cart(cart)
48
+ add_msg = f">>>>>>>>>>> The item '{name}' has been added to the cart. <<<<<<<<<<"
49
  return df, total, add_msg, ""
50
 
51
  def remove_item_from_cart(index, cart):
 
65
 
66
  with gr.Blocks(title="Fruit Shopping Cart System") as demo:
67
  gr.Markdown("## Fruit Shopping Cart System")
 
 
68
  cart_state = gr.State([])
69
 
70
  with gr.Row():
 
79
 
80
  with gr.Row():
81
  with gr.Column(scale=3):
82
+ gr.Markdown("### Your Cart\n_Use 0-based index for removal_")
83
+ empty_df = pd.DataFrame(columns=["Index","Name","Quantity","Price Per KG"])
84
+ cart_df = gr.Dataframe(value=empty_df, interactive=False)
 
 
85
  add_msg_out = gr.Textbox(label="Add Item Message", interactive=False)
86
  rm_msg_out = gr.Textbox(label="Remove Item Message", interactive=False)
87
  total_cost_out = gr.Textbox(label="Total Cost", interactive=False)
88
  with gr.Column(scale=2):
89
+ gr.Markdown(inventory_markdown())
90
  gr.Markdown("""
91
  ### Business Requirements
92
  1. **Add Products to the Shopping Cart**: Add by ID from the inventory; quantities aggregate automatically.
 
104
  total_str = f"$ {total:,.2f}"
105
  return df, add_msg, rm_msg, total_str, cart
106
 
107
+ add_btn.click(handle_add, [pid_in, cart_state],
108
+ [cart_df, add_msg_out, rm_msg_out, total_cost_out, cart_state])
109
+ rm_btn.click(handle_remove, [rm_index_in, cart_state],
110
+ [cart_df, add_msg_out, rm_msg_out, total_cost_out, cart_state])
 
 
 
 
 
 
 
111
 
112
  if __name__ == "__main__":
113
  demo.launch()