Skip to content

deepaksaranay/stem-mcq-generator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 

Repository files navigation

🎓 STEM MCQ Generator

Typing SVG

Python FastAPI Google Gemini Docker Pytest License


Generate high-quality STEM Multiple Choice Questions from any topic or PDF using Google Gemini AI.

Built for educators, students, and STEM content creators.

📖 API Docs  ·  🚀 Quick Start  ·  🐳 Docker  ·  🧪 Tests  ·  🗺️ Roadmap


📸 Preview

POST /api/v1/generate/topic
───────────────────────────────────────────────────────────────
Input  → Topic: "Newton's Laws of Motion" | Difficulty: Hard
Output → 5 MCQs with options, correct answers & explanations
───────────────────────────────────────────────────────────────
{
  "success": true,
  "data": {
    "title": "Newton's Laws of Motion — Hard MCQs",
    "subject": "physics",
    "difficulty": "hard",
    "total_questions": 5,
    "questions": [
      {
        "id": "a1b2c3d4",
        "question": "A 5kg block is pushed with 20N on μ=0.3 surface. Find acceleration.",
        "options": [
          { "key": "A", "text": "1.06 m/s²" },
          { "key": "B", "text": "4.00 m/s²" },
          { "key": "C", "text": "2.94 m/s²" },
          { "key": "D", "text": "0.94 m/s²" }
        ],
        "correct_answer": "A",
        "explanation": "Net F = 20−(0.3×5×9.8) = 5.3N. a = 5.3/5 = 1.06 m/s²",
        "difficulty": "hard",
        "topic": "Newton's Second Law with Friction"
      }
    ]
  }
}

✨ Features

Feature Description Status
🧠 AI Generation Google Gemini 1.5 Flash for accurate MCQs ✅ Live
📄 PDF Upload Extract text from textbooks & generate MCQs ✅ Live
🎯 Difficulty Levels Easy / Medium / Hard (Class 6 → GATE level) ✅ Live
📚 6 STEM Subjects Physics, Chemistry, Math, Biology, CS, General ✅ Live
Answer Validation Submit answers → get score + grade + explanation ✅ Live
📊 Export Options Download as JSON / CSV / Printable Text ✅ Live
🐳 Docker Ready One-command deployment ✅ Live
🔁 Mock Mode Works without API key (for demo/testing) ✅ Live
🌐 Swagger UI Auto-generated interactive API docs at /docs ✅ Live
💾 Redis Storage Persistent MCQ storage 🔜 Roadmap

🏗️ Project Structure

stem-mcq-generator/
│
├── 📁 app/
│   ├── 🐍 main.py                  ← FastAPI app entry point
│   │
│   ├── 📁 api/
│   │   └── 🐍 routes.py            ← All 9 API endpoints
│   │
│   ├── 📁 core/
│   │   └── 🐍 config.py            ← Settings via pydantic-settings
│   │
│   ├── 📁 models/
│   │   └── 🐍 schemas.py           ← Pydantic request/response models
│   │
│   └── 📁 services/
│       ├── 🐍 mcq_service.py       ← Gemini AI MCQ generation logic
│       ├── 🐍 pdf_service.py       ← PDF extraction with PyMuPDF
│       └── 🐍 export_service.py    ← JSON / CSV / Text export
│
├── 📁 tests/
│   └── 🧪 test_api.py              ← 30+ pytest test cases
│
├── 🐳 Dockerfile                   ← Multi-stage production build
├── 🐳 docker-compose.yml           ← One-command deployment
├── 📋 requirements.txt
├── 🔐 .env.example                 ← Environment variable template
└── 📖 README.md

🚀 Quick Start

Prerequisites

Python 3.11+
Google Gemini API Key (free) → https://aistudio.google.com/app/apikey

Installation

# 1️⃣  Clone the repository
git clone https://github.com/YOUR_USERNAME/stem-mcq-generator.git
cd stem-mcq-generator

# 2️⃣  Create virtual environment
python -m venv venv

# Activate (Linux/Mac)
source venv/bin/activate

# Activate (Windows)
venv\Scripts\activate

# 3️⃣  Install dependencies
pip install -r requirements.txt

# 4️⃣  Configure environment
cp .env.example .env
# Open .env and add your GEMINI_API_KEY

# 5️⃣  Run the server
uvicorn app.main:app --reload

# 6️⃣  Open interactive API docs
# 👉 http://localhost:8000/docs

💡 No API key? App runs in mock mode automatically — perfect for testing!


🐳 Docker Deployment

# 1️⃣  Clone & configure
git clone https://github.com/YOUR_USERNAME/stem-mcq-generator.git
cd stem-mcq-generator
cp .env.example .env
# Add GEMINI_API_KEY to .env

# 2️⃣  Build and run
docker-compose up --build

# 3️⃣  Access
# 👉 http://localhost:8000/docs

📡 API Endpoints

🔵 Generate

Method Endpoint Description
POST /api/v1/generate/topic Generate MCQs from a topic string
POST /api/v1/generate/pdf Generate MCQs from uploaded PDF file

🟢 Retrieve & Validate

Method Endpoint Description
GET /api/v1/mcq/{set_id} Retrieve MCQ set by ID
POST /api/v1/validate Submit answers → get score + grade

🟡 Export

Method Endpoint Description
GET /api/v1/export/{id}/json Download as JSON
GET /api/v1/export/{id}/csv Download as CSV (Excel-compatible)
GET /api/v1/export/{id}/text Download as printable text

⚪ Utility

Method Endpoint Description
GET /api/v1/subjects List all supported subjects
GET /api/v1/difficulties List difficulty levels with descriptions
GET /health API health check
GET /docs Interactive Swagger UI

🎯 Supported Subjects & Difficulty Levels

📚 Subjects

Subject Value Example Topics
⚛️ Physics physics Newton's Laws, Thermodynamics, Optics
🧪 Chemistry chemistry Periodic Table, Chemical Bonding, Reactions
➕ Mathematics mathematics Calculus, Algebra, Trigonometry
🧬 Biology biology DNA Replication, Photosynthesis, Cell Division
💻 Computer Science computer_science Binary Trees, Sorting, OOP
🔬 General Science general_science Mixed STEM topics

🎯 Difficulty Levels

Level Target Audience Question Style
🟢 easy Class 6–8 Basic recall, definitions, simple facts
🟡 medium Class 9–12 Application, understanding, diagrams
🔴 hard JEE / NEET / GATE Analysis, numerical problems, evaluation

🧪 Running Tests

# Run all tests
pytest tests/ -v

# Run with coverage report
pytest tests/ -v --cov=app --cov-report=html

# Run specific test class
pytest tests/test_api.py::TestGenerate -v

🧾 Test Coverage

Test Class Tests Coverage
TestHealth 2 Health endpoints
TestGenerate 5 MCQ generation (topic + PDF)
TestMCQStructure 3 Question format validation
TestRetrieval 2 Get by ID, 404 handling
TestValidation 3 Score, grade, answer checking
TestExport 3 JSON, CSV, text export
TestUtility 2 Subjects & difficulties list
Total 20+ Full API coverage

🛠️ Tech Stack

Layer Technology Purpose
🌐 Framework FastAPI 0.115 REST API with async support
🤖 AI / LLM Google Gemini 1.5 Flash MCQ generation
📄 PDF PyMuPDF (fitz) Text extraction
Validation Pydantic v2 Request/response schemas
🧪 Testing pytest + httpx 20+ test cases
🐳 Deployment Docker + Compose Containerized deployment
📖 API Docs Swagger UI Auto-generated interactive docs

🔑 Environment Variables

# Required
GEMINI_API_KEY=your_google_gemini_api_key

# Optional
LLM_PROVIDER=gemini           # gemini | openai
ENVIRONMENT=development        # development | production
MAX_NUM_QUESTIONS=50
TEMPERATURE=0.7
MAX_FILE_SIZE_MB=10
RATE_LIMIT_PER_MINUTE=20

🗺️ Roadmap

  • Topic-based MCQ generation
  • PDF upload & text extraction
  • Answer validation with scoring
  • JSON / CSV / Text export
  • Docker deployment
  • 🔜 Redis for persistent storage
  • 🔜 Streamlit frontend UI
  • 🔜 JWT user authentication
  • 🔜 Hindi language support
  • 🔜 Image-based questions
  • 🔜 Bulk topic generation
  • 🔜 Leaderboard & quiz sessions

🤝 Contributing

Contributions are welcome! 🎉

# 1. Fork the repo
# 2. Create your feature branch
git checkout -b feature/amazing-feature

# 3. Commit your changes
git commit -m "✨ Add amazing feature"

# 4. Push to branch
git push origin feature/amazing-feature

# 5. Open a Pull Request

📄 License

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


👤 Author

Saranay

GitHub LinkedIn

AI/ML Professional · STEM Educator · Python Developer


Star this repo if it helped you!

Built with ❤️ using FastAPI + Google Gemini

About

stem-mcq-generator

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors