nagasurendra commited on
Commit
bff1031
·
verified ·
1 Parent(s): 585270a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +399 -115
app.py CHANGED
@@ -1,10 +1,6 @@
1
  import gradio as gr
2
  import pandas as pd
3
  from bcrypt import hashpw, gensalt, checkpw
4
- import speech_recognition as sr
5
- from gtts import gTTS
6
- import tempfile
7
- import os
8
 
9
  # File for storing user data
10
  USER_FILE = "users.xlsx"
@@ -44,24 +40,6 @@ def check_credentials(email, password):
44
  except FileNotFoundError:
45
  return False
46
 
47
- # Text-to-Speech Function
48
- def generate_voice_response(text):
49
- tts = gTTS(text)
50
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
51
- temp_file.close()
52
- tts.save(temp_file.name)
53
- return temp_file.name
54
-
55
- # Speech-to-Text Function
56
- def recognize_audio(audio_path):
57
- recognizer = sr.Recognizer()
58
- with sr.AudioFile(audio_path) as source:
59
- try:
60
- audio_data = recognizer.record(source)
61
- return recognizer.recognize_google(audio_data)
62
- except sr.UnknownValueError:
63
- return ""
64
-
65
  # Function to load the menu data
66
  def load_menu():
67
  menu_file = "menu.xlsx" # Ensure this file exists in the same directory
@@ -70,6 +48,7 @@ def load_menu():
70
  except Exception as e:
71
  raise ValueError(f"Error loading menu file: {e}")
72
 
 
73
  # Function to filter menu items based on preference
74
  def filter_menu(preference):
75
  menu_data = load_menu()
@@ -82,133 +61,438 @@ def filter_menu(preference):
82
  else:
83
  filtered_data = menu_data
84
 
85
- return filtered_data
86
-
87
- # Dynamic Voice Interaction Function
88
- def dynamic_voice_interaction(audio_path, current_state, menu_data):
89
- """Handles dynamic voice-based interactions based on the user's voice input."""
90
- user_input = recognize_audio(audio_path)
91
- response_text = ""
92
- tts_path = None
93
-
94
- # Determine action based on current state
95
- if current_state == "preferences":
96
- if "vegetarian" in user_input.lower():
97
- response_text = "You selected Vegetarian. Let me show you the menu."
98
- menu_data = filter_menu("Vegetarian")
99
- elif "halal" in user_input.lower():
100
- response_text = "You selected Halal. Let me show you the menu."
101
- menu_data = filter_menu("Halal/Non-Veg")
102
- elif "guilt free" in user_input.lower():
103
- response_text = "You selected Guilt-Free. Let me show you the menu."
104
- menu_data = filter_menu("Guilt-Free")
105
- else:
106
- response_text = "I didn’t catch that. Please say Vegetarian, Halal, or Guilt-Free."
107
-
108
- elif current_state == "menu":
109
- response_text = "The menu includes the following items: "
110
- for _, row in menu_data.iterrows():
111
- response_text += f"{row['Dish Name']} priced at {row['Price ($)']} dollars. "
112
-
113
- elif current_state == "modal":
114
- if "add" in user_input.lower():
115
- response_text = "Item added to cart."
116
- elif "close" in user_input.lower():
117
- response_text = "Closing modal."
118
-
119
- elif current_state == "cart":
120
- if "finalize" in user_input.lower():
121
- response_text = "Your order has been finalized. Thank you for ordering!"
122
- elif "remove" in user_input.lower():
123
- response_text = "Item removed from cart."
124
-
125
- # Generate voice response for user
126
- tts_path = generate_voice_response(response_text)
127
- return response_text, tts_path, menu_data
128
-
129
- # Modal, Cart, and Final Order Functions
130
  modal_and_cart_js = """
131
  <style>
132
  .cart-container {
133
- width: 90%;
134
  margin: auto;
135
  display: flex;
136
  flex-direction: column;
137
- gap: 10px;
138
- }
139
- .cart-item {
140
  display: flex;
141
- justify-content: space-between;
142
- width: 100%;
 
 
143
  padding: 10px;
144
  border: 1px solid #ccc;
145
  border-radius: 5px;
146
  background-color: #f9f9f9;
147
- }
148
- .cart-total {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  font-size: 1.2em;
150
  font-weight: bold;
151
  text-align: center;
152
- }
153
- button {
 
154
  background-color: #007bff;
155
  color: white;
156
  border: none;
157
  padding: 10px;
158
  border-radius: 5px;
 
159
  cursor: pointer;
160
- }
 
 
 
 
 
 
 
 
 
 
161
  </style>
162
  <script>
163
- let cart = [];
164
- function openModal(name, description, price) {
165
- const modal = document.getElementById('modal');
166
- modal.style.display = 'block';
167
- document.getElementById('modal-name').innerText = name;
168
- document.getElementById('modal-description').innerText = description;
169
- document.getElementById('modal-price').innerText = price;
170
- }
171
- function closeModal() {
172
- document.getElementById('modal').style.display = 'none';
173
- }
174
- function addToCart(name, price, quantity) {
175
- cart.push({ name, price, quantity });
176
- alert(`${name} added to cart!`);
177
- }
178
- function submitCart() {
179
- alert('Order submitted!');
180
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  </script>
182
  """
 
 
 
 
 
 
183
 
184
- # Gradio App
 
 
 
 
 
 
 
185
 
 
 
 
 
186
  def app():
187
  with gr.Blocks() as demo:
188
- # Login and Signup Sections
189
- login_section = gr.Column(visible=True)
190
- signup_section = gr.Column(visible=False)
191
-
192
  # Login Page
193
- with login_section:
 
194
  login_email = gr.Textbox(label="Email", placeholder="Enter your email")
195
  login_password = gr.Textbox(label="Password", placeholder="Enter your password", type="password")
 
196
  login_button = gr.Button("Login")
 
197
 
198
- # Modal and Cart Section
199
- modal_window = gr.HTML("""
200
- <div id="modal" style="display: none; background: white; padding: 20px;">
201
- <h3 id="modal-name"></h3>
202
- <p id="modal-description"></p>
203
- <p id="modal-price"></p>
204
- <button onclick="closeModal()">Close</button>
205
- </div>
206
- """ + modal_and_cart_js)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
 
208
- # Trigger Voice Interaction
209
- menu_data = filter_menu("All")
210
- user_audio.change(dynamic_voice_interaction, inputs=[user_audio, "preferences", menu_data], outputs=[response_text, response_audio])
211
  return demo
212
 
213
  if __name__ == "__main__":
214
- app().launch()
 
1
  import gradio as gr
2
  import pandas as pd
3
  from bcrypt import hashpw, gensalt, checkpw
 
 
 
 
4
 
5
  # File for storing user data
6
  USER_FILE = "users.xlsx"
 
40
  except FileNotFoundError:
41
  return False
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  # Function to load the menu data
44
  def load_menu():
45
  menu_file = "menu.xlsx" # Ensure this file exists in the same directory
 
48
  except Exception as e:
49
  raise ValueError(f"Error loading menu file: {e}")
50
 
51
+
52
  # Function to filter menu items based on preference
53
  def filter_menu(preference):
54
  menu_data = load_menu()
 
61
  else:
62
  filtered_data = menu_data
63
 
64
+ html_content = ""
65
+ for _, item in filtered_data.iterrows():
66
+ html_content += f"""
67
+ <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);">
68
+ <div style="flex: 1; margin-right: 15px;">
69
+ <h3 style="margin: 0; font-size: 18px;">{item['Dish Name']}</h3>
70
+ <p style="margin: 5px 0; font-size: 16px; color: #888;">${item['Price ($)']}</p>
71
+ <p style="margin: 5px 0; font-size: 14px; color: #555;">{item['Description']}</p>
72
+ </div>
73
+ <div style="flex-shrink: 0; text-align: center;">
74
+ <img src="{item['Image URL']}" alt="{item['Dish Name']}" style="width: 100px; height: 100px; border-radius: 8px; object-fit: cover; margin-bottom: 10px;">
75
+ <button style="background-color: #28a745; color: white; border: none; padding: 8px 15px; font-size: 14px; border-radius: 5px; cursor: pointer;" onclick="openModal('{item['Dish Name']}', '{item['Image 2 URL']}', '{item['Description']}', '{item['Price ($)']}')">Add</button>
76
+ </div>
77
+ </div>
78
+ """
79
+ return html_content
80
+ # Preserving your JavaScript for modal and cart functionality (Your original JavaScript logic)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  modal_and_cart_js = """
82
  <style>
83
  .cart-container {
84
+ width: 90%; /* Ensure it fits the screen */
85
  margin: auto;
86
  display: flex;
87
  flex-direction: column;
88
+ gap: 10px; /* Add space between cart items */
89
+ }
90
+ .cart-item {
91
  display: flex;
92
+ flex-wrap: wrap; /* Wrap content to the next line if needed */
93
+ align-items: center; /* Vertically align items */
94
+ justify-content: space-between; /* Distribute space between items */
95
+ width: 100%; /* Ensure it takes full width */
96
  padding: 10px;
97
  border: 1px solid #ccc;
98
  border-radius: 5px;
99
  background-color: #f9f9f9;
100
+ }
101
+ .cart-item span {
102
+ margin-right: 10px;
103
+ flex: 1; /* Allow text to take available space */
104
+ min-width: 50px; /* Prevent collapsing */
105
+ }
106
+ .cart-item .quantity-container {
107
+ display: flex;
108
+ align-items: center;
109
+ gap: 5px;
110
+ }
111
+ .cart-item button {
112
+ background-color: red;
113
+ color: white;
114
+ border: none;
115
+ padding: 5px 10px;
116
+ cursor: pointer;
117
+ border-radius: 5px;
118
+ flex-shrink: 0; /* Prevent the button from shrinking */
119
+ }
120
+ .cart-total {
121
  font-size: 1.2em;
122
  font-weight: bold;
123
  text-align: center;
124
+ }
125
+ button {
126
+ margin-top: 10px;
127
  background-color: #007bff;
128
  color: white;
129
  border: none;
130
  padding: 10px;
131
  border-radius: 5px;
132
+ width: 100%;
133
  cursor: pointer;
134
+ }
135
+ @media (max-width: 768px) {
136
+ .cart-item {
137
+ flex-direction: column; /* Stack items on mobile */
138
+ align-items: flex-start; /* Align to the left */
139
+ }
140
+ .cart-item button {
141
+ align-self: flex-end; /* Place the remove button at the end */
142
+ margin-top: 5px; /* Add some space on top */
143
+ }
144
+ }
145
  </style>
146
  <script>
147
+ let cart = [];
148
+ const extrasPrices = {
149
+ "Thums up": 2,
150
+ "Sprite": 2,
151
+ "Extra Raitha": 1,
152
+ "Extra Salan": 2,
153
+ "Extra Onion & Lemon": 2,
154
+ "Chilli Chicken": 14,
155
+ "Veg Manchurian": 12
156
+ };
157
+ let finalized = false;
158
+ function openModal(name, image2, description, price) {
159
+ if (finalized) {
160
+ alert("You cannot add more items after finalizing your order.");
161
+ return;
162
+ }
163
+ const modal = document.getElementById('modal');
164
+ modal.style.display = 'block';
165
+ modal.style.position = 'fixed';
166
+ if (window.innerWidth <= 768) {
167
+ modal.style.width = '90%';
168
+ modal.style.top = `${event.touches ? event.touches[0].screenY : event.clientY}px`;
169
+ } else {
170
+ modal.style.width = '30%';
171
+ modal.style.top = `${event.clientY}px`;// Use mouse Y position for laptop
172
+ }
173
+ modal.style.left = '50%';
174
+ modal.style.transform = 'translate(-50%, -50%)';
175
+ document.getElementById('modal-image').src = image2;
176
+ document.getElementById('modal-name').innerText = name;
177
+ document.getElementById('modal-description').innerText = description;
178
+ document.getElementById('modal-price').innerText = price;
179
+ const extrasInputs = document.querySelectorAll('input[name="biryani-extra"]');
180
+ extrasInputs.forEach(input => input.checked = false);
181
+ document.getElementById('quantity').value = 1;
182
+ document.getElementById('special-instructions').value = '';
183
+ }
184
+ function closeModal() {
185
+ document.getElementById('modal').style.display = 'none';
186
+ }
187
+ function addToCart() {
188
+ if (finalized) {
189
+ alert("You cannot add more items after finalizing your order.");
190
+ return;
191
+ }
192
+ const name = document.getElementById('modal-name').innerText;
193
+ const price = parseFloat(document.getElementById('modal-price').innerText.replace('$', ''));
194
+ const quantity = parseInt(document.getElementById('quantity').value) || 1;
195
+ const instructions = document.getElementById('special-instructions').value;
196
+ const extras = Array.from(document.querySelectorAll('input[name="biryani-extra"]:checked')).map(extra => extra.value);
197
+ const extrasCost = extras.reduce((sum, extra) => sum + (extrasPrices[extra] || 0), 0);
198
+ const itemTotal = (price + extrasCost) * quantity;
199
+ const cartItem = { name, price, quantity, instructions, extras, itemTotal, extrasQuantities: extras.map(() => 1) };
200
+ cart.push(cartItem);
201
+ alert(`${name} added to cart!`);
202
+ updateCartDisplay();
203
+ closeModal();
204
+ }
205
+ function updateCartDisplay() {
206
+ let totalBill = 0;
207
+ let cartHTML = "<div class='cart-container'>";
208
+ cart.forEach((item, index) => {
209
+ totalBill += item.itemTotal;
210
+ const extras = item.extras.map((extra, i) => {
211
+ const extraQuantity = item.extrasQuantities ? item.extrasQuantities[i] || 1 : 1;
212
+ const extraTotal = extrasPrices[extra] * extraQuantity;
213
+ totalBill += extraTotal;
214
+ return `<div class='cart-item'>
215
+ <span>${extra}</span>
216
+ <span>Price: $${extrasPrices[extra].toFixed(2)}</span>
217
+ <div class='quantity-container'>
218
+ <label for='extra-quantity-${index}-${i}'>Quantity:</label>
219
+ <input type='number' id='extra-quantity-${index}-${i}' value='${extraQuantity}' min='1' style='width: 50px;' onchange='updateExtraQuantity(${index}, ${i}, this.value)'>
220
+ </div>
221
+ <span>Total: $${extraTotal.toFixed(2)}</span>
222
+ <button style='background-color: red; color: white; border: none; padding: 5px 10px; cursor: pointer;' onclick='removeExtra(${index}, ${i})'>Remove</button>
223
+ </div>`;
224
+ }).join('');
225
+ cartHTML += `<div class='cart-item'>
226
+ <span>${item.name}</span>
227
+ <span>Item Price: $${item.price.toFixed(2)}</span>
228
+ <div class='quantity-container'>
229
+ <label for='item-quantity-${index}'>Quantity:</label>
230
+ <input type='number' id='item-quantity-${index}' value='${item.quantity}' min='1' style='width: 50px;' onchange='updateItemQuantity(${index}, this.value)'>
231
+ </div>
232
+ <span>Total: $${(item.price * item.quantity).toFixed(2)}</span>
233
+ <button style='background-color: red; color: white; border: none; padding: 5px 10px; cursor: pointer;' onclick='removeItem(${index})'>Remove</button>
234
+ </div>
235
+ ${extras}
236
+ <div class='cart-item'><strong>Instructions:</strong> ${item.instructions || "None"}</div>`;
237
+ });
238
+ cartHTML += `</div><p class='cart-total'>Total Bill: $${totalBill.toFixed(2)}</p>`;
239
+ cartHTML += `<button style='margin-top: 10px; background-color: #007bff; color: white; border: none; padding: 10px; border-radius: 5px; width: 100%; cursor: pointer;' onclick='submitCart()'>Submit</button>`;
240
+ document.getElementById('floating-cart').innerHTML = cartHTML;
241
+ }
242
+ function updateItemQuantity(index, newQuantity) {
243
+ const quantity = parseInt(newQuantity) || 1;
244
+ cart[index].quantity = quantity;
245
+ cart[index].itemTotal = cart[index].price * quantity;
246
+ updateCartDisplay();
247
+ }
248
+ function updateExtraQuantity(cartIndex, extraIndex, newQuantity) {
249
+ const quantity = parseInt(newQuantity) || 1;
250
+ cart[cartIndex].extrasQuantities = cart[cartIndex].extrasQuantities || [];
251
+ cart[cartIndex].extrasQuantities[extraIndex] = quantity;
252
+ updateCartDisplay();
253
+ }
254
+ function removeExtra(cartIndex, extraIndex) {
255
+ cart[cartIndex].extras.splice(extraIndex, 1);
256
+ if (cart[cartIndex].extrasQuantities) {
257
+ cart[cartIndex].extrasQuantities.splice(extraIndex, 1);
258
+ }
259
+ updateCartDisplay();
260
+ }
261
+ function removeItem(index) {
262
+ cart.splice(index, 1);
263
+ updateCartDisplay();
264
+ }
265
+ function submitCart() {
266
+ let finalOrderHTML = "<h3>Final Order:</h3><ul>";
267
+ let totalBill = 0;
268
+ cart.forEach(item => {
269
+ totalBill += item.itemTotal;
270
+ const extras = item.extras.map((extra, i) => {
271
+ const extraQuantity = item.extrasQuantities ? item.extrasQuantities[i] || 1 : 1;
272
+ const extraTotal = extrasPrices[extra] * extraQuantity;
273
+ totalBill += extraTotal;
274
+ return `${extra} (x${extraQuantity}) - $${extraTotal.toFixed(2)}`;
275
+ }).join(', ');
276
+ finalOrderHTML += `<li>
277
+ ${item.name} (x${item.quantity}) - $${item.itemTotal.toFixed(2)}
278
+ <br>Extras: ${extras}
279
+ <br>Instructions: ${item.instructions || "None"}
280
+ </li>`;
281
+ });
282
+ finalOrderHTML += `</ul><p><strong>Total Bill: $${totalBill.toFixed(2)}</strong></p>`;
283
+ document.getElementById('final-order').innerHTML = finalOrderHTML;
284
+ alert("Your final order has been submitted!");
285
+ }
286
  </script>
287
  """
288
+ # Authentication and Navigation Logic
289
+ def authenticate_user(email, password):
290
+ if check_credentials(email, password):
291
+ return gr.update(visible=False), gr.update(visible=True), ""
292
+ else:
293
+ return gr.update(visible=True), gr.update(visible=False), "Invalid email or password. Try again."
294
 
295
+ def navigate_to_signup():
296
+ return gr.update(visible=False), gr.update(visible=True)
297
+
298
+ def create_account(name, phone, email, password):
299
+ if save_user(name, phone, email, password):
300
+ return "Account created successfully! You can now log in.", gr.update(visible=True), gr.update(visible=False)
301
+ else:
302
+ return "Email already exists. Try logging in.", gr.update(visible=False), gr.update(visible=True)
303
 
304
+ def navigate_to_login():
305
+ return gr.update(visible=True), gr.update(visible=False)
306
+
307
+ # Gradio App
308
  def app():
309
  with gr.Blocks() as demo:
 
 
 
 
310
  # Login Page
311
+ with gr.Column(visible=True) as login_section:
312
+ gr.Markdown("# Login Page")
313
  login_email = gr.Textbox(label="Email", placeholder="Enter your email")
314
  login_password = gr.Textbox(label="Password", placeholder="Enter your password", type="password")
315
+ login_error = gr.Label("")
316
  login_button = gr.Button("Login")
317
+ go_to_signup = gr.Button("Create an Account")
318
 
319
+ # Signup Page
320
+ with gr.Column(visible=False) as signup_section:
321
+ gr.Markdown("# Signup Page")
322
+ signup_name = gr.Textbox(label="Name", placeholder="Enter your full name")
323
+ signup_phone = gr.Textbox(label="Phone", placeholder="Enter your phone number")
324
+ signup_email = gr.Textbox(label="Email", placeholder="Enter your email")
325
+ signup_password = gr.Textbox(label="Password", placeholder="Enter your password", type="password")
326
+ signup_message = gr.Label("")
327
+ signup_button = gr.Button("Sign Up")
328
+ go_to_login = gr.Button("Back to Login")
329
+
330
+ # Menu Page
331
+ with gr.Column(visible=False) as menu_section:
332
+ gr.Markdown("### Menu Page (Accessible Only After Login)")
333
+
334
+ # View Cart Button (Top Position)
335
+ view_cart_button_top = gr.Button("View Cart")
336
+
337
+ # Radio button for selecting preference
338
+ selected_preference = gr.Radio(
339
+ choices=["All", "Vegetarian", "Halal/Non-Veg", "Guilt Free"],
340
+ value="All",
341
+ label="Choose a Preference",
342
+ )
343
+ empty_div = gr.HTML('<div style="height: 20px;"></div>')
344
+
345
+ # Output area for menu items
346
+ menu_output = gr.HTML(value=filter_menu("All"))
347
+
348
+ # View Cart Button (Original Position)
349
+ view_cart_button_bottom = gr.Button("View Cart")
350
+ empty_div = gr.HTML('<div style="height: 300px;"></div>')
351
+
352
+ # Modal window
353
+ modal_window = gr.HTML("""
354
+ <div id="modal" style="display: none; position: fixed; background: white; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); padding: 20px; z-index: 1000;">
355
+ <div style="text-align: right;">
356
+ <button onclick="closeModal()" style="background: none; border: none; font-size: 18px; cursor: pointer;">&times;</button>
357
+ </div>
358
+ <img id="modal-image" style="width: 100%; height: 300px; border-radius: 8px; margin-bottom: 20px;" />
359
+ <h2 id="modal-name"></h2>
360
+ <p id="modal-description"></p>
361
+ <p id="modal-price"></p>
362
+ <!-- Biryani Extras -->
363
+ <label for="biryani-extras">Extras :</label>
364
+ <div id="biryani-extras-options" style="display: flex; flex-wrap: wrap; gap: 10px; margin: 10px 0;">
365
+ <label><input type="checkbox" name="biryani-extra" value="Thums up" /> Thums up + $2.00</label>
366
+ <label><input type="checkbox" name="biryani-extra" value="Sprite" /> Sprite + $2.00</label>
367
+ <label><input type="checkbox" name="biryani-extra" value="Extra Raitha" /> Extra Raitha + $1.00</label>
368
+ <label><input type="checkbox" name="biryani-extra" value="Extra Salan" /> Extra Salan + $2.00</label>
369
+ <label><input type="checkbox" name="biryani-extra" value="Extra Onion & Lemon" /> Extra Onion & Lemon + $2.00</label>
370
+ <label><input type="checkbox" name="biryani-extra" value="Chilli Chicken" /> Chilli Chicken + $14.00</label>
371
+ <label><input type="checkbox" name="biryani-extra" value="Veg Manchurian" /> Veg Manchurian + $12.00</label>
372
+ </div>
373
+ <!-- Quantity and Special Instructions -->
374
+ <label for="quantity">Quantity:</label>
375
+ <input type="number" id="quantity" value="1" min="1" style="width: 50px;" />
376
+ <br><br>
377
+ <textarea id="special-instructions" placeholder="Add special instructions here..." style="width: 100%; height: 60px;"></textarea>
378
+ <br><br>
379
+ <!-- Add to Cart Button -->
380
+ <button style="background-color: #28a745; color: white; border: none; padding: 10px 20px; font-size: 14px; border-radius: 5px; cursor: pointer;" onclick="addToCart()">Add to Cart</button>
381
+ </div>
382
+ """)
383
+
384
+ # Update menu dynamically based on preference
385
+ selected_preference.change(filter_menu, inputs=[selected_preference], outputs=[menu_output])
386
+
387
+ # Layout
388
+ gr.Row(view_cart_button_top) # View Cart button at the top
389
+ gr.Row([selected_preference])
390
+ gr.Row(menu_output)
391
+ gr.Row(view_cart_button_bottom) # View Cart button at the bottom
392
+ gr.Row(modal_window)
393
+ gr.HTML(modal_and_cart_js)
394
+
395
+ # Cart & Final Order Page
396
+ with gr.Column(visible=False) as cart_section:
397
+ gr.Markdown("### Cart & Final Order Page")
398
+
399
+ # Floating cart display
400
+ cart_output = gr.HTML(value="Your cart is empty.", elem_id="floating-cart")
401
+
402
+ # Final order display
403
+ final_order_output = gr.HTML(value="", elem_id="final-order")
404
+
405
+ # Button to navigate back to Menu Page
406
+ back_to_menu_button = gr.Button("Back to Menu")
407
+
408
+ gr.Row(cart_output)
409
+ gr.Row(final_order_output)
410
+
411
+ # Button Bindings
412
+ # Login Button
413
+ login_button.click(
414
+ lambda email, password: (gr.update(visible=False), gr.update(visible=True), "") if check_credentials(email, password) else (gr.update(), gr.update(), "Invalid email or password."),
415
+ inputs=[login_email, login_password],
416
+ outputs=[login_section, menu_section, login_error],
417
+ )
418
+ # Signup Button
419
+ signup_button.click(
420
+ lambda name, phone, email, password: ("Signup successful! Please login.", gr.update(visible=True), gr.update(visible=False)) if save_user(name, phone, email, password) else ("Email already exists.", gr.update(visible=False), gr.update(visible=True)),
421
+ inputs=[signup_name, signup_phone, signup_email, signup_password],
422
+ outputs=[signup_message, login_section, signup_section],
423
+ )
424
+ # Navigate to Signup Page
425
+ go_to_signup.click(
426
+ lambda: (gr.update(visible=False), gr.update(visible=True)),
427
+ outputs=[login_section, signup_section],
428
+ )
429
+ # Navigate Back to Login Page
430
+ go_to_login.click(
431
+ lambda: (gr.update(visible=True), gr.update(visible=False)),
432
+ outputs=[login_section, signup_section],
433
+ )
434
+ # Navigate to Cart Page (Both Buttons Use the Same Logic)
435
+ view_cart_button_top.click(
436
+ lambda: (gr.update(visible=False), gr.update(visible=True)),
437
+ outputs=[menu_section, cart_section],
438
+ )
439
+ view_cart_button_bottom.click(
440
+ lambda: (gr.update(visible=False), gr.update(visible=True)),
441
+ outputs=[menu_section, cart_section],
442
+ )
443
+ # Navigate Back to Menu Page
444
+ back_to_menu_button.click(
445
+ lambda: (gr.update(visible=True), gr.update(visible=False)),
446
+ outputs=[menu_section, cart_section],
447
+ )
448
+ def main_app():
449
+ return "Welcome to the menu ordering system. Interact with items to hear details."
450
+
451
+ # Add custom HTML and JavaScript for voice accessibility
452
+ custom_html = """
453
+ <script>
454
+ // Function to speak text
455
+ function speak(text) {
456
+ const speech = new SpeechSynthesisUtterance(text);
457
+ speech.lang = 'en-US'; // Set language
458
+ speech.pitch = 1.0; // Adjust pitch (optional)
459
+ speech.rate = 1.0; // Adjust rate (optional)
460
+ window.speechSynthesis.speak(speech);
461
+ }
462
+
463
+ // Event listeners for hover and click
464
+ document.addEventListener('DOMContentLoaded', (event) => {
465
+ // Add hoverable elements
466
+ document.querySelectorAll('.hoverable').forEach((element) => {
467
+ element.addEventListener('mouseenter', () => {
468
+ const text = element.getAttribute('aria-label') || element.innerText;
469
+ speak(`This is ${text}`);
470
+ });
471
+ });
472
+
473
+ // Add clickable elements
474
+ document.querySelectorAll('.clickable').forEach((element) => {
475
+ element.addEventListener('click', () => {
476
+ const text = element.getAttribute('aria-label') || element.innerText;
477
+ speak(`You clicked on ${text}`);
478
+ });
479
+ });
480
+ });
481
+ </script>
482
+ """
483
+
484
+ # Define the Gradio Interface
485
+ demo = gr.Interface(
486
+ fn=main_app, # Your main app function
487
+ inputs=[], # Define your inputs
488
+ outputs="html", # Define your outputs
489
+ live=True # Enable live updates
490
+ )
491
+
492
+ # Add the custom JavaScript to the app
493
+ demo.custom_html = custom_html
494
 
 
 
 
495
  return demo
496
 
497
  if __name__ == "__main__":
498
+ app().launch()