Spaces:
Sleeping

campuss / src /database.py
faiz3123's picture
Upload 10 files
746a47e verified
Raw History Blame Contribute Delete
20.2 kB
import psycopg2
import psycopg2.extras
import os
import pandas as pd
from datetime import datetime, date
import streamlit as st
import bcrypt
def get_db_connection():
"""Get database connection using environment variables"""
try:
# Try using DATABASE_URL first
database_url = os.getenv('DATABASE_URL')
if database_url:
conn = psycopg2.connect(database_url)
else:
# Fallback to individual parameters
conn = psycopg2.connect(
host=os.getenv('PGHOST', 'localhost'),
database=os.getenv('PGDATABASE', 'skillverse'),
user=os.getenv('PGUSER', 'postgres'),
password=os.getenv('PGPASSWORD', 'password'),
port=os.getenv('PGPORT', '5432')
)
return conn
except Exception as e:
st.error(f"Database connection failed: {str(e)}")
return None
def init_database():
"""Initialize database with required tables and sample data"""
conn = get_db_connection()
if not conn:
return False
try:
cur = conn.cursor()
# Create users table
cur.execute("""
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255),
name VARCHAR(255) NOT NULL,
role VARCHAR(50) NOT NULL CHECK (role IN ('student', 'faculty')),
roll_number INTEGER,
points INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Create achievements table
cur.execute("""
CREATE TABLE IF NOT EXISTS achievements (
id SERIAL PRIMARY KEY,
student_id INTEGER NOT NULL,
title VARCHAR(255) NOT NULL,
description TEXT,
proof_url VARCHAR(255),
status VARCHAR(50) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')),
points_awarded INTEGER DEFAULT 0,
reviewed_by INTEGER,
reviewed_at TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (student_id) REFERENCES users (id),
FOREIGN KEY (reviewed_by) REFERENCES users (id)
)
""")
# Create attendance table
cur.execute("""
CREATE TABLE IF NOT EXISTS attendance (
id SERIAL PRIMARY KEY,
date DATE NOT NULL,
student_id INTEGER NOT NULL,
class_name VARCHAR(255),
present BOOLEAN NOT NULL,
FOREIGN KEY (student_id) REFERENCES users (id)
)
""")
# Insert sample users if they don't exist
cur.execute("SELECT COUNT(*) FROM users")
user_count_result = cur.fetchone()
user_count = user_count_result[0] if user_count_result else 0
if user_count == 0:
# Insert sample students
students = [
('alex@student.com', 'Alex Johnson', 'student', 1001),
('sara@student.com', 'Sara Wilson', 'student', 1002),
('mike@student.com', 'Mike Chen', 'student', 1003),
('emily@student.com', 'Emily Davis', 'student', 1004),
('david@student.com', 'David Brown', 'student', 1005),
('lisa@student.com', 'Lisa Garcia', 'student', 1006),
('james@student.com', 'James Miller', 'student', 1007),
('anna@student.com', 'Anna Taylor', 'student', 1008),
('tom@student.com', 'Tom Anderson', 'student', 1009),
('sophie@student.com', 'Sophie Clark', 'student', 1010)
]
for email, name, role, roll in students:
cur.execute("""
INSERT INTO users (email, name, role, roll_number, points)
VALUES (%s, %s, %s, %s, %s)
""", (email, name, role, roll, 0))
# Insert sample faculty
cur.execute("""
INSERT INTO users (email, name, role, points)
VALUES ('prof.smith@faculty.com', 'Professor Smith', 'faculty', 0)
""")
# Insert sample faculty 2
cur.execute("""
INSERT INTO users (email, name, role, points)
VALUES ('dr.jones@faculty.com', 'Dr. Jones', 'faculty', 0)
""")
conn.commit()
cur.close()
conn.close()
# Update existing users with default passwords (demo mode only)
if os.getenv('DEMO_MODE', 'true').lower() == 'true':
update_existing_users_passwords()
return True
except Exception as e:
st.error(f"Database initialization failed: {str(e)}")
if conn:
conn.rollback()
if 'cur' in locals():
cur.close()
if conn:
conn.close()
return False
def get_user_by_role(role):
"""Get all users by role for authentication dropdown"""
conn = get_db_connection()
if not conn:
return []
try:
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("SELECT id, name, email, role, roll_number FROM users WHERE role = %s ORDER BY name", (role,))
users = cur.fetchall()
cur.close()
conn.close()
return users
except Exception as e:
st.error(f"Error fetching users: {str(e)}")
return []
def get_user_profile(user_id):
"""Get user profile with calculated attendance percentage"""
conn = get_db_connection()
if not conn:
return None
try:
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
# Get user basic info
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
user = cur.fetchone()
if not user:
cur.close()
conn.close()
return None
# Calculate attendance percentage
cur.execute("""
SELECT
COUNT(*) as total_classes,
SUM(CASE WHEN present THEN 1 ELSE 0 END) as attended_classes
FROM attendance
WHERE student_id = %s
""", (user_id,))
attendance_data = cur.fetchone()
if attendance_data and attendance_data['total_classes'] and attendance_data['total_classes'] > 0:
attendance_percentage = (attendance_data['attended_classes'] / attendance_data['total_classes']) * 100
else:
attendance_percentage = 0
# Get user's rank
cur.execute("""
SELECT COUNT(*) + 1 as rank
FROM users
WHERE role = 'student' AND points > %s
""", (user['points'],))
rank_data = cur.fetchone()
user_profile = dict(user)
user_profile['attendance_percentage'] = round(attendance_percentage, 1)
user_profile['rank'] = rank_data['rank'] if rank_data else 1
cur.close()
conn.close()
return user_profile
except Exception as e:
st.error(f"Error fetching user profile: {str(e)}")
return None
def get_user_achievements(user_id):
"""Get all achievements for a user"""
conn = get_db_connection()
if not conn:
return []
try:
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
SELECT a.*, u.name as reviewed_by_name
FROM achievements a
LEFT JOIN users u ON a.reviewed_by = u.id
WHERE a.student_id = %s
ORDER BY a.created_at DESC
""", (user_id,))
achievements = cur.fetchall()
cur.close()
conn.close()
return achievements
except Exception as e:
st.error(f"Error fetching achievements: {str(e)}")
return []
def submit_achievement(student_id, title, description, proof_url):
"""Submit a new achievement"""
conn = get_db_connection()
if not conn:
return False
try:
cur = conn.cursor()
cur.execute("""
INSERT INTO achievements (student_id, title, description, proof_url)
VALUES (%s, %s, %s, %s)
""", (student_id, title, description, proof_url))
conn.commit()
cur.close()
conn.close()
return True
except Exception as e:
st.error(f"Error submitting achievement: {str(e)}")
conn.rollback()
return False
def get_pending_achievements():
"""Get all pending achievements for faculty review"""
conn = get_db_connection()
if not conn:
return []
try:
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
SELECT a.*, u.name as student_name, u.roll_number
FROM achievements a
JOIN users u ON a.student_id = u.id
WHERE a.status = 'pending'
ORDER BY a.created_at ASC
""", )
achievements = cur.fetchall()
cur.close()
conn.close()
return achievements
except Exception as e:
st.error(f"Error fetching pending achievements: {str(e)}")
return []
def review_achievement(achievement_id, action, points, faculty_id):
"""Approve or reject an achievement"""
conn = get_db_connection()
if not conn:
return False
try:
cur = conn.cursor()
# Update achievement status
cur.execute("""
UPDATE achievements
SET status = %s, points_awarded = %s, reviewed_by = %s, reviewed_at = %s
WHERE id = %s
""", (action, points if action == 'approved' else 0, faculty_id, datetime.now(), achievement_id))
# If approved, update student's total points
if action == 'approved':
cur.execute("""
UPDATE users
SET points = points + %s
WHERE id = (SELECT student_id FROM achievements WHERE id = %s)
""", (points, achievement_id))
conn.commit()
cur.close()
conn.close()
return True
except Exception as e:
st.error(f"Error reviewing achievement: {str(e)}")
conn.rollback()
return False
def get_leaderboard():
"""Get student leaderboard ordered by points"""
conn = get_db_connection()
if not conn:
return []
try:
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
SELECT
name,
roll_number,
points,
ROW_NUMBER() OVER (ORDER BY points DESC, name ASC) as rank
FROM users
WHERE role = 'student'
ORDER BY points DESC, name ASC
""")
leaderboard = cur.fetchall()
cur.close()
conn.close()
return leaderboard
except Exception as e:
st.error(f"Error fetching leaderboard: {str(e)}")
return []
def upload_attendance(class_name, date, roll_numbers):
"""Upload attendance for multiple students"""
conn = get_db_connection()
if not conn:
return False
try:
cur = conn.cursor()
# Get all students
cur.execute("SELECT id, roll_number FROM users WHERE role = 'student'")
students = cur.fetchall()
# Mark attendance for all students
for student_id, roll_number in students:
present = roll_number in roll_numbers
# Check if attendance already exists for this date and student
cur.execute("""
SELECT id FROM attendance
WHERE date = %s AND student_id = %s AND class_name = %s
""", (date, student_id, class_name))
existing = cur.fetchone()
if existing:
# Update existing record
cur.execute("""
UPDATE attendance
SET present = %s
WHERE date = %s AND student_id = %s AND class_name = %s
""", (present, date, student_id, class_name))
else:
# Insert new record
cur.execute("""
INSERT INTO attendance (date, student_id, class_name, present)
VALUES (%s, %s, %s, %s)
""", (date, student_id, class_name, present))
conn.commit()
cur.close()
conn.close()
return True
except Exception as e:
st.error(f"Error uploading attendance: {str(e)}")
conn.rollback()
return False
def hash_password(password):
"""Hash a password for storing in database"""
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed.decode('utf-8')
def verify_password(password, hashed):
"""Verify a password against its hash"""
return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))
def authenticate_user(email, password):
"""Authenticate user with email and password"""
conn = get_db_connection()
if not conn:
return None
try:
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("SELECT * FROM users WHERE email = %s", (email,))
user = cur.fetchone()
if user and user['password_hash'] and verify_password(password, user['password_hash']):
cur.close()
conn.close()
return dict(user)
cur.close()
conn.close()
return None
except Exception as e:
st.error(f"Authentication failed: {str(e)}")
if conn:
conn.close()
return None
def register_user(email, password, name, role, roll_number=None):
"""Register a new user"""
conn = get_db_connection()
if not conn:
return False
try:
cur = conn.cursor()
# Check if email already exists
cur.execute("SELECT id FROM users WHERE email = %s", (email,))
existing_user = cur.fetchone()
if existing_user:
st.error("Email already registered")
if conn:
cur.close()
conn.close()
return False
# Hash password and create user
password_hash = hash_password(password)
if role == 'student' and roll_number:
cur.execute("""
INSERT INTO users (email, password_hash, name, role, roll_number, points)
VALUES (%s, %s, %s, %s, %s, 0)
""", (email, password_hash, name, role, roll_number))
else:
cur.execute("""
INSERT INTO users (email, password_hash, name, role, points)
VALUES (%s, %s, %s, %s, 0)
""", (email, password_hash, name, role))
conn.commit()
cur.close()
conn.close()
return True
except Exception as e:
st.error(f"Registration failed: {str(e)}")
if conn:
conn.rollback()
conn.close()
return False
def update_existing_users_passwords():
"""Update existing demo users with default passwords for testing"""
conn = get_db_connection()
if not conn:
return False
try:
cur = conn.cursor()
# Update all users without password_hash to have default password "password123"
default_password_hash = hash_password("password123")
cur.execute("""
UPDATE users
SET password_hash = %s
WHERE password_hash IS NULL OR password_hash = ''
""", (default_password_hash,))
conn.commit()
cur.close()
conn.close()
return True
except Exception as e:
st.error(f"Error updating passwords: {str(e)}")
if conn:
conn.rollback()
conn.close()
return False
def get_student_portfolio(student_id):
"""Get complete student portfolio with achievements and stats"""
conn = get_db_connection()
if not conn:
return None
try:
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
# Get student profile
cur.execute("""
SELECT id, name, email, roll_number, points, created_at
FROM users
WHERE id = %s AND role = 'student'
""", (student_id,))
student = cur.fetchone()
if not student:
cur.close()
conn.close()
return None
# Get student achievements with approval details
cur.execute("""
SELECT a.*, u.name as reviewed_by_name
FROM achievements a
LEFT JOIN users u ON a.reviewed_by = u.id
WHERE a.student_id = %s AND a.status = 'approved'
ORDER BY a.reviewed_at DESC
""", (student_id,))
achievements = cur.fetchall()
# Get student rank
cur.execute("""
SELECT COUNT(*) + 1 as rank
FROM users
WHERE role = 'student' AND points > %s
""", (student['points'],))
rank_data = cur.fetchone()
# Calculate achievement stats
cur.execute("""
SELECT
COUNT(*) as total_achievements,
SUM(points_awarded) as total_points_from_achievements,
AVG(points_awarded) as avg_points_per_achievement
FROM achievements
WHERE student_id = %s AND status = 'approved'
""", (student_id,))
stats = cur.fetchone()
# Calculate attendance percentage
cur.execute("""
SELECT
COUNT(*) as total_classes,
SUM(CASE WHEN present THEN 1 ELSE 0 END) as attended_classes
FROM attendance
WHERE student_id = %s
""", (student_id,))
attendance_data = cur.fetchone()
portfolio = {
'student': dict(student),
'achievements': [dict(a) for a in achievements],
'rank': rank_data['rank'] if rank_data else 1,
'stats': dict(stats) if stats else {
'total_achievements': 0,
'total_points_from_achievements': 0,
'avg_points_per_achievement': 0
},
'attendance_percentage': (
(attendance_data['attended_classes'] / attendance_data['total_classes'] * 100)
if attendance_data and attendance_data['total_classes'] > 0 else 0
)
}
cur.close()
conn.close()
return portfolio
except Exception as e:
st.error(f"Error fetching student portfolio: {str(e)}")
if conn:
conn.close()
return None
def get_all_students_for_portfolio():
"""Get all students for portfolio browsing"""
conn = get_db_connection()
if not conn:
return []
try:
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
SELECT
id, name, roll_number, points,
ROW_NUMBER() OVER (ORDER BY points DESC, name ASC) as rank
FROM users
WHERE role = 'student'
ORDER BY points DESC, name ASC
""")
students = cur.fetchall()
cur.close()
conn.close()
return students
except Exception as e:
st.error(f"Error fetching students: {str(e)}")
return []