An enterprise-grade, full-stack academic analytics platform designed to predict student performance, detect early academic risk, and enable timely educational interventions.
The platform pairs a responsive React 19 + TypeScript frontend with a FastAPI REST backend, a PostgreSQL database (featuring isolated demo sandboxing), and a scikit-learn Machine Learning pipeline for single-student and bulk batch predictions.
- Early Risk Forecasting: Predicts academic outcomes (GPA range, Risk Level, Confidence Score) using random forest classification models trained on academic and behavioral signals.
- Behavioral Signal Processing: Analyzes attendance rates, study hours, GPA history, assignment scores, exam averages, class participation, and late submission metrics.
- Batch CSV Processing: Upload CSV datasets for bulk prediction with error validation and batch history tracking.
- Actionable Interventions: Generates automated recommendations and tracks counselor/teacher intervention workflows for at-risk students.
- Dedicated PostgreSQL Schema: Demo accounts (
teacher_demo,student_demo) operate in a completely isolateddemodatabase schema, preventing any modification or leakage of production data. - Automatic Background Reseeding: Periodic automated schema resets (
DEMO_RESET_INTERVAL_MINUTES=60) maintain a clean sandbox environment. - Rate Limiting & Safety: Demo-specific rate limiting (
DemoRateLimitMiddleware) and non-demo write guards (require_non_demo) protect the system against abuse.
- Role-Based Access Control (RBAC): Support for
admin,teacher,counselor,student, andparentroles with strict route & resource authorization. - Dual-Token Authentication: JWT Access Tokens + Rotating Refresh Tokens with persistent session tracking in PostgreSQL (
auth_sessions). - Audit Logging: Comprehensive activity tracking (
audit_log) recording IP addresses, endpoint calls, state changes (old/new values), and permission checks. - Account Lockout Protection: Automatic account locks after repeated failed login attempts (
MAX_FAILED_LOGIN_ATTEMPTS=5).
- Invite Token Workflow: Secure, token-based enrollment invitation links generated by admins/teachers for student onboarding.
- Account Linking: Self-service student linking request system allowing students to request account linkage to academic records with admin review/approval.
- Guardian Integration: Parent/guardian contact tracking with primary contact flags and direct communication options.
- Interactive Landing Page: Feature showcase, live ML playground, role-selector demo login, and responsive dark/light aesthetics.
- Role-Tailored Dashboards: Dedicated views for Admins (system analytics, user governance), Teachers (class metrics, CSV bulk upload), and Students (personal progress, risk indicators).
- Cold-Start & Connection Management: UX notices for cloud backend spin-ups (Render free tier) and frontend request batching to prevent DB connection pool (
QueuePool) exhaustion.
+---------------------------------------+
| React 19 + Vite SPA |
| (Tailwind CSS, Framer Motion) |
+---------------------------------------+
|
HTTPS / JSON API
|
v
+---------------------------------------------------------------------------------------------------+
| FastAPI Backend |
| |
| +---------------------------+ +-------------------------------+ +-------------------------+ |
| | DemoScopeMiddleware | | DemoRateLimitMiddleware | | CORSMiddleware | |
| +---------------------------+ +-------------------------------+ +-------------------------+ |
| | |
| +---------------------------------------------------------------------------------------------+ |
| | Routers (Auth, Students, Predict, etc.) | |
| +---------------------------------------------------------------------------------------------+ |
| | |
| +--------------------------------------+-----------------------------------+ |
| | (Production Scope) | (Demo) |
| v v |
| +-------------------+ +--------------------+ +--------------------+ +---------------+ |
| | SQLAlchemy ORM | | Joblib ML Engine | | SMTP Email Svc | | Demo Schema | |
| | (public schema) | | (RandomForest) | | (Invites/Alerts) | | (demo schema)| |
| +-------------------+ +--------------------+ +--------------------+ +---------------+ |
+---------------------------------------------------------------------------------------------------+
|
v
+---------------------------------------+
| PostgreSQL Database |
| (Neon / Local PostgreSQL) |
+---------------------------------------+
| Layer | Technologies |
|---|---|
| Backend | Python 3.11+, FastAPI, SQLAlchemy, Pydantic v2, Uvicorn, Passlib (bcrypt), PyJWT / python-jose, Starlette |
| Frontend | React 19, TypeScript 5.8, Vite 7, Tailwind CSS 3, Framer Motion 12, Recharts, Lucide Icons, React Router 7, React Hook Form 7 |
| Database | PostgreSQL 15+ (Hosted on Neon or Local), SQLAlchemy ORM |
| Machine Learning | pandas, scikit-learn, joblib, NumPy |
| DevOps & Deploy | Render (Backend API), Vercel (Frontend SPA), Docker (Multi-stage), GitHub Actions & GHCR |
ai_student_performance_predictor/
βββ .github/
β βββ workflows/
β βββ publish-backend-image.yml # GitHub Actions CI/CD for Docker image publishing to GHCR
βββ data/
β βββ raw/ # Raw input datasets
β βββ processed/ # Processed features CSV
β βββ uploads/ # Uploaded CSV batch files
βββ database/
β βββ schema.sql # PostgreSQL schema DDL, triggers, and views
β βββ queries.sql # Common analytical SQL queries
βββ frontend/
β βββ my-react-app/
β βββ public/ # Static assets
β βββ src/
β β βββ api/ # API wrapper modules (http, auth, predict, students, etc.)
β β βββ components/ # UI components (Button, Card, Layout, Tables, Modals)
β β βββ context/ # AuthContext for state & token management
β β βββ lib/ # Utility helpers (cn, formatting)
β β βββ pages/ # Home, Login, RegisterUser, MainDashboard, StudentDashboard,
β β β # Predictor, PredictionResult, Students, AtRiskStudents,
β β β # Analytics, UsersManagement, AuditLogs, Invites, AcceptInvite,
β β β # EnrollmentPending, About, Settings, AccessDenied
β β βββ App.tsx # React Router setup & protected route guards
β β βββ main.tsx # SPA entrypoint
β βββ package.json
β βββ vercel.json # Vercel SPA rewrite configuration
β βββ vite.config.js # Vite build configuration & dev proxy
βββ models/
β βββ random_forest.joblib # Trained Random Forest model artifact
βββ src/
β βββ api/ # FastAPI Route Handlers
β β βββ admin.py # User management & audit logs endpoints
β β βββ auth.py # Login, signup, refresh, logout, profile endpoints
β β βββ dashboard.py # Student me/dashboard summary endpoint
β β βββ enrollments.py # Invites & student linking request workflows
β β βββ middleware.py # Demo scope & demo rate-limiting middleware
β β βββ predict.py # Single & batch prediction endpoints
β β βββ students.py # Student CRUD, search, performance & profile endpoints
β β βββ upload.py # CSV batch upload endpoint
β βββ auth/ # Security, JWT tokens, RBAC dependencies & bootstrapper
β β βββ bootstrap.py # Startup admin creation & legacy demo decommissioning
β β βββ dependencies.py # Role & self-access authorization guards
β β βββ security.py # Password hashing & JWT generation/verification
β βββ core/
β β βββ config.py # Pydantic BaseSettings application configuration
β βββ database/ # SQLAlchemy ORM, Engine, CRUD & Demo Sandbox
β β βββ connection.py # Engine setup & DB session generators
β β βββ crud.py # Database query functions
β β βββ demo.py # Isolated demo schema lifecycle & reset logic
β β βββ models.py # SQLAlchemy ORM model definitions
β βββ features/
β β βββ preprocess.py # ML feature extraction & preprocessing pipeline
β βββ models/
β β βββ train_model.py # Model training, comparison & artifact export script
β βββ scripts/ # Dataset generator & data ingestion scripts
β βββ services/
β β βββ email_service.py # Email notification service for student invitations
β βββ main.py # FastAPI application entrypoint & middleware setup
β βββ model_loader.py # Singleton ML model artifact loader
βββ Dockerfile # Production multi-stage Docker build
βββ render.yaml # Render deployment configuration
βββ requirements.txt # Backend Python dependencies
βββ README.md
The PostgreSQL database uses a normalized relational schema supporting full data tracking, session management, and audit governance.
+------------------+ +----------------------+ +--------------------+
| students |<-------| academic_records | | users |
+------------------+ +----------------------+ +--------------------+
| student_id (PK) | | record_id (PK) | | user_id (PK) |
| student_code | | student_id (FK) | | username |
| first_name | | academic_year | | email |
| last_name | | semester | | password_hash |
| email | | gpa | | role |
| date_of_birth | | attendance_rate | | student_id (FK) |
| status | | study_hours_per_week | | is_active, is_demo |
+------------------+ +----------------------+ +--------------------+
| | |
| +--------------------+ |
v v v
+---------------+ +--------------------+ +--------------------+
| parents | | predictions | | auth_sessions |
+---------------+ +--------------------+ +--------------------+
| parent_id(PK) | | prediction_id (PK) | | session_id (PK) |
| student_id(FK)| | student_id (FK) | | user_id (FK) |
| name | | model_id (FK) | | refresh_token_hash |
| relationship | | predicted_gpa | | expires_at |
| phone, email | | risk_level | | revoked_at |
+---------------+ | confidence_score | +--------------------+
+--------------------+ |
| v
v +--------------------+
+--------------------+ | audit_log |
| interventions | +--------------------+
+--------------------+ | log_id (PK) |
| intervention_id(PK)| | user_id (FK) |
| prediction_id (FK) | | action |
| intervention_type | | table_name |
| priority, status | | old/new_values |
+--------------------+ | ip_address |
+--------------------+
students: Core demographic and academic status info.parents: Student guardian contact details and primary contact indicators.academic_records: Historical semester-by-semester metrics (GPA, attendance, study hours, participation, late submissions).courses,enrollments,grades: Course catalog, student course enrollments, and granular assessment scores.ml_models: Metadata, metrics (accuracy, precision, recall, F1), and hyperparameters for trained models.predictions: Generated ML prediction records, feature inputs snapshot, predicted GPA, confidence score, and risk level.interventions: Action items assigned to educators to support at-risk students.users: System user accounts with roles (admin,teacher,counselor,student,parent).auth_sessions: Refresh token session tracking with token family rotation and remote revocation.audit_log: Security and governance log tracking user actions, IP addresses, and state changes.upload_history: Tracking history and error summaries for CSV batch uploads.enrollment_invites: Invitation tokens for onboarding new students.linking_requests: Student self-service linking requests pending administrative approval.
Incoming predictions pass through src/features/preprocess.py to process:
- Demographics:
gender,age,parent_education - Academic Metrics:
attendance_rate,study_hours,previous_gpa,final_grade,assignment_score_avg,exam_score_avg - Behavioral Signals:
class_participation,late_submissions,previous_gpa_sem1,previous_gpa_sem2 - Engineered Features:
hours_per_gpa,grade_trend
Running python src/models/train_model.py:
- Loads processed student data from
data/processed/students_processed.csv. - Trains and evaluates candidate models (
LogisticRegressionvs.RandomForestClassifier). - Computes metrics: Accuracy, Precision, Recall, F1-Score, and ROC-AUC.
- Automatically exports the highest-performing model to
models/random_forest.joblib.
- API receives features payload at
POST /api/predict. - Model Singleton (
src/model_loader.py) loadsmodels/random_forest.joblib. - Input is cleaned, one-hot encoded, and aligned with training columns.
- Model calculates class probability using
predict_proba(). - Risk Level is computed (
Low,Medium,High,Critical). - Result and recommended interventions are persisted to PostgreSQL and returned to the client.
| Method | Endpoint | Access | Description |
|---|---|---|---|
GET |
/ |
Public | HTML landing & API status page |
GET |
/health |
Public | System and database connectivity check |
GET |
/api/stats |
Public | Summary statistics endpoint |
| Method | Endpoint | Access | Description |
|---|---|---|---|
POST |
/api/auth/login |
Public | Authenticate user & return JWT token pair |
POST |
/api/auth/signup |
Public | Self-registration endpoint (Student/Teacher) |
POST |
/api/auth/register |
Admin | Admin endpoint to register user with explicit role |
POST |
/api/auth/refresh |
Public | Exchange refresh token for new access token |
POST |
/api/auth/logout |
Authenticated | Revoke current refresh token session |
POST |
/api/auth/logout-all |
Authenticated | Revoke all active refresh sessions for user |
GET |
/api/auth/me |
Authenticated | Fetch current authenticated user profile |
| Method | Endpoint | Access | Description |
|---|---|---|---|
GET |
/api/admin/users |
Admin | List all system users with status & roles |
PATCH |
/api/admin/users/{id} |
Admin | Update user role or active status |
DELETE |
/api/admin/users/{id} |
Admin | Soft-delete user (deactivate & revoke sessions) |
GET |
/api/admin/audit-logs |
Admin | Retrieve recent system audit logs |
| Method | Endpoint | Access | Description |
|---|---|---|---|
GET |
/api/students |
Admin, Teacher | Paginated list of students |
POST |
/api/students |
Admin, Teacher | Create a new student record |
GET |
/api/students/search |
Admin, Teacher | Search students by name or code |
GET |
/api/students/{code} |
Admin, Teacher, Self | Fetch student details |
GET |
/api/students/{code}/performance |
Admin, Teacher, Self | Fetch student performance metrics |
GET |
/api/students/{code}/profile |
Admin, Teacher, Self | Complete profile data with predictions |
PUT |
/api/students/{code} |
Admin, Teacher | Update student record |
DELETE |
/api/students/{code} |
Admin | Delete student record |
| Method | Endpoint | Access | Description |
|---|---|---|---|
POST |
/api/predict |
Admin, Teacher, Self | Run ML prediction for a student |
GET |
/api/predictions/{code} |
Admin, Teacher, Self | Get prediction history for a student |
GET |
/api/at-risk-students |
Admin, Teacher | List all students flagged as High or Critical risk |
GET/POST |
/api/at-risk-students/{code}/guardian-contact |
Admin, Teacher | View or update guardian contact details |
POST |
/api/at-risk-students/{code}/interventions |
Admin, Teacher | Log an intervention for an at-risk student |
| Method | Endpoint | Access | Description |
|---|---|---|---|
POST |
/api/upload-csv |
Admin, Teacher | Upload CSV dataset for bulk ML predictions |
GET |
/api/upload-history |
Admin, Teacher | Retrieve history of batch CSV uploads |
| Method | Endpoint | Access | Description |
|---|---|---|---|
POST |
/api/enrollments/preview |
Admin, Teacher | Preview student record match for email/code |
POST |
/api/enrollments/invite |
Admin, Teacher | Create an enrollment invite link |
GET |
/api/enrollments/status/{token} |
Public | Check validity of an invite token |
POST |
/api/enrollments/accept |
Public | Accept invite token & complete account setup |
POST |
/api/enrollments/request-link |
Student | Request manual linkage to a student record |
GET |
/api/enrollments/my-request |
Student | View pending linking request status |
GET |
/api/enrollments/link-requests/pending |
Admin, Teacher | List pending linking requests |
POST |
/api/enrollments/link-requests/{id}/approve |
Admin, Teacher | Approve student linking request |
POST |
/api/enrollments/link-requests/{id}/reject |
Admin, Teacher | Reject student linking request |
- Python 3.11+
- Node.js 18+ & npm
- PostgreSQL 15+ running locally (or a Neon database URI)
git clone https://github.com/MandarK07/ai_student_performance_predictor.git
cd ai_student_performance_predictor# Windows (PowerShell)
python -m venv venv
.\venv\Scripts\activate
# macOS / Linux
python3 -m venv venv
source venv/bin/activatepip install -r requirements.txtCreate a .env file in the project root based on .env.example:
# Database Configuration
DATABASE_URL=postgresql://postgres:password@localhost:5432/student_performance_db
# Application Settings
APP_ENV=development
DEBUG=True
SECRET_KEY=super-secret-key-change-in-production
# Authentication Settings
JWT_SECRET=super-secret-jwt-key-change-in-production
JWT_ALGORITHM=HS256
JWT_ISSUER=ai-student-performance-predictor
ACCESS_TOKEN_EXPIRE_MINUTES=10080
REFRESH_TOKEN_EXPIRE_DAYS=7
MAX_FAILED_LOGIN_ATTEMPTS=5
ACCOUNT_LOCK_MINUTES=15
# CORS Settings (comma-separated origins)
FRONTEND_URL=http://localhost:5173,https://ai-student-performance-predictor.vercel.app
# Model Configuration
MODEL_PATH=models/random_forest.joblib
# File Upload Settings
MAX_UPLOAD_SIZE=10485760
UPLOAD_DIR=data/uploads/
# Admin Bootstrap Credentials
ADMIN_USERNAME=admin
ADMIN_EMAIL=admin@studentai.com
ADMIN_PASSWORD=admin123
ADMIN_FULL_NAME=System AdministratorCreate the local PostgreSQL database, then apply database/schema.sql:
# Using psql CLI
psql -U postgres -c "CREATE DATABASE student_performance_db;"
psql -U postgres -d student_performance_db -f database/schema.sqlpython -m uvicorn src.main:app --reload --host 0.0.0.0 --port 8000- API Base:
http://localhost:8000 - Interactive Swagger Docs:
http://localhost:8000/docs - Redoc Documentation:
http://localhost:8000/redoc
cd frontend/my-react-app
npm installCreate frontend/my-react-app/.env.local (or .env):
VITE_API_BASE_URL=http://localhost:8000/apinpm run dev- Frontend App:
http://localhost:5173
If you want to regenerate synthetic data and retrain the Machine Learning model:
# 1. Generate synthetic student data
python src/scripts/generate_dataset.py
# 2. Ingest and preprocess raw dataset
python src/scripts/ingest_data.py
# 3. Train models, evaluate performance & export the best artifact to models/
python src/models/train_model.pyThis project is configured for cloud deployment using free-tier services:
- Create a free PostgreSQL project on Neon.
- Copy the connection string (ensure
sslmode=require). - Execute
database/schema.sqlagainst the Neon database usingpsqlor Neon SQL Editor.
- Create a new Web Service on Render connected to this repository (or use
render.yaml). - Build Command:
pip install -r requirements.txt - Start Command:
uvicorn src.main:app --host 0.0.0.0 --port $PORT - Set Environment Variables:
DATABASE_URL:<your-neon-connection-string>FRONTEND_URL:https://<your-vercel-app>.vercel.appMODEL_PATH:models/random_forest.joblibJWT_SECRET:<strong-random-secret>ADMIN_USERNAME:adminADMIN_EMAIL:admin@studentai.comADMIN_PASSWORD:<strong-admin-password>
- Import
frontend/my-react-appinto Vercel. - Framework Preset: Vite
- Build Command:
npm run build - Output Directory:
dist - Environment Variable:
VITE_API_BASE_URL:https://<your-render-service>.onrender.com/api
# Build Docker image
docker build -t ai-student-performance-api .
# Run Container
docker run -d -p 8000:8000 --env-file .env ai-student-performance-apiThe repository includes a GitHub Actions workflow (.github/workflows/publish-backend-image.yml).
On push to main, it automatically builds an linux/amd64 Docker image and publishes it to GitHub Container Registry:
ghcr.io/<your-github-username>/ai-student-performance-api:latest
Render can pull directly from this private GHCR image for deployments.
- Isolated Demo Sandbox: Demo operations run inside a separate PostgreSQL schema (
demo) with rate-limiting and non-demo operational guards. - Password Security: Passwords are hashed using bcrypt with salt rounds.
- Session Revocation: JWT refresh tokens are tracked in
auth_sessionsand can be invalidated globally or individually. - Audit Logging: All access control events (grants, denials, role changes) log client IP address, action type, and JSON state diffs to
audit_log. - CORS Safeguards: Strict CORS origin verification with fallback headers for unhandled exception responses.
- Fork the Repository
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature') - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
Distributed under the MIT License. See LICENSE for more information.