nagasurendra commited on
Commit
0ca1045
·
verified ·
1 Parent(s): ffd44f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -149
app.py CHANGED
@@ -1,20 +1,6 @@
1
  import gradio as gr
2
  import pandas as pd
3
 
4
- # Initialize cart globally
5
- cart_items = []
6
-
7
- # Pricing for extras
8
- EXTRAS_PRICES = {
9
- "Extra Raitha 4oz": 1,
10
- "Extra Raitha 8oz": 2,
11
- "Extra Salan 4oz": 1,
12
- "Extra Salan 8oz": 2,
13
- "Extra Onion": 1,
14
- "Extra Onion & Lemon": 2,
15
- "Extra Fried Onion 4oz": 2,
16
- }
17
-
18
  # Function to load the menu data
19
  def load_menu():
20
  menu_file = "menu.xlsx" # Ensure this file exists in the same directory
@@ -23,78 +9,101 @@ def load_menu():
23
  except Exception as e:
24
  raise ValueError(f"Error loading menu file: {e}")
25
 
26
- # Function to filter menu items based on preference
27
- def filter_menu(preference):
28
- menu_data = load_menu()
29
- if preference == "Halal/Non-Veg":
30
- filtered_data = menu_data[menu_data["Ingredients"].str.contains("Chicken|Mutton|Fish|Prawns|Goat", case=False, na=False)]
31
- elif preference == "Vegetarian":
32
- filtered_data = menu_data[~menu_data["Ingredients"].str.contains("Chicken|Mutton|Fish|Prawns|Goat", case=False, na=False)]
33
- elif preference == "Guilt-Free":
34
- filtered_data = menu_data[menu_data["Description"].str.contains(r"Fat: ([0-9]|10)g", case=False, na=False)]
35
- else:
36
- filtered_data = menu_data
37
-
38
- html_content = ""
39
- for _, item in filtered_data.iterrows():
40
- html_content += f"""
41
- <div style=\"display: flex; align-items: center; border: 1px solid #ddd; border-radius: 8px; padding: 15px; margin-bottom: 10px; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);\">
42
- <div style=\"flex: 1; margin-right: 15px;\">
43
- <h3 style=\"margin: 0; font-size: 18px;\">{item['Dish Name']}</h3>
44
- <p style=\"margin: 5px 0; font-size: 16px; color: #888;\">${item['Price ($)']}</p>
45
- <p style=\"margin: 5px 0; font-size: 14px; color: #555;\">{item['Description']}</p>
46
- </div>
47
- <div style=\"flex-shrink: 0; text-align: center;\">
48
- <img src=\"{item['Image URL']}\" alt=\"{item['Dish Name']}\" style=\"width: 100px; height: 100px; border-radius: 8px; object-fit: cover; margin-bottom: 10px;\">
49
- <button style=\"background-color: #28a745; color: white; border: none; padding: 8px 15px; font-size: 14px; border-radius: 5px; cursor: pointer;\" onclick=\"addToCart('{item['Dish Name']}', '{item['Price ($)']}', '{item['Description']}', '{item['Image URL']}')\">Add</button>
50
- </div>
51
- </div>
52
- """
53
- return html_content
54
-
55
- # Function to update the cart display
56
- def update_cart_display():
57
- global cart_items
58
-
59
- if len(cart_items) == 0:
60
- return "Your cart is empty."
61
-
62
- cart_html = "<h3>Your Cart:</h3><ul style='list-style-type: none; padding: 0;'>"
63
- for item in cart_items:
64
- extras = ", ".join(item.get("extras", []))
65
- cart_html += f"<li style='margin-bottom: 20px;'>"
66
- cart_html += f"<strong>Item:</strong> {item['name']} - ${item['price']:.2f}<br>"
67
- cart_html += f"<strong>Spice Level:</strong> {item['spiceLevel']}<br>"
68
- cart_html += f"<strong>Extras:</strong> {extras}<br>"
69
- cart_html += f"<strong>Instructions:</strong> {item['instructions']}<br>"
70
- cart_html += f"<strong>Quantity:</strong> {item['quantity']}<br>"
71
- cart_html += "</li>"
72
- cart_html += "</ul>"
73
-
74
- total_bill = sum(item['price'] for item in cart_items)
75
- cart_html += f"<p><strong>Total Bill: ${total_bill:.2f}</strong></p>"
76
-
77
- return cart_html
78
-
79
- # Function to finalize the order
80
- def finalize_order():
81
- global cart_items
82
-
83
- if len(cart_items) == 0:
84
- return "Your order is empty."
85
-
86
- order_summary = "<h3>Final Order:</h3><ul>"
87
- for item in cart_items:
88
- order_summary += f"<li>{item['name']} - ${item['price']:.2f}</li>"
89
- order_summary += "</ul>"
90
-
91
- total_bill = sum(item['price'] for item in cart_items)
92
- order_summary += f"<p><strong>Total Bill: ${total_bill:.2f}</strong></p>"
93
-
94
- # Lock the cart after finalizing
95
- cart_items = []
96
-
97
- return order_summary
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
  # Gradio app definition
100
  def app():
@@ -109,70 +118,13 @@ def app():
109
  )
110
 
111
  # Output area for menu items
112
- menu_output = gr.HTML(value=filter_menu("All"))
113
 
114
  # Floating cart display
115
  cart_output = gr.HTML(value="Your cart is empty.", elem_id="floating-cart")
116
 
117
- # JavaScript for modal and cart behavior
118
- modal_and_cart_js = """
119
- <script>
120
- let cart = [];
121
- const extrasPrices = {
122
- "Extra Raitha 4oz": 1,
123
- "Extra Raitha 8oz": 2,
124
- "Extra Salan 4oz": 1,
125
- "Extra Salan 8oz": 2,
126
- "Extra Onion": 1,
127
- "Extra Onion & Lemon": 2,
128
- "Extra Fried Onion 4oz": 2
129
- };
130
- function openModal(name, image, description, price) {
131
- document.getElementById('modal').style.display = 'block';
132
- document.getElementById('modal-image').src = image;
133
- document.getElementById('modal-name').innerText = name;
134
- document.getElementById('modal-description').innerText = description;
135
- document.getElementById('modal-price').innerText = price;
136
-
137
- // Reset spice levels and extras
138
- const spiceLevelInputs = document.querySelectorAll('input[name="spice-level"]');
139
- spiceLevelInputs.forEach(input => input.checked = false);
140
- const extrasInputs = document.querySelectorAll('input[name="biryani-extra"]');
141
- extrasInputs.forEach(input => input.checked = false);
142
- document.getElementById('quantity').value = 1;
143
- document.getElementById('special-instructions').value = '';
144
- }
145
- function closeModal() {
146
- document.getElementById('modal').style.display = 'none';
147
- }
148
- function addToCart() {
149
- const name = document.getElementById('modal-name').innerText;
150
- const price = document.getElementById('modal-price').innerText;
151
- const spiceLevel = document.querySelector('input[name="spice-level"]:checked')?.value || "Not Selected";
152
- const quantity = parseInt(document.getElementById('quantity').value) || 1;
153
- const instructions = document.getElementById('special-instructions').value;
154
- const extras = Array.from(document.querySelectorAll('input[name="biryani-extra"]:checked')).map(extra => extra.value);
155
- const extrasCost = extras.reduce((sum, extra) => sum + (extrasPrices[extra] || 0), 0);
156
- const itemTotal = (parseFloat(price.replace('$', '')) + extrasCost) * quantity;
157
- const cartItem = { name, price, spiceLevel, quantity, instructions, extras, itemTotal };
158
- cart.push(cartItem);
159
- alert(`${name} added to cart!`);
160
- updateCartDisplay();
161
- closeModal();
162
- }
163
- function updateCartDisplay() {
164
- let totalBill = 0;
165
- let cartHTML = "<h3>Your Cart:</h3><ul>";
166
- cart.forEach(item => {
167
- totalBill += item.itemTotal;
168
- const extras = item.extras.join(', ');
169
- cartHTML += `<li>${item.name} (x${item.quantity}, Spice: ${item.spiceLevel}, Extras: ${extras}, Instructions: ${item.instructions}) - $${item.itemTotal.toFixed(2)}</li>`;
170
- });
171
- cartHTML += `</ul><p><strong>Total Bill: $${totalBill.toFixed(2)}</strong></p>`;
172
- document.getElementById('floating-cart').innerHTML = cartHTML;
173
- }
174
- </script>
175
- """
176
 
177
  # Modal window
178
  modal_window = gr.HTML("""
@@ -216,17 +168,23 @@ def app():
216
  </div>
217
  """)
218
 
219
- # Interactivity
220
- selected_preference.change(filter_menu, inputs=[selected_preference], outputs=[menu_output])
 
 
 
221
 
222
  # Layout
223
  gr.Row([selected_preference])
224
  gr.Row(menu_output)
225
  gr.Row(cart_output)
226
  gr.Row(modal_window)
 
 
227
  gr.HTML(modal_and_cart_js)
228
 
229
  return demo
230
 
231
  if __name__ == "__main__":
232
- app().launch()
 
 
1
  import gradio as gr
2
  import pandas as pd
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  # Function to load the menu data
5
  def load_menu():
6
  menu_file = "menu.xlsx" # Ensure this file exists in the same directory
 
9
  except Exception as e:
10
  raise ValueError(f"Error loading menu file: {e}")
11
 
12
+ # JavaScript for modal and cart behavior
13
+ modal_and_cart_js = """
14
+ <script>
15
+ let cart = [];
16
+ const extrasPrices = {
17
+ "Extra Raitha 4oz": 1,
18
+ "Extra Raitha 8oz": 2,
19
+ "Extra Salan 4oz": 1,
20
+ "Extra Salan 8oz": 2,
21
+ "Extra Onion": 1,
22
+ "Extra Onion & Lemon": 2,
23
+ "Extra Fried Onion 4oz": 2
24
+ };
25
+ let finalized = false;
26
+
27
+ function openModal(name, image, description, price) {
28
+ if (finalized) {
29
+ alert("You cannot add more items after finalizing your order.");
30
+ return;
31
+ }
32
+ document.getElementById('modal').style.display = 'block';
33
+ document.getElementById('modal-image').src = image;
34
+ document.getElementById('modal-name').innerText = name;
35
+ document.getElementById('modal-description').innerText = description;
36
+ document.getElementById('modal-price').innerText = price;
37
+
38
+ // Reset spice levels and extras
39
+ const spiceLevelInputs = document.querySelectorAll('input[name="spice-level"]');
40
+ spiceLevelInputs.forEach(input => input.checked = false);
41
+ const extrasInputs = document.querySelectorAll('input[name="biryani-extra"]');
42
+ extrasInputs.forEach(input => input.checked = false);
43
+ document.getElementById('quantity').value = 1;
44
+ document.getElementById('special-instructions').value = '';
45
+ }
46
+
47
+ function closeModal() {
48
+ document.getElementById('modal').style.display = 'none';
49
+ }
50
+
51
+ function addToCart() {
52
+ if (finalized) {
53
+ alert("You cannot add more items after finalizing your order.");
54
+ return;
55
+ }
56
+ const name = document.getElementById('modal-name').innerText;
57
+ const price = parseFloat(document.getElementById('modal-price').innerText.replace('$', ''));
58
+ const spiceLevel = document.querySelector('input[name="spice-level"]:checked')?.value || "Not Selected";
59
+ const quantity = parseInt(document.getElementById('quantity').value) || 1;
60
+ const instructions = document.getElementById('special-instructions').value;
61
+ const extras = Array.from(document.querySelectorAll('input[name="biryani-extra"]:checked')).map(extra => extra.value);
62
+ const extrasCost = extras.reduce((sum, extra) => sum + (extrasPrices[extra] || 0), 0);
63
+ const itemTotal = (price + extrasCost) * quantity;
64
+ const cartItem = { name, price, spiceLevel, quantity, instructions, extras, itemTotal };
65
+ cart.push(cartItem);
66
+ alert(`${name} added to cart!`);
67
+ updateCartDisplay();
68
+ closeModal();
69
+ }
70
+
71
+ function updateCartDisplay() {
72
+ let totalBill = 0;
73
+ let cartHTML = "<h3>Your Cart:</h3><ul>";
74
+ cart.forEach((item, index) => {
75
+ totalBill += item.itemTotal;
76
+ const extras = item.extras.join(', ');
77
+ cartHTML += `<li><input type='checkbox' id='cart-item-${index}' value='${index}' checked onclick='removeItem(${index})'> ${item.name} (x${item.quantity}, Spice: ${item.spiceLevel}, Extras: ${extras}, Instructions: ${item.instructions}) - $${item.itemTotal.toFixed(2)}</li>`;
78
+ });
79
+ cartHTML += `</ul><p><strong>Total Bill: $${totalBill.toFixed(2)}</strong></p>`;
80
+ document.getElementById('floating-cart').innerHTML = cartHTML;
81
+ }
82
+
83
+ function removeItem(index) {
84
+ cart.splice(index, 1);
85
+ updateCartDisplay();
86
+ }
87
+
88
+ function finalizeOrder() {
89
+ if (cart.length === 0) {
90
+ alert("Your cart is empty. Please add items before finalizing.");
91
+ return;
92
+ }
93
+ finalized = true;
94
+ let finalOrderHTML = "<h3>Final Order:</h3><ul>";
95
+ let totalBill = 0;
96
+ cart.forEach(item => {
97
+ totalBill += item.itemTotal;
98
+ const extras = item.extras.join(', ');
99
+ finalOrderHTML += `<li>${item.name} (x${item.quantity}, Spice: ${item.spiceLevel}, Extras: ${extras}, Instructions: ${item.instructions}) - $${item.itemTotal.toFixed(2)}</li>`;
100
+ });
101
+ finalOrderHTML += `</ul><p><strong>Total Bill: $${totalBill.toFixed(2)}</strong></p>`;
102
+ document.getElementById('final-order').innerHTML = finalOrderHTML;
103
+ alert("Your order has been finalized. You cannot make changes now.");
104
+ }
105
+ </script>
106
+ """
107
 
108
  # Gradio app definition
109
  def app():
 
118
  )
119
 
120
  # Output area for menu items
121
+ menu_output = gr.HTML(value="Loading menu...")
122
 
123
  # Floating cart display
124
  cart_output = gr.HTML(value="Your cart is empty.", elem_id="floating-cart")
125
 
126
+ # Final order display
127
+ final_order_output = gr.HTML(value="", elem_id="final-order")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
  # Modal window
130
  modal_window = gr.HTML("""
 
168
  </div>
169
  """)
170
 
171
+ # Finalize Order Button
172
+ finalize_button = gr.Button("Finalize Order")
173
+
174
+ # Finalize order button click event
175
+ finalize_button.click(lambda: "Order finalized!", outputs=[final_order_output])
176
 
177
  # Layout
178
  gr.Row([selected_preference])
179
  gr.Row(menu_output)
180
  gr.Row(cart_output)
181
  gr.Row(modal_window)
182
+ gr.Row(finalize_button)
183
+ gr.Row(final_order_output)
184
  gr.HTML(modal_and_cart_js)
185
 
186
  return demo
187
 
188
  if __name__ == "__main__":
189
+ demo = app()
190
+ demo.launch()