import gradio as gr
import pandas as pd
from bcrypt import hashpw, gensalt, checkpw
# File for storing user data
USER_FILE = "users.xlsx"
# Utility Functions
def save_user(name, phone, email, password):
"""Save user details to Excel file."""
try:
# Load existing users
try:
users = pd.read_excel(USER_FILE)
except FileNotFoundError:
users = pd.DataFrame(columns=["Name", "Phone", "Email", "Password"])
# Check if email already exists
if email in users["Email"].values:
return False # User already exists
# Add new user
hashed_password = hashpw(password.encode(), gensalt()).decode()
new_user = {"Name": name, "Phone": phone, "Email": email, "Password": hashed_password}
users = pd.concat([users, pd.DataFrame([new_user])], ignore_index=True)
users.to_excel(USER_FILE, index=False)
return True
except Exception as e:
print(f"Error saving user: {e}")
return False
def check_credentials(email, password):
"""Check user credentials during login."""
try:
users = pd.read_excel(USER_FILE)
user = users[users["Email"] == email]
if not user.empty:
return checkpw(password.encode(), user.iloc[0]["Password"].encode())
return False
except FileNotFoundError:
return False
# Function to load the menu data
def load_menu():
menu_file = "menu.xlsx" # Ensure this file exists in the same directory
try:
return pd.read_excel(menu_file)
except Exception as e:
raise ValueError(f"Error loading menu file: {e}")
# Function to filter menu items based on preference
def filter_menu(preference):
menu_data = load_menu()
if preference == "Halal/Non-Veg":
filtered_data = menu_data[menu_data["Ingredients"].str.contains("Chicken|Mutton|Fish|Prawns|Goat", case=False, na=False)]
elif preference == "Vegetarian":
filtered_data = menu_data[~menu_data["Ingredients"].str.contains("Chicken|Mutton|Fish|Prawns|Goat", case=False, na=False)]
elif preference == "Guilt-Free":
filtered_data = menu_data[menu_data["Description"].str.contains(r"Fat: ([0-9]|10)g", case=False, na=False)]
else:
filtered_data = menu_data
html_content = ""
for _, item in filtered_data.iterrows():
html_content += f"""
{item['Dish Name']}
${item['Price ($)']}
{item['Description']}
"""
return html_content
# Preserving your JavaScript for modal and cart functionality (Your original JavaScript logic)
modal_and_cart_js = """
"""
# Authentication and Navigation Logic
def authenticate_user(email, password):
if check_credentials(email, password):
return gr.update(visible=False), gr.update(visible=True), ""
else:
return gr.update(visible=True), gr.update(visible=False), "Invalid email or password. Try again."
def navigate_to_signup():
return gr.update(visible=False), gr.update(visible=True)
def create_account(name, phone, email, password):
if save_user(name, phone, email, password):
return "Account created successfully! You can now log in.", gr.update(visible=True), gr.update(visible=False)
else:
return "Email already exists. Try logging in.", gr.update(visible=False), gr.update(visible=True)
def navigate_to_login():
return gr.update(visible=True), gr.update(visible=False)
# Gradio App
def app():
with gr.Blocks() as demo:
# Login Page
with gr.Column(visible=True) as login_section:
gr.Markdown("# Login Page")
login_email = gr.Textbox(label="Email", placeholder="Enter your email")
login_password = gr.Textbox(label="Password", placeholder="Enter your password", type="password")
login_error = gr.Label("")
login_button = gr.Button("Login")
go_to_signup = gr.Button("Create an Account")
# Signup Page
with gr.Column(visible=False) as signup_section:
gr.Markdown("# Signup Page")
signup_name = gr.Textbox(label="Name", placeholder="Enter your full name")
signup_phone = gr.Textbox(label="Phone", placeholder="Enter your phone number")
signup_email = gr.Textbox(label="Email", placeholder="Enter your email")
signup_password = gr.Textbox(label="Password", placeholder="Enter your password", type="password")
signup_message = gr.Label("")
signup_button = gr.Button("Sign Up")
go_to_login = gr.Button("Back to Login")
# Menu Page
with gr.Column(visible=False) as menu_section:
gr.Markdown("### Menu Page (Accessible Only After Login)")
# View Cart Button (Top Position)
view_cart_button_top = gr.Button("View Cart")
# Radio button for selecting preference
selected_preference = gr.Radio(
choices=["All", "Vegetarian", "Halal/Non-Veg", "Guilt Free"],
value="All",
label="Choose a Preference",
)
empty_div = gr.HTML('')
# Output area for menu items
menu_output = gr.HTML(value=filter_menu("All"))
# View Cart Button (Original Position)
view_cart_button_bottom = gr.Button("View Cart")
empty_div = gr.HTML('')
# Modal window
modal_window = gr.HTML("""
""")
# Update menu dynamically based on preference
selected_preference.change(filter_menu, inputs=[selected_preference], outputs=[menu_output])
# Layout
gr.Row(view_cart_button_top) # View Cart button at the top
gr.Row([selected_preference])
gr.Row(menu_output)
gr.Row(view_cart_button_bottom) # View Cart button at the bottom
gr.Row(modal_window)
gr.HTML(modal_and_cart_js)
# Cart & Final Order Page
with gr.Column(visible=False, elem_id="cart-section") as cart_section:
gr.Markdown("### Cart Page")
cart_output = gr.HTML(value="Your cart is empty.", elem_id="floating-cart")
#submitCart_button = gr.Button("Submit Cart") # Keep only this button
back_to_menu_button = gr.Button("Back to Menu")
with gr.Column(visible=False, elem_id="final-order-section") as final_order_section:
gr.Markdown("### Final Order")
final_order_output = gr.HTML(value="", elem_id="final-order")
# Floating cart display
#cart_output = gr.HTML(value="Your cart is empty.", elem_id="floating-cart")
# Final order display
#final_order_output = gr.HTML(value="", elem_id="final-order")
# Button to navigate back to Menu Page
#back_to_menu_button = gr.Button("Back to Menu")
gr.Row(cart_output)
gr.Row(final_order_output)
# Button Bindings
# Login Button
login_button.click(
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."),
inputs=[login_email, login_password],
outputs=[login_section, menu_section, login_error],
)
# Signup Button
signup_button.click(
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)),
inputs=[signup_name, signup_phone, signup_email, signup_password],
outputs=[signup_message, login_section, signup_section],
)
# Navigate to Signup Page
go_to_signup.click(
lambda: (gr.update(visible=False), gr.update(visible=True)),
outputs=[login_section, signup_section],
)
# Navigate Back to Login Page
go_to_login.click(
lambda: (gr.update(visible=True), gr.update(visible=False)),
outputs=[login_section, signup_section],
)
# Navigate to Cart Page (Both Buttons Use the Same Logic)
view_cart_button_top.click(
lambda: (gr.update(visible=False), gr.update(visible=True)),
outputs=[menu_section, cart_section],
)
view_cart_button_bottom.click(
lambda: (gr.update(visible=False), gr.update(visible=True)),
outputs=[menu_section, cart_section],
)
# Navigate to Final Order Page
# Navigate to Final Order Page
#submitCart_button.click(
#lambda: (gr.update(visible=False), gr.update(visible=True)),
#outputs=[cart_section, final_order_section],
#)
# Navigate Back to Menu Page
back_to_menu_button.click(
lambda: (gr.update(visible=True), gr.update(visible=False)),
outputs=[menu_section, cart_section], # Show menu, hide cart
)
return demo
if __name__ == "__main__":
app().launch()