Skip to content

muzammaldeveloper/ai-assignment-generator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸŽ“ AI Assignment Generator

Transform any topic into a fully researched, professionally formatted academic assignment in minutes β€” powered by Groq LLM, Google Imagen 3, and Tavily web search.

Python Flask Next.js React TailwindCSS SQLite License: MIT


πŸ“‹ Table of Contents


πŸ€” What is this?

AI Assignment Generator is a full-stack web application that automates the creation of academic assignments from scratch. You simply enter a topic, choose your settings, and the system does everything else:

  • πŸ” Researches the topic using live web search
  • 🧠 Generates a structured outline using AI
  • ✍️ Writes full academic content with proper citations
  • πŸ–ΌοΈ Creates relevant images for each section
  • πŸ“„ Exports a professionally formatted DOCX and PDF with a cover page

No more spending hours writing assignments. The AI handles research, writing, formatting, and document generation β€” all in one click.


βš™οΈ How it Works & System Flow

The entire orchestration pipeline runs asynchronously using a non-blocking background thread (or an optional production-ready Celery task queue). The Next.js frontend initiates the request, receives an instant confirmation, and then polls the status periodically to display a dynamic, real-time progress bar.

graph TD
    %% Define Styles
    classDef client fill:#3b82f6,stroke:#1d4ed8,stroke-width:2px,color:#fff;
    classDef server fill:#10b981,stroke:#047857,stroke-width:2px,color:#fff;
    classDef db fill:#f59e0b,stroke:#d97706,stroke-width:2px,color:#fff;
    classDef pipeline fill:#8b5cf6,stroke:#6d28d9,stroke-width:2px,color:#fff;

    User([πŸŽ“ Student User]) -->|1. Enters Topic & Settings| FE[Next.js App Router Frontend]
    FE -->|2. POST /api/v1/assignments/generate| BE[Flask RESTful API Backend]
    
    subgraph Backend Core
        BE -->|3. Starts Background Thread / Queue| Pipeline[Pipeline Service Orchestrator]
        BE -->|4. Instantly Returns 202 Accepted| FE
        
        subgraph 7-Step AI Orchestration Pipeline
            Pipeline -->|Step 1: Sanitize| Guard[Prompt Guard / HTML Bleach]
            Guard -->|Step 2: Tavily Search| Web[Tavily Search: Live Web Research]
            Web -->|Step 3: Groq LLM| Outline[Groq: Outline Generation JSON]
            Outline -->|Step 4: Groq LLM| Content[Groq: Content & Citations Writer]
            Content -->|Step 5: Imagen 3 / Gemini| Images[Google Imagen 3: Section Illustration]
            Images -->|Step 6: python-docx| Word[Word Document Builder]
            Word -->|Step 7: ReportLab| PDF[PDF Document Builder]
        end
        
        Word -->|Save generated doc paths| DB[(SQLite / PostgreSQL Database)]
        PDF -->|Save generated doc paths| DB
    end

    FE -->|5. GET /api/v1/assignments/:id polling| BE
    BE -->|Query Status & Progress| DB
    DB -->|Progress 0% - 100%| FE
    FE -->|6. Ready for Download| Download[⬇️ Download DOCX / PDF with Custom Templates]

    %% Assign classes
    class FE client;
    class BE server;
    class DB db;
    class Pipeline,Guard,Web,Outline,Content,Images,Word,PDF pipeline;
Loading

Note

The background orchestration is designed to run asynchronously using Flask's multi-threading capabilities, meaning no extra dependencies like Redis or Celery are required for local development. For production, Celery is fully supported and configured.


πŸ’‘ Key Benefits

Benefit Description
⚑ Fast Full assignment generated in 2–5 minutes
🎨 5 Templates Professional, Academic, Modern, Minimal, Colorful
πŸ“š 4 Citation Styles APA, MLA, Harvard, IEEE
πŸ–ΌοΈ AI Images Auto-generated images per section via Imagen 3
✏️ Editable Edit any section inline after generation
πŸ“₯ Dual Export Download as DOCX or PDF
πŸ”’ Secure JWT auth, bcrypt passwords, prompt injection guard
πŸ’» Local-first Runs fully on SQLite β€” no Docker, no PostgreSQL needed

πŸ› οΈ Full Tech Stack

Backend

Technology Version Purpose
Python 3.11+ Runtime language
Flask 3.1.0 Web framework
SQLAlchemy 2.0.36 ORM for database
Flask-SQLAlchemy 3.1.1 Flask + SQLAlchemy bridge
Flask-JWT-Extended 4.7.1 JWT access + refresh tokens
Flask-Limiter 3.8.0 Rate limiting
Flask-CORS 5.0.1 Cross-origin requests
Flask-Migrate 4.1.0 Database migrations
Marshmallow 3.23.2 Input validation & serialization
Pydantic 2.10.4 Settings management via .env
Groq 0.13.1 LLM β€” llama-3.3-70b-versatile
google-generativeai 0.8.4 Imagen 3 image generation
tavily-python 0.5.0 Live web research API
python-docx 1.1.2 DOCX document generation
ReportLab 4.2.5 PDF document generation
Pillow 11.1.0 Image processing
bcrypt 4.2.1 Password hashing (rounds=12)
bleach 6.2.0 HTML sanitization
tenacity 9.0.0 Retry logic for API calls
python-dotenv 1.0.1 Load .env variables
SQLite built-in Local database (zero setup)
Celery + Redis 5.4.0 Optional β€” production task queue

Frontend

Technology Version Purpose
Next.js 15.1.0 React framework with App Router
React 19.0.0 UI library
Tailwind CSS 3.4.17 Utility-first CSS framework
Framer Motion 11.15.0 Animations and transitions
Axios 1.7.9 HTTP client with JWT interceptors
js-cookie 3.0.5 Cookie management for tokens
lucide-react 0.468.0 Icon library
react-hot-toast 2.4.1 Toast notifications
@tailwindcss/typography 0.5.15 Prose styling for content

AI Services

Service Model Purpose
Groq llama-3.3-70b-versatile Outline + full content generation
Google Imagen 3 imagen-3.0-generate-002 Section image generation
Google Gemini Flash gemini-2.0-flash-exp Image fallback
Tavily Search API Live web research (5 sources)

πŸ“ Project Structure

ai-assignment-generator/
β”‚
β”œβ”€β”€ Backend/                          # Flask REST API
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ api/
β”‚   β”‚   β”‚   β”œβ”€β”€ assignment_api.py     # Generate, list, download, edit, regenerate
β”‚   β”‚   β”‚   β”œβ”€β”€ auth_api.py           # Register, login, refresh, me
β”‚   β”‚   β”‚   β”œβ”€β”€ health_api.py         # Health check endpoint
β”‚   β”‚   β”‚   β”œβ”€β”€ routes.py             # Blueprint registration
β”‚   β”‚   β”‚   └── user_api.py           # User profile
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”‚   β”œβ”€β”€ assignment.py         # Assignment model (topic, template, student info)
β”‚   β”‚   β”‚   β”œβ”€β”€ user.py               # User model with bcrypt
β”‚   β”‚   β”‚   β”œβ”€β”€ section.py            # Section model (title, content, order)
β”‚   β”‚   β”‚   β”œβ”€β”€ image.py              # Image model (path, caption)
β”‚   β”‚   β”‚   └── reference.py          # Reference model (citation text)
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ schemas/
β”‚   β”‚   β”‚   β”œβ”€β”€ assignment_schema.py  # Marshmallow validation schemas
β”‚   β”‚   β”‚   └── user_schema.py        # User register/login schemas
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”‚   β”œβ”€β”€ pipeline_service.py       # 7-step pipeline orchestrator
β”‚   β”‚   β”‚   β”œβ”€β”€ research_service.py       # Tavily web research
β”‚   β”‚   β”‚   β”œβ”€β”€ outline_service.py        # Groq outline generation
β”‚   β”‚   β”‚   β”œβ”€β”€ text_generation_service.py # Groq content generation
β”‚   β”‚   β”‚   β”œβ”€β”€ image_generation_service.py # Imagen 3 + Gemini fallback
β”‚   β”‚   β”‚   └── document_service.py       # DOCX + PDF with 5 templates
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”‚   β”œβ”€β”€ logger.py             # Structured logging
β”‚   β”‚   β”‚   β”œβ”€β”€ prompt_guard.py       # Prompt injection detection
β”‚   β”‚   β”‚   β”œβ”€β”€ validators.py         # Input sanitization
β”‚   β”‚   β”‚   └── file_helpers.py       # File path utilities
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ errors/
β”‚   β”‚   β”‚   └── handlers.py           # Global error handlers (422, 500, etc.)
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ extensions.py             # Flask extensions init
β”‚   β”‚   └── factory.py                # App factory + auto table creation
β”‚   β”‚
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   └── settings.py               # Pydantic settings (SQLite path fix)
β”‚   β”‚
β”‚   β”œβ”€β”€ instance/
β”‚   β”‚   └── app.db                    # SQLite database (auto-created)
β”‚   β”‚
β”‚   β”œβ”€β”€ storage/
β”‚   β”‚   β”œβ”€β”€ documents/                # Generated .docx and .pdf files
β”‚   β”‚   └── images/                   # Generated .png images
β”‚   β”‚
β”‚   β”œβ”€β”€ tests/                        # Pytest test suite
β”‚   β”œβ”€β”€ .env.example                  # Environment template
β”‚   └── requirements.txt              # Python dependencies
β”‚
β”œβ”€β”€ Frontend/                         # Next.js App
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”‚   β”œβ”€β”€ page.js               # Landing page
β”‚   β”‚   β”‚   β”œβ”€β”€ login/page.js         # Login
β”‚   β”‚   β”‚   β”œβ”€β”€ register/page.js      # Register
β”‚   β”‚   β”‚   β”œβ”€β”€ generate/page.js      # Assignment generator form
β”‚   β”‚   β”‚   └── dashboard/
β”‚   β”‚   β”‚       β”œβ”€β”€ page.js           # Assignment history list
β”‚   β”‚   β”‚       └── [id]/page.js      # Assignment detail + viewer
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”œβ”€β”€ GenerateForm.js       # 4-step wizard form
β”‚   β”‚   β”‚   β”œβ”€β”€ AssignmentViewer.js   # Detail view + inline editing
β”‚   β”‚   β”‚   β”œβ”€β”€ AssignmentCard.js     # Dashboard card
β”‚   β”‚   β”‚   β”œβ”€β”€ Navbar.js             # Glassmorphism navbar
β”‚   β”‚   β”‚   β”œβ”€β”€ HeroSection.js        # Landing hero
β”‚   β”‚   β”‚   β”œβ”€β”€ FeaturesSection.js    # Features grid
β”‚   β”‚   β”‚   β”œβ”€β”€ HowItWorks.js         # Steps section
β”‚   β”‚   β”‚   └── StatusBadge.js        # Colored status pill
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ hooks/
β”‚   β”‚   β”‚   β”œβ”€β”€ useAuth.js            # Auth state management
β”‚   β”‚   β”‚   └── useAssignments.js     # Assignment fetch + generate
β”‚   β”‚   β”‚
β”‚   β”‚   └── lib/
β”‚   β”‚       β”œβ”€β”€ api.js                # Axios + JWT interceptor + auto-refresh
β”‚   β”‚       β”œβ”€β”€ auth.js               # Login/register/logout helpers
β”‚   β”‚       └── constants.js          # Templates, levels, citation styles
β”‚   β”‚
β”‚   β”œβ”€β”€ next.config.js                # Proxy /api/* β†’ localhost:5000
β”‚   └── package.json
β”‚
β”œβ”€β”€ .gitignore                        # Root gitignore
β”œβ”€β”€ README.md                         # This file
└── LICENSE                           # MIT License

πŸš€ Quick Start

Prerequisites

  • Python 3.11+
  • Node.js 18+
  • API keys for: Groq, Google Gemini, Tavily

Step 1 β€” Clone

git clone https://github.com/muzammaldeveloper/ai-assignment-generator.git
cd ai-assignment-generator

Step 2 β€” Backend Setup

cd Backend

# Create virtual environment
python -m venv .venv

# Activate β€” Windows PowerShell
.\.venv\Scripts\Activate.ps1

# Activate β€” Linux / macOS
source .venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Create .env from template
copy .env.example .env        # Windows
cp .env.example .env          # Linux/macOS

Edit .env and fill in your API keys (see Environment Variables).

# Run backend
flask run --host=0.0.0.0 --port=5000 --debug

βœ… Database (instance/app.db) is created automatically on first run. No migrations needed.


Step 3 β€” Frontend Setup

cd Frontend
npm install
npm run dev

Step 4 β€” Open in Browser

Service URL
🌐 Frontend http://localhost:3000
βš™οΈ Backend API http://localhost:5000
πŸ’š Health Check http://localhost:5000/api/v1/health

πŸ”‘ Environment Variables

Create Backend/.env from Backend/.env.example:

# ── Flask ──
FLASK_APP=app.factory:create_app
FLASK_ENV=development
SECRET_KEY=your-secret-key-minimum-32-chars
DEBUG=true

# ── JWT ──
JWT_SECRET_KEY=your-jwt-secret-minimum-32-chars
JWT_ACCESS_TOKEN_EXPIRES_MINUTES=60
JWT_REFRESH_TOKEN_EXPIRES_DAYS=30

# ── Database (SQLite β€” no PostgreSQL needed locally) ──
DATABASE_URL=sqlite:///instance/app.db

# ── Redis (not needed locally) ──
REDIS_URL=redis://localhost:6379/0

# ── Groq (text generation) ──
GROQ_API_KEY=your-groq-api-key
GROQ_MODEL=llama-3.3-70b-versatile
GROQ_MAX_TOKENS=4096
GROQ_TEMPERATURE=0.7

# ── Google Gemini (image generation) ──
GEMINI_API_KEY=your-gemini-api-key
GEMINI_MODEL=gemini-2.0-flash-exp

# ── Tavily (web research) ──
TAVILY_API_KEY=your-tavily-api-key
TAVILY_MAX_RESULTS=5

# ── Rate Limiting (memory:// = no Redis needed locally) ──
RATE_LIMIT_DEFAULT=100/hour
RATE_LIMIT_GENERATION=10/hour
RATE_LIMIT_STORAGE_URI=memory://

# ── CORS ──
CORS_ALLOWED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000

# ── Storage ──
STORAGE_BACKEND=local
STORAGE_LOCAL_PATH=storage
MAX_CONTENT_LENGTH_MB=10

Where to get API Keys (all free tier)

Service Free Tier Get Key
Groq βœ… Fast LLM inference https://console.groq.com
Google Gemini βœ… Imagen 3 included https://aistudio.google.com
Tavily βœ… 1000 searches/month https://tavily.com

πŸ“‘ API Reference

Base URL: http://localhost:5000/api/v1

Authentication Endpoints

Method Endpoint Auth Description
POST /auth/register ❌ Register new user
POST /auth/login ❌ Login, get tokens
POST /auth/refresh Refresh token Rotate access token
GET /auth/me βœ… Get current user

Register / Login body:

{
  "name": "Ali Hassan",
  "email": "ali@example.com",
  "password": "SecurePass123"
}

Response:

{
  "success": true,
  "data": {
    "user": { "id": "uuid", "name": "Ali Hassan", "email": "ali@example.com" },
    "access_token": "eyJ...",
    "refresh_token": "eyJ..."
  }
}

Assignment Endpoints

Method Endpoint Auth Description
POST /assignments/generate βœ… Start generation
GET /assignments βœ… List all (paginated)
GET /assignments/{id} βœ… Get full details + poll status
GET /assignments/{id}/download?format=pdf βœ… Download DOCX or PDF
PATCH /assignments/{id}/update-info βœ… Update student name, roll, department
PATCH /assignments/{id}/sections/{sid} βœ… Edit section content
POST /assignments/{id}/regenerate-docs βœ… Rebuild DOCX + PDF after edits

Generate request body:

{
  "topic": "Artificial Intelligence in Healthcare",
  "academic_level": "university",
  "word_count": 1500,
  "citation_style": "apa",
  "template": "professional",
  "student_name": "Ali Hassan",
  "roll_number": "CS-2021-001",
  "department": "Department of Computer Science"
}

Valid field values:

Field Options
academic_level school college university research
word_count 800 1000 1200 1500 2000 3000 5000
citation_style apa mla harvard ieee
template professional academic modern minimal colorful

Generate response (202 Accepted):

{
  "success": true,
  "data": {
    "assignment_id": "uuid",
    "status": "pending",
    "status_url": "/api/v1/assignments/uuid"
  }
}

Poll for completion:

curl http://localhost:5000/api/v1/assignments/{id} \
  -H "Authorization: Bearer <access_token>"

System

Method Endpoint Auth Description
GET /health ❌ Health check

πŸ”„ Generation Pipeline

Step 1 β€” Input Validation
         └── Prompt injection guard
         └── Topic sanitization with bleach

Step 2 β€” Web Research                    [10%]
         └── Tavily fetches 5 live sources
         └── Extracts relevant academic content

Step 3 β€” Outline Generation              [25%]
         └── Groq LLM creates JSON outline
         └── Title, abstract, 5-8 sections, image hints

Step 4 β€” Content Generation              [40%]
         └── Groq writes Introduction
         └── Groq writes each body section
         └── Groq writes Conclusion
         └── Groq formats References (APA/MLA/Harvard/IEEE)

Step 5 β€” Image Generation                [60%]
         └── Google Imagen 3 β†’ one image per section
         └── Fallback: Gemini 2.0 Flash
         └── Graceful β€” assignment continues without images

Step 6 β€” DOCX Generation                 [80%]
         └── python-docx builds Word document
         └── Cover page + sections + images + references

Step 7 β€” PDF Generation                 [100%]
         └── ReportLab builds PDF
         └── Cover page + colored headings + images + page numbers

🎨 Document Templates

Template Primary Color Font Style
Professional Navy #003366 Calibri Clean corporate
Academic Dark Slate #2C3E50 + Dark Red Times New Roman Traditional scholarly
Modern Violet #6C63FF + Pink Calibri Bold contemporary
Minimal Near-black #1A1A1A Arial Ultra clean
Colorful Purple #7B2D8B + Magenta Calibri Vibrant eye-catching

Cover Page (every document includes)

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   β”‚  ← Colored header bar
β”‚                                     β”‚
β”‚       ASSIGNMENT SUBMISSION         β”‚
β”‚                                     β”‚
β”‚    Artificial Intelligence in       β”‚
β”‚         Healthcare                  β”‚  ← Assignment title
β”‚                                     β”‚
β”‚  ─────────────────────────────────  β”‚  ← Divider
β”‚                                     β”‚
β”‚  Student Name:   Ali Hassan         β”‚
β”‚  Roll Number:    CS-2021-001        β”‚  ← Student info (editable)
β”‚  Department:     Computer Science   β”‚
β”‚  Date:           January 01, 2025   β”‚
β”‚                                     β”‚
β”‚  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   β”‚  ← Colored footer bar
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

PDF Extra Features

  • Section headings with colored underline dividers
  • Images with captions (never split across pages β€” KeepTogether)
  • Footer on every page: title left + page number right
  • Hanging-indent formatted references

πŸ”’ Security

Feature Implementation
Prompt Injection Guard Blocks LLM hijacking via topic input
Input Sanitization All user content cleaned with bleach
Password Hashing bcrypt with rounds=12
JWT Tokens 60min access + 30day refresh tokens
Rate Limiting 100 req/hour default, 20/hour for generation
CORS Restricted to configured origins only
No Secrets in Code All config via .env

Production: Set DEBUG=false, use Redis for rate limiting, PostgreSQL for database, AWS S3 for file storage, and strong random keys for SECRET_KEY and JWT_SECRET_KEY.


🌍 Local vs Production

Feature Local Production
Database SQLite (auto-created) PostgreSQL
Task Queue Background thread Celery + Redis
Rate Limiting In-memory Redis
File Storage storage/ folder AWS S3
Debug DEBUG=true DEBUG=false
Workers Single thread Gunicorn multi-worker

πŸš€ Deployment

Backend (Flask)

  • PythonAnywhere (Free Plan): Detailed step-by-step instructions are available in DEPLOY_PYTHONANYWHERE.md.
  • Vercel: Configuration is provided in vercel.json using the @vercel/python builder, with index.py as the entry point.

Frontend (Next.js)

  • Vercel: Fully optimized for Next.js out-of-the-box. Ensure your environment variables are configured in Vercel settings (see Frontend/.env.example).

πŸ§ͺ Testing

# Backend tests
cd Backend
pytest tests/ -v --cov=app --cov-report=term-missing

# Frontend lint
cd Frontend
npm run lint

πŸ“„ License

MIT β€” see LICENSE for details.


Built with ❀️ using Flask · Next.js · Groq · Google Imagen 3 · Tavily

About

πŸŽ“ Advanced AI Assignment Generator & Academic Paper Writer. Automates research, structuring, writing, illustration, and formatting (DOCX/PDF). Powered by Next.js 15, React 19, Flask 3, Groq Cloud (Llama 3.3), Google Imagen 3, and Tavily Search API.

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Contributors