Jayabalambika's picture
Create app.py
f83e458 verified
raw
history blame
5.36 kB
import gradio as gr
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import sqlite3
from datetime import datetime
import pandas as pd
from werkzeug.security import generate_password_hash, check_password_hash
import random
import string
# Database setup
conn = sqlite3.connect("attendance.db", check_same_thread=False)
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
email TEXT UNIQUE,
password TEXT,
verified INTEGER DEFAULT 0
)''')
cursor.execute('''CREATE TABLE IF NOT EXISTS attendance (
id INTEGER PRIMARY KEY,
email TEXT,
date TEXT,
status TEXT
)''')
# Helper Functions
def generate_random_password():
return ''.join(random.choices(string.ascii_letters + string.digits, k=8))
def send_email(to_email, subject, body):
try:
print(f"Sending email to {to_email}: {subject}\n{body}") # Mock email sending
return "Email sent successfully!"
except Exception as e:
return f"Failed to send email: {e}"
# User Registration
user_verification_tokens = {}
def register_user(email):
random_password = generate_random_password()
hashed_password = generate_password_hash(random_password)
try:
cursor.execute("INSERT INTO users (email, password) VALUES (?, ?)", (email, hashed_password))
conn.commit()
# Generate verification link
verification_token = ''.join(random.choices(string.ascii_letters + string.digits, k=16))
user_verification_tokens[email] = verification_token
verification_link = f"http://localhost/verify/{verification_token}" # Replace with actual host
send_email(email, "Verify Your Account", f"Click here to verify your account: {verification_link}\nYour temporary password: {random_password}")
return "Registration successful! Check your email to verify your account."
except sqlite3.IntegrityError:
return "Email already registered."
# Verify User
def verify_user(token):
for email, stored_token in user_verification_tokens.items():
if stored_token == token:
cursor.execute("UPDATE users SET verified = 1 WHERE email = ?", (email,))
conn.commit()
return "Account verified! Please log in and change your password."
return "Invalid verification token."
# Change Password
def change_password(email, old_password, new_password):
cursor.execute("SELECT password FROM users WHERE email = ?", (email,))
result = cursor.fetchone()
if result and check_password_hash(result[0], old_password):
hashed_new_password = generate_password_hash(new_password)
cursor.execute("UPDATE users SET password = ? WHERE email = ?", (hashed_new_password, email))
conn.commit()
return "Password changed successfully!"
return "Incorrect old password."
# Log Attendance
def log_attendance(email, status):
date = datetime.now().strftime("%Y-%m-%d")
cursor.execute("INSERT INTO attendance (email, date, status) VALUES (?, ?, ?)", (email, date, status))
conn.commit()
return "Attendance logged!"
# Generate Monthly Fees Report
def calculate_fees(email):
current_month = datetime.now().strftime("%Y-%m")
cursor.execute("SELECT COUNT(*) FROM attendance WHERE email = ? AND status = 'Present' AND date LIKE ?", (email, f"{current_month}%"))
count_present = cursor.fetchone()[0]
total_fees = count_present * 66.67
# Send email with fees details
send_email(email, "Monthly Fees", f"You attended {count_present} classes. Your total fees for the month: ${total_fees:.2f}")
return f"Fees calculated and email sent: ${total_fees:.2f}"
# Gradio Interface
def login(email, password):
cursor.execute("SELECT password, verified FROM users WHERE email = ?", (email,))
result = cursor.fetchone()
if result and check_password_hash(result[0], password):
if result[1] == 1:
return f"Welcome {email}!", gr.update(visible=True), email
else:
return "Account not verified. Check your email.", gr.update(visible=False), None
return "Invalid credentials.", gr.update(visible=False), None
with gr.Blocks() as app:
email_state = gr.State()
# Login Page
with gr.Row():
gr.Markdown("# Attendance Tracker")
with gr.Row():
email = gr.Textbox(label="Email")
password = gr.Textbox(label="Password", type="password")
login_button = gr.Button("Login")
login_message = gr.Textbox(label="Message", interactive=False)
attendance_section = gr.Group(visible=False)
with attendance_section:
with gr.Row():
gr.Markdown("### Log Attendance")
email_display = gr.Textbox(label="Email", interactive=False)
status = gr.Radio(["Present", "Absent"], label="Status")
log_button = gr.Button("Log Attendance")
attendance_message = gr.Textbox(label="Message", interactive=False)
login_button.click(login, inputs=[email, password], outputs=[login_message, attendance_section, email_state])
log_button.click(log_attendance, inputs=[email_state, status], outputs=[attendance_message])
app.launch()