dschandra commited on
Commit
81886a7
·
verified ·
1 Parent(s): 87913e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -64
app.py CHANGED
@@ -4,26 +4,22 @@ import pandas as pd
4
  # Load menu data from Excel file
5
  def load_menu(file_path="menu.xlsx"):
6
  """
7
- Load menu data from an Excel file and dynamically map its columns to required fields.
8
  """
9
  menu_df = pd.read_excel(file_path)
10
- # Normalize column names (strip spaces and make lowercase)
11
  menu_df.columns = menu_df.columns.str.strip().str.lower()
12
 
13
- # Map dynamic column names to required fields
14
  column_mapping = {
15
  "name": next((col for col in menu_df.columns if "name" in col), None),
16
  "price": next((col for col in menu_df.columns if "price" in col), None),
17
  "description": next((col for col in menu_df.columns if "description" in col), None),
18
  "image": next((col for col in menu_df.columns if "image" in col), None),
19
  }
20
-
21
- # Ensure all required columns are present
22
  missing_columns = [key for key, col in column_mapping.items() if col is None]
23
  if missing_columns:
24
  raise ValueError(f"Excel file is missing one or more required columns: {missing_columns}")
25
 
26
- # Map data to required structure
27
  menu = []
28
  for _, row in menu_df.iterrows():
29
  menu.append({
@@ -36,96 +32,86 @@ def load_menu(file_path="menu.xlsx"):
36
 
37
  # Initialize menu and cart
38
  menu_data = load_menu("menu.xlsx")
39
- cart = []
40
 
41
  def display_menu():
42
  """
43
- Render the menu dynamically as HTML.
44
  """
45
  menu_html = ""
46
  for item in menu_data:
47
  menu_html += f"""
48
- <div style="display: flex; margin-bottom: 15px; align-items: center; border: 1px solid #ddd; padding: 10px; border-radius: 5px;">
49
- <img src="{item['image']}" alt="{item['name']}" style="width: 100px; height: 100px; margin-right: 15px; border-radius: 5px;">
50
- <div style="flex-grow: 1;">
51
  <h4 style="margin: 0;">{item['name']} - ${item['price']}</h4>
52
- <p style="margin: 5px 0; font-size: 12px;">{item['description']}</p>
53
- <label for="quantity-{item['name']}" style="margin-right: 10px;">Quantity:</label>
54
- <input type="number" id="quantity-{item['name']}" value="1" min="1" style="width: 50px;">
55
  </div>
56
- <button onclick="add_to_cart('{item['name']}', document.getElementById('quantity-{item['name']}').value)" style="background-color: #28a745; color: white; border: none; padding: 8px 12px; border-radius: 5px; cursor: pointer;">Add</button>
57
  </div>
58
  """
59
  return menu_html
60
 
61
- def add_to_cart(item_name, quantity):
62
  """
63
- Add an item to the cart and return success message with cart count.
64
  """
65
- quantity = int(quantity)
66
- # Check if the item already exists in the cart
67
- for item in cart:
68
- if item["name"] == item_name:
69
- item["quantity"] += quantity
70
- break
71
  else:
72
- # Add new item to cart
73
  for item in menu_data:
74
  if item["name"] == item_name:
75
- cart.append({"name": item_name, "price": item["price"], "quantity": quantity})
 
 
 
 
76
  break
77
- return f"{item_name} added to cart! Total items: {len(cart)}"
 
 
 
 
 
 
 
 
 
 
 
78
 
79
  def view_cart():
80
  """
81
- Render the cart contents and calculate the total price.
82
  """
83
  if not cart:
84
  return "Your cart is empty."
85
 
86
- cart_html = "<h3>Cart Summary:</h3><ul>"
87
  total_price = 0
88
- for item in cart:
89
- cart_html += f"<li>{item['name']} (x{item['quantity']}) - ${item['price'] * item['quantity']}</li>"
90
- total_price += item["price"] * item["quantity"]
91
- cart_html += f"</ul><h4>Total Price: ${total_price}</h4>"
 
 
 
 
 
 
 
 
 
 
 
92
  return cart_html
93
 
94
  # Gradio Interface
95
- def menu_page():
96
- return gr.update(value=display_menu(), visible=True), gr.update(visible=False)
97
-
98
- def cart_page():
99
- return gr.update(value=view_cart(), visible=True), gr.update(visible=False)
100
-
101
  with gr.Blocks() as demo:
102
  gr.Markdown("# Dynamic Food Menu")
103
 
104
- # Menu and Cart Views
105
- menu_display = gr.HTML(value=display_menu(), visible=True)
106
- cart_display = gr.HTML(visible=False)
107
- notification = gr.Textbox(label="Notification", value="", interactive=False)
108
-
109
- # Navigation Buttons
110
  with gr.Row():
111
- menu_button = gr.Button("Menu")
112
- cart_button = gr.Button("View Cart")
113
 
114
- # Add item interaction
115
- food_item_input = gr.Textbox(visible=False) # Hidden input to capture item name
116
- quantity_input = gr.Number(visible=False) # Hidden input to capture quantity
117
- add_button = gr.Button("Add to Cart", visible=False) # Simulated button for functionality
118
-
119
- # Notification when item is added
120
- add_button.click(add_to_cart, inputs=[food_item_input, quantity_input], outputs=notification)
121
-
122
- # Navigation between Menu and Cart pages
123
- menu_button.click(menu_page, outputs=[menu_display, cart_display])
124
- cart_button.click(cart_page, outputs=[cart_display, menu_display])
125
-
126
- # Render components inside Blocks
127
- menu_display
128
- cart_display
129
- notification
130
-
131
- demo.launch()
 
4
  # Load menu data from Excel file
5
  def load_menu(file_path="menu.xlsx"):
6
  """
7
+ Load menu data from an Excel file dynamically based on column headers.
8
  """
9
  menu_df = pd.read_excel(file_path)
 
10
  menu_df.columns = menu_df.columns.str.strip().str.lower()
11
 
 
12
  column_mapping = {
13
  "name": next((col for col in menu_df.columns if "name" in col), None),
14
  "price": next((col for col in menu_df.columns if "price" in col), None),
15
  "description": next((col for col in menu_df.columns if "description" in col), None),
16
  "image": next((col for col in menu_df.columns if "image" in col), None),
17
  }
18
+
 
19
  missing_columns = [key for key, col in column_mapping.items() if col is None]
20
  if missing_columns:
21
  raise ValueError(f"Excel file is missing one or more required columns: {missing_columns}")
22
 
 
23
  menu = []
24
  for _, row in menu_df.iterrows():
25
  menu.append({
 
32
 
33
  # Initialize menu and cart
34
  menu_data = load_menu("menu.xlsx")
35
+ cart = {}
36
 
37
  def display_menu():
38
  """
39
+ Render the menu dynamically.
40
  """
41
  menu_html = ""
42
  for item in menu_data:
43
  menu_html += f"""
44
+ <div style="display: flex; align-items: center; margin-bottom: 15px; border: 1px solid #ddd; padding: 10px; border-radius: 5px;">
45
+ <img src="{item['image']}" alt="{item['name']}" style="width: 80px; height: 80px; border-radius: 5px; margin-right: 15px;">
46
+ <div>
47
  <h4 style="margin: 0;">{item['name']} - ${item['price']}</h4>
48
+ <p style="font-size: 12px; color: gray;">{item['description']}</p>
 
 
49
  </div>
50
+ <button onclick="add_to_cart('{item['name']}')" style="background-color: #28a745; color: white; border: none; padding: 8px 12px; border-radius: 5px; cursor: pointer; margin-left: auto;">Add</button>
51
  </div>
52
  """
53
  return menu_html
54
 
55
+ def add_to_cart(item_name):
56
  """
57
+ Add an item to the cart.
58
  """
59
+ if item_name in cart:
60
+ cart[item_name]["quantity"] += 1
 
 
 
 
61
  else:
 
62
  for item in menu_data:
63
  if item["name"] == item_name:
64
+ cart[item_name] = {
65
+ "name": item["name"],
66
+ "price": item["price"],
67
+ "quantity": 1
68
+ }
69
  break
70
+ return view_cart()
71
+
72
+ def update_quantity(item_name, new_quantity):
73
+ """
74
+ Update the quantity of an item in the cart.
75
+ """
76
+ if item_name in cart:
77
+ if new_quantity <= 0:
78
+ del cart[item_name]
79
+ else:
80
+ cart[item_name]["quantity"] = new_quantity
81
+ return view_cart()
82
 
83
  def view_cart():
84
  """
85
+ Render the cart dynamically.
86
  """
87
  if not cart:
88
  return "Your cart is empty."
89
 
90
+ cart_html = "<h3>Your Cart:</h3>"
91
  total_price = 0
92
+ for item in cart.values():
93
+ item_total = item["price"] * item["quantity"]
94
+ total_price += item_total
95
+ cart_html += f"""
96
+ <div style="display: flex; align-items: center; margin-bottom: 15px; border: 1px solid #ddd; padding: 10px; border-radius: 5px;">
97
+ <h4 style="margin: 0;">{item['name']}</h4>
98
+ <div style="margin-left: auto; display: flex; align-items: center;">
99
+ <button onclick="update_quantity('{item['name']}', {item['quantity'] - 1})" style="background-color: #dc3545; color: white; border: none; padding: 5px; border-radius: 5px;">-</button>
100
+ <span style="margin: 0 10px;">{item['quantity']}</span>
101
+ <button onclick="update_quantity('{item['name']}', {item['quantity'] + 1})" style="background-color: #28a745; color: white; border: none; padding: 5px; border-radius: 5px;">+</button>
102
+ </div>
103
+ <p style="margin: 0 0 0 15px;">${item_total:.2f}</p>
104
+ </div>
105
+ """
106
+ cart_html += f"<h4>Total: ${total_price:.2f}</h4>"
107
  return cart_html
108
 
109
  # Gradio Interface
 
 
 
 
 
 
110
  with gr.Blocks() as demo:
111
  gr.Markdown("# Dynamic Food Menu")
112
 
 
 
 
 
 
 
113
  with gr.Row():
114
+ menu_html = gr.HTML(value=display_menu())
115
+ cart_html = gr.HTML(value=view_cart())
116
 
117
+ demo.launch()