import gradio as gr
import pandas as pd
from bcrypt import hashpw, gensalt, checkpw
# Path to the Excel file for user storage
USER_FILE = "users.xlsx"
# Load users from Excel
def load_users():
try:
df = pd.read_excel(USER_FILE)
return {row['Email']: row for _, row in df.iterrows()}
except FileNotFoundError:
df = pd.DataFrame(columns=["Name", "Phone", "Email", "Password"])
df.to_excel(USER_FILE, index=False)
return {}
# Save users to Excel
def save_users(users):
df = pd.DataFrame(users.values())
df.to_excel(USER_FILE, index=False)
# Signup user
def signup_user(name, phone, email, password):
users = load_users()
if email in users:
return False, "Email already exists. Please use a different email."
hashed_password = hashpw(password.encode(), gensalt()).decode()
users[email] = {"Name": name, "Phone": phone, "Email": email, "Password": hashed_password}
save_users(users)
return True, "Signup successful! Redirecting to the login page..."
# Validate login
def validate_login(email, password):
users = load_users()
if email in users and checkpw(password.encode(), users[email]["Password"].encode()):
return True, "Login successful! Redirecting to the menu page..."
return False, "Invalid email or password."
# Session management
active_sessions = {}
def login_user(email, password):
success, message = validate_login(email, password)
if success:
active_sessions[email] = True
return True, message
return False, message
def is_logged_in(email):
return active_sessions.get(email, 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 = """
"""
# Gradio app
def app():
with gr.Blocks() as demo:
gr.Markdown("## Secure Food Ordering System")
# State variable to track the current page
current_page = gr.State("signup") # Default page is Signup
# Signup Page
with gr.Row(visible=lambda state: state == "signup", state=current_page):
gr.Markdown("### Signup Page")
name = gr.Textbox(label="Name")
phone = gr.Textbox(label="Phone Number")
email = gr.Textbox(label="Email")
password = gr.Textbox(label="Password", type="password")
signup_btn = gr.Button("Signup")
signup_message = gr.Label()
# Signup callback
def handle_signup(name, phone, email, password):
message, next_page = signup_user(name, phone, email, password)
return message, next_page
signup_btn.click(
handle_signup,
inputs=[name, phone, email, password],
outputs=[signup_message, current_page],
)
# Login Page
with gr.Row(visible=lambda state: state == "login", state=current_page):
gr.Markdown("### Login Page")
login_email = gr.Textbox(label="Email")
login_password = gr.Textbox(label="Password", type="password")
login_btn = gr.Button("Login")
login_message = gr.Label()
# Login callback
def handle_login(email, password):
message, next_page = login_user(email, password)
return message, next_page
login_btn.click(
handle_login,
inputs=[login_email, login_password],
outputs=[login_message, current_page],
)
# Menu Page
with gr.Row(visible=lambda state: state == "menu", state=current_page):
gr.Markdown("### Menu Page (Accessible Only After Login)")
# Radio button for selecting preference
selected_preference = gr.Radio(
choices=["All", "Vegetarian", "Halal/Non-Veg", "Guilt-Free"],
value="All",
label="Choose a Preference",
)
# Output area for menu items
menu_output = gr.HTML(value=filter_menu("All"))
# 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")
# 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([selected_preference])
gr.Row(menu_output)
gr.Row(cart_output)
gr.Row(modal_window)
gr.Row(final_order_output)
gr.HTML(modal_and_cart_js)
return demo
if __name__ == "__main__":
app().launch()