Skip to content

finalflash159/exam-hub

Repository files navigation

Exam Hub - Online Exam & Practice Platform with AI Generation

AI-powered exam generation system — Document analysis & multiple-choice question creation

Exam Hub uses AI to analyze documents (PDF, DOCX), detect images/tables, and automatically generate multiple-choice questions.


System Architecture

flowchart TB
    subgraph Client["🌐 Client"]
        FE[React App<br/>Port 5173]
    end

    subgraph Server["⚙️ Backend API - FastAPI"]
        API[REST API<br/>Port 5001]

        subgraph Services["📦 Services"]
            AUTH[Auth Service]
            EXAM[Exam Service]
            GENAI[GenAI Service]
            VISION[Vision Service]
            UPLOAD[Upload Service]
        end

        subgraph AI["🤖 AI Providers"]
            OPENAI[OpenAI GPT-4]
            GEMINI[Google Gemini]
        end
    end

    subgraph ML["🧠 ML Models"]
        DETR[Deformable DETR<br/>DocLayNet]
        GEMINI_VISION[Gemini Vision<br/>Image Analysis]
    end

    subgraph Data["💾 Data Layer"]
        DB[(SQLite<br/>PostgreSQL)]
        REDIS[(Redis)]
        FILES[File Storage<br/>./uploads]
    end

    FE <-->|HTTP/REST| API
    API <--> AUTH
    API <--> EXAM
    API <--> UPLOAD

    EXAM <--> GENAI
    GENAI <--> OPENAI
    GENAI <--> GEMINI

    EXAM <--> VISION
    VISION <--> DETR
    VISION <--> GEMINI_VISION

    AUTH <--> DB
    EXAM <--> DB
    UPLOAD <--> DB
    UPLOAD <--> FILES

    GENAI <--> REDIS
    VISION <--> REDIS
Loading

Exam Generation Flow

sequenceDiagram
    participant User
    participant FE as Frontend
    participant API as FastAPI
    participant SVC as Services
    participant GENAI as GenAI
    participant VISION as Vision
    participant AI as OpenAI/Gemini
    participant DB as Database

    User->>FE: Upload PDF document
    FE->>API: POST /upload
    API->>DB: Save file metadata
    Note over API,DB: File saved to ./uploads

    User->>FE: Generate exam<br/>(Vision enabled)
    FE->>API: POST /exam/generate<br/>enable_vision=true<br/>file_id=xxx

    API->>SVC: generate_exam_from_text()
    SVC->>VISION: analyze_document()

    rect rgb(0.9, 0.9, 1)
        Note over VISION: Vision Pipeline
        VISION->>VISION: Render PDF to images
        VISION->>DETR: Detect figures/tables
        VISION->>VISION: Extract images
        VISION->>GEMINI_VISION: Analyze with AI
        VISION-->>SVC: vision_context + image_refs
    end

    SVC->>GENAI: generate_exam(prompt + vision_context)
    GENAI->>AI: Send prompt
    AI-->>GENAI: Questions JSON
    GENAI-->>SVC: Normalized questions

    Note over SVC: Inject image_refs into questions

    SVC->>DB: Save exam
    DB-->>SVC: exam_id
    SVC-->>API: Questions with images
    API-->>FE: Success + questions

    User->>FE: Take exam
    FE->>API: GET /exam/{id}
    API-->>FE: Exam with image descriptions
    Note over FE: Display images in questions
Loading

✨ Features

AI Exam Generation

  • Multi-Provider: OpenAI GPT-4, Google Gemini, Mock (testing)
  • Smart Prompts: YAML-based Jinja2 templates
  • Auto Retry: Exponential backoff on API failures
  • Response Caching: Redis-based cache
  • Difficulty Balance: Auto, Easy, Medium, Hard
  • Multi-language: Vietnamese, English

👁️ Vision Document Analysis

  • Figure Detection: Deformable DETR (DocLayNet model)
  • Table Detection: Heuristic-based detection
  • Image Analysis: Gemini AI for descriptions
  • Context Injection: Rich visual context in prompts

Authentication & Security

  • JWT authentication (access + refresh tokens)
  • Argon2 password hashing
  • Role-based access control (USER, ADMIN)
  • Rate limiting (Redis-based)
  • Input validation (Pydantic)

File Management

  • Secure upload with validation
  • SHA-256 duplicate detection
  • Content extraction (PDF, DOCX, TXT)
  • User-scoped file management

🚀 Quick Start

Prerequisites

Requirement Version
Python 3.11+
Node.js 18+
Redis 7+ (optional)
OpenAI API Key -
Gemini API Key -

1. Clone & Install

git clone <repo-url>
cd exam-hub

2. Backend Setup

cd backend

# Create virtual environment
python -m venv venv
source venv/bin/activate  # Linux/macOS
# venv\Scripts\activate  # Windows

# Install dependencies
pip install -r requirements.txt

# Configure environment
cp .env.example .env
# Edit .env with your API keys:
#   OPENAI_API_KEY=sk-...
#   GEMINI_API_KEY=AI...
#   DEFAULT_AI_PROVIDER=openai

3. Initialize Database

# Start server (auto-creates DB)
python -m app.main

# OR manually initialize:
python -c "from app.database.connection import init_database; import asyncio; asyncio.run(init_database())"

4. Create Admin User

python -c "
from app.database.connection import get_db_session
from app.models.user import User, UserRole
from app.core.security import get_password_hash
import asyncio

async def create_admin():
    async for session in get_db_session():
        user = User(
            email='admin@exam.com',
            hashed_password=get_password_hash('admin123'),
            full_name='Admin',
            role=UserRole.ADMIN,
            is_active=True,
            email_verified=True
        )
        session.add(user)
        await session.commit()
        print('Admin created: admin@exam.com / admin123')
        break

asyncio.run(create_admin())
"

5. Frontend Setup

cd exam-app

# Install dependencies
npm install

# Configure environment
echo "VITE_API_URL=http://localhost:5001" > .env

# Start dev server
npm run dev

6. Access

Service URL
Frontend http://localhost:5173
Backend API http://localhost:5001
API Docs http://localhost:5001/docs
Health http://localhost:5001/health

Default Login: admin@exam.com / admin123


Project Structure

exam-hub/
├── exam-app/                    # Frontend (React + Vite + MUI)
│   ├── src/
│   │   ├── features/           # Feature modules
│   │   │   ├── auth/          # Login, Register, Verify
│   │   │   ├── dashboard/      # Dashboard
│   │   │   ├── exams/          # Exam CRUD, Create, Take
│   │   │   ├── analytics/      # Analytics & Reports
│   │   │   └── history/        # Exam history
│   │   ├── components/         # Shared UI components
│   │   │   ├── layout/        # Layout (Header, Sidebar)
│   │   │   └── common/        # Common (Loading, etc.)
│   │   ├── api/               # API client
│   │   ├── context/            # React Context
│   │   ├── config/             # Routes, Design system
│   │   └── theme/              # MUI themes
│   └── package.json
│
├── backend/                     # Backend API (FastAPI)
│   ├── app/
│   │   ├── api/                # REST endpoints
│   │   │   ├── auth.py         # Authentication
│   │   │   ├── exam.py         # Exam CRUD + Generate
│   │   │   ├── upload.py       # File upload
│   │   │   ├── vision.py        # Vision analysis
│   │   │   ├── folder.py       # Folder management
│   │   │   └── analytics.py     # Analytics
│   │   │
│   │   ├── services/           # Business logic
│   │   │   ├── auth_service.py
│   │   │   ├── exam_service.py
│   │   │   ├── genai_service.py
│   │   │   ├── vision_service.py
│   │   │   └── upload_service.py
│   │   │
│   │   ├── repositories/        # Data access
│   │   │   ├── user_repository.py
│   │   │   ├── exam_repository.py
│   │   │   └── file_repository.py
│   │   │
│   │   ├── models/             # SQLAlchemy models
│   │   │   ├── user.py
│   │   │   ├── exam.py         # Exam, Question, ExamAttempt
│   │   │   └── file.py
│   │   │
│   │   ├── schemas/            # Pydantic schemas
│   │   │   ├── auth_schemas.py
│   │   │   ├── exam_schemas.py
│   │   │   └── file_schemas.py
│   │   │
│   │   ├── genai/              # AI integration
│   │   │   ├── clients/        # OpenAI, Gemini clients
│   │   │   ├── prompts/        # YAML prompt templates
│   │   │   ├── validators/     # Question validation
│   │   │   └── utils/          # Retry, caching
│   │   │
│   │   ├── vision/             # Vision module
│   │   │   └── analyzer.py     # AI image analyzer
│   │   │
│   │   ├── auth/               # Authentication
│   │   ├── core/               # Config, security
│   │   └── database/           # DB, Redis
│   │
│   ├── requirements.txt
│   └── pytest.ini
│
└── docs/                       # Documentation
    └── architecture/

Environment Variables

Backend (backend/.env)

# Database
DATABASE_URL=sqlite+aiosqlite:///./exam_hub.db

# Security
SECRET_KEY=your-secret-key-min-32-chars
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# CORS
ALLOWED_ORIGINS=http://localhost:5173

# Redis (optional)
REDIS_HOST=localhost
REDIS_PORT=6379
RATE_LIMIT_ENABLED=false

# AI Providers
OPENAI_API_KEY=sk-your-openai-key
GEMINI_API_KEY=your-gemini-key
DEFAULT_AI_PROVIDER=openai

# Environment
ENV=development

Frontend (exam-app/.env)

VITE_API_URL=http://localhost:5001

API Endpoints

Authentication (/auth)

Method Endpoint Description
POST /auth/register User registration
POST /auth/login User login
POST /auth/refresh-token Refresh token
POST /auth/logout User logout
POST /auth/forgot-password Request password reset
POST /auth/reset-password Reset password

Exam Management (/exam)

Method Endpoint Description
POST /exam/generate Generate exam (AI)
POST /exam/save Save exam to DB
GET /exam/{id} Get exam details
GET /exam List user's exams
POST /exam/{id}/submit Submit exam answers
GET /exam/{id}/result Get exam result

File Upload (/upload)

Method Endpoint Description
POST /upload/ Upload file
GET /upload/ List user's files
GET /upload/{id} Get file info
DELETE /upload/{id} Delete file
POST /upload/{id}/process Process file
GET /upload/{id}/content Get extracted content

Vision Analysis (/vision)

Method Endpoint Description
POST /vision/analyze Analyze document
GET /vision/{id}/figures Get detected figures

Testing

# Backend
cd backend
pytest tests/ -v

# Frontend
cd exam-app
npm test

Deployment

Docker Compose

# Start all services
docker-compose up -d

# View logs
docker-compose logs -f backend

Manual

# Backend
cd backend
pip install -r requirements.txt
python -m app.main

# Frontend
cd exam-app
npm install
npm run build
npm run preview

Documentation


License

MIT License

About

A flexible and customizable exam application platform for various subjects and tools. Build, manage, and deliver interactive examinations with support for multiple question types, subject-specific testing, and extensible modules for different educational tools.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors