diff --git a/.env b/.env new file mode 100644 index 0000000000000000000000000000000000000000..d74c13eaddace66ab819ec138f52da02249f6ca6 --- /dev/null +++ b/.env @@ -0,0 +1,11 @@ +# ── Anthropic ────────────────────────────────────────────── +ANTHROPIC_API_KEY=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 + +# ── Supabase ─────────────────────────────────────────────── +SUPABASE_URL=https://vzeyifrgjbmxjzqcpwhg.supabase.co +SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZ6ZXlpZnJnamJteGp6cWNwd2hnIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI0MTU3NjksImV4cCI6MjA4Nzk5MTc2OX0.yTtAs2bAtNftmfgO3Qz9UphnuAHfpLH2mqTW0gqRGSg +SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZ6ZXlpZnJnamJteGp6cWNwd2hnIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc3MjQxNTc2OSwiZXhwIjoyMDg3OTkxNzY5fQ.IAspx2EAv_AFIuyigYnxrX5dEp_mqkW0tFcnQ2L-jlw + +# ── FastAPI ──────────────────────────────────────────────── +ALLOWED_ORIGINS=http://localhost:8501 +API_BASE_URL=http://localhost:8000 diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cd6ff5cede3eb00b6ab9f4598273ce094a738d96 --- /dev/null +++ b/README.md @@ -0,0 +1,201 @@ +# 🧮 MathMind AI — MVP + +AI-powered adaptive math tutor for **Grades 6–12**. +Built with **Streamlit · FastAPI · Anthropic Claude · Supabase**. + +--- + +## Architecture + +``` +Streamlit (localhost:8501) + └── httpx calls → FastAPI (localhost:8000) + ├── Anthropic Claude API (AI explanations + tests) + └── Supabase (Auth + PostgreSQL) +``` + +--- + +## Quick Start + +### 1. Clone & Install + +```bash +git clone +cd mathmind +pip install -r requirements.txt +``` + +### 2. Configure Environment + +```bash +cp .env.example .env +# Fill in the values in .env (see Environment Variables section below) +``` + +### 3. Set Up Supabase + +1. Create a free project at [supabase.com](https://supabase.com) +2. Go to **SQL Editor** and run the scripts **in order**: + - `database/01_schema.sql` + - `database/02_rls.sql` + - `database/03_seed.sql` +3. Copy your project URL and keys from **Settings → API** + +### 4. Run the Backend + +```bash +# From the mathmind/ root directory +uvicorn backend.main:app --reload --port 8000 +``` + +Verify: open [http://localhost:8000/api/health](http://localhost:8000/api/health) +You should see: `{"status": "ok"}` + +### 5. Run the Frontend + +```bash +# In a second terminal, from the mathmind/ root directory +streamlit run streamlit_app/app.py +``` + +Open [http://localhost:8501](http://localhost:8501) in your browser. + +--- + +## Environment Variables + +Create a `.env` file in the `mathmind/` root: + +```bash +# Anthropic — get your key at console.anthropic.com +ANTHROPIC_API_KEY=sk-ant-... + +# Supabase — from your project: Settings → API +SUPABASE_URL=https://xxxx.supabase.co +SUPABASE_ANON_KEY=eyJ... # "anon" key (public) +SUPABASE_SERVICE_ROLE_KEY=eyJ... # "service_role" key (secret — never expose to browser) + +# FastAPI +ALLOWED_ORIGINS=http://localhost:8501 +API_BASE_URL=http://localhost:8000 +``` + +--- + +## Project Structure + +``` +mathmind/ +├── .env.example +├── README.md +├── requirements.txt +│ +├── streamlit_app/ # Frontend (Streamlit) +│ ├── app.py # Landing page + router +│ ├── pages/ +│ │ ├── 1_Login.py # Auth (login + signup) +│ │ ├── 2_Tutor.py # Core learning flow +│ │ └── 3_Dashboard.py # Badges + streak + history +│ └── utils/ +│ ├── auth.py # Supabase auth helpers +│ ├── api_client.py # FastAPI HTTP client +│ └── state.py # session_state helpers +│ +├── backend/ # API (FastAPI) +│ ├── main.py # App entry + CORS +│ ├── core/ +│ │ ├── config.py # Env var loading +│ │ └── auth.py # JWT verification +│ ├── routers/ +│ │ ├── explain.py # POST /api/explain +│ │ ├── practice.py # POST /api/practice +│ │ ├── test.py # POST /api/test/* +│ │ └── badges.py # GET/POST /api/badges +│ ├── services/ +│ │ ├── claude_service.py # Anthropic SDK wrapper +│ │ ├── supabase_service.py # Supabase client wrapper +│ │ └── prompt_templates.py # Grade-level prompts +│ └── models/ # Pydantic request/response models +│ +└── database/ + ├── 01_schema.sql # Table definitions + ├── 02_rls.sql # Row Level Security + ├── 03_seed.sql # Badge definitions + └── README.md +``` + +--- + +## API Endpoints + +| Method | Endpoint | Description | Auth | +|--------|----------|-------------|------| +| GET | `/api/health` | Health check | None | +| POST | `/api/explain` | Stream grade-appropriate explanation | JWT | +| POST | `/api/practice` | Generate 3 practice problems | JWT | +| POST | `/api/test/generate` | Generate 5-question mini-test | JWT | +| POST | `/api/test/evaluate` | Evaluate answers + save result | JWT | +| GET | `/api/badges` | Get student's earned badges | JWT | +| POST | `/api/badges/check` | Check + award new badges | JWT | + +Interactive docs: [http://localhost:8000/docs](http://localhost:8000/docs) + +--- + +## Student Flow + +``` +Sign Up → Select Grade → Ask Question + → Streamed Explanation + → Practice Problems (3x) + → Mini-Test (5 questions) + ├── PASS (≥80%) → Badge Awarded → Dashboard + └── FAIL (<80%) → See Feedback → Retry Test +``` + +--- + +## Badge System + +| Badge | Emoji | Condition | +|-------|-------|-----------| +| First Try Champion | 🏆 | Pass your first test | +| Getting Started | 🚀 | Complete 5 sessions | +| Math Explorer | 🌟 | Complete 10 sessions | +| On Fire | 🔥 | 5-day streak | +| Perfect Score | 💯 | Score 100% on a test | + +--- + +## Tech Stack + +| Layer | Technology | +|-------|-----------| +| Frontend | Streamlit 1.35+ | +| Backend | FastAPI + Uvicorn | +| AI | Anthropic Claude `claude-sonnet-4-6` | +| Database | Supabase (PostgreSQL + Auth + RLS) | +| HTTP Client | httpx (async-capable) | +| Validation | Pydantic v2 | + +--- + +## Development Notes + +- **Backend auto-reloads** on file changes with `--reload` +- **Streamlit auto-reloads** on file saves +- **JWT flow:** Supabase issues JWT on login → stored in `st.session_state` → sent as `Authorization: Bearer ` to FastAPI → FastAPI verifies via Supabase auth API +- **Streaming:** `/api/explain` uses FastAPI `StreamingResponse` + Anthropic streaming SDK → Streamlit renders chunks live +- **Service role key** is used by FastAPI only — bypasses RLS for server-side writes. Never expose to the browser. + +--- + +## Phase 2 Roadmap (not in MVP) + +- [ ] Re-engagement email nudges (SendGrid) +- [ ] LMS integration (Google Classroom, Canvas) +- [ ] Parent weekly report emails +- [ ] Adaptive ML difficulty engine +- [ ] Subscription/payment (Stripe) +- [ ] Mobile app diff --git a/backend/__init__.py b/backend/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/__pycache__/__init__.cpython-313.pyc b/backend/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c150b2bd0767e4dc31dfce0deeeff2804b9b80e3 Binary files /dev/null and b/backend/__pycache__/__init__.cpython-313.pyc differ diff --git a/backend/__pycache__/main.cpython-313.pyc b/backend/__pycache__/main.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..626fa4a444ce8482ebf1511de610b67bd96af179 Binary files /dev/null and b/backend/__pycache__/main.cpython-313.pyc differ diff --git a/backend/core/__init__.py b/backend/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/core/__pycache__/__init__.cpython-313.pyc b/backend/core/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84ce626488e7a58b49fc3bc16780cf1197371b0b Binary files /dev/null and b/backend/core/__pycache__/__init__.cpython-313.pyc differ diff --git a/backend/core/__pycache__/auth.cpython-313.pyc b/backend/core/__pycache__/auth.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef74444459cb86fc8e269e6f1e7d6c2cd7666aca Binary files /dev/null and b/backend/core/__pycache__/auth.cpython-313.pyc differ diff --git a/backend/core/__pycache__/config.cpython-313.pyc b/backend/core/__pycache__/config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37636ff606e8c7afe9b9f2cecd38f4a207d5ebe6 Binary files /dev/null and b/backend/core/__pycache__/config.cpython-313.pyc differ diff --git a/backend/core/auth.py b/backend/core/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..12d0ae7ba270feb5c665cdcbc1ebbdbebf5ff5c3 --- /dev/null +++ b/backend/core/auth.py @@ -0,0 +1,29 @@ +from fastapi import Depends, HTTPException, status +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +from supabase import create_client +from backend.core.config import settings + +bearer_scheme = HTTPBearer() + +# Service-role client — used only for JWT verification +_supabase = create_client(settings.supabase_url, settings.supabase_service_role_key) + + +async def get_current_user( + credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme), +) -> dict: + """ + Verify the Supabase JWT passed in the Authorization header. + Returns the decoded user payload on success. + """ + token = credentials.credentials + try: + response = _supabase.auth.get_user(token) + if response.user is None: + raise ValueError("No user in token") + return {"id": response.user.id, "email": response.user.email} + except Exception: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid or expired token", + ) diff --git a/backend/core/config.py b/backend/core/config.py new file mode 100644 index 0000000000000000000000000000000000000000..055a8206842086bc53ef0329181cb7a32a56916c --- /dev/null +++ b/backend/core/config.py @@ -0,0 +1,19 @@ +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + model_config = SettingsConfigDict(env_file=".env", extra="ignore") + + anthropic_api_key: str + supabase_url: str + supabase_anon_key: str + supabase_service_role_key: str + allowed_origins: str = "http://localhost:8501" + api_base_url: str = "http://localhost:8000" + + @property + def origins_list(self) -> list[str]: + return [o.strip() for o in self.allowed_origins.split(",")] + + +settings = Settings() diff --git a/backend/main.py b/backend/main.py new file mode 100644 index 0000000000000000000000000000000000000000..02f0d054cdbe1e2f6f3fb2f1a37c7bf6ad36a8d0 --- /dev/null +++ b/backend/main.py @@ -0,0 +1,32 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from backend.core.config import settings +from backend.routers import badges, explain, practice, test + +app = FastAPI( + title="MathMind AI API", + description="Adaptive math tutor backend — Grades 6–12", + version="1.0.0", +) + +# ── CORS ─────────────────────────────────────────────────────────────────────── +app.add_middleware( + CORSMiddleware, + allow_origins=settings.origins_list, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# ── Routers ──────────────────────────────────────────────────────────────────── +app.include_router(explain.router) +app.include_router(practice.router) +app.include_router(test.router) +app.include_router(badges.router) + + +# ── Health ───────────────────────────────────────────────────────────────────── +@app.get("/api/health", tags=["health"]) +async def health(): + return {"status": "ok", "service": "MathMind AI API", "version": "1.0.0"} diff --git a/backend/models/__init__.py b/backend/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/models/__pycache__/__init__.cpython-313.pyc b/backend/models/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d6f31d6f04e7f81e08c9cb9699f9c9a3bd0eedd Binary files /dev/null and b/backend/models/__pycache__/__init__.cpython-313.pyc differ diff --git a/backend/models/__pycache__/badges.cpython-313.pyc b/backend/models/__pycache__/badges.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df6897159811afa776e207bedf58ed1b2e64aa19 Binary files /dev/null and b/backend/models/__pycache__/badges.cpython-313.pyc differ diff --git a/backend/models/__pycache__/explain.cpython-313.pyc b/backend/models/__pycache__/explain.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c67463d343a2ae33fc4e3735f1c63164e04be2c7 Binary files /dev/null and b/backend/models/__pycache__/explain.cpython-313.pyc differ diff --git a/backend/models/__pycache__/practice.cpython-313.pyc b/backend/models/__pycache__/practice.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ea92a7988551ea3167ea0d69cb38e12c3a1bd37 Binary files /dev/null and b/backend/models/__pycache__/practice.cpython-313.pyc differ diff --git a/backend/models/__pycache__/test.cpython-313.pyc b/backend/models/__pycache__/test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c25450d8ae4a4817ae97fa17393baf07c85d8ae Binary files /dev/null and b/backend/models/__pycache__/test.cpython-313.pyc differ diff --git a/backend/models/badges.py b/backend/models/badges.py new file mode 100644 index 0000000000000000000000000000000000000000..bec8ee7e9c7de6d3b61e0c2f6c7166a4916dc964 --- /dev/null +++ b/backend/models/badges.py @@ -0,0 +1,23 @@ +from pydantic import BaseModel + + +class Badge(BaseModel): + id: str + name: str + emoji: str + description: str + + +class StudentBadge(BaseModel): + badge_id: str + earned_at: str + badges: Badge | None = None + + +class BadgeCheckRequest(BaseModel): + session_id: str + + +class BadgeCheckResponse(BaseModel): + newly_awarded: list[Badge] + total_badges: int diff --git a/backend/models/explain.py b/backend/models/explain.py new file mode 100644 index 0000000000000000000000000000000000000000..b3f9a70492dd488a1a0941a3f3555981000c831d --- /dev/null +++ b/backend/models/explain.py @@ -0,0 +1,7 @@ +from pydantic import BaseModel, Field + + +class ExplainRequest(BaseModel): + query: str = Field(..., min_length=3, max_length=500) + grade: int = Field(..., ge=6, le=12) + session_id: str | None = None # pass existing session ID to append diff --git a/backend/models/practice.py b/backend/models/practice.py new file mode 100644 index 0000000000000000000000000000000000000000..4e52a50fc41a95b0611c4201b6edf6ef0ea89324 --- /dev/null +++ b/backend/models/practice.py @@ -0,0 +1,20 @@ +from pydantic import BaseModel, Field + + +class PracticeRequest(BaseModel): + topic: str = Field(..., min_length=2, max_length=200) + grade: int = Field(..., ge=6, le=12) + session_id: str + count: int = Field(default=3, ge=1, le=5) + + +class PracticeProblem(BaseModel): + question: str + answer: str + hint: str + difficulty: str + + +class PracticeResponse(BaseModel): + problems: list[PracticeProblem] + session_id: str diff --git a/backend/models/test.py b/backend/models/test.py new file mode 100644 index 0000000000000000000000000000000000000000..e99e5872b4d4669ff93984123a4b2cb54bebb775 --- /dev/null +++ b/backend/models/test.py @@ -0,0 +1,46 @@ +from pydantic import BaseModel, Field + + +class TestGenerateRequest(BaseModel): + topic: str = Field(..., min_length=2, max_length=200) + grade: int = Field(..., ge=6, le=12) + session_id: str + + +class TestQuestion(BaseModel): + question: str + correct_answer: str + solution_steps: list[str] + type: str # "numerical" | "short_answer" + + +class TestGenerateResponse(BaseModel): + questions: list[TestQuestion] + session_id: str + + +class StudentAnswer(BaseModel): + question_index: int + question: str + correct_answer: str + student_answer: str + + +class TestEvaluateRequest(BaseModel): + session_id: str + answers: list[StudentAnswer] + attempt_number: int = 1 + + +class QuestionResult(BaseModel): + question_index: int + is_correct: bool + feedback: str + + +class TestEvaluateResponse(BaseModel): + results: list[QuestionResult] + score: int + passed: bool + encouragement: str + session_id: str diff --git a/backend/routers/__init__.py b/backend/routers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/routers/__pycache__/__init__.cpython-313.pyc b/backend/routers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2fecf0d10826d57ec412d8071a66f96d18c4e38 Binary files /dev/null and b/backend/routers/__pycache__/__init__.cpython-313.pyc differ diff --git a/backend/routers/__pycache__/badges.cpython-313.pyc b/backend/routers/__pycache__/badges.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdba573bd93bb67fb5a8de4f95c3fb3b1d349c6b Binary files /dev/null and b/backend/routers/__pycache__/badges.cpython-313.pyc differ diff --git a/backend/routers/__pycache__/explain.cpython-313.pyc b/backend/routers/__pycache__/explain.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0da6d616be36ab555c261f5c6ae4f2ec2a62305d Binary files /dev/null and b/backend/routers/__pycache__/explain.cpython-313.pyc differ diff --git a/backend/routers/__pycache__/practice.cpython-313.pyc b/backend/routers/__pycache__/practice.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e01c6e1029a51d8dda0a64cbc95b0eac39d6da2 Binary files /dev/null and b/backend/routers/__pycache__/practice.cpython-313.pyc differ diff --git a/backend/routers/__pycache__/test.cpython-313.pyc b/backend/routers/__pycache__/test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca54649b6d3c8ea2b711ba23ed8356166076ca53 Binary files /dev/null and b/backend/routers/__pycache__/test.cpython-313.pyc differ diff --git a/backend/routers/badges.py b/backend/routers/badges.py new file mode 100644 index 0000000000000000000000000000000000000000..a650abd8d4fe82b0af7f8eaa20698d7a5b148f1c --- /dev/null +++ b/backend/routers/badges.py @@ -0,0 +1,76 @@ +from fastapi import APIRouter, Depends + +from backend.core.auth import get_current_user +from backend.models.badges import Badge, BadgeCheckRequest, BadgeCheckResponse +from backend.services import supabase_service + +router = APIRouter(prefix="/api", tags=["badges"]) + +# Badge condition keys — matched against student stats +BADGE_CONDITIONS = { + "first_pass": lambda stats: stats["passed_tests"] >= 1, + "five_sessions": lambda stats: stats["total_sessions"] >= 5, + "ten_sessions": lambda stats: stats["total_sessions"] >= 10, + "streak_5": lambda stats: stats["streak"] >= 5, + "perfect_score": lambda stats: stats["last_score"] == 100, +} + + +@router.get("/badges", response_model=list[dict]) +async def get_badges(user: dict = Depends(get_current_user)): + """Return all badges earned by the current student.""" + return supabase_service.get_student_badges(user["id"]) + + +@router.post("/badges/check", response_model=BadgeCheckResponse) +async def check_badges( + body: BadgeCheckRequest, + user: dict = Depends(get_current_user), +): + """ + Check all badge conditions against current student stats. + Award any newly unlocked badges and return them. + """ + user_id = user["id"] + + # Gather stats + profile = supabase_service.get_profile(user_id) or {} + passed_tests = supabase_service.count_passed_tests(user_id) + total_sessions = supabase_service.count_sessions(user_id) + streak = profile.get("streak_count", 0) + + # Get last test score for this session + results = supabase_service.get_test_results(user_id) + last_score = 0 + if results: + last_score = results[0].get("score", 0) + + stats = { + "passed_tests": passed_tests, + "total_sessions": total_sessions, + "streak": streak, + "last_score": last_score, + } + + # Get all badge definitions and already-earned badges + all_badges = supabase_service.get_all_badges() + earned = {b["badge_id"] for b in supabase_service.get_student_badges(user_id)} + + newly_awarded: list[Badge] = [] + for badge in all_badges: + condition_key = badge.get("condition_key") + if condition_key in BADGE_CONDITIONS and badge["id"] not in earned: + if BADGE_CONDITIONS[condition_key](stats): + awarded = supabase_service.award_badge(user_id, badge["id"]) + if awarded: + newly_awarded.append( + Badge( + id=badge["id"], + name=badge["name"], + emoji=badge["emoji"], + description=badge["description"], + ) + ) + + total = len(supabase_service.get_student_badges(user_id)) + return BadgeCheckResponse(newly_awarded=newly_awarded, total_badges=total) diff --git a/backend/routers/explain.py b/backend/routers/explain.py new file mode 100644 index 0000000000000000000000000000000000000000..91a7098d877dce97b06eed5b20ec3edee63aa6f3 --- /dev/null +++ b/backend/routers/explain.py @@ -0,0 +1,44 @@ +from fastapi import APIRouter, Depends +from fastapi.responses import StreamingResponse + +from backend.core.auth import get_current_user +from backend.models.explain import ExplainRequest +from backend.services import claude_service, prompt_templates, supabase_service + +router = APIRouter(prefix="/api", tags=["explain"]) + + +@router.post("/explain") +async def explain( + body: ExplainRequest, + user: dict = Depends(get_current_user), +): + """ + Stream a grade-appropriate explanation for the student's math query. + Also creates a session record in Supabase and returns session_id in headers. + """ + system = prompt_templates.explanation_system(body.grade) + user_msg = prompt_templates.explanation_user(body.query) + + # Collect full explanation for DB storage while streaming to client + full_text_parts: list[str] = [] + + async def generate(): + async for chunk in claude_service.stream(system, user_msg): + full_text_parts.append(chunk) + yield chunk + # After stream complete — save session to Supabase + full_text = "".join(full_text_parts) + supabase_service.create_session( + user_id=user["id"], + topic=_extract_topic(body.query), + grade=body.grade, + explanation=full_text, + ) + + return StreamingResponse(generate(), media_type="text/plain") + + +def _extract_topic(query: str) -> str: + """Simple topic extraction — first 80 chars of query as topic label.""" + return query[:80].strip() diff --git a/backend/routers/practice.py b/backend/routers/practice.py new file mode 100644 index 0000000000000000000000000000000000000000..32baac5544c673208aebb708c43ca4935c91b1f0 --- /dev/null +++ b/backend/routers/practice.py @@ -0,0 +1,35 @@ +from fastapi import APIRouter, Depends, HTTPException + +from backend.core.auth import get_current_user +from backend.models.practice import PracticeRequest, PracticeResponse, PracticeProblem +from backend.services import claude_service, prompt_templates + +router = APIRouter(prefix="/api", tags=["practice"]) + + +@router.post("/practice", response_model=PracticeResponse) +async def generate_practice( + body: PracticeRequest, + user: dict = Depends(get_current_user), +): + """Generate 3 adaptive practice problems for the given topic and grade.""" + system = prompt_templates.practice_system(body.grade) + user_msg = prompt_templates.practice_user(body.topic, body.count) + + try: + raw = await claude_service.complete_json(system, user_msg) + except ValueError as e: + raise HTTPException(status_code=502, detail=str(e)) + + problems = [] + for item in (raw if isinstance(raw, list) else []): + problems.append( + PracticeProblem( + question=item.get("question", ""), + answer=item.get("answer", ""), + hint=item.get("hint", ""), + difficulty=item.get("difficulty", "medium"), + ) + ) + + return PracticeResponse(problems=problems, session_id=body.session_id) diff --git a/backend/routers/test.py b/backend/routers/test.py new file mode 100644 index 0000000000000000000000000000000000000000..eb89c7000a9565f09c1f0c08dc8d8f41163fe729 --- /dev/null +++ b/backend/routers/test.py @@ -0,0 +1,95 @@ +from fastapi import APIRouter, Depends, HTTPException + +from backend.core.auth import get_current_user +from backend.models.test import ( + TestEvaluateRequest, + TestEvaluateResponse, + TestGenerateRequest, + TestGenerateResponse, + TestQuestion, + QuestionResult, +) +from backend.services import claude_service, prompt_templates, supabase_service + +router = APIRouter(prefix="/api/test", tags=["test"]) + + +@router.post("/generate", response_model=TestGenerateResponse) +async def generate_test( + body: TestGenerateRequest, + user: dict = Depends(get_current_user), +): + """Generate a 5-question mini-test for the session topic.""" + system = prompt_templates.test_system(body.grade) + user_msg = prompt_templates.test_user(body.topic) + + try: + raw = await claude_service.complete_json(system, user_msg) + except ValueError as e: + raise HTTPException(status_code=502, detail=str(e)) + + questions = [] + for item in (raw if isinstance(raw, list) else []): + questions.append( + TestQuestion( + question=item.get("question", ""), + correct_answer=item.get("correct_answer", ""), + solution_steps=item.get("solution_steps", []), + type=item.get("type", "short_answer"), + ) + ) + + return TestGenerateResponse(questions=questions, session_id=body.session_id) + + +@router.post("/evaluate", response_model=TestEvaluateResponse) +async def evaluate_test( + body: TestEvaluateRequest, + user: dict = Depends(get_current_user), +): + """Evaluate student answers, save result to Supabase, return score + feedback.""" + system = prompt_templates.evaluate_system() + user_msg = prompt_templates.evaluate_user( + [a.model_dump() for a in body.answers] + ) + + try: + raw = await claude_service.complete_json(system, user_msg) + except ValueError as e: + raise HTTPException(status_code=502, detail=str(e)) + + score = int(raw.get("score", 0)) + passed = bool(raw.get("passed", False)) + encouragement = raw.get("encouragement", "Keep going!") + + results = [ + QuestionResult( + question_index=r.get("question_index", i), + is_correct=bool(r.get("is_correct", False)), + feedback=r.get("feedback", ""), + ) + for i, r in enumerate(raw.get("results", [])) + ] + + # Persist result + supabase_service.save_test_result( + session_id=body.session_id, + user_id=user["id"], + score=score, + passed=passed, + attempt_number=body.attempt_number, + ) + + # Update streak if passed + if passed: + profile = supabase_service.get_profile(user["id"]) + current_streak = (profile or {}).get("streak_count", 0) + supabase_service.update_streak(user["id"], current_streak + 1) + + return TestEvaluateResponse( + results=results, + score=score, + passed=passed, + encouragement=encouragement, + session_id=body.session_id, + ) diff --git a/backend/services/__init__.py b/backend/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/services/__pycache__/__init__.cpython-313.pyc b/backend/services/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09bb7ca2fb7b570796b1451566bf50bcb938ecf2 Binary files /dev/null and b/backend/services/__pycache__/__init__.cpython-313.pyc differ diff --git a/backend/services/__pycache__/claude_service.cpython-313.pyc b/backend/services/__pycache__/claude_service.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed4d2f53bb88659465b1f1310a84372230b77b91 Binary files /dev/null and b/backend/services/__pycache__/claude_service.cpython-313.pyc differ diff --git a/backend/services/__pycache__/prompt_templates.cpython-313.pyc b/backend/services/__pycache__/prompt_templates.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c76e243a9d70cb4013e72028352c8a52614084da Binary files /dev/null and b/backend/services/__pycache__/prompt_templates.cpython-313.pyc differ diff --git a/backend/services/__pycache__/supabase_service.cpython-313.pyc b/backend/services/__pycache__/supabase_service.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49a42ade8fd7b49a0db3cb833f4ade3a8e7ed1a2 Binary files /dev/null and b/backend/services/__pycache__/supabase_service.cpython-313.pyc differ diff --git a/backend/services/claude_service.py b/backend/services/claude_service.py new file mode 100644 index 0000000000000000000000000000000000000000..5b4d23872b643494c366f35651ebb14900d99eee --- /dev/null +++ b/backend/services/claude_service.py @@ -0,0 +1,60 @@ +""" +Claude service — wraps the Anthropic async client. +Provides two modes: + - stream() : yields text chunks (for explanations) + - complete() : returns full text (for JSON outputs) +""" + +import json +import re +from typing import AsyncIterator + +import anthropic + +from backend.core.config import settings + +MODEL = "claude-sonnet-4-6" +MAX_TOKENS = 1024 + +_client = anthropic.AsyncAnthropic(api_key=settings.anthropic_api_key) + + +async def stream(system: str, user: str) -> AsyncIterator[str]: + """Stream response chunks — used for explanation endpoint.""" + async with _client.messages.stream( + model=MODEL, + max_tokens=MAX_TOKENS, + system=system, + messages=[{"role": "user", "content": user}], + ) as stream: + async for text in stream.text_stream: + yield text + + +async def complete(system: str, user: str, max_tokens: int = MAX_TOKENS) -> str: + """Return full response text — used for JSON-output endpoints.""" + message = await _client.messages.create( + model=MODEL, + max_tokens=max_tokens, + system=system, + messages=[{"role": "user", "content": user}], + ) + return message.content[0].text + + +async def complete_json(system: str, user: str) -> dict | list: + """ + Return parsed JSON — retries once if the first response is malformed. + Strips markdown code fences if present. + """ + for attempt in range(2): + raw = await complete(system, user) + # Strip ```json ... ``` fences + cleaned = re.sub(r"^```(?:json)?\s*|\s*```$", "", raw.strip(), flags=re.MULTILINE) + try: + return json.loads(cleaned) + except json.JSONDecodeError: + if attempt == 1: + raise ValueError(f"Claude returned invalid JSON after 2 attempts: {raw[:200]}") + # Retry with an explicit reminder + user = user + "\n\nIMPORTANT: Return ONLY valid JSON. No markdown." diff --git a/backend/services/prompt_templates.py b/backend/services/prompt_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..74fefdb37c2996807dc19f5f1d12340a0755aab7 --- /dev/null +++ b/backend/services/prompt_templates.py @@ -0,0 +1,121 @@ +""" +Prompt templates for each grade band and each AI call type. +Grade bands: 6-7 (elementary), 8-9 (middle), 10-12 (high school) +""" + +GRADE_BAND = { + 6: "elementary", 7: "elementary", + 8: "middle", 9: "middle", + 10: "high", 11: "high", 12: "high", +} + +GRADE_STYLE = { + "elementary": ( + "Use very simple, everyday language. Avoid jargon. " + "Use at most 4 numbered steps. Include a fun real-world example. " + "Encourage the student warmly." + ), + "middle": ( + "Use clear language and introduce formal math terms with brief definitions. " + "Use at most 6 numbered steps with a worked example. " + "Keep an encouraging but slightly more academic tone." + ), + "high": ( + "Use precise mathematical language and full algebraic notation. " + "Use up to 8 numbered steps. Include exam-style worked examples. " + "Assume the student is preparing for standardised tests." + ), +} + + +def band(grade: int) -> str: + return GRADE_BAND.get(grade, "middle") + + +def style(grade: int) -> str: + return GRADE_STYLE.get(band(grade), GRADE_STYLE["middle"]) + + +# ── Explanation ──────────────────────────────────────────────────────────────── +def explanation_system(grade: int) -> str: + return ( + f"You are MathMind AI, an expert mathematics tutor for Grade {grade} students. " + f"{style(grade)} " + "Only answer mathematics questions. If the question is off-topic, respond: " + "'I can only help with math! Try asking me about a specific topic like algebra or fractions.' " + "Format your response as numbered steps. End with: 'Ready to practise? Type YES!'" + ) + + +def explanation_user(query: str) -> str: + return f"Explain the following math concept or solve this problem:\n\n{query}" + + +# ── Practice Problems ────────────────────────────────────────────────────────── +def practice_system(grade: int) -> str: + return ( + f"You are MathMind AI generating practice problems for a Grade {grade} student. " + f"{style(grade)} " + "Respond ONLY with a valid JSON array. No markdown, no preamble. " + "Each element must have exactly these keys: " + '"question" (string), "answer" (string), "hint" (string), "difficulty" ("easy"|"medium"|"hard"). ' + "All problems must be solvable with Grade {grade} knowledge." + ) + + +def practice_user(topic: str, count: int = 3) -> str: + return ( + f"Generate {count} practice problems on the topic: {topic}. " + "Return ONLY the JSON array." + ) + + +# ── Test Generation ──────────────────────────────────────────────────────────── +def test_system(grade: int) -> str: + return ( + f"You are MathMind AI generating a mini-test for a Grade {grade} student. " + f"{style(grade)} " + "Respond ONLY with a valid JSON array. No markdown, no preamble. " + "Each element must have exactly these keys: " + '"question" (string), "correct_answer" (string), ' + '"solution_steps" (array of strings), "type" ("numerical"|"short_answer"). ' + "Generate exactly 5 questions of increasing difficulty." + ) + + +def test_user(topic: str) -> str: + return f"Generate a 5-question mini-test on the topic: {topic}. Return ONLY the JSON array." + + +# ── Answer Evaluation ────────────────────────────────────────────────────────── +def evaluate_system() -> str: + return ( + "You are a math answer evaluator. " + "You will receive a list of questions with correct answers and student answers. " + "Be lenient with formatting differences (e.g. '1/2' == '0.5'). " + "Respond ONLY with a valid JSON object with these keys: " + '"results" (array of {"question_index": int, "is_correct": bool, "feedback": string}), ' + '"score" (integer 0-100), ' + '"passed" (bool, true if score >= 80), ' + '"encouragement" (string, a short motivating message). ' + "No markdown, no preamble." + ) + + +def evaluate_user(qa_pairs: list[dict]) -> str: + lines = [] + for i, pair in enumerate(qa_pairs): + lines.append( + f"Q{i+1}: {pair['question']}\n" + f" Correct answer: {pair['correct_answer']}\n" + f" Student answer: {pair['student_answer']}" + ) + return "Evaluate these answers:\n\n" + "\n\n".join(lines) + + +# ── Weekly Report (Phase 2 placeholder) ─────────────────────────────────────── +def weekly_report_system() -> str: + return ( + "You are MathMind AI writing a friendly weekly progress report. " + "Keep it under 200 words. Be warm, specific, and encouraging." + ) diff --git a/backend/services/supabase_service.py b/backend/services/supabase_service.py new file mode 100644 index 0000000000000000000000000000000000000000..ad78264f120b8432336d2959a8888e2d37e13903 --- /dev/null +++ b/backend/services/supabase_service.py @@ -0,0 +1,170 @@ +""" +Supabase service — single client instance used by all routers. +Uses the service role key so it can bypass RLS for server operations. +""" + +from supabase import Client, create_client +from backend.core.config import settings + +_client: Client = create_client( + settings.supabase_url, + settings.supabase_service_role_key, +) + + +def db() -> Client: + """Return the Supabase client.""" + return _client + + +# ── Profiles ─────────────────────────────────────────────────────────────────── +def get_profile(user_id: str) -> dict | None: + res = _client.table("profiles").select("*").eq("id", user_id).single().execute() + return res.data + + +def upsert_profile(user_id: str, grade: int) -> dict: + res = ( + _client.table("profiles") + .upsert({"id": user_id, "grade": grade}) + .execute() + ) + return res.data[0] if res.data else {} + + +def update_streak(user_id: str, streak: int) -> None: + from datetime import date + _client.table("profiles").update( + {"streak_count": streak, "last_active": date.today().isoformat()} + ).eq("id", user_id).execute() + + +# ── Sessions ─────────────────────────────────────────────────────────────────── +def create_session(user_id: str, topic: str, grade: int, explanation: str) -> dict: + res = ( + _client.table("sessions") + .insert( + { + "user_id": user_id, + "topic": topic, + "grade": grade, + "explanation": explanation, + } + ) + .execute() + ) + return res.data[0] + + +def get_sessions(user_id: str, limit: int = 10) -> list[dict]: + res = ( + _client.table("sessions") + .select("*") + .eq("user_id", user_id) + .order("created_at", desc=True) + .limit(limit) + .execute() + ) + return res.data or [] + + +# ── Practice Attempts ────────────────────────────────────────────────────────── +def save_practice_attempts(session_id: str, attempts: list[dict]) -> None: + rows = [ + { + "session_id": session_id, + "question": a["question"], + "student_answer": a.get("student_answer", ""), + "is_correct": a.get("is_correct", False), + } + for a in attempts + ] + _client.table("practice_attempts").insert(rows).execute() + + +# ── Test Results ─────────────────────────────────────────────────────────────── +def save_test_result( + session_id: str, user_id: str, score: int, passed: bool, attempt_number: int = 1 +) -> dict: + res = ( + _client.table("test_results") + .insert( + { + "session_id": session_id, + "user_id": user_id, + "score": score, + "passed": passed, + "attempts": attempt_number, + } + ) + .execute() + ) + return res.data[0] + + +def get_test_results(user_id: str) -> list[dict]: + res = ( + _client.table("test_results") + .select("*, sessions(topic)") + .eq("user_id", user_id) + .order("created_at", desc=True) + .limit(20) + .execute() + ) + return res.data or [] + + +# ── Badges ───────────────────────────────────────────────────────────────────── +def get_all_badges() -> list[dict]: + res = _client.table("badges").select("*").execute() + return res.data or [] + + +def get_student_badges(user_id: str) -> list[dict]: + res = ( + _client.table("student_badges") + .select("*, badges(name, emoji, description)") + .eq("user_id", user_id) + .execute() + ) + return res.data or [] + + +def award_badge(user_id: str, badge_id: str) -> dict | None: + # Check not already awarded + existing = ( + _client.table("student_badges") + .select("id") + .eq("user_id", user_id) + .eq("badge_id", badge_id) + .execute() + ) + if existing.data: + return None + res = ( + _client.table("student_badges") + .insert({"user_id": user_id, "badge_id": badge_id}) + .execute() + ) + return res.data[0] if res.data else None + + +def count_passed_tests(user_id: str) -> int: + res = ( + _client.table("test_results") + .select("id", count="exact") + .eq("user_id", user_id) + .eq("passed", True) + .execute() + ) + return res.count or 0 + + +def count_sessions(user_id: str) -> int: + res = ( + _client.table("sessions") + .select("id", count="exact") + .eq("user_id", user_id) + .execute() + ) + return res.count or 0 diff --git a/database/01_schema.sql b/database/01_schema.sql new file mode 100644 index 0000000000000000000000000000000000000000..afaa2d9c083432772628dff41fd20a99bb1cd4e7 --- /dev/null +++ b/database/01_schema.sql @@ -0,0 +1,133 @@ +-- ============================================================ +-- MathMind AI — Database Schema +-- Run this in: Supabase Dashboard → SQL Editor +-- Order: 01_schema.sql → 02_rls.sql → 03_seed.sql +-- ============================================================ + +-- Enable UUID generation +create extension if not exists "pgcrypto"; + +-- ── 1. profiles ──────────────────────────────────────────── +-- Extends auth.users — one row per student +create table if not exists public.profiles ( + id uuid primary key references auth.users(id) on delete cascade, + grade smallint not null check (grade between 6 and 12), + streak_count integer not null default 0, + last_active date, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +comment on table public.profiles is 'Student profile — extends Supabase auth.users'; + +-- Auto-update updated_at +create or replace function public.set_updated_at() +returns trigger language plpgsql as $$ +begin + new.updated_at = now(); + return new; +end; +$$; + +create trigger profiles_updated_at + before update on public.profiles + for each row execute function public.set_updated_at(); + + +-- ── 2. sessions ──────────────────────────────────────────── +-- One row per tutor session (question + explanation) +create table if not exists public.sessions ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references public.profiles(id) on delete cascade, + topic text not null, + grade smallint not null check (grade between 6 and 12), + explanation text not null, + created_at timestamptz not null default now() +); + +comment on table public.sessions is 'One tutor session per student question'; + +create index if not exists sessions_user_id_idx on public.sessions(user_id); +create index if not exists sessions_created_at_idx on public.sessions(created_at desc); + + +-- ── 3. practice_attempts ─────────────────────────────────── +-- Practice problem responses within a session +create table if not exists public.practice_attempts ( + id uuid primary key default gen_random_uuid(), + session_id uuid not null references public.sessions(id) on delete cascade, + question text not null, + student_answer text not null default '', + is_correct boolean not null default false, + created_at timestamptz not null default now() +); + +comment on table public.practice_attempts is 'Student answers to practice problems'; + +create index if not exists practice_attempts_session_idx on public.practice_attempts(session_id); + + +-- ── 4. test_results ──────────────────────────────────────── +-- Mini-test outcomes per session +create table if not exists public.test_results ( + id uuid primary key default gen_random_uuid(), + session_id uuid not null references public.sessions(id) on delete cascade, + user_id uuid not null references public.profiles(id) on delete cascade, + score smallint not null check (score between 0 and 100), + passed boolean not null default false, + attempts smallint not null default 1, + created_at timestamptz not null default now() +); + +comment on table public.test_results is 'Mini-test results — 80% threshold for pass'; + +create index if not exists test_results_user_id_idx on public.test_results(user_id); +create index if not exists test_results_session_idx on public.test_results(session_id); + + +-- ── 5. badges ────────────────────────────────────────────── +-- Badge definitions (populated by 03_seed.sql) +create table if not exists public.badges ( + id uuid primary key default gen_random_uuid(), + name text not null unique, + emoji text not null, + condition_key text not null unique, -- matched in Python badge engine + description text not null, + created_at timestamptz not null default now() +); + +comment on table public.badges is 'Badge definitions — condition_key matched by badge engine'; + + +-- ── 6. student_badges ────────────────────────────────────── +-- Badges earned by each student +create table if not exists public.student_badges ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references public.profiles(id) on delete cascade, + badge_id uuid not null references public.badges(id) on delete cascade, + earned_at timestamptz not null default now(), + unique(user_id, badge_id) -- a student earns each badge only once +); + +comment on table public.student_badges is 'Badges awarded to students'; + +create index if not exists student_badges_user_idx on public.student_badges(user_id); + + +-- ── Auto-create profile on signup ────────────────────────── +-- Triggered when a new user signs up via Supabase Auth +-- Grade defaults to 8 until the student sets it in the app +create or replace function public.handle_new_user() +returns trigger language plpgsql security definer as $$ +begin + insert into public.profiles (id, grade) + values (new.id, 8) + on conflict (id) do nothing; + return new; +end; +$$; + +drop trigger if exists on_auth_user_created on auth.users; +create trigger on_auth_user_created + after insert on auth.users + for each row execute function public.handle_new_user(); diff --git a/database/02_rls.sql b/database/02_rls.sql new file mode 100644 index 0000000000000000000000000000000000000000..ee1c4a9d160010756658bb0914ce3f354a958bb6 --- /dev/null +++ b/database/02_rls.sql @@ -0,0 +1,93 @@ +-- ============================================================ +-- MathMind AI — Row Level Security (RLS) +-- Run AFTER 01_schema.sql +-- ============================================================ + +-- Enable RLS on all student-data tables +alter table public.profiles enable row level security; +alter table public.sessions enable row level security; +alter table public.practice_attempts enable row level security; +alter table public.test_results enable row level security; +alter table public.student_badges enable row level security; + +-- badges table is read-only for all authenticated users (definitions, not student data) +alter table public.badges enable row level security; + + +-- ── profiles ─────────────────────────────────────────────── +create policy "Students can view own profile" + on public.profiles for select + using (auth.uid() = id); + +create policy "Students can update own profile" + on public.profiles for update + using (auth.uid() = id); + +create policy "Students can insert own profile" + on public.profiles for insert + with check (auth.uid() = id); + + +-- ── sessions ─────────────────────────────────────────────── +create policy "Students can view own sessions" + on public.sessions for select + using (auth.uid() = user_id); + +create policy "Students can insert own sessions" + on public.sessions for insert + with check (auth.uid() = user_id); + + +-- ── practice_attempts ────────────────────────────────────── +-- Students access their own attempts via session ownership +create policy "Students can view own practice attempts" + on public.practice_attempts for select + using ( + exists ( + select 1 from public.sessions s + where s.id = practice_attempts.session_id + and s.user_id = auth.uid() + ) + ); + +create policy "Students can insert own practice attempts" + on public.practice_attempts for insert + with check ( + exists ( + select 1 from public.sessions s + where s.id = practice_attempts.session_id + and s.user_id = auth.uid() + ) + ); + + +-- ── test_results ─────────────────────────────────────────── +create policy "Students can view own test results" + on public.test_results for select + using (auth.uid() = user_id); + +create policy "Students can insert own test results" + on public.test_results for insert + with check (auth.uid() = user_id); + + +-- ── badges (definitions — read-only for all auth users) ──── +create policy "All authenticated users can read badges" + on public.badges for select + using (auth.role() = 'authenticated'); + + +-- ── student_badges ───────────────────────────────────────── +create policy "Students can view own earned badges" + on public.student_badges for select + using (auth.uid() = user_id); + +create policy "Students can insert own earned badges" + on public.student_badges for insert + with check (auth.uid() = user_id); + + +-- ── Service role bypass ──────────────────────────────────── +-- The FastAPI backend uses service_role key which bypasses RLS. +-- This is intentional — backend does server-side validation before +-- writing to the DB. Never expose service_role key to the client. diff --git a/database/03_seed.sql b/database/03_seed.sql new file mode 100644 index 0000000000000000000000000000000000000000..cb111fe36cac53a356f19e2af918536dd602f14a --- /dev/null +++ b/database/03_seed.sql @@ -0,0 +1,90 @@ +-- ============================================================ +-- MathMind AI — Seed Data +-- Run AFTER 02_rls.sql +-- ============================================================ + +-- ── Badge definitions ────────────────────────────────────── +-- condition_key must match keys in backend/routers/badges.py BADGE_CONDITIONS + +insert into public.badges (name, emoji, condition_key, description) values + ( + 'First Try Champion', + '🏆', + 'first_pass', + 'Passed your first mini-test — you''re officially a MathMind champion!' + ), + ( + 'Getting Started', + '🚀', + 'five_sessions', + 'Completed 5 learning sessions — the journey has begun!' + ), + ( + 'Math Explorer', + '🌟', + 'ten_sessions', + 'Completed 10 sessions — you are truly exploring mathematics!' + ), + ( + 'On Fire', + '🔥', + 'streak_5', + 'Maintained a 5-day learning streak — you''re on fire!' + ), + ( + 'Perfect Score', + '💯', + 'perfect_score', + 'Scored 100% on a mini-test — flawless!' + ) +on conflict (name) do nothing; + + +-- ── Sample math topics (for reference / future topic picker UI) ───────────── +-- This is a reference table only — not used by the app logic directly. +-- Uncomment and extend if you add a topic browser feature. + +/* +create table if not exists public.sample_topics ( + id uuid primary key default gen_random_uuid(), + grade smallint not null, + topic text not null +); + +insert into public.sample_topics (grade, topic) values + -- Grade 6 + (6, 'Fractions and mixed numbers'), + (6, 'Ratios and proportions'), + (6, 'Area and perimeter'), + (6, 'Introduction to negative numbers'), + -- Grade 7 + (7, 'Linear equations'), + (7, 'Percentages and discounts'), + (7, 'Angles and triangles'), + (7, 'Introduction to probability'), + -- Grade 8 + (8, 'Systems of linear equations'), + (8, 'Pythagorean theorem'), + (8, 'Functions and graphs'), + (8, 'Scientific notation'), + -- Grade 9 + (9, 'Quadratic equations'), + (9, 'Factoring polynomials'), + (9, 'Introduction to trigonometry'), + (9, 'Inequalities'), + -- Grade 10 + (10, 'Trigonometric ratios'), + (10, 'Circle theorems'), + (10, 'Sequences and series'), + (10, 'Probability and statistics'), + -- Grade 11 + (11, 'Logarithms and exponentials'), + (11, 'Binomial theorem'), + (11, 'Vectors'), + (11, 'Differentiation introduction'), + -- Grade 12 + (12, 'Integration'), + (12, 'Complex numbers'), + (12, 'Matrices'), + (12, 'Permutations and combinations'); +*/ diff --git a/database/README.md b/database/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f9320c290eaad71cea8b8228160934361ee9c09a --- /dev/null +++ b/database/README.md @@ -0,0 +1,27 @@ +# MathMind AI — Database Setup + +## Steps + +1. Go to your **Supabase Dashboard → SQL Editor** +2. Run the scripts **in order**: + - `01_schema.sql` — creates all 6 tables + triggers + - `02_rls.sql` — enables Row Level Security + - `03_seed.sql` — inserts 5 badge definitions + +## Tables Created + +| Table | Purpose | +|-------|---------| +| `profiles` | Student grade + streak (extends auth.users) | +| `sessions` | One row per tutor session | +| `practice_attempts` | Practice problem responses | +| `test_results` | Mini-test scores and pass/fail | +| `badges` | Badge definitions | +| `student_badges` | Badges earned by each student | + +## Notes + +- **RLS is enabled** — students can only read/write their own data +- **Service role key** used by FastAPI backend bypasses RLS (server-side only — never expose to client) +- **Auto-trigger** creates a `profiles` row (grade=8 default) on every new signup +- Student must update their grade in the app after signup diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..86e33427c412c79308fb54384609136183f28a4c --- /dev/null +++ b/requirements.txt @@ -0,0 +1,13 @@ +# Backend +fastapi>=0.111.0 +uvicorn[standard]>=0.29.0 +anthropic>=0.25.0 +supabase>=2.4.0 +python-dotenv>=1.0.0 +pydantic-settings>=2.2.0 +pydantic>=2.6.0 +httpx>=0.27.0 +python-jose[cryptography]>=3.3.0 + +# Frontend +streamlit>=1.35.0 diff --git a/streamlit_app/app.py b/streamlit_app/app.py new file mode 100644 index 0000000000000000000000000000000000000000..337e2862569880df851d0656784dc24bf45ac62d --- /dev/null +++ b/streamlit_app/app.py @@ -0,0 +1,51 @@ +import streamlit as st +import sys, os +sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) + +st.set_page_config( + page_title="MathMind AI", + page_icon="🧮", + layout="centered", + initial_sidebar_state="auto", +) + +from streamlit_app.utils.auth import is_logged_in + +# ── Landing page ─────────────────────────────────────────────────────────────── +st.markdown(""" + + +
+

🧮 MathMind AI

+

Your personal AI math tutor for Grades 6 – 12

+
+""", unsafe_allow_html=True) + +col1, col2, col3 = st.columns(3) +with col1: + st.info("🧠 **Adaptive Explanations**\nGrade-calibrated, step-by-step answers to any math question") +with col2: + st.info("📝 **Mini-Tests**\nProve your understanding with a 5-question test and instant feedback") +with col3: + st.info("🏆 **Badges & Streaks**\nEarn rewards and track your daily learning streak") + +st.divider() + +if is_logged_in(): + st.success(f"Welcome back! You're logged in as **{st.session_state.get('user_email', '')}**") + col_a, col_b = st.columns(2) + with col_a: + st.page_link("pages/2_Tutor.py", label="▶️ Start Learning", use_container_width=True) + with col_b: + st.page_link("pages/3_Dashboard.py", label="📊 My Dashboard", use_container_width=True) +else: + st.page_link("pages/1_Login.py", label="🚀 Get Started — Login or Sign Up", use_container_width=True) diff --git a/streamlit_app/pages/1_Login.py b/streamlit_app/pages/1_Login.py new file mode 100644 index 0000000000000000000000000000000000000000..60a2d91dd643a20335225213d4de2ccf9b41a57e --- /dev/null +++ b/streamlit_app/pages/1_Login.py @@ -0,0 +1,69 @@ +import streamlit as st +import sys, os +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) + +from streamlit_app.utils.auth import login, signup, is_logged_in, logout + +st.set_page_config(page_title="MathMind AI — Login", page_icon="🔐", layout="centered") + +# Already logged in +if is_logged_in(): + st.success(f"✅ Logged in as **{st.session_state.get('user_email')}**") + st.page_link("pages/2_Tutor.py", label="▶️ Go to Tutor", use_container_width=True) + if st.button("Log out"): + logout() + st.rerun() + st.stop() + +st.title("🔐 Login to MathMind AI") +st.caption("Your personal AI math tutor — Grades 6–12") +st.divider() + +tab_login, tab_signup = st.tabs(["Log In", "Sign Up"]) + +# ── Login Tab ────────────────────────────────────────────────────────────────── +with tab_login: + st.subheader("Welcome back!") + email_l = st.text_input("Email", key="login_email", placeholder="you@example.com") + pass_l = st.text_input("Password", type="password", key="login_pass") + + if st.button("Log In", type="primary", use_container_width=True, key="btn_login"): + if not email_l or not pass_l: + st.error("Please enter your email and password.") + else: + with st.spinner("Logging in…"): + ok, err = login(email_l, pass_l) + if ok: + st.success("Logged in! Redirecting…") + st.page_link("pages/2_Tutor.py", label="▶️ Start Learning") + st.rerun() + else: + st.error(f"Login failed: {err}") + +# ── Signup Tab ───────────────────────────────────────────────────────────────── +with tab_signup: + st.subheader("Create your account") + email_s = st.text_input("Email", key="signup_email", placeholder="you@example.com") + pass_s = st.text_input("Password", type="password", key="signup_pass", + help="Minimum 6 characters") + pass_s2 = st.text_input("Confirm Password", type="password", key="signup_pass2") + grade_s = st.selectbox("Your Grade", options=list(range(6, 13)), index=2, key="signup_grade") + + if st.button("Create Account", type="primary", use_container_width=True, key="btn_signup"): + if not email_s or not pass_s: + st.error("Please fill in all fields.") + elif pass_s != pass_s2: + st.error("Passwords do not match.") + elif len(pass_s) < 6: + st.error("Password must be at least 6 characters.") + else: + with st.spinner("Creating your account…"): + ok, err = signup(email_s, pass_s) + if ok: + # Store grade in session state — will be saved to profile by Tutor page + st.session_state["grade"] = grade_s + st.success("Account created! Welcome to MathMind AI 🎉") + st.page_link("pages/2_Tutor.py", label="▶️ Start Learning") + st.rerun() + else: + st.error(f"Signup failed: {err}") diff --git a/streamlit_app/pages/2_Tutor.py b/streamlit_app/pages/2_Tutor.py new file mode 100644 index 0000000000000000000000000000000000000000..26fa22283ed7392f32aceb8161712610eb829f0c --- /dev/null +++ b/streamlit_app/pages/2_Tutor.py @@ -0,0 +1,293 @@ +import streamlit as st +import sys, os +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) + +from streamlit_app.utils.auth import require_login, get_token +from streamlit_app.utils.state import init_tutor_state, reset_tutor, set_stage, get_stage +from streamlit_app.utils import api_client + +st.set_page_config(page_title="MathMind AI — Tutor", page_icon="🧮", layout="centered") +require_login() +init_tutor_state() + +grade = st.session_state.get("grade", 8) +email = st.session_state.get("user_email", "") + +# ── Sidebar ──────────────────────────────────────────────────────────────────── +with st.sidebar: + st.markdown("### 🧮 MathMind AI") + st.caption(f"Logged in as {email}") + st.divider() + grade = st.selectbox( + "Your Grade", + options=list(range(6, 13)), + index=list(range(6, 13)).index(grade), + key="grade_select", + ) + st.session_state["grade"] = grade + st.divider() + if st.button("🔄 New Question", use_container_width=True): + reset_tutor() + st.rerun() + st.page_link("pages/3_Dashboard.py", label="📊 My Dashboard", use_container_width=True) + +# ── Header ───────────────────────────────────────────────────────────────────── +st.title("🧮 Math Tutor") +st.caption(f"Grade {grade} · Ask me any math question!") + +stage = get_stage() + +# ══════════════════════════════════════════════════════════════════════════════ +# STAGE 1: ASK +# ══════════════════════════════════════════════════════════════════════════════ +if stage == "ask": + st.markdown("### 💬 What would you like to learn?") + + examples = [ + "How do I solve linear equations?", + "Explain the Pythagorean theorem", + "What are fractions and how do I add them?", + "How does factoring quadratics work?", + ] + + example_cols = st.columns(2) + for i, ex in enumerate(examples): + with example_cols[i % 2]: + if st.button(ex, use_container_width=True, key=f"ex_{i}"): + st.session_state["current_query"] = ex + + query = st.text_area( + "Or type your own question:", + value=st.session_state.get("current_query", ""), + placeholder="e.g. How do I find the area of a circle?", + height=100, + key="query_input", + ) + + if st.button("🚀 Get Explanation", type="primary", use_container_width=True): + if not query.strip(): + st.error("Please enter a math question first.") + else: + st.session_state["current_query"] = query.strip() + st.session_state["current_topic"] = query.strip()[:80] + set_stage("explain") + st.rerun() + +# ══════════════════════════════════════════════════════════════════════════════ +# STAGE 2: EXPLAIN (streaming) +# ══════════════════════════════════════════════════════════════════════════════ +elif stage == "explain": + query = st.session_state["current_query"] + st.markdown(f"### 📖 Explanation for Grade {grade}") + st.info(f"**Your question:** {query}") + + if not st.session_state.get("current_explanation"): + with st.spinner("MathMind AI is thinking…"): + try: + explanation_chunks = [] + placeholder = st.empty() + full_text = "" + for chunk in api_client.stream_explanation(query, grade): + full_text += chunk + placeholder.markdown(full_text + "▌") + placeholder.markdown(full_text) + st.session_state["current_explanation"] = full_text + # Session ID comes back via Supabase — we'll store in next call + st.session_state["current_session_id"] = "pending" + except Exception as e: + st.error(f"Could not get explanation: {e}") + if st.button("Try Again"): + reset_tutor() + st.rerun() + st.stop() + else: + st.markdown(st.session_state["current_explanation"]) + + st.divider() + col1, col2 = st.columns(2) + with col1: + if st.button("📝 Practice Problems", type="primary", use_container_width=True): + set_stage("practice") + st.rerun() + with col2: + if st.button("⏭️ Skip to Test", use_container_width=True): + set_stage("test") + st.rerun() + +# ══════════════════════════════════════════════════════════════════════════════ +# STAGE 3: PRACTICE PROBLEMS +# ══════════════════════════════════════════════════════════════════════════════ +elif stage == "practice": + st.markdown("### ✏️ Practice Problems") + st.caption("Try these problems to reinforce what you just learned.") + + if not st.session_state.get("practice_problems"): + with st.spinner("Generating practice problems…"): + try: + session_id = st.session_state.get("current_session_id", "temp") + result = api_client.get_practice( + topic=st.session_state["current_topic"], + grade=grade, + session_id=session_id, + ) + st.session_state["practice_problems"] = result.get("problems", []) + except Exception as e: + st.error(f"Could not generate problems: {e}") + st.stop() + + problems = st.session_state["practice_problems"] + all_answered = True + + for i, prob in enumerate(problems): + with st.expander(f"Problem {i+1} — {prob.get('difficulty','').capitalize()}", expanded=True): + st.markdown(f"**{prob['question']}**") + answer_key = f"practice_ans_{i}" + user_ans = st.text_input("Your answer:", key=answer_key) + + if st.button("Check Answer 💡", key=f"check_{i}"): + if not user_ans.strip(): + st.warning("Please enter an answer first.") + else: + correct_ans = prob.get("answer", "").strip().lower() + student_ans = user_ans.strip().lower() + if student_ans == correct_ans or student_ans in correct_ans: + st.success("✅ Correct! Well done!") + else: + st.error(f"❌ Not quite. **Hint:** {prob.get('hint', '')}") + st.info(f"**Correct answer:** {prob['answer']}") + + if not user_ans.strip(): + all_answered = False + + st.divider() + if st.button("📋 Take Mini-Test", type="primary", use_container_width=True): + set_stage("test") + st.rerun() + +# ══════════════════════════════════════════════════════════════════════════════ +# STAGE 4: MINI-TEST +# ══════════════════════════════════════════════════════════════════════════════ +elif stage == "test": + st.markdown("### 📋 Mini-Test") + st.caption("5 questions · Pass mark: 80% · You can retry if you don't pass!") + + if not st.session_state.get("test_questions"): + with st.spinner("Generating your mini-test…"): + try: + session_id = st.session_state.get("current_session_id", "temp") + result = api_client.generate_test( + topic=st.session_state["current_topic"], + grade=grade, + session_id=session_id, + ) + st.session_state["test_questions"] = result.get("questions", []) + except Exception as e: + st.error(f"Could not generate test: {e}") + st.stop() + + questions = st.session_state["test_questions"] + answers = st.session_state.get("test_answers", {}) + + with st.form("test_form"): + for i, q in enumerate(questions): + st.markdown(f"**Question {i+1}:** {q['question']}") + ans = st.text_input(f"Your answer:", key=f"test_q_{i}", value=answers.get(str(i), "")) + answers[str(i)] = ans + st.divider() + + submitted = st.form_submit_button("✅ Submit Test", type="primary", use_container_width=True) + + if submitted: + st.session_state["test_answers"] = answers + # Build answers payload + payload = [] + for i, q in enumerate(questions): + payload.append({ + "question_index": i, + "question": q["question"], + "correct_answer": q["correct_answer"], + "student_answer": answers.get(str(i), ""), + }) + + with st.spinner("Evaluating your answers…"): + try: + session_id = st.session_state.get("current_session_id", "temp") + result = api_client.evaluate_test( + session_id=session_id, + answers=payload, + ) + st.session_state["test_result"] = result + # Check for new badges + try: + badge_result = api_client.check_badges(session_id) + st.session_state["new_badges"] = badge_result.get("newly_awarded", []) + except Exception: + st.session_state["new_badges"] = [] + set_stage("result") + st.rerun() + except Exception as e: + st.error(f"Could not evaluate test: {e}") + +# ══════════════════════════════════════════════════════════════════════════════ +# STAGE 5: RESULT +# ══════════════════════════════════════════════════════════════════════════════ +elif stage == "result": + result = st.session_state.get("test_result", {}) + score = result.get("score", 0) + passed = result.get("passed", False) + encour = result.get("encouragement", "Keep learning!") + items = result.get("results", []) + + if passed: + st.balloons() + st.success(f"## 🎉 You Passed! Score: {score}%") + else: + st.warning(f"## 📚 Score: {score}% — Keep Going!") + + st.markdown(f"*{encour}*") + st.divider() + + # Show question-level feedback + st.markdown("### 📊 Question Breakdown") + questions = st.session_state.get("test_questions", []) + answers = st.session_state.get("test_answers", {}) + for item in items: + idx = item["question_index"] + q_text = questions[idx]["question"] if idx < len(questions) else f"Q{idx+1}" + icon = "✅" if item["is_correct"] else "❌" + with st.expander(f"{icon} Question {idx+1}: {q_text[:60]}…", expanded=not item["is_correct"]): + st.write(f"**Your answer:** {answers.get(str(idx), '—')}") + st.write(f"**Feedback:** {item['feedback']}") + if not item["is_correct"] and idx < len(questions): + steps = questions[idx].get("solution_steps", []) + if steps: + st.markdown("**Solution steps:**") + for j, step in enumerate(steps, 1): + st.markdown(f"{j}. {step}") + + # New badges + new_badges = st.session_state.get("new_badges", []) + if new_badges: + st.divider() + st.markdown("### 🏆 New Badges Earned!") + cols = st.columns(len(new_badges)) + for i, badge in enumerate(new_badges): + with cols[i]: + st.markdown(f"## {badge['emoji']}") + st.markdown(f"**{badge['name']}**") + st.caption(badge["description"]) + + st.divider() + col1, col2 = st.columns(2) + with col1: + if not passed: + if st.button("🔄 Retry Test", type="primary", use_container_width=True): + st.session_state["test_questions"] = [] + st.session_state["test_answers"] = {} + st.session_state["test_result"] = None + set_stage("test") + st.rerun() + with col2: + if st.button("🆕 New Question", use_container_width=True): + reset_tutor() + st.rerun() diff --git a/streamlit_app/pages/3_Dashboard.py b/streamlit_app/pages/3_Dashboard.py new file mode 100644 index 0000000000000000000000000000000000000000..18c09f3188616711dbb74dbdbdfd664dac2249bf --- /dev/null +++ b/streamlit_app/pages/3_Dashboard.py @@ -0,0 +1,143 @@ +import streamlit as st +import sys, os +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) + +from streamlit_app.utils.auth import require_login +from streamlit_app.utils import api_client +from streamlit_app.utils.auth import get_supabase, get_user_id + +st.set_page_config(page_title="MathMind AI — Dashboard", page_icon="📊", layout="centered") +require_login() + +email = st.session_state.get("user_email", "") +user_id = get_user_id() + +st.title("📊 My Dashboard") +st.caption(f"Welcome, **{email}**") +st.divider() + +# ── Fetch data ───────────────────────────────────────────────────────────────── +@st.cache_data(ttl=30, show_spinner=False) +def fetch_dashboard_data(uid: str): + try: + sb = get_supabase() + # Profile (streak) + profile = sb.table("profiles").select("*").eq("id", uid).single().execute() + profile_data = profile.data or {} + + # Recent sessions + sessions = ( + sb.table("sessions") + .select("*") + .eq("user_id", uid) + .order("created_at", desc=True) + .limit(10) + .execute() + ) + + # Test results + results = ( + sb.table("test_results") + .select("*, sessions(topic)") + .eq("user_id", uid) + .order("created_at", desc=True) + .limit(10) + .execute() + ) + + return { + "profile": profile_data, + "sessions": sessions.data or [], + "results": results.data or [], + } + except Exception as e: + return {"profile": {}, "sessions": [], "results": [], "error": str(e)} + + +@st.cache_data(ttl=30, show_spinner=False) +def fetch_badges(uid: str): + try: + return api_client.get_badges() + except Exception: + return [] + + +with st.spinner("Loading your progress…"): + data = fetch_dashboard_data(user_id) + badges = fetch_badges(user_id) + +# ── Stats row ────────────────────────────────────────────────────────────────── +profile = data["profile"] +sessions = data["sessions"] +results = data["results"] + +streak = profile.get("streak_count", 0) +total_sess = len(sessions) +passed = sum(1 for r in results if r.get("passed")) +avg_score = (sum(r.get("score", 0) for r in results) // len(results)) if results else 0 + +col1, col2, col3, col4 = st.columns(4) +col1.metric("🔥 Streak", f"{streak} days") +col2.metric("📚 Sessions", total_sess) +col3.metric("✅ Tests Passed", passed) +col4.metric("📈 Avg Score", f"{avg_score}%") + +st.divider() + +# ── Badges ───────────────────────────────────────────────────────────────────── +st.markdown("### 🏆 My Badges") +if badges: + badge_cols = st.columns(min(len(badges), 5)) + for i, b in enumerate(badges): + badge_data = b.get("badges") or b + with badge_cols[i % 5]: + emoji = badge_data.get("emoji", "🏅") + name = badge_data.get("name", "Badge") + desc = badge_data.get("description", "") + earned_at = b.get("earned_at", "")[:10] if b.get("earned_at") else "" + st.markdown( + f""" +
+
{emoji}
+
{name}
+
{earned_at}
+
+ """, + unsafe_allow_html=True, + ) +else: + st.info("No badges yet — complete your first mini-test to earn **🏆 First Try Champion**!") + +st.divider() + +# ── Recent test results ──────────────────────────────────────────────────────── +st.markdown("### 📝 Recent Test Results") +if results: + for r in results[:5]: + topic = (r.get("sessions") or {}).get("topic", "Unknown topic") if isinstance(r.get("sessions"), dict) else r.get("topic", "Unknown topic") + score = r.get("score", 0) + passed_ = r.get("passed", False) + date_ = str(r.get("created_at", ""))[:10] + icon = "✅" if passed_ else "❌" + st.markdown( + f"{icon} **{topic[:60]}** — Score: **{score}%** · {date_}" + ) +else: + st.info("No test results yet — start a session in the Tutor!") + +st.divider() + +# ── Recent sessions ──────────────────────────────────────────────────────────── +st.markdown("### 💬 Recent Sessions") +if sessions: + for s in sessions[:5]: + topic = s.get("topic", "")[:80] + grade = s.get("grade", "") + date_ = str(s.get("created_at", ""))[:10] + st.markdown(f"📖 **{topic}** · Grade {grade} · {date_}") +else: + st.info("No sessions yet — ask your first question in the Tutor!") + +st.divider() +st.page_link("pages/2_Tutor.py", label="▶️ Start a New Session", use_container_width=True) diff --git a/streamlit_app/utils/__pycache__/api_client.cpython-313.pyc b/streamlit_app/utils/__pycache__/api_client.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c92861b2be9034b197faceea37e2dcf1cd064428 Binary files /dev/null and b/streamlit_app/utils/__pycache__/api_client.cpython-313.pyc differ diff --git a/streamlit_app/utils/__pycache__/auth.cpython-313.pyc b/streamlit_app/utils/__pycache__/auth.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6603438bfca5d17bede754bf0f5b8966ebdbe08 Binary files /dev/null and b/streamlit_app/utils/__pycache__/auth.cpython-313.pyc differ diff --git a/streamlit_app/utils/__pycache__/state.cpython-313.pyc b/streamlit_app/utils/__pycache__/state.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad754b56620e32c73536df989cd6963f990707d9 Binary files /dev/null and b/streamlit_app/utils/__pycache__/state.cpython-313.pyc differ diff --git a/streamlit_app/utils/api_client.py b/streamlit_app/utils/api_client.py new file mode 100644 index 0000000000000000000000000000000000000000..4a9065ce8655e64bac4824b3e5bd0fc3b0f30463 --- /dev/null +++ b/streamlit_app/utils/api_client.py @@ -0,0 +1,95 @@ +""" +httpx-based API client for calling the MathMind FastAPI backend. +All calls include the Supabase JWT in the Authorization header. +""" + +import os +import httpx +import streamlit as st +from dotenv import load_dotenv + +load_dotenv() + +API_BASE = os.getenv("API_BASE_URL", "http://localhost:8000") +TIMEOUT = 60.0 # seconds — generous for streaming + + +def _headers() -> dict: + token = st.session_state.get("access_token", "") + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +def health_check() -> bool: + try: + r = httpx.get(f"{API_BASE}/api/health", timeout=5) + return r.status_code == 200 + except Exception: + return False + + +def stream_explanation(query: str, grade: int): + """ + Generator that yields text chunks from the streaming explanation endpoint. + Use with st.write_stream(). + """ + with httpx.Client(timeout=TIMEOUT) as client: + with client.stream( + "POST", + f"{API_BASE}/api/explain", + json={"query": query, "grade": grade}, + headers=_headers(), + ) as response: + response.raise_for_status() + for chunk in response.iter_text(): + if chunk: + yield chunk + + +def get_practice(topic: str, grade: int, session_id: str, count: int = 3) -> dict: + r = httpx.post( + f"{API_BASE}/api/practice", + json={"topic": topic, "grade": grade, "session_id": session_id, "count": count}, + headers=_headers(), + timeout=TIMEOUT, + ) + r.raise_for_status() + return r.json() + + +def generate_test(topic: str, grade: int, session_id: str) -> dict: + r = httpx.post( + f"{API_BASE}/api/test/generate", + json={"topic": topic, "grade": grade, "session_id": session_id}, + headers=_headers(), + timeout=TIMEOUT, + ) + r.raise_for_status() + return r.json() + + +def evaluate_test(session_id: str, answers: list[dict], attempt_number: int = 1) -> dict: + r = httpx.post( + f"{API_BASE}/api/test/evaluate", + json={"session_id": session_id, "answers": answers, "attempt_number": attempt_number}, + headers=_headers(), + timeout=TIMEOUT, + ) + r.raise_for_status() + return r.json() + + +def get_badges() -> list[dict]: + r = httpx.get(f"{API_BASE}/api/badges", headers=_headers(), timeout=TIMEOUT) + r.raise_for_status() + return r.json() + + +def check_badges(session_id: str) -> dict: + r = httpx.post( + f"{API_BASE}/api/badges/check", + json={"session_id": session_id}, + headers=_headers(), + timeout=TIMEOUT, + ) + r.raise_for_status() + return r.json() diff --git a/streamlit_app/utils/auth.py b/streamlit_app/utils/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..f626021af722d07678e563a97bbfb7480a11bf72 --- /dev/null +++ b/streamlit_app/utils/auth.py @@ -0,0 +1,77 @@ +""" +Supabase Auth helpers for Streamlit. +Stores JWT and user info in st.session_state. +""" + +import streamlit as st +from supabase import Client, create_client +import os +from dotenv import load_dotenv + +load_dotenv() + +SUPABASE_URL = os.getenv("SUPABASE_URL", "") +SUPABASE_ANON_KEY = os.getenv("SUPABASE_ANON_KEY", "") + + +@st.cache_resource +def get_supabase() -> Client: + return create_client(SUPABASE_URL, SUPABASE_ANON_KEY) + + +def login(email: str, password: str) -> tuple[bool, str]: + """Sign in with email/password. Returns (success, error_message).""" + try: + res = get_supabase().auth.sign_in_with_password( + {"email": email, "password": password} + ) + st.session_state["access_token"] = res.session.access_token + st.session_state["user_id"] = res.user.id + st.session_state["user_email"] = res.user.email + return True, "" + except Exception as e: + return False, str(e) + + +def signup(email: str, password: str) -> tuple[bool, str]: + """Sign up with email/password. Returns (success, error_message).""" + try: + res = get_supabase().auth.sign_up( + {"email": email, "password": password} + ) + if res.user: + # Auto-login after signup + return login(email, password) + return False, "Signup failed. Please try again." + except Exception as e: + return False, str(e) + + +def logout(): + """Clear session state and sign out.""" + try: + get_supabase().auth.sign_out() + except Exception: + pass + for key in ["access_token", "user_id", "user_email", "grade"]: + st.session_state.pop(key, None) + + +def is_logged_in() -> bool: + return bool(st.session_state.get("access_token")) + + +def require_login(): + """Redirect to login page if not authenticated.""" + if not is_logged_in(): + st.warning("Please log in to continue.") + st.page_link("pages/1_Login.py", label="Go to Login →") + st.stop() + + +def get_token() -> str: + return st.session_state.get("access_token", "") + + +def get_user_id() -> str: + return st.session_state.get("user_id", "") diff --git a/streamlit_app/utils/state.py b/streamlit_app/utils/state.py new file mode 100644 index 0000000000000000000000000000000000000000..0a350ba42baeedfbe16aca3164e774ab27450e42 --- /dev/null +++ b/streamlit_app/utils/state.py @@ -0,0 +1,39 @@ +"""Helpers to read/write tutor session state cleanly.""" +import streamlit as st + + +def init_tutor_state(): + defaults = { + "tutor_stage": "ask", # ask | explain | practice | test | result + "current_query": "", + "current_topic": "", + "current_explanation": "", + "current_session_id": None, + "practice_problems": [], + "test_questions": [], + "test_answers": {}, + "test_result": None, + "new_badges": [], + } + for k, v in defaults.items(): + if k not in st.session_state: + st.session_state[k] = v + + +def reset_tutor(): + keys = [ + "tutor_stage", "current_query", "current_topic", "current_explanation", + "current_session_id", "practice_problems", "test_questions", + "test_answers", "test_result", "new_badges", + ] + for k in keys: + st.session_state.pop(k, None) + init_tutor_state() + + +def set_stage(stage: str): + st.session_state["tutor_stage"] = stage + + +def get_stage() -> str: + return st.session_state.get("tutor_stage", "ask")