Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

36 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿง  SmartStudy AI

Your Personal AI-Powered Learning Companion

MIT License Python FastAPI React TypeScript Docker

Revolutionize your study habits with machine learning-powered insights and personalized recommendations

Features โ€ข Architecture โ€ข Quick Start โ€ข API Docs โ€ข Contributing


๐Ÿ“– Overview

SmartStudy AI is a comprehensive, full-stack web application engineered to revolutionize your study habits. By leveraging machine learning, it analyzes your unique study patterns to provide personalized, data-driven insights and recommendations. Move beyond generic advice and unlock your peak productivity, improve knowledge retention, and achieve your academic goals with a smarter approach to learning.

This application provides an end-to-end solution, from tracking individual study sessions to offering predictive analytics on exam performance and implementing a sophisticated spaced repetition system for flashcards.

๐ŸŽฏ Why SmartStudy AI?

  • ๐Ÿค– Machine Learning Integration - Random Forest Classifier predicts your optimal study times with confidence scores
  • ๐Ÿ“Š Advanced Analytics - Interactive charts and comprehensive dashboards track every aspect of your learning journey
  • ๐ŸŽด Intelligent Flashcards - SM-2 spaced repetition algorithm maximizes long-term retention
  • ๐Ÿ“ˆ Exam Predictions - AI estimates your performance based on study patterns and consistency
  • ๐ŸŽจ Modern UI/UX - Beautiful, responsive interface built with React, TypeScript & Tailwind CSS
  • ๐Ÿ”’ Enterprise-Grade Security - JWT authentication, secure password hashing, and protected routes
  • ๐Ÿ“ฆ Containerized Deployment - Docker-ready for seamless development and production environments

โœจ Core Features

1. ๐Ÿ“Š Unified Dashboard

The central hub of your learning journey. The dashboard provides an at-a-glance overview of your progress and quick access to all key features.

Key Components:

  • ๐Ÿ“ˆ Key Statistics - Instantly view your total study time, number of sessions completed, and average effectiveness rating
  • โฐ Productivity Snapshot - See your most productive time of day, as identified by the AI model
  • ๐Ÿ“ Recent Activity - Review your most recent study sessions to maintain momentum
  • ๐ŸŽฏ Action Hub - Jump directly into logging a new session, practicing flashcards, or viewing detailed analytics
  • ๐Ÿ’ก AI-Generated Insights - Receive dynamic, personalized tips based on your latest study data

2. ๐Ÿ“š Intelligent Study Session Tracker

The foundation of the platform. Meticulously log your study sessions to feed the AI model with the data it needs to help you.

Features:

  • ๐Ÿ“ Detailed Logging - Record the subject, start and end times, and your perceived effectiveness on a 1-5 scale
  • ๐Ÿ’ฌ Qualitative Notes - Add context to your sessions with notes on your focus level, distractions, or topics covered
  • โœ๏ธ Full CRUD Functionality - Easily create, review, update, and delete any study session
  • ๐Ÿค– Automated Calculations - The system automatically calculates the duration, day of the week, and time of day for each entry, creating a rich dataset for analysis

Why It Matters: Every logged session enriches the ML model's understanding of your unique study patterns, making recommendations more accurate over time.


3. ๐Ÿ“‰ Comprehensive Analytics

Visualize your study habits through an interactive and user-friendly analytics dashboard.

Visualization Tools:

  • ๐Ÿ“Š Study Time Analysis - A bar chart displays your total study time per day (for weekly/monthly views) or per week (for all-time view), helping you see your consistency
  • ๐Ÿฅง Subject Distribution - A pie chart breaks down your study time by subject, showing you where you're investing your efforts
  • ๐ŸŽฏ Key Performance Indicators (KPIs) - Track high-level metrics like total study time, session count, and average effectiveness
  • ๐Ÿ—“๏ธ Dynamic Time Ranges - Filter your analytics view by the current week, month, or all time to identify short-term and long-term trends

Insights You Gain:

  • Identify which subjects need more attention
  • Discover consistency patterns in your study schedule
  • Track improvement in session effectiveness over time
  • Understand how your study distribution aligns with your goals

4. ๐Ÿค– AI-Powered Recommendations & Predictions

This is where the magic happens. SmartStudy AI transforms your raw data into actionable advice.

Optimal Study Times: The backend ProductivityPatternModel (a Random Forest Classifier) analyzes your session history to identify your peak productivity windows. The recommendations page displays:

  • โฐ Best hours to study for each day of the week
  • ๐Ÿ“Š Confidence scores for each suggestion
  • ๐Ÿ’ก Fallback recommendations - If you have insufficient data, it provides general, research-backed recommendations

Productivity Insights: The system generates personalized text-based insights, such as:

  • "You are most productive during the morning"
  • "Your optimal study session length is 45-60 minutes"
  • "You show 85% higher effectiveness on weekday afternoons"

Exam Performance Predictor: Predict your readiness for an upcoming exam by providing:

  • ๐Ÿ“… Exam date - When you'll be tested
  • ๐ŸŽฏ Target score - What you're aiming for
  • ๐Ÿ“š Subject - Which subject to analyze

The model estimates your likely score based on:

  • Total study time invested
  • Session consistency and frequency
  • Average effectiveness ratings
  • Time remaining until exam

It also provides tailored recommendations to help you close any gaps and reach your target.


5. ๐ŸŽด Spaced Repetition Flashcards (SM-2 Algorithm)

Master new concepts with a powerful, integrated flashcard system that optimizes for long-term retention.

Deck Management:

  • ๐Ÿ“š Organize flashcards into distinct decks for different subjects or topics
  • ๐ŸŽจ Link decks to subjects for better organization
  • ๐Ÿ“ Add descriptions to provide context

Card Creation:

  • โ“ Question field - What you want to remember
  • โœ… Answer field - The correct response
  • Simple, intuitive interface for rapid card creation

Intelligent Review Sessions: The system uses the proven SM-2 algorithm to determine which cards are due for review:

  • ๐Ÿ“… Cards appear based on their next review date
  • ๐Ÿง  Algorithm adapts to your recall performance
  • โฐ Optimize study time by focusing on what matters

Difficulty-Based Scheduling: After revealing a card's answer, you rate your recall difficulty:

  • Again โŒ - Complete failure, reset progress
  • Hard ๐Ÿ˜ฐ - Recalled with difficulty
  • Good โœ… - Recalled correctly with effort
  • Easy ๐ŸŽฏ - Perfect recall, minimal effort

This rating determines the next review date for that specific card, ensuring you spend more time on material you struggle with and less on what you already know.

SM-2 Benefits:

  • Maximizes long-term retention
  • Minimizes study time
  • Focuses on weak areas
  • Prevents forgetting through timed reviews

6. โš™๏ธ User & Subject Management

Customize the application to fit your academic life.

Subject Control:

  • โž• Create and manage a list of your subjects
  • ๐ŸŽจ Assign custom names and colors for easy identification in charts and lists
  • ๐Ÿ“Š View per-subject analytics and insights
  • โœ๏ธ Edit or delete subjects as your curriculum changes

Profile Settings:

  • ๐Ÿ‘ค Update your personal information, including your name
  • ๐ŸŒ Set your timezone for accurate time-based analytics
  • ๐Ÿ” Change your password securely
  • ๐Ÿ“ง Manage your email preferences

Preference Center:

  • ๐ŸŒ“ Toggle dark mode for comfortable studying at night
  • ๐Ÿ”” Manage notification settings (coming soon)
  • ๐Ÿ“ฑ Customize dashboard layout preferences
  • โš™๏ธ Fine-tune app behavior to match your workflow

๐Ÿ›๏ธ System Architecture

SmartStudy AI is built on a modern, decoupled client-server architecture, ensuring scalability, maintainability, and extensibility.

graph TB
    subgraph "Client Layer"
        A[React 18 + TypeScript]
        B[Tailwind CSS]
        C[React Router v6]
        D[Recharts]
        E[Axios HTTP Client]
    end
    
    subgraph "API Layer"
        F[FastAPI Framework]
        G[Pydantic Validation]
        H[JWT Authentication]
        I[API Routers]
    end
    
    subgraph "Business Logic"
        J[SQLAlchemy ORM]
        K[Service Layer]
        L[ML Model Interface]
    end
    
    subgraph "ML & Algorithms"
        M[Random Forest Classifier]
        N[SM-2 Spaced Repetition]
        O[Feature Engineering]
    end
    
    subgraph "Data Layer"
        P[(PostgreSQL)]
        Q[(Redis Cache)]
        R[Model Persistence]
    end
    
    A --> F
    F --> G
    F --> H
    F --> I
    I --> J
    I --> K
    K --> L
    L --> M
    M --> O
    J --> P
    F --> Q
    M --> R
    N --> J
Loading

๐Ÿ”ง Backend (FastAPI)

The backend is a robust asynchronous API built with Python and FastAPI.

Architecture Highlights:

  • ๐Ÿ—‚๏ธ Modular Design - Endpoints are organized into logical routers (auth, sessions, subjects, flashcards, recommendations), making the API clean and extensible
  • โœ… Data Validation - Pydantic schemas are used extensively for request/response validation, ensuring data integrity and providing clear, automatic API documentation
  • ๐Ÿ—„๏ธ Database Interaction - SQLAlchemy ORM provides a powerful and flexible interface for all database operations. A custom GUID type is implemented for cross-database compatibility (PostgreSQL and SQLite)
  • ๐Ÿ” Authentication - Secure JWT-based authentication is implemented, with access tokens for requests and a mechanism for refresh tokens
  • ๐Ÿค– Machine Learning Integration - The ProductivityPatternModel is seamlessly integrated to provide real-time predictions and insights through dedicated API endpoints

Router Structure:

/api/auth          - User registration, login, token refresh
/api/users         - Profile management, preferences
/api/subjects      - Subject CRUD operations
/api/sessions      - Study session tracking
/api/flashcards    - Deck and card management, review sessions
/api/recommendations - ML predictions, optimal times, exam forecasts
/api/analytics     - Statistical data for visualizations

Technology Stack:

  • Framework: FastAPI (async/await support)
  • ORM: SQLAlchemy 2.0 with async support
  • Validation: Pydantic v2 for schema validation
  • Authentication: python-jose for JWT, passlib for password hashing
  • Database Drivers: asyncpg (PostgreSQL), aiosqlite (SQLite)
  • ML Library: scikit-learn, numpy, pandas
  • Task Queue: Redis for caching and future background tasks

๐ŸŽจ Frontend (React)

The frontend is a dynamic and responsive single-page application (SPA) built with React and TypeScript.

Architecture Highlights:

  • ๐Ÿงฉ Component-Based UI - The interface is constructed from reusable React components, styled with Tailwind CSS for a modern and consistent look
  • ๐Ÿ—บ๏ธ Client-Side Routing - React Router v6 manages navigation, providing a smooth, app-like user experience without full page reloads
  • ๐Ÿ”„ State Management - React's Context API is used for managing global state, such as user authentication (AuthContext) and theme (ThemeContext)
  • ๐ŸŒ API Communication - Axios is configured as the HTTP client for all communication with the backend API. An interceptor automatically attaches the JWT token to authorized requests
  • ๐Ÿ“Š Data Visualization - Recharts is used to render the interactive charts on the Analytics page

Component Hierarchy:

App
โ”œโ”€โ”€ AuthProvider (Context)
โ”œโ”€โ”€ ThemeProvider (Context)
โ”œโ”€โ”€ Router
    โ”œโ”€โ”€ Public Routes
    โ”‚   โ”œโ”€โ”€ Login
    โ”‚   โ””โ”€โ”€ Register
    โ””โ”€โ”€ Protected Routes
        โ”œโ”€โ”€ Dashboard
        โ”œโ”€โ”€ StudySessions
        โ”‚   โ”œโ”€โ”€ SessionList
        โ”‚   โ”œโ”€โ”€ SessionForm
        โ”‚   โ””โ”€โ”€ SessionDetail
        โ”œโ”€โ”€ Analytics
        โ”‚   โ”œโ”€โ”€ TimeChart
        โ”‚   โ”œโ”€โ”€ SubjectChart
        โ”‚   โ””โ”€โ”€ KPICards
        โ”œโ”€โ”€ Flashcards
        โ”‚   โ”œโ”€โ”€ DeckList
        โ”‚   โ”œโ”€โ”€ CardEditor
        โ”‚   โ””โ”€โ”€ ReviewSession
        โ”œโ”€โ”€ Recommendations
        โ”‚   โ”œโ”€โ”€ OptimalTimes
        โ”‚   โ””โ”€โ”€ ExamPredictor
        โ””โ”€โ”€ Settings
            โ”œโ”€โ”€ Profile
            โ”œโ”€โ”€ Subjects
            โ””โ”€โ”€ Preferences

Technology Stack:

  • Framework: React 18 with TypeScript
  • Build Tool: Vite for fast development and optimized builds
  • Styling: Tailwind CSS with custom design system
  • Routing: React Router v6
  • HTTP: Axios with interceptors
  • Charts: Recharts for responsive visualizations
  • Forms: React Hook Form for efficient form handling
  • Icons: Lucide React for consistent iconography

๐Ÿค– Machine Learning Model

The core of the "smart" features is the ProductivityPatternModel, located at backend/app/ml/productivity_model.py.

Model Specifications

Architecture:

RandomForestClassifier(
    n_estimators=100,      # 100 decision trees
    max_depth=10,          # Maximum tree depth
    min_samples_split=5,   # Minimum samples to split
    random_state=42        # Reproducible results
)

Purpose: To classify a given time slot as having "High" or "Low" predicted productivity for the user based on historical patterns.

Feature Engineering

Features Used for Training:

Feature Type Description Example Values
hour_of_day Integer Hour in 24h format 0-23
day_of_week Integer Day of week 0 (Mon) - 6 (Sun)
session_duration Float Length in minutes 30, 45, 60, 90
is_weekend Binary Weekend flag 0 (No), 1 (Yes)
time_of_day_category Categorical Time period Morning, Afternoon, Evening, Night

Feature Preprocessing:

  • Time of day categories are encoded numerically
  • Duration is normalized to handle various session lengths
  • All features are scaled for optimal model performance

Target Variable

The effectiveness_rating (1-5 scale) provided by the user is converted into a binary classification target:

  • High Productivity (1): Ratings of 4-5
  • Low Productivity (0): Ratings of 1-3

Model Training Process

# Pseudocode representation
1. Load user's study sessions from database
2. Extract and engineer features
3. Convert effectiveness ratings to binary labels
4. Split data (80% train, 20% validation)
5. Train Random Forest model
6. Validate with cross-validation
7. Save model for predictions

Prediction Output

When predicting optimal study times, the model provides:

  • Classification Label: "High" or "Low" productivity
  • Confidence Score: Probability (0-100%) of the prediction
  • Recommendation Context: Contextual advice based on confidence

Example Output:

{
  "day": "Monday",
  "hour": 14,
  "prediction": "High",
  "confidence": 87.5,
  "recommendation": "Highly recommended study time based on your patterns"
}

Model Limitations

  • Minimum Data Requirement: Needs at least 20 study sessions for reliable predictions
  • Cold Start Problem: New users receive research-based general recommendations until sufficient data is collected
  • Drift Handling: Model should be retrained periodically as study patterns evolve

๐Ÿ—ƒ๏ธ Database Schema

The application relies on a relational database (PostgreSQL in production, SQLite in development) with carefully designed tables optimized for both queries and machine learning.

Entity Relationship Diagram

erDiagram
    USERS ||--o{ SUBJECTS : owns
    USERS ||--o{ STUDY_SESSIONS : creates
    USERS ||--o{ FLASHCARD_DECKS : creates
    USERS ||--o{ PRODUCTIVITY_PROFILES : has
    SUBJECTS ||--o{ STUDY_SESSIONS : categorizes
    SUBJECTS ||--o{ FLASHCARD_DECKS : categorizes
    FLASHCARD_DECKS ||--o{ FLASHCARDS : contains
    
    USERS {
        uuid id PK
        string email UK
        string password_hash
        string full_name
        string timezone
        json preferences
        datetime created_at
        datetime updated_at
    }
    
    SUBJECTS {
        uuid id PK
        uuid user_id FK
        string name
        string color
        datetime created_at
    }
    
    STUDY_SESSIONS {
        uuid id PK
        uuid user_id FK
        uuid subject_id FK
        datetime start_time
        datetime end_time
        integer duration_minutes
        integer effectiveness_rating
        text notes
        integer day_of_week
        string time_of_day_category
        datetime created_at
    }
    
    FLASHCARD_DECKS {
        uuid id PK
        uuid user_id FK
        uuid subject_id FK
        string name
        text description
        datetime created_at
    }
    
    FLASHCARDS {
        uuid id PK
        uuid deck_id FK
        text question
        text answer
        datetime next_review_date
        integer interval_days
        float ease_factor
        integer review_count
        datetime created_at
        datetime last_reviewed
    }
    
    PRODUCTIVITY_PROFILES {
        uuid id PK
        uuid user_id FK
        binary model_data
        json metadata
        datetime created_at
        datetime updated_at
    }
Loading

Table Descriptions

๐Ÿ‘ค users

Stores user account information and preferences.

Column Type Description
id UUID Primary Key
email String(255) Unique identifier for login, indexed
password_hash String Bcrypt hashed password
full_name String(255) User's display name
timezone String(50) User's local timezone (e.g., "America/New_York")
preferences JSON App preferences like theme, notifications
created_at DateTime Account creation timestamp
updated_at DateTime Last profile update

๐Ÿ“š subjects

Stores user-defined academic subjects.

Column Type Description
id UUID Primary Key
user_id UUID Foreign Key โ†’ users.id
name String(100) Subject name (e.g., "Calculus I")
color String(7) Hex color code for UI (e.g., "#3B82F6")
created_at DateTime Subject creation timestamp

Indexes: user_id, composite index on (user_id, name)


๐Ÿ“ study_sessions

The central table for logging study dataโ€”the foundation of ML predictions.

Column Type Description
id UUID Primary Key
user_id UUID Foreign Key โ†’ users.id
subject_id UUID Foreign Key โ†’ subjects.id
start_time DateTime Session start timestamp
end_time DateTime Session end timestamp
duration_minutes Integer Calculated duration
effectiveness_rating Integer User rating (1-5 scale)
notes Text Optional session notes
day_of_week Integer Calculated (0=Monday, 6=Sunday)
time_of_day_category String(20) Calculated (Morning/Afternoon/Evening/Night)
created_at DateTime Log creation timestamp

Indexes: user_id, subject_id, start_time, composite index on (user_id, start_time DESC)

Business Logic:

  • Duration is auto-calculated: (end_time - start_time) in minutes
  • Day of week is derived from start_time
  • Time category is determined by hour:
    • Morning: 5:00-11:59
    • Afternoon: 12:00-16:59
    • Evening: 17:00-20:59
    • Night: 21:00-4:59

๐Ÿ—‚๏ธ flashcard_decks

Represents a collection of related flashcards.

Column Type Description
id UUID Primary Key
user_id UUID Foreign Key โ†’ users.id
subject_id UUID Foreign Key โ†’ subjects.id (optional)
name String(200) Deck name
description Text Optional description
created_at DateTime Deck creation timestamp

Indexes: user_id, subject_id


๐ŸŽด flashcards

Represents individual flashcards with SM-2 spaced repetition metadata.

Column Type Description
id UUID Primary Key
deck_id UUID Foreign Key โ†’ flashcard_decks.id
question Text Card front (question)
answer Text Card back (answer)
next_review_date DateTime When card is next due
interval_days Integer Current interval in days
ease_factor Float SM-2 ease factor (default 2.5)
review_count Integer Number of successful reviews
created_at DateTime Card creation timestamp
last_reviewed DateTime Last review timestamp

Indexes: deck_id, next_review_date, composite index on (deck_id, next_review_date)

SM-2 Algorithm Fields:

  • ease_factor: Determines how quickly intervals grow (min 1.3)
  • interval_days: Days until next review
  • next_review_date: Calculated as last_reviewed + interval_days

๐Ÿค– productivity_profiles

(Future Enhancement) Stores serialized trained ML models per user.

Column Type Description
id UUID Primary Key
user_id UUID Foreign Key โ†’ users.id, unique
model_data Binary Pickled scikit-learn model
metadata JSON Model metrics, training info
created_at DateTime Model creation timestamp
updated_at DateTime Last retrain timestamp

Indexes: user_id (unique)


๐Ÿš€ Getting Started

Follow these instructions to get the project running on your local machine for development and testing purposes.

Prerequisites

Ensure you have the following installed:

  • ๐Ÿณ Docker & Docker Compose - For the recommended containerized setup
  • ๐Ÿ“ฆ Node.js - v18 or higher (for manual frontend setup)
  • ๐Ÿ Python - v3.10 or higher (for manual backend setup)
  • ๐Ÿ“š Git - For cloning the repository
  • ๐Ÿ—„๏ธ PostgreSQL - (Optional) If running manually without Docker

1. ๐Ÿ“ฅ Clone the Repository

git clone <your-repository-url>
cd qwen-test

2. โš™๏ธ Configuration

The project uses .env files for environment variables. While the docker-compose.yml sets the necessary variables for the containers, for manual setup you will need to create these files.

Backend Configuration

Create a .env file inside the backend directory:

# Database Configuration
DATABASE_URL=postgresql+asyncpg://smartstudy:password@localhost:5432/smartstudy_db
# For SQLite (development): DATABASE_URL=sqlite+aiosqlite:///./smartstudy.db

# Security
SECRET_KEY=your-super-secret-key-change-this-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# Redis (for caching and background tasks)
REDIS_URL=redis://localhost:6379/0

# Application Settings
DEBUG=True
CORS_ORIGINS=["http://localhost:3000","http://localhost:5173"]

# ML Model Settings
MIN_SESSIONS_FOR_TRAINING=20
MODEL_CONFIDENCE_THRESHOLD=0.6

Frontend Configuration

Create a .env file inside the frontend directory:

# API Configuration
VITE_API_URL=http://localhost:8000

# Application Settings
VITE_APP_NAME=SmartStudy AI
VITE_APP_VERSION=1.0.0

3. ๐Ÿš€ Running the Application

Option A: Docker (Recommended) ๐Ÿณ

This is the simplest way to get the entire stack running (Frontend, Backend, PostgreSQL, Redis).

# Build and start all containers
docker-compose up --build

# Or run in detached mode
docker-compose up -d --build

Access the Application:

Docker Services:

  • frontend - React app (Port 3000)
  • backend - FastAPI server (Port 8000)
  • postgres - PostgreSQL database (Port 5432)
  • redis - Redis cache (Port 6379)

Useful Docker Commands:

# View logs
docker-compose logs -f

# Stop all services
docker-compose down

# Rebuild a specific service
docker-compose up -d --build backend

# Access backend shell
docker-compose exec backend bash

# Access PostgreSQL
docker-compose exec postgres psql -U smartstudy -d smartstudy_db

Option B: Manual Setup ๐Ÿ’ป

Use this method if you want to run the frontend and backend servers directly on your host machine.

Automated Setup (Windows)

The repository includes Windows batch scripts for quick setup:

# Install all dependencies (Python + Node.js)
setup.bat

# Start both development servers (opens 2 terminal windows)
start-dev.bat
Manual Steps (All Platforms)
1. Backend Setup
# Navigate to backend directory
cd backend

# Create and activate a virtual environment
python -m venv venv

# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Run database migrations (if using Alembic)
alembic upgrade head

# Start the FastAPI server
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

The backend will be available at: http://localhost:8000

2. Frontend Setup

Open a new terminal window:

# Navigate to frontend directory
cd frontend

# Install dependencies
npm install

# Start the development server
npm run dev

The frontend will be available at: http://localhost:5173 (or 3000 depending on Vite config)


Option C: Production Deployment ๐Ÿš€

For production deployment, you'll want to:

  1. Build optimized frontend:
cd frontend
npm run build
# Serve the 'dist' folder with Nginx or similar
  1. Run backend with production ASGI server:
cd backend
gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
  1. Use environment-specific configuration:
  • Set DEBUG=False
  • Use strong SECRET_KEY
  • Configure proper CORS_ORIGINS
  • Use managed PostgreSQL and Redis services
  1. Set up reverse proxy (Nginx example):
server {
    listen 80;
    server_name yourdomain.com;
    
    # Frontend
    location / {
        root /var/www/smartstudy/frontend/dist;
        try_files $uri $uri/ /index.html;
    }
    
    # Backend API
    location /api {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

๐Ÿ“š API Documentation

The FastAPI backend automatically generates interactive API documentation using OpenAPI (Swagger) and ReDoc.

Accessing Documentation

Once the backend server is running, access the documentation at:

Authentication

Most endpoints require JWT authentication. To test authenticated endpoints:

  1. Register a new user via /api/auth/register
  2. Login via /api/auth/login to get an access token
  3. Click the "Authorize" button in Swagger UI
  4. Enter: Bearer <your-access-token>
  5. Test protected endpoints

Core API Endpoints

๐Ÿ” Authentication (/api/auth)

Method Endpoint Description Auth Required
POST /api/auth/register Create new user account โŒ
POST /api/auth/login Authenticate and get JWT token โŒ
POST /api/auth/refresh Refresh access token โœ…
POST /api/auth/logout Invalidate tokens โœ…

Example Registration:

POST /api/auth/register
{
  "email": "student@example.com",
  "password": "SecurePass123!",
  "full_name": "John Doe",
  "timezone": "America/New_York"
}

๐Ÿ‘ค Users (/api/users)

Method Endpoint Description Auth Required
GET /api/users/me Get current user profile โœ…
PUT /api/users/me Update profile information โœ…
PUT /api/users/me/password Change password โœ…
PATCH /api/users/me/preferences Update app preferences โœ…

๐Ÿ“š Subjects (/api/subjects)

Method Endpoint Description Auth Required
GET /api/subjects List all user subjects โœ…
POST /api/subjects Create new subject โœ…
GET /api/subjects/{id} Get subject details โœ…
PUT /api/subjects/{id} Update subject โœ…
DELETE /api/subjects/{id} Delete subject โœ…

Example Subject Creation:

POST /api/subjects
{
  "name": "Calculus II",
  "color": "#3B82F6"
}

๐Ÿ“ Study Sessions (/api/sessions)

Method Endpoint Description Auth Required
GET /api/sessions List study sessions (with filters) โœ…
POST /api/sessions Log new study session โœ…
GET /api/sessions/{id} Get session details โœ…
PUT /api/sessions/{id} Update session โœ…
DELETE /api/sessions/{id} Delete session โœ…
GET /api/sessions/stats Get session statistics โœ…

Query Parameters for GET /api/sessions:

  • subject_id - Filter by subject
  • start_date - Filter sessions after date
  • end_date - Filter sessions before date
  • min_effectiveness - Filter by minimum rating
  • limit - Number of results (default: 50)
  • offset - Pagination offset

Example Session Creation:

POST /api/sessions
{
  "subject_id": "uuid-here",
  "start_time": "2025-10-03T14:00:00Z",
  "end_time": "2025-10-03T15:30:00Z",
  "effectiveness_rating": 4,
  "notes": "Focused session on derivatives. Good concentration."
}

๐ŸŽด Flashcards (/api/flashcards)

Method Endpoint Description Auth Required
GET /api/flashcards/decks List all decks โœ…
POST /api/flashcards/decks Create new deck โœ…
GET /api/flashcards/decks/{id} Get deck details โœ…
PUT /api/flashcards/decks/{id} Update deck โœ…
DELETE /api/flashcards/decks/{id} Delete deck โœ…
GET /api/flashcards/decks/{id}/cards List cards in deck โœ…
POST /api/flashcards/decks/{id}/cards Add card to deck โœ…
GET /api/flashcards/cards/{id} Get card details โœ…
PUT /api/flashcards/cards/{id} Update card โœ…
DELETE /api/flashcards/cards/{id} Delete card โœ…
GET /api/flashcards/due Get cards due for review โœ…
POST /api/flashcards/cards/{id}/review Submit review result โœ…

Example Review Submission:

POST /api/flashcards/cards/{id}/review
{
  "difficulty": "good"  // Options: "again", "hard", "good", "easy"
}

The SM-2 algorithm automatically calculates the next review date based on difficulty.


๐Ÿค– Recommendations (/api/recommendations)

Method Endpoint Description Auth Required
GET /api/recommendations/optimal-times Get AI-predicted best study times โœ…
GET /api/recommendations/insights Get productivity insights โœ…
POST /api/recommendations/predict-exam Predict exam performance โœ…
POST /api/recommendations/train-model Manually trigger model training โœ…

Example Exam Prediction Request:

POST /api/recommendations/predict-exam
{
  "subject_id": "uuid-here",
  "exam_date": "2025-12-15",
  "target_score": 85
}

Example Response:

{
  "predicted_score": 78.5,
  "confidence": 0.82,
  "recommendations": [
    "Increase study frequency to 5 sessions per week",
    "Focus on morning sessions (9-11 AM) for best results",
    "Aim for 60-minute sessions with 10-minute breaks"
  ],
  "days_until_exam": 73,
  "total_study_time_hours": 45.5,
  "sessions_completed": 28
}

๐Ÿ“Š Analytics (/api/analytics)

Method Endpoint Description Auth Required
GET /api/analytics/summary Get overall statistics โœ…
GET /api/analytics/time-distribution Study time by day/week โœ…
GET /api/analytics/subject-breakdown Time per subject โœ…
GET /api/analytics/effectiveness-trends Rating trends over time โœ…

Query Parameters:

  • period - Time range: "week", "month", "all"
  • subject_id - Filter by specific subject

Response Format

All API responses follow a consistent format:

Success Response:

{
  "status": "success",
  "data": { /* response data */ },
  "message": "Operation completed successfully"
}

Error Response:

{
  "status": "error",
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input data",
    "details": { /* error details */ }
  }
}

HTTP Status Codes:

  • 200 - Success
  • 201 - Created
  • 400 - Bad Request (validation error)
  • 401 - Unauthorized (invalid/missing token)
  • 403 - Forbidden (insufficient permissions)
  • 404 - Not Found
  • 500 - Internal Server Error

๐Ÿงช Testing

The project includes comprehensive test suites for both backend and frontend to ensure code quality and reliability.

Backend Tests (Pytest)

The backend uses Pytest with async support for testing.

Run all tests:

cd backend
pytest

Run with coverage report:

pytest --cov=app --cov-report=html

Run specific test file:

pytest tests/test_sessions.py

Run with verbose output:

pytest -v

Test Structure:

backend/tests/
โ”œโ”€โ”€ conftest.py              # Pytest fixtures and configuration
โ”œโ”€โ”€ test_auth.py             # Authentication tests
โ”œโ”€โ”€ test_sessions.py         # Study session tests
โ”œโ”€โ”€ test_subjects.py         # Subject management tests
โ”œโ”€โ”€ test_flashcards.py       # Flashcard and SM-2 algorithm tests
โ”œโ”€โ”€ test_recommendations.py  # ML model and predictions tests
โ””โ”€โ”€ test_analytics.py        # Analytics endpoint tests

Example Test:

@pytest.mark.asyncio
async def test_create_study_session(client, auth_headers):
    """Test creating a new study session"""
    response = await client.post(
        "/api/sessions",
        json={
            "subject_id": str(subject_id),
            "start_time": "2025-10-03T14:00:00Z",
            "end_time": "2025-10-03T15:00:00Z",
            "effectiveness_rating": 4
        },
        headers=auth_headers
    )
    assert response.status_code == 201
    assert response.json()["data"]["duration_minutes"] == 60

Frontend Tests (Vitest)

The frontend uses Vitest and React Testing Library for component and integration testing.

Run all tests:

cd frontend
npm run test

Run with coverage:

npm run test:coverage

Run in watch mode:

npm run test:watch

Run UI mode (interactive):

npm run test:ui

Test Structure:

frontend/src/
โ”œโ”€โ”€ components/
โ”‚   โ””โ”€โ”€ __tests__/
โ”‚       โ”œโ”€โ”€ Dashboard.test.tsx
โ”‚       โ”œโ”€โ”€ SessionForm.test.tsx
โ”‚       โ””โ”€โ”€ Analytics.test.tsx
โ”œโ”€โ”€ contexts/
โ”‚   โ””โ”€โ”€ __tests__/
โ”‚       โ”œโ”€โ”€ AuthContext.test.tsx
โ”‚       โ””โ”€โ”€ ThemeContext.test.tsx
โ””โ”€โ”€ utils/
    โ””โ”€โ”€ __tests__/
        โ””โ”€โ”€ api.test.ts

Example Component Test:

import { render, screen } from '@testing-library/react';
import { Dashboard } from '../Dashboard';

describe('Dashboard', () => {
  it('displays user statistics', () => {
    render(<Dashboard />);
    expect(screen.getByText(/Total Study Time/i)).toBeInTheDocument();
    expect(screen.getByText(/Sessions Completed/i)).toBeInTheDocument();
  });
});

Integration Tests

For end-to-end testing, consider using Playwright or Cypress:

# Example with Playwright
npm install -D @playwright/test
npx playwright test

Test Coverage Goals

  • Backend: Aim for 80%+ code coverage
  • Frontend: Aim for 70%+ code coverage
  • Critical Paths: 100% coverage for authentication, data validation, and ML predictions

๐Ÿ” Security Considerations

SmartStudy AI implements multiple security layers to protect user data:

Authentication & Authorization

  • JWT Tokens: Secure, stateless authentication
  • Password Hashing: Bcrypt with salt rounds
  • Token Expiration: Configurable access token lifetime
  • Refresh Tokens: Secure token rotation mechanism

Data Protection

  • SQL Injection Prevention: SQLAlchemy ORM with parameterized queries
  • XSS Protection: React's built-in escaping, Content Security Policy headers
  • CSRF Protection: SameSite cookies, CORS configuration
  • Input Validation: Pydantic schemas validate all inputs

Infrastructure

  • HTTPS Only: Enforce SSL/TLS in production
  • Environment Variables: Sensitive data never hardcoded
  • Rate Limiting: Prevent abuse (via Redis)
  • Database Encryption: Encrypted connections to PostgreSQL

Best Practices

  • Regular dependency updates
  • Security audits with npm audit and safety check
  • Principle of least privilege
  • Secure session management

๐ŸŽจ UI/UX Design Philosophy

SmartStudy AI follows modern design principles:

Design System

  • Color Palette: Carefully chosen colors for accessibility (WCAG AA compliant)
  • Typography: Clear hierarchy with readable fonts
  • Spacing: Consistent 8px grid system
  • Components: Reusable, composable UI elements

User Experience

  • Minimal Friction: Quick session logging (< 30 seconds)
  • Smart Defaults: AI-suggested times, auto-fill forms
  • Progressive Disclosure: Complex features hidden until needed
  • Feedback: Instant visual feedback for all actions
  • Mobile-First: Responsive design for all screen sizes

Accessibility

  • Keyboard Navigation: Full keyboard support
  • Screen Readers: ARIA labels and semantic HTML
  • Color Contrast: Meets WCAG guidelines
  • Focus Indicators: Clear focus states

๐Ÿ—บ๏ธ Roadmap

Phase 1: Current Features โœ…

  • โœ… Study session tracking
  • โœ… AI-powered recommendations
  • โœ… Spaced repetition flashcards
  • โœ… Analytics dashboard
  • โœ… Subject management

Phase 2: Enhanced Intelligence ๐Ÿšง

  • Deep Learning Models - LSTM for time-series prediction
  • NLP Analysis - Extract insights from session notes
  • Study Pattern Anomaly Detection - Alert when patterns deviate
  • Personalized Study Plans - AI-generated weekly schedules
  • Learning Style Assessment - Visual/Auditory/Kinesthetic profiling

Phase 3: Social & Collaboration ๐Ÿ“‹

  • Study Groups - Collaborative sessions and shared goals
  • Leaderboards - Friendly competition with peers
  • Mentor Matching - Connect with experienced students
  • Shared Flashcard Decks - Community-contributed content
  • Discussion Forums - Subject-specific Q&A

Phase 4: Advanced Features ๐Ÿ”ฎ

  • Mobile Apps - iOS and Android (React Native)
  • Calendar Integration - Google Calendar, Outlook sync
  • Voice Logging - Speech-to-text session notes
  • Pomodoro Timer - Built-in focus timer
  • Browser Extension - Quick-log from any webpage
  • Gamification - XP, levels, achievements, streaks
  • PDF/Document Scanner - Extract flashcards from documents
  • Video Integration - Track time spent on educational videos

Phase 5: Export & Integration ๐Ÿ”—

  • Export Reports - PDF, CSV study reports
  • LMS Integration - Canvas, Moodle, Blackboard
  • Notion/Obsidian Sync - Two-way note synchronization
  • Anki Import/Export - Flashcard compatibility
  • API for Third-Party Apps - Public developer API

๐Ÿค Contributing

Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated!

How to Contribute

  1. Fork the Project

    # Click the 'Fork' button on GitHub
  2. Clone Your Fork

    git clone https://github.com/your-username/qwen-test.git
    cd qwen-test
  3. Create a Feature Branch

    git checkout -b feature/AmazingFeature
  4. Make Your Changes

    • Write clean, documented code
    • Follow existing code style
    • Add tests for new features
  5. Commit Your Changes

    git commit -m 'Add some AmazingFeature'
  6. Push to Your Fork

    git push origin feature/AmazingFeature
  7. Open a Pull Request

    • Describe your changes clearly
    • Reference any related issues
    • Wait for code review

Development Guidelines

Code Style

  • Python: Follow PEP 8, use black formatter, type hints required
  • TypeScript: Follow ESLint rules, use Prettier formatter
  • Commits: Use conventional commits (feat:, fix:, docs:, etc.)

Documentation

  • Update README for new features
  • Add docstrings to Python functions
  • Comment complex logic
  • Update API docs if endpoints change

Testing

  • Write unit tests for new functions
  • Add integration tests for new endpoints
  • Ensure all tests pass before submitting PR
  • Aim for >80% code coverage

Pull Request Checklist

  • Code follows project style guidelines
  • Tests added and passing
  • Documentation updated
  • No merge conflicts
  • Descriptive PR title and description
  • Linked to related issue (if applicable)

Reporting Bugs

Found a bug? Please open an issue with:

  • Clear title - Summarize the bug
  • Steps to reproduce - How to trigger the bug
  • Expected behavior - What should happen
  • Actual behavior - What actually happens
  • Screenshots - If applicable
  • Environment - OS, browser, versions

Feature Requests

Have an idea? Open an issue with:

  • Use case - Why is this feature needed?
  • Proposed solution - How would it work?
  • Alternatives - Any alternative approaches?
  • Additional context - Mockups, examples, etc.

๐Ÿ’ฌ Community & Support

Get Help

  • ๐Ÿ“š Documentation: Check this README and API docs
  • ๐Ÿ’ฌ Discussions: Use GitHub Discussions for questions
  • ๐Ÿ› Issues: Report bugs via GitHub Issues
  • ๐Ÿ“ง Email: Contact Mudit Sharma (link in profile)

Stay Updated

  • โญ Star this repo to get notifications
  • ๐Ÿ‘€ Watch releases for new versions
  • ๐Ÿฆ Follow on social media (if applicable)

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

What this means:

  • โœ… Commercial use allowed
  • โœ… Modification allowed
  • โœ… Distribution allowed
  • โœ… Private use allowed
  • โš ๏ธ Liability and warranty limitations apply

๐Ÿ‘จโ€๐Ÿ’ป Creator

Mudit Sharma

Passionate about leveraging AI and machine learning to solve real-world problems and enhance learning experiences.

GitHub LinkedIn

Open to collaboration, feedback, and new opportunities!


๐Ÿ™ Acknowledgments

Special thanks to the amazing open-source community and these fantastic tools:

Frameworks & Libraries

  • FastAPI - Modern, fast web framework for Python
  • React - A JavaScript library for building user interfaces
  • TypeScript - JavaScript with syntax for types
  • scikit-learn - Machine learning in Python
  • SQLAlchemy - The Python SQL toolkit and ORM

UI & Visualization

Development Tools

  • Docker - Containerization platform
  • Vite - Next generation frontend tooling
  • Pytest - Testing framework for Python
  • Vitest - Blazing fast unit test framework

Research & Algorithms

  • SM-2 Algorithm - Created by Piotr Wozniak for spaced repetition
  • Random Forest - Leo Breiman's ensemble learning method
  • Various research papers on productivity and learning science

Inspiration

  • Study tracking apps that paved the way
  • Educational psychology research
  • The open-source community

๐Ÿ“Š Project Stats

GitHub repo size GitHub stars GitHub forks GitHub issues GitHub pull requests GitHub contributors GitHub last commit


๐ŸŒŸ Show Your Support

If you find SmartStudy AI helpful, please consider:

  • โญ Starring the repository - It helps others discover the project
  • ๐Ÿด Forking and contributing - Make it even better
  • ๐Ÿ› Reporting bugs - Help improve quality
  • ๐Ÿ’ก Suggesting features - Share your ideas
  • ๐Ÿ“ข Sharing with friends - Spread the word

๐Ÿ“š Study Smarter, Not Harder

Made with โค๏ธ, โ˜•, and ๐Ÿค– by Mudit Sharma


"The beautiful thing about learning is that no one can take it away from you." - B.B. King

About

Full-stack AI study companion: FastAPI + React, ML productivity predictions (Random Forest), SM-2 flashcards, session tracking, analytics, and Docker deployment.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages