geethareddy commited on
Commit
9a5300a
·
verified ·
1 Parent(s): 727d970

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -166
app.py CHANGED
@@ -1,135 +1,116 @@
1
  import gradio as gr
2
  import pandas as pd
3
- from utils.database_handler import check_credentials, save_user
4
-
5
- # Function to load the menu data
6
- def load_menu():
7
- menu_file = "menu.xlsx" # Ensure this file exists in the same directory
8
- try:
9
- return pd.read_excel(menu_file)
10
- except Exception as e:
11
- raise ValueError(f"Error loading menu file: {e}")
12
-
13
- # Function to filter menu items based on preference
14
- def filter_menu(preference):
15
- menu_data = load_menu()
16
- if preference == "Halal/Non-Veg":
17
- filtered_data = menu_data[menu_data["Ingredients"].str.contains("Chicken|Mutton|Fish|Prawns|Goat", case=False, na=False)]
18
- elif preference == "Vegetarian":
19
- filtered_data = menu_data[~menu_data["Ingredients"].str.contains("Chicken|Mutton|Fish|Prawns|Goat", case=False, na=False)]
20
- elif preference == "Guilt-Free":
21
- filtered_data = menu_data[menu_data["Description"].str.contains(r"Fat: ([0-9]|10)g", case=False, na=False)]
22
- else:
23
- filtered_data = menu_data
24
-
25
- html_content = ""
26
- for _, item in filtered_data.iterrows():
27
- html_content += f"""
28
- <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);">
29
- <div style="flex: 1; margin-right: 15px;">
30
- <h3 style="margin: 0; font-size: 18px;">{item['Dish Name']}</h3>
31
- <p style="margin: 5px 0; font-size: 16px; color: #888;">${item['Price ($)']}</p>
32
- <p style="margin: 5px 0; font-size: 14px; color: #555;">{item['Description']}</p>
33
  </div>
34
- <div style="flex-shrink: 0; text-align: center;">
35
- <img src="{item['Image URL']}" alt="{item['Dish Name']}" style="width: 100px; height: 100px; border-radius: 8px; object-fit: cover; margin-bottom: 10px;">
36
- <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 URL']}', '{item['Description']}', '{item['Price ($)']}')">Add</button>
37
  </div>
38
  </div>
39
  """
40
- return html_content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- # Login and Signup Functions
43
  def authenticate_user(email, password):
44
- if check_credentials(email, password):
45
- return gr.update(visible=False), gr.update(visible=True), ""
46
- else:
47
- return gr.update(visible=True), gr.update(visible=False), "Invalid email or password. Try again."
48
-
49
- def navigate_to_signup():
50
- return gr.update(visible=False), gr.update(visible=True)
51
 
52
- def create_account(name, phone, email, password):
53
- if save_user(name, phone, email, password):
54
- return "Account created successfully! You can now log in.", gr.update(visible=True), gr.update(visible=False)
55
- else:
56
- return "Email already exists. Try logging in.", gr.update(visible=False), gr.update(visible=True)
57
 
58
- def navigate_to_login():
59
- return gr.update(visible=True), gr.update(visible=False)
60
-
61
- # Gradio app with popup modal and cart system
62
  def app():
63
  with gr.Blocks() as demo:
64
  # Login Page
65
- with gr.Column(visible=True) as login_section:
66
  gr.Markdown("# Login Page")
67
- email = gr.Textbox(label="Email", placeholder="Enter your email")
68
- password = gr.Textbox(label="Password", placeholder="Enter your password", type="password")
69
- error_box = gr.Markdown("", visible=False)
70
  login_btn = gr.Button("Login")
71
- create_account_btn = gr.Button("Create an Account")
72
-
73
- # Sign-Up Page
74
- with gr.Column(visible=False) as signup_section:
75
- gr.Markdown("# Sign Up Page")
76
- name = gr.Textbox(label="Name", placeholder="Enter your full name")
77
- phone = gr.Textbox(label="Phone", placeholder="Enter your phone number")
78
- signup_email = gr.Textbox(label="Email", placeholder="Enter your email")
79
- signup_password = gr.Textbox(label="Password", placeholder="Enter a password", type="password")
80
- success_message = gr.Markdown("", visible=False)
81
- error_message = gr.Markdown("", visible=False)
82
- submit_btn = gr.Button("Sign Up")
83
- back_to_login_btn = gr.Button("Back to Login")
84
-
85
- # Preferences and Menu Section
86
- with gr.Column(visible=False) as preference_section:
87
- gr.Markdown("## Preferences")
88
- selected_preference = gr.Radio(
89
- choices=["All", "Vegetarian", "Halal/Non-Veg", "Guilt-Free"],
90
- value="All",
91
- label="Choose a Preference",
92
- )
93
- menu_output = gr.HTML(value=filter_menu("All"))
94
- cart_output = gr.HTML(value="Your cart is empty.", elem_id="floating-cart")
95
- modal_window = gr.HTML("""
96
- <div id="modal" style="display: none; position: fixed; top: 10%; left: 50%; transform: translate(-50%, 0); background: white; padding: 20px; border-radius: 10px; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2); z-index: 1000;">
97
- <div style="text-align: right;">
98
- <button onclick="closeModal()" style="background: none; border: none; font-size: 20px; cursor: pointer;">&times;</button>
99
- </div>
100
- <img id="modal-image" style="width: 100%; height: auto; border-radius: 8px; margin-bottom: 15px;" />
101
- <h3 id="modal-name"></h3>
102
- <p id="modal-description"></p>
103
- <p id="modal-price" style="font-size: 18px; color: #28a745; font-weight: bold;"></p>
104
- <label>Extras:</label>
105
- <div style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 10px;">
106
- <label><input type="checkbox" name="extra" value="Thums up" /> Thums up + $2.00</label>
107
- <label><input type="checkbox" name="extra" value="Sprite" /> Sprite + $2.00</label>
108
- <label><input type="checkbox" name="extra" value="Extra Raitha" /> Extra Raitha + $1.00</label>
109
- <label><input type="checkbox" name="extra" value="Extra Salan" /> Extra Salan + $2.00</label>
110
- <label><input type="checkbox" name="extra" value="Extra Onion & Lemon" /> Extra Onion & Lemon + $2.00</label>
111
- <label><input type="checkbox" name="extra" value="Chilli Chicken" /> Chilli Chicken + $14.00</label>
112
- <label><input type="checkbox" name="extra" value="Veg Manchurian" /> Veg Manchurian + $12.00</label>
113
- </div>
114
- <label for="quantity">Quantity:</label>
115
- <input type="number" id="quantity" value="1" min="1" style="width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 5px;" />
116
- <label for="special-instructions">Special Instructions:</label>
117
- <textarea id="special-instructions" placeholder="Add special instructions here..." style="width: 100%; height: 60px; padding: 10px; border: 1px solid #ddd; border-radius: 5px; margin-bottom: 10px;"></textarea>
118
- <button onclick="addToCart()" style="width: 100%; padding: 10px; background-color: #28a745; color: white; border: none; border-radius: 5px; font-size: 16px;">Add to Cart</button>
119
- </div>
120
- """)
121
- selected_preference.change(filter_menu, inputs=[selected_preference], outputs=[menu_output])
122
 
123
  # Button Actions
124
- login_btn.click(authenticate_user, inputs=[email, password], outputs=[login_section, preference_section, error_box])
125
- create_account_btn.click(navigate_to_signup, inputs=[], outputs=[login_section, signup_section])
126
- submit_btn.click(create_account, inputs=[name, phone, signup_email, signup_password], outputs=[success_message, signup_section, login_section])
127
- back_to_login_btn.click(navigate_to_login, inputs=[], outputs=[login_section, signup_section])
128
-
129
- # Cart HTML Placeholder
130
- gr.HTML('<div id="floating-cart" style="margin-top: 20px;"></div>')
131
-
132
- # JavaScript for Popup and Cart Management
 
133
  gr.HTML("""
134
  <script>
135
  let cart = [];
@@ -138,22 +119,13 @@ def app():
138
  "Sprite": 2,
139
  "Extra Raitha": 1,
140
  "Extra Salan": 2,
141
- "Extra Onion & Lemon": 2,
142
- "Chilli Chicken": 14,
143
- "Veg Manchurian": 12
144
  };
145
 
146
- function openModal(name, image, description, price) {
147
  const modal = document.getElementById('modal');
148
  modal.style.display = 'block';
149
- modal.style.position = 'fixed';
150
- modal.style.top = '10%';
151
- modal.style.left = '50%';
152
- modal.style.transform = 'translate(-50%, 0)';
153
- document.getElementById('modal-image').src = image;
154
  document.getElementById('modal-name').innerText = name;
155
- document.getElementById('modal-description').innerText = description;
156
- document.getElementById('modal-price').innerText = `$${price}`;
157
  }
158
 
159
  function closeModal() {
@@ -162,59 +134,27 @@ def app():
162
 
163
  function addToCart() {
164
  const name = document.getElementById('modal-name').innerText;
165
- const price = parseFloat(document.getElementById('modal-price').innerText.replace('$', ''));
166
  const quantity = parseInt(document.getElementById('quantity').value) || 1;
167
  const specialInstructions = document.getElementById('special-instructions').value || "None";
168
 
169
- const selectedExtras = Array.from(document.querySelectorAll('input[name="extra"]:checked')).map(extra => extra.value);
170
- const extrasCost = selectedExtras.reduce((sum, extra) => sum + (extrasPrices[extra] || 0), 0);
171
 
172
- const itemTotal = (price + extrasCost) * quantity;
173
 
174
  cart.push({
175
  name,
176
  price,
177
  quantity,
178
- selectedExtras,
179
- extrasCost,
180
- itemTotal,
181
- specialInstructions
182
  });
183
 
184
  alert(`${name} added to cart!`);
185
  closeModal();
186
- updateCart();
187
- }
188
-
189
- function updateCart() {
190
- let cartHTML = '<div style="padding: 10px; border: 1px solid #ddd; border-radius: 8px;">';
191
- let totalAmount = 0;
192
-
193
- cart.forEach((item, index) => {
194
- totalAmount += item.itemTotal;
195
- const extrasList = item.selectedExtras.length ? item.selectedExtras.join(', ') : "No extras";
196
-
197
- cartHTML += `
198
- <div style="margin-bottom: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
199
- <strong>${item.name}</strong> <br>
200
- Price: $${item.price.toFixed(2)} <br>
201
- Quantity: ${item.quantity} <br>
202
- Extras: ${extrasList} (Total Extras Cost: $${item.extrasCost.toFixed(2)}) <br>
203
- Special Instructions: ${item.specialInstructions} <br>
204
- Item Total: $${item.itemTotal.toFixed(2)}
205
- <button style="margin-top: 5px; background-color: red; color: white; border: none; padding: 5px 10px; border-radius: 5px; cursor: pointer;" onclick="removeFromCart(${index})">Remove</button>
206
- </div>
207
- `;
208
- });
209
-
210
- cartHTML += `<div style="text-align: right; font-size: 16px; font-weight: bold;">Total Amount: $${totalAmount.toFixed(2)}</div>`;
211
- cartHTML += '</div>';
212
- document.getElementById('floating-cart').innerHTML = cartHTML;
213
- }
214
-
215
- function removeFromCart(index) {
216
- cart.splice(index, 1);
217
- updateCart();
218
  }
219
  </script>
220
  """)
 
1
  import gradio as gr
2
  import pandas as pd
3
+
4
+ # Sample menu data
5
+ menu_data = pd.DataFrame([
6
+ {"Dish Name": "Veg Samosa", "Price ($)": 9, "Description": "Crispy fried pastry filled with spiced potatoes and peas.", "Image URL": "https://example.com/samosa.jpg"},
7
+ {"Dish Name": "Prawn Fry", "Price ($)": 15, "Description": "Succulent prawns fried with a blend of spices and herbs.", "Image URL": "https://example.com/prawns.jpg"},
8
+ {"Dish Name": "Chicken Curry", "Price ($)": 14, "Description": "Traditional chicken curry cooked in a flavorful gravy.", "Image URL": "https://example.com/chickencurry.jpg"},
9
+ {"Dish Name": "Paneer Butter Masala", "Price ($)": 12, "Description": "Cottage cheese in creamy tomato-based gravy.", "Image URL": "https://example.com/paneer.jpg"},
10
+ {"Dish Name": "Veg Biryani", "Price ($)": 10, "Description": "Mixed vegetables cooked with fragrant rice.", "Image URL": "https://example.com/vegbiryani.jpg"},
11
+ ])
12
+
13
+ # Global cart
14
+ cart = []
15
+
16
+ # Function to render the menu
17
+ def render_menu():
18
+ menu_html = ""
19
+ for _, item in menu_data.iterrows():
20
+ menu_html += f"""
21
+ <div style="display: flex; align-items: center; border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; border-radius: 8px;">
22
+ <div style="flex: 1;">
23
+ <h3>{item['Dish Name']}</h3>
24
+ <p>${item['Price ($)']}</p>
25
+ <p>{item['Description']}</p>
 
 
 
 
 
 
 
26
  </div>
27
+ <div>
28
+ <img src="{item['Image URL']}" alt="{item['Dish Name']}" style="width: 100px; height: 100px; object-fit: cover; border-radius: 5px;">
29
+ <button onclick="openModal('{item['Dish Name']}', {item['Price ($)']})" style="margin-top: 10px; background-color: #28a745; color: white; padding: 8px; border: none; border-radius: 5px;">Add</button>
30
  </div>
31
  </div>
32
  """
33
+ return menu_html
34
+
35
+ # Function to view cart
36
+ def view_cart():
37
+ if not cart:
38
+ return "<p>Your cart is empty.</p>"
39
+
40
+ cart_html = "<h2>Your Cart</h2><div>"
41
+ total_amount = 0
42
+ for item in cart:
43
+ item_total = item["price"] * item["quantity"]
44
+ total_amount += item_total
45
+ extras = ", ".join(item["extras"]) if item["extras"] else "No extras"
46
+ cart_html += f"""
47
+ <div style="margin-bottom: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
48
+ <h3>{item['name']}</h3>
49
+ <p>Price: ${item['price']}</p>
50
+ <p>Quantity: {item['quantity']}</p>
51
+ <p>Extras: {extras} (Extras Total: ${item['extras_total']:.2f})</p>
52
+ <p>Special Instructions: {item['instructions']}</p>
53
+ <p><strong>Total: ${item_total:.2f}</strong></p>
54
+ </div>
55
+ """
56
+ cart_html += f"<h3>Grand Total: ${total_amount:.2f}</h3></div>"
57
+ return cart_html
58
 
59
+ # Function for login and signup
60
  def authenticate_user(email, password):
61
+ # This is a dummy function. Replace with your actual user authentication logic.
62
+ if email == "test@example.com" and password == "password":
63
+ return gr.update(visible=False), gr.update(visible=True)
64
+ return gr.update(visible=True), gr.update(visible=False), "Invalid email or password."
 
 
 
65
 
66
+ def create_account(name, email, password):
67
+ # Dummy function to simulate account creation
68
+ return f"Account created for {name}. Please log in."
 
 
69
 
70
+ # Gradio App
 
 
 
71
  def app():
72
  with gr.Blocks() as demo:
73
  # Login Page
74
+ with gr.Column(visible=True) as login_page:
75
  gr.Markdown("# Login Page")
76
+ email = gr.Textbox(label="Email")
77
+ password = gr.Textbox(label="Password", type="password")
78
+ login_error = gr.Textbox(visible=False, label="Error", interactive=False)
79
  login_btn = gr.Button("Login")
80
+ signup_btn = gr.Button("Create Account")
81
+
82
+ # Signup Page
83
+ with gr.Column(visible=False) as signup_page:
84
+ gr.Markdown("# Signup Page")
85
+ name = gr.Textbox(label="Name")
86
+ signup_email = gr.Textbox(label="Email")
87
+ signup_password = gr.Textbox(label="Password", type="password")
88
+ signup_message = gr.Textbox(interactive=False, label="Message")
89
+ create_account_btn = gr.Button("Sign Up")
90
+ back_to_login = gr.Button("Back to Login")
91
+
92
+ # Menu Page
93
+ with gr.Column(visible=False) as menu_page:
94
+ gr.Markdown("# Menu")
95
+ menu_display = gr.HTML(render_menu())
96
+ view_cart_btn = gr.Button("View Cart")
97
+
98
+ # Cart Page
99
+ with gr.Column(visible=False) as cart_page:
100
+ cart_display = gr.HTML("")
101
+ back_to_menu_btn = gr.Button("Back to Menu")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  # Button Actions
104
+ login_btn.click(authenticate_user, inputs=[email, password], outputs=[login_page, menu_page, login_error])
105
+ signup_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[login_page, signup_page])
106
+ create_account_btn.click(create_account, inputs=[name, signup_email, signup_password], outputs=[signup_message])
107
+ back_to_login.click(lambda: (gr.update(visible=True), gr.update(visible=False)), outputs=[login_page, signup_page])
108
+ view_cart_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True), view_cart()),
109
+ outputs=[menu_page, cart_page, cart_display])
110
+ back_to_menu_btn.click(lambda: (gr.update(visible=True), gr.update(visible=False)),
111
+ outputs=[menu_page, cart_page])
112
+
113
+ # JavaScript for Modal Popup
114
  gr.HTML("""
115
  <script>
116
  let cart = [];
 
119
  "Sprite": 2,
120
  "Extra Raitha": 1,
121
  "Extra Salan": 2,
 
 
 
122
  };
123
 
124
+ function openModal(name, price) {
125
  const modal = document.getElementById('modal');
126
  modal.style.display = 'block';
 
 
 
 
 
127
  document.getElementById('modal-name').innerText = name;
128
+ document.getElementById('modal-price').innerText = price;
 
129
  }
130
 
131
  function closeModal() {
 
134
 
135
  function addToCart() {
136
  const name = document.getElementById('modal-name').innerText;
137
+ const price = parseFloat(document.getElementById('modal-price').innerText);
138
  const quantity = parseInt(document.getElementById('quantity').value) || 1;
139
  const specialInstructions = document.getElementById('special-instructions').value || "None";
140
 
141
+ const selectedExtras = Array.from(document.querySelectorAll('input[name="extras"]:checked')).map(extra => extra.value);
142
+ const extrasTotal = selectedExtras.reduce((sum, extra) => sum + (extrasPrices[extra] || 0), 0);
143
 
144
+ const itemTotal = (price + extrasTotal) * quantity;
145
 
146
  cart.push({
147
  name,
148
  price,
149
  quantity,
150
+ extras: selectedExtras,
151
+ extras_total: extrasTotal,
152
+ instructions: specialInstructions,
153
+ item_total: itemTotal
154
  });
155
 
156
  alert(`${name} added to cart!`);
157
  closeModal();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  }
159
  </script>
160
  """)