Skip to content

Repository files navigation

AI Student Performance Predictor

FastAPI React TypeScript Vite Tailwind CSS PostgreSQL scikit-learn License

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.


🌟 Key Features

πŸ€– Machine Learning & Risk Analytics

  • 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.

πŸ›‘οΈ Isolated Demo Sandbox

  • Dedicated PostgreSQL Schema: Demo accounts (teacher_demo, student_demo) operate in a completely isolated demo database 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.

πŸ”’ Enterprise Security & Governance

  • Role-Based Access Control (RBAC): Support for admin, teacher, counselor, student, and parent roles 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).

πŸŽ“ Student Onboarding & Invites

  • 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.

🎨 Modern Frontend Experience

  • 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.

πŸ—οΈ High-Level Architecture

                                +---------------------------------------+
                                |          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)       |
                                +---------------------------------------+

🧰 Tech Stack

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

πŸ“ Project Structure

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

πŸ—„οΈ Database Design

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         |
                                                             +--------------------+

Table Summary

  • 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.

⚑ ML Pipeline & Inference

1. Feature Set

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

2. Model Training & Comparison

Running python src/models/train_model.py:

  • Loads processed student data from data/processed/students_processed.csv.
  • Trains and evaluates candidate models (LogisticRegression vs. RandomForestClassifier).
  • Computes metrics: Accuracy, Precision, Recall, F1-Score, and ROC-AUC.
  • Automatically exports the highest-performing model to models/random_forest.joblib.

3. Real-Time Inference Flow

  1. API receives features payload at POST /api/predict.
  2. Model Singleton (src/model_loader.py) loads models/random_forest.joblib.
  3. Input is cleaned, one-hot encoded, and aligned with training columns.
  4. Model calculates class probability using predict_proba().
  5. Risk Level is computed (Low, Medium, High, Critical).
  6. Result and recommended interventions are persisted to PostgreSQL and returned to the client.

πŸ”Œ API Endpoint Overview

System & Health

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

Authentication & Profile (/api/auth)

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

Admin Governance (/api/admin)

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

Students (/api/students)

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

Predictions & Risk (/api)

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

Batch Uploads (/api)

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

Enrollments & Student Linking (/api/enrollments)

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

πŸ’» Local Setup & Development

Prerequisites

  • Python 3.11+
  • Node.js 18+ & npm
  • PostgreSQL 15+ running locally (or a Neon database URI)

1. Clone the Repository

git clone https://github.com/MandarK07/ai_student_performance_predictor.git
cd ai_student_performance_predictor

2. Backend Setup

Create and Activate Virtual Environment

# Windows (PowerShell)
python -m venv venv
.\venv\Scripts\activate

# macOS / Linux
python3 -m venv venv
source venv/bin/activate

Install Backend Dependencies

pip install -r requirements.txt

Environment Variables Configuration

Create 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 Administrator

Initialize Database Schema

Create 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.sql

Start Backend Server

python -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

3. Frontend Setup

cd frontend/my-react-app
npm install

Frontend Environment File

Create frontend/my-react-app/.env.local (or .env):

VITE_API_BASE_URL=http://localhost:8000/api

Launch Frontend Dev Server

npm run dev
  • Frontend App: http://localhost:5173

πŸ”¬ Data & Model Training Workflow

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.py

πŸš€ Free-Tier Cloud Deployment Guide

This project is configured for cloud deployment using free-tier services:

  • Database: PostgreSQL on Neon
  • Backend API: FastAPI on Render
  • Frontend SPA: React on Vercel

1. Database Deployment (Neon)

  1. Create a free PostgreSQL project on Neon.
  2. Copy the connection string (ensure sslmode=require).
  3. Execute database/schema.sql against the Neon database using psql or Neon SQL Editor.

2. Backend Deployment (Render)

  1. Create a new Web Service on Render connected to this repository (or use render.yaml).
  2. Build Command: pip install -r requirements.txt
  3. Start Command: uvicorn src.main:app --host 0.0.0.0 --port $PORT
  4. Set Environment Variables:
    • DATABASE_URL: <your-neon-connection-string>
    • FRONTEND_URL: https://<your-vercel-app>.vercel.app
    • MODEL_PATH: models/random_forest.joblib
    • JWT_SECRET: <strong-random-secret>
    • ADMIN_USERNAME: admin
    • ADMIN_EMAIL: admin@studentai.com
    • ADMIN_PASSWORD: <strong-admin-password>

3. Frontend Deployment (Vercel)

  1. Import frontend/my-react-app into Vercel.
  2. Framework Preset: Vite
  3. Build Command: npm run build
  4. Output Directory: dist
  5. Environment Variable:
    • VITE_API_BASE_URL: https://<your-render-service>.onrender.com/api

🐳 Docker & CI/CD Deployment

Local Docker Run

# Build Docker image
docker build -t ai-student-performance-api .

# Run Container
docker run -d -p 8000:8000 --env-file .env ai-student-performance-api

Private Repository GHCR Workflow

The 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.


πŸ”’ Security & Best Practices

  • 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_sessions and 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.

🀝 Contributing

  1. Fork the Repository
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“œ License

Distributed under the MIT License. See LICENSE for more information.

Releases

Packages

Contributors

Languages