Spaces:
Configuration error
Configuration error
Commit ·
e46d575
0
Parent(s):
AI MVP
Browse filesMathAI Tutor
This view is limited to 50 files because it contains too many changes. See raw diff
- .env +11 -0
- README.md +201 -0
- backend/__init__.py +0 -0
- backend/__pycache__/__init__.cpython-313.pyc +0 -0
- backend/__pycache__/main.cpython-313.pyc +0 -0
- backend/core/__init__.py +0 -0
- backend/core/__pycache__/__init__.cpython-313.pyc +0 -0
- backend/core/__pycache__/auth.cpython-313.pyc +0 -0
- backend/core/__pycache__/config.cpython-313.pyc +0 -0
- backend/core/auth.py +29 -0
- backend/core/config.py +19 -0
- backend/main.py +32 -0
- backend/models/__init__.py +0 -0
- backend/models/__pycache__/__init__.cpython-313.pyc +0 -0
- backend/models/__pycache__/badges.cpython-313.pyc +0 -0
- backend/models/__pycache__/explain.cpython-313.pyc +0 -0
- backend/models/__pycache__/practice.cpython-313.pyc +0 -0
- backend/models/__pycache__/test.cpython-313.pyc +0 -0
- backend/models/badges.py +23 -0
- backend/models/explain.py +7 -0
- backend/models/practice.py +20 -0
- backend/models/test.py +46 -0
- backend/routers/__init__.py +0 -0
- backend/routers/__pycache__/__init__.cpython-313.pyc +0 -0
- backend/routers/__pycache__/badges.cpython-313.pyc +0 -0
- backend/routers/__pycache__/explain.cpython-313.pyc +0 -0
- backend/routers/__pycache__/practice.cpython-313.pyc +0 -0
- backend/routers/__pycache__/test.cpython-313.pyc +0 -0
- backend/routers/badges.py +76 -0
- backend/routers/explain.py +44 -0
- backend/routers/practice.py +35 -0
- backend/routers/test.py +95 -0
- backend/services/__init__.py +0 -0
- backend/services/__pycache__/__init__.cpython-313.pyc +0 -0
- backend/services/__pycache__/claude_service.cpython-313.pyc +0 -0
- backend/services/__pycache__/prompt_templates.cpython-313.pyc +0 -0
- backend/services/__pycache__/supabase_service.cpython-313.pyc +0 -0
- backend/services/claude_service.py +60 -0
- backend/services/prompt_templates.py +121 -0
- backend/services/supabase_service.py +170 -0
- database/01_schema.sql +133 -0
- database/02_rls.sql +93 -0
- database/03_seed.sql +90 -0
- database/README.md +27 -0
- requirements.txt +13 -0
- streamlit_app/app.py +51 -0
- streamlit_app/pages/1_Login.py +69 -0
- streamlit_app/pages/2_Tutor.py +293 -0
- streamlit_app/pages/3_Dashboard.py +143 -0
- streamlit_app/utils/__pycache__/api_client.cpython-313.pyc +0 -0
.env
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ── Anthropic ──────────────────────────────────────────────
|
| 2 |
+
ANTHROPIC_API_KEY=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
|
| 3 |
+
|
| 4 |
+
# ── Supabase ───────────────────────────────────────────────
|
| 5 |
+
SUPABASE_URL=https://vzeyifrgjbmxjzqcpwhg.supabase.co
|
| 6 |
+
SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZ6ZXlpZnJnamJteGp6cWNwd2hnIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI0MTU3NjksImV4cCI6MjA4Nzk5MTc2OX0.yTtAs2bAtNftmfgO3Qz9UphnuAHfpLH2mqTW0gqRGSg
|
| 7 |
+
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZ6ZXlpZnJnamJteGp6cWNwd2hnIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc3MjQxNTc2OSwiZXhwIjoyMDg3OTkxNzY5fQ.IAspx2EAv_AFIuyigYnxrX5dEp_mqkW0tFcnQ2L-jlw
|
| 8 |
+
|
| 9 |
+
# ── FastAPI ────────────────────────────────────────────────
|
| 10 |
+
ALLOWED_ORIGINS=http://localhost:8501
|
| 11 |
+
API_BASE_URL=http://localhost:8000
|
README.md
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🧮 MathMind AI — MVP
|
| 2 |
+
|
| 3 |
+
AI-powered adaptive math tutor for **Grades 6–12**.
|
| 4 |
+
Built with **Streamlit · FastAPI · Anthropic Claude · Supabase**.
|
| 5 |
+
|
| 6 |
+
---
|
| 7 |
+
|
| 8 |
+
## Architecture
|
| 9 |
+
|
| 10 |
+
```
|
| 11 |
+
Streamlit (localhost:8501)
|
| 12 |
+
└── httpx calls → FastAPI (localhost:8000)
|
| 13 |
+
├── Anthropic Claude API (AI explanations + tests)
|
| 14 |
+
└── Supabase (Auth + PostgreSQL)
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
## Quick Start
|
| 20 |
+
|
| 21 |
+
### 1. Clone & Install
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
git clone <repo-url>
|
| 25 |
+
cd mathmind
|
| 26 |
+
pip install -r requirements.txt
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
### 2. Configure Environment
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
cp .env.example .env
|
| 33 |
+
# Fill in the values in .env (see Environment Variables section below)
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
### 3. Set Up Supabase
|
| 37 |
+
|
| 38 |
+
1. Create a free project at [supabase.com](https://supabase.com)
|
| 39 |
+
2. Go to **SQL Editor** and run the scripts **in order**:
|
| 40 |
+
- `database/01_schema.sql`
|
| 41 |
+
- `database/02_rls.sql`
|
| 42 |
+
- `database/03_seed.sql`
|
| 43 |
+
3. Copy your project URL and keys from **Settings → API**
|
| 44 |
+
|
| 45 |
+
### 4. Run the Backend
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
# From the mathmind/ root directory
|
| 49 |
+
uvicorn backend.main:app --reload --port 8000
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
Verify: open [http://localhost:8000/api/health](http://localhost:8000/api/health)
|
| 53 |
+
You should see: `{"status": "ok"}`
|
| 54 |
+
|
| 55 |
+
### 5. Run the Frontend
|
| 56 |
+
|
| 57 |
+
```bash
|
| 58 |
+
# In a second terminal, from the mathmind/ root directory
|
| 59 |
+
streamlit run streamlit_app/app.py
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
Open [http://localhost:8501](http://localhost:8501) in your browser.
|
| 63 |
+
|
| 64 |
+
---
|
| 65 |
+
|
| 66 |
+
## Environment Variables
|
| 67 |
+
|
| 68 |
+
Create a `.env` file in the `mathmind/` root:
|
| 69 |
+
|
| 70 |
+
```bash
|
| 71 |
+
# Anthropic — get your key at console.anthropic.com
|
| 72 |
+
ANTHROPIC_API_KEY=sk-ant-...
|
| 73 |
+
|
| 74 |
+
# Supabase — from your project: Settings → API
|
| 75 |
+
SUPABASE_URL=https://xxxx.supabase.co
|
| 76 |
+
SUPABASE_ANON_KEY=eyJ... # "anon" key (public)
|
| 77 |
+
SUPABASE_SERVICE_ROLE_KEY=eyJ... # "service_role" key (secret — never expose to browser)
|
| 78 |
+
|
| 79 |
+
# FastAPI
|
| 80 |
+
ALLOWED_ORIGINS=http://localhost:8501
|
| 81 |
+
API_BASE_URL=http://localhost:8000
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
---
|
| 85 |
+
|
| 86 |
+
## Project Structure
|
| 87 |
+
|
| 88 |
+
```
|
| 89 |
+
mathmind/
|
| 90 |
+
├── .env.example
|
| 91 |
+
├── README.md
|
| 92 |
+
├── requirements.txt
|
| 93 |
+
│
|
| 94 |
+
├── streamlit_app/ # Frontend (Streamlit)
|
| 95 |
+
│ ├── app.py # Landing page + router
|
| 96 |
+
│ ├── pages/
|
| 97 |
+
│ │ ├── 1_Login.py # Auth (login + signup)
|
| 98 |
+
│ │ ├── 2_Tutor.py # Core learning flow
|
| 99 |
+
│ │ └── 3_Dashboard.py # Badges + streak + history
|
| 100 |
+
│ └── utils/
|
| 101 |
+
│ ├── auth.py # Supabase auth helpers
|
| 102 |
+
│ ├── api_client.py # FastAPI HTTP client
|
| 103 |
+
│ └── state.py # session_state helpers
|
| 104 |
+
│
|
| 105 |
+
├── backend/ # API (FastAPI)
|
| 106 |
+
│ ├── main.py # App entry + CORS
|
| 107 |
+
│ ├── core/
|
| 108 |
+
│ │ ├── config.py # Env var loading
|
| 109 |
+
│ │ └── auth.py # JWT verification
|
| 110 |
+
│ ├── routers/
|
| 111 |
+
│ │ ├── explain.py # POST /api/explain
|
| 112 |
+
│ │ ├── practice.py # POST /api/practice
|
| 113 |
+
│ │ ├── test.py # POST /api/test/*
|
| 114 |
+
│ │ └── badges.py # GET/POST /api/badges
|
| 115 |
+
│ ├── services/
|
| 116 |
+
│ │ ├── claude_service.py # Anthropic SDK wrapper
|
| 117 |
+
│ │ ├── supabase_service.py # Supabase client wrapper
|
| 118 |
+
│ │ └── prompt_templates.py # Grade-level prompts
|
| 119 |
+
│ └── models/ # Pydantic request/response models
|
| 120 |
+
│
|
| 121 |
+
└── database/
|
| 122 |
+
├── 01_schema.sql # Table definitions
|
| 123 |
+
├── 02_rls.sql # Row Level Security
|
| 124 |
+
├── 03_seed.sql # Badge definitions
|
| 125 |
+
└── README.md
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
---
|
| 129 |
+
|
| 130 |
+
## API Endpoints
|
| 131 |
+
|
| 132 |
+
| Method | Endpoint | Description | Auth |
|
| 133 |
+
|--------|----------|-------------|------|
|
| 134 |
+
| GET | `/api/health` | Health check | None |
|
| 135 |
+
| POST | `/api/explain` | Stream grade-appropriate explanation | JWT |
|
| 136 |
+
| POST | `/api/practice` | Generate 3 practice problems | JWT |
|
| 137 |
+
| POST | `/api/test/generate` | Generate 5-question mini-test | JWT |
|
| 138 |
+
| POST | `/api/test/evaluate` | Evaluate answers + save result | JWT |
|
| 139 |
+
| GET | `/api/badges` | Get student's earned badges | JWT |
|
| 140 |
+
| POST | `/api/badges/check` | Check + award new badges | JWT |
|
| 141 |
+
|
| 142 |
+
Interactive docs: [http://localhost:8000/docs](http://localhost:8000/docs)
|
| 143 |
+
|
| 144 |
+
---
|
| 145 |
+
|
| 146 |
+
## Student Flow
|
| 147 |
+
|
| 148 |
+
```
|
| 149 |
+
Sign Up → Select Grade → Ask Question
|
| 150 |
+
→ Streamed Explanation
|
| 151 |
+
→ Practice Problems (3x)
|
| 152 |
+
→ Mini-Test (5 questions)
|
| 153 |
+
├── PASS (≥80%) → Badge Awarded → Dashboard
|
| 154 |
+
└── FAIL (<80%) → See Feedback → Retry Test
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
---
|
| 158 |
+
|
| 159 |
+
## Badge System
|
| 160 |
+
|
| 161 |
+
| Badge | Emoji | Condition |
|
| 162 |
+
|-------|-------|-----------|
|
| 163 |
+
| First Try Champion | 🏆 | Pass your first test |
|
| 164 |
+
| Getting Started | 🚀 | Complete 5 sessions |
|
| 165 |
+
| Math Explorer | 🌟 | Complete 10 sessions |
|
| 166 |
+
| On Fire | 🔥 | 5-day streak |
|
| 167 |
+
| Perfect Score | 💯 | Score 100% on a test |
|
| 168 |
+
|
| 169 |
+
---
|
| 170 |
+
|
| 171 |
+
## Tech Stack
|
| 172 |
+
|
| 173 |
+
| Layer | Technology |
|
| 174 |
+
|-------|-----------|
|
| 175 |
+
| Frontend | Streamlit 1.35+ |
|
| 176 |
+
| Backend | FastAPI + Uvicorn |
|
| 177 |
+
| AI | Anthropic Claude `claude-sonnet-4-6` |
|
| 178 |
+
| Database | Supabase (PostgreSQL + Auth + RLS) |
|
| 179 |
+
| HTTP Client | httpx (async-capable) |
|
| 180 |
+
| Validation | Pydantic v2 |
|
| 181 |
+
|
| 182 |
+
---
|
| 183 |
+
|
| 184 |
+
## Development Notes
|
| 185 |
+
|
| 186 |
+
- **Backend auto-reloads** on file changes with `--reload`
|
| 187 |
+
- **Streamlit auto-reloads** on file saves
|
| 188 |
+
- **JWT flow:** Supabase issues JWT on login → stored in `st.session_state` → sent as `Authorization: Bearer <token>` to FastAPI → FastAPI verifies via Supabase auth API
|
| 189 |
+
- **Streaming:** `/api/explain` uses FastAPI `StreamingResponse` + Anthropic streaming SDK → Streamlit renders chunks live
|
| 190 |
+
- **Service role key** is used by FastAPI only — bypasses RLS for server-side writes. Never expose to the browser.
|
| 191 |
+
|
| 192 |
+
---
|
| 193 |
+
|
| 194 |
+
## Phase 2 Roadmap (not in MVP)
|
| 195 |
+
|
| 196 |
+
- [ ] Re-engagement email nudges (SendGrid)
|
| 197 |
+
- [ ] LMS integration (Google Classroom, Canvas)
|
| 198 |
+
- [ ] Parent weekly report emails
|
| 199 |
+
- [ ] Adaptive ML difficulty engine
|
| 200 |
+
- [ ] Subscription/payment (Stripe)
|
| 201 |
+
- [ ] Mobile app
|
backend/__init__.py
ADDED
|
File without changes
|
backend/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (149 Bytes). View file
|
|
|
backend/__pycache__/main.cpython-313.pyc
ADDED
|
Binary file (1.35 kB). View file
|
|
|
backend/core/__init__.py
ADDED
|
File without changes
|
backend/core/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (154 Bytes). View file
|
|
|
backend/core/__pycache__/auth.cpython-313.pyc
ADDED
|
Binary file (1.56 kB). View file
|
|
|
backend/core/__pycache__/config.cpython-313.pyc
ADDED
|
Binary file (1.28 kB). View file
|
|
|
backend/core/auth.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import Depends, HTTPException, status
|
| 2 |
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
| 3 |
+
from supabase import create_client
|
| 4 |
+
from backend.core.config import settings
|
| 5 |
+
|
| 6 |
+
bearer_scheme = HTTPBearer()
|
| 7 |
+
|
| 8 |
+
# Service-role client — used only for JWT verification
|
| 9 |
+
_supabase = create_client(settings.supabase_url, settings.supabase_service_role_key)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
async def get_current_user(
|
| 13 |
+
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
|
| 14 |
+
) -> dict:
|
| 15 |
+
"""
|
| 16 |
+
Verify the Supabase JWT passed in the Authorization header.
|
| 17 |
+
Returns the decoded user payload on success.
|
| 18 |
+
"""
|
| 19 |
+
token = credentials.credentials
|
| 20 |
+
try:
|
| 21 |
+
response = _supabase.auth.get_user(token)
|
| 22 |
+
if response.user is None:
|
| 23 |
+
raise ValueError("No user in token")
|
| 24 |
+
return {"id": response.user.id, "email": response.user.email}
|
| 25 |
+
except Exception:
|
| 26 |
+
raise HTTPException(
|
| 27 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 28 |
+
detail="Invalid or expired token",
|
| 29 |
+
)
|
backend/core/config.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class Settings(BaseSettings):
|
| 5 |
+
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
| 6 |
+
|
| 7 |
+
anthropic_api_key: str
|
| 8 |
+
supabase_url: str
|
| 9 |
+
supabase_anon_key: str
|
| 10 |
+
supabase_service_role_key: str
|
| 11 |
+
allowed_origins: str = "http://localhost:8501"
|
| 12 |
+
api_base_url: str = "http://localhost:8000"
|
| 13 |
+
|
| 14 |
+
@property
|
| 15 |
+
def origins_list(self) -> list[str]:
|
| 16 |
+
return [o.strip() for o in self.allowed_origins.split(",")]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
settings = Settings()
|
backend/main.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
|
| 4 |
+
from backend.core.config import settings
|
| 5 |
+
from backend.routers import badges, explain, practice, test
|
| 6 |
+
|
| 7 |
+
app = FastAPI(
|
| 8 |
+
title="MathMind AI API",
|
| 9 |
+
description="Adaptive math tutor backend — Grades 6–12",
|
| 10 |
+
version="1.0.0",
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
# ── CORS ───────────────────────────────────────────────────────────────────────
|
| 14 |
+
app.add_middleware(
|
| 15 |
+
CORSMiddleware,
|
| 16 |
+
allow_origins=settings.origins_list,
|
| 17 |
+
allow_credentials=True,
|
| 18 |
+
allow_methods=["*"],
|
| 19 |
+
allow_headers=["*"],
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
# ── Routers ────────────────────────────────────────────────────────────────────
|
| 23 |
+
app.include_router(explain.router)
|
| 24 |
+
app.include_router(practice.router)
|
| 25 |
+
app.include_router(test.router)
|
| 26 |
+
app.include_router(badges.router)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# ── Health ─────────────────────────────────────────────────────────────────────
|
| 30 |
+
@app.get("/api/health", tags=["health"])
|
| 31 |
+
async def health():
|
| 32 |
+
return {"status": "ok", "service": "MathMind AI API", "version": "1.0.0"}
|
backend/models/__init__.py
ADDED
|
File without changes
|
backend/models/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (156 Bytes). View file
|
|
|
backend/models/__pycache__/badges.cpython-313.pyc
ADDED
|
Binary file (1.33 kB). View file
|
|
|
backend/models/__pycache__/explain.cpython-313.pyc
ADDED
|
Binary file (710 Bytes). View file
|
|
|
backend/models/__pycache__/practice.cpython-313.pyc
ADDED
|
Binary file (1.35 kB). View file
|
|
|
backend/models/__pycache__/test.cpython-313.pyc
ADDED
|
Binary file (2.56 kB). View file
|
|
|
backend/models/badges.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class Badge(BaseModel):
|
| 5 |
+
id: str
|
| 6 |
+
name: str
|
| 7 |
+
emoji: str
|
| 8 |
+
description: str
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class StudentBadge(BaseModel):
|
| 12 |
+
badge_id: str
|
| 13 |
+
earned_at: str
|
| 14 |
+
badges: Badge | None = None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class BadgeCheckRequest(BaseModel):
|
| 18 |
+
session_id: str
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class BadgeCheckResponse(BaseModel):
|
| 22 |
+
newly_awarded: list[Badge]
|
| 23 |
+
total_badges: int
|
backend/models/explain.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class ExplainRequest(BaseModel):
|
| 5 |
+
query: str = Field(..., min_length=3, max_length=500)
|
| 6 |
+
grade: int = Field(..., ge=6, le=12)
|
| 7 |
+
session_id: str | None = None # pass existing session ID to append
|
backend/models/practice.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class PracticeRequest(BaseModel):
|
| 5 |
+
topic: str = Field(..., min_length=2, max_length=200)
|
| 6 |
+
grade: int = Field(..., ge=6, le=12)
|
| 7 |
+
session_id: str
|
| 8 |
+
count: int = Field(default=3, ge=1, le=5)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class PracticeProblem(BaseModel):
|
| 12 |
+
question: str
|
| 13 |
+
answer: str
|
| 14 |
+
hint: str
|
| 15 |
+
difficulty: str
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class PracticeResponse(BaseModel):
|
| 19 |
+
problems: list[PracticeProblem]
|
| 20 |
+
session_id: str
|
backend/models/test.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class TestGenerateRequest(BaseModel):
|
| 5 |
+
topic: str = Field(..., min_length=2, max_length=200)
|
| 6 |
+
grade: int = Field(..., ge=6, le=12)
|
| 7 |
+
session_id: str
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestQuestion(BaseModel):
|
| 11 |
+
question: str
|
| 12 |
+
correct_answer: str
|
| 13 |
+
solution_steps: list[str]
|
| 14 |
+
type: str # "numerical" | "short_answer"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class TestGenerateResponse(BaseModel):
|
| 18 |
+
questions: list[TestQuestion]
|
| 19 |
+
session_id: str
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class StudentAnswer(BaseModel):
|
| 23 |
+
question_index: int
|
| 24 |
+
question: str
|
| 25 |
+
correct_answer: str
|
| 26 |
+
student_answer: str
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class TestEvaluateRequest(BaseModel):
|
| 30 |
+
session_id: str
|
| 31 |
+
answers: list[StudentAnswer]
|
| 32 |
+
attempt_number: int = 1
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class QuestionResult(BaseModel):
|
| 36 |
+
question_index: int
|
| 37 |
+
is_correct: bool
|
| 38 |
+
feedback: str
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class TestEvaluateResponse(BaseModel):
|
| 42 |
+
results: list[QuestionResult]
|
| 43 |
+
score: int
|
| 44 |
+
passed: bool
|
| 45 |
+
encouragement: str
|
| 46 |
+
session_id: str
|
backend/routers/__init__.py
ADDED
|
File without changes
|
backend/routers/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (157 Bytes). View file
|
|
|
backend/routers/__pycache__/badges.cpython-313.pyc
ADDED
|
Binary file (3.76 kB). View file
|
|
|
backend/routers/__pycache__/explain.cpython-313.pyc
ADDED
|
Binary file (2.37 kB). View file
|
|
|
backend/routers/__pycache__/practice.cpython-313.pyc
ADDED
|
Binary file (2.14 kB). View file
|
|
|
backend/routers/__pycache__/test.cpython-313.pyc
ADDED
|
Binary file (4.59 kB). View file
|
|
|
backend/routers/badges.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends
|
| 2 |
+
|
| 3 |
+
from backend.core.auth import get_current_user
|
| 4 |
+
from backend.models.badges import Badge, BadgeCheckRequest, BadgeCheckResponse
|
| 5 |
+
from backend.services import supabase_service
|
| 6 |
+
|
| 7 |
+
router = APIRouter(prefix="/api", tags=["badges"])
|
| 8 |
+
|
| 9 |
+
# Badge condition keys — matched against student stats
|
| 10 |
+
BADGE_CONDITIONS = {
|
| 11 |
+
"first_pass": lambda stats: stats["passed_tests"] >= 1,
|
| 12 |
+
"five_sessions": lambda stats: stats["total_sessions"] >= 5,
|
| 13 |
+
"ten_sessions": lambda stats: stats["total_sessions"] >= 10,
|
| 14 |
+
"streak_5": lambda stats: stats["streak"] >= 5,
|
| 15 |
+
"perfect_score": lambda stats: stats["last_score"] == 100,
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@router.get("/badges", response_model=list[dict])
|
| 20 |
+
async def get_badges(user: dict = Depends(get_current_user)):
|
| 21 |
+
"""Return all badges earned by the current student."""
|
| 22 |
+
return supabase_service.get_student_badges(user["id"])
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@router.post("/badges/check", response_model=BadgeCheckResponse)
|
| 26 |
+
async def check_badges(
|
| 27 |
+
body: BadgeCheckRequest,
|
| 28 |
+
user: dict = Depends(get_current_user),
|
| 29 |
+
):
|
| 30 |
+
"""
|
| 31 |
+
Check all badge conditions against current student stats.
|
| 32 |
+
Award any newly unlocked badges and return them.
|
| 33 |
+
"""
|
| 34 |
+
user_id = user["id"]
|
| 35 |
+
|
| 36 |
+
# Gather stats
|
| 37 |
+
profile = supabase_service.get_profile(user_id) or {}
|
| 38 |
+
passed_tests = supabase_service.count_passed_tests(user_id)
|
| 39 |
+
total_sessions = supabase_service.count_sessions(user_id)
|
| 40 |
+
streak = profile.get("streak_count", 0)
|
| 41 |
+
|
| 42 |
+
# Get last test score for this session
|
| 43 |
+
results = supabase_service.get_test_results(user_id)
|
| 44 |
+
last_score = 0
|
| 45 |
+
if results:
|
| 46 |
+
last_score = results[0].get("score", 0)
|
| 47 |
+
|
| 48 |
+
stats = {
|
| 49 |
+
"passed_tests": passed_tests,
|
| 50 |
+
"total_sessions": total_sessions,
|
| 51 |
+
"streak": streak,
|
| 52 |
+
"last_score": last_score,
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
# Get all badge definitions and already-earned badges
|
| 56 |
+
all_badges = supabase_service.get_all_badges()
|
| 57 |
+
earned = {b["badge_id"] for b in supabase_service.get_student_badges(user_id)}
|
| 58 |
+
|
| 59 |
+
newly_awarded: list[Badge] = []
|
| 60 |
+
for badge in all_badges:
|
| 61 |
+
condition_key = badge.get("condition_key")
|
| 62 |
+
if condition_key in BADGE_CONDITIONS and badge["id"] not in earned:
|
| 63 |
+
if BADGE_CONDITIONS[condition_key](stats):
|
| 64 |
+
awarded = supabase_service.award_badge(user_id, badge["id"])
|
| 65 |
+
if awarded:
|
| 66 |
+
newly_awarded.append(
|
| 67 |
+
Badge(
|
| 68 |
+
id=badge["id"],
|
| 69 |
+
name=badge["name"],
|
| 70 |
+
emoji=badge["emoji"],
|
| 71 |
+
description=badge["description"],
|
| 72 |
+
)
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
total = len(supabase_service.get_student_badges(user_id))
|
| 76 |
+
return BadgeCheckResponse(newly_awarded=newly_awarded, total_badges=total)
|
backend/routers/explain.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends
|
| 2 |
+
from fastapi.responses import StreamingResponse
|
| 3 |
+
|
| 4 |
+
from backend.core.auth import get_current_user
|
| 5 |
+
from backend.models.explain import ExplainRequest
|
| 6 |
+
from backend.services import claude_service, prompt_templates, supabase_service
|
| 7 |
+
|
| 8 |
+
router = APIRouter(prefix="/api", tags=["explain"])
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@router.post("/explain")
|
| 12 |
+
async def explain(
|
| 13 |
+
body: ExplainRequest,
|
| 14 |
+
user: dict = Depends(get_current_user),
|
| 15 |
+
):
|
| 16 |
+
"""
|
| 17 |
+
Stream a grade-appropriate explanation for the student's math query.
|
| 18 |
+
Also creates a session record in Supabase and returns session_id in headers.
|
| 19 |
+
"""
|
| 20 |
+
system = prompt_templates.explanation_system(body.grade)
|
| 21 |
+
user_msg = prompt_templates.explanation_user(body.query)
|
| 22 |
+
|
| 23 |
+
# Collect full explanation for DB storage while streaming to client
|
| 24 |
+
full_text_parts: list[str] = []
|
| 25 |
+
|
| 26 |
+
async def generate():
|
| 27 |
+
async for chunk in claude_service.stream(system, user_msg):
|
| 28 |
+
full_text_parts.append(chunk)
|
| 29 |
+
yield chunk
|
| 30 |
+
# After stream complete — save session to Supabase
|
| 31 |
+
full_text = "".join(full_text_parts)
|
| 32 |
+
supabase_service.create_session(
|
| 33 |
+
user_id=user["id"],
|
| 34 |
+
topic=_extract_topic(body.query),
|
| 35 |
+
grade=body.grade,
|
| 36 |
+
explanation=full_text,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
return StreamingResponse(generate(), media_type="text/plain")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _extract_topic(query: str) -> str:
|
| 43 |
+
"""Simple topic extraction — first 80 chars of query as topic label."""
|
| 44 |
+
return query[:80].strip()
|
backend/routers/practice.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, HTTPException
|
| 2 |
+
|
| 3 |
+
from backend.core.auth import get_current_user
|
| 4 |
+
from backend.models.practice import PracticeRequest, PracticeResponse, PracticeProblem
|
| 5 |
+
from backend.services import claude_service, prompt_templates
|
| 6 |
+
|
| 7 |
+
router = APIRouter(prefix="/api", tags=["practice"])
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@router.post("/practice", response_model=PracticeResponse)
|
| 11 |
+
async def generate_practice(
|
| 12 |
+
body: PracticeRequest,
|
| 13 |
+
user: dict = Depends(get_current_user),
|
| 14 |
+
):
|
| 15 |
+
"""Generate 3 adaptive practice problems for the given topic and grade."""
|
| 16 |
+
system = prompt_templates.practice_system(body.grade)
|
| 17 |
+
user_msg = prompt_templates.practice_user(body.topic, body.count)
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
raw = await claude_service.complete_json(system, user_msg)
|
| 21 |
+
except ValueError as e:
|
| 22 |
+
raise HTTPException(status_code=502, detail=str(e))
|
| 23 |
+
|
| 24 |
+
problems = []
|
| 25 |
+
for item in (raw if isinstance(raw, list) else []):
|
| 26 |
+
problems.append(
|
| 27 |
+
PracticeProblem(
|
| 28 |
+
question=item.get("question", ""),
|
| 29 |
+
answer=item.get("answer", ""),
|
| 30 |
+
hint=item.get("hint", ""),
|
| 31 |
+
difficulty=item.get("difficulty", "medium"),
|
| 32 |
+
)
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
return PracticeResponse(problems=problems, session_id=body.session_id)
|
backend/routers/test.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, HTTPException
|
| 2 |
+
|
| 3 |
+
from backend.core.auth import get_current_user
|
| 4 |
+
from backend.models.test import (
|
| 5 |
+
TestEvaluateRequest,
|
| 6 |
+
TestEvaluateResponse,
|
| 7 |
+
TestGenerateRequest,
|
| 8 |
+
TestGenerateResponse,
|
| 9 |
+
TestQuestion,
|
| 10 |
+
QuestionResult,
|
| 11 |
+
)
|
| 12 |
+
from backend.services import claude_service, prompt_templates, supabase_service
|
| 13 |
+
|
| 14 |
+
router = APIRouter(prefix="/api/test", tags=["test"])
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@router.post("/generate", response_model=TestGenerateResponse)
|
| 18 |
+
async def generate_test(
|
| 19 |
+
body: TestGenerateRequest,
|
| 20 |
+
user: dict = Depends(get_current_user),
|
| 21 |
+
):
|
| 22 |
+
"""Generate a 5-question mini-test for the session topic."""
|
| 23 |
+
system = prompt_templates.test_system(body.grade)
|
| 24 |
+
user_msg = prompt_templates.test_user(body.topic)
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
raw = await claude_service.complete_json(system, user_msg)
|
| 28 |
+
except ValueError as e:
|
| 29 |
+
raise HTTPException(status_code=502, detail=str(e))
|
| 30 |
+
|
| 31 |
+
questions = []
|
| 32 |
+
for item in (raw if isinstance(raw, list) else []):
|
| 33 |
+
questions.append(
|
| 34 |
+
TestQuestion(
|
| 35 |
+
question=item.get("question", ""),
|
| 36 |
+
correct_answer=item.get("correct_answer", ""),
|
| 37 |
+
solution_steps=item.get("solution_steps", []),
|
| 38 |
+
type=item.get("type", "short_answer"),
|
| 39 |
+
)
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
return TestGenerateResponse(questions=questions, session_id=body.session_id)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@router.post("/evaluate", response_model=TestEvaluateResponse)
|
| 46 |
+
async def evaluate_test(
|
| 47 |
+
body: TestEvaluateRequest,
|
| 48 |
+
user: dict = Depends(get_current_user),
|
| 49 |
+
):
|
| 50 |
+
"""Evaluate student answers, save result to Supabase, return score + feedback."""
|
| 51 |
+
system = prompt_templates.evaluate_system()
|
| 52 |
+
user_msg = prompt_templates.evaluate_user(
|
| 53 |
+
[a.model_dump() for a in body.answers]
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
raw = await claude_service.complete_json(system, user_msg)
|
| 58 |
+
except ValueError as e:
|
| 59 |
+
raise HTTPException(status_code=502, detail=str(e))
|
| 60 |
+
|
| 61 |
+
score = int(raw.get("score", 0))
|
| 62 |
+
passed = bool(raw.get("passed", False))
|
| 63 |
+
encouragement = raw.get("encouragement", "Keep going!")
|
| 64 |
+
|
| 65 |
+
results = [
|
| 66 |
+
QuestionResult(
|
| 67 |
+
question_index=r.get("question_index", i),
|
| 68 |
+
is_correct=bool(r.get("is_correct", False)),
|
| 69 |
+
feedback=r.get("feedback", ""),
|
| 70 |
+
)
|
| 71 |
+
for i, r in enumerate(raw.get("results", []))
|
| 72 |
+
]
|
| 73 |
+
|
| 74 |
+
# Persist result
|
| 75 |
+
supabase_service.save_test_result(
|
| 76 |
+
session_id=body.session_id,
|
| 77 |
+
user_id=user["id"],
|
| 78 |
+
score=score,
|
| 79 |
+
passed=passed,
|
| 80 |
+
attempt_number=body.attempt_number,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# Update streak if passed
|
| 84 |
+
if passed:
|
| 85 |
+
profile = supabase_service.get_profile(user["id"])
|
| 86 |
+
current_streak = (profile or {}).get("streak_count", 0)
|
| 87 |
+
supabase_service.update_streak(user["id"], current_streak + 1)
|
| 88 |
+
|
| 89 |
+
return TestEvaluateResponse(
|
| 90 |
+
results=results,
|
| 91 |
+
score=score,
|
| 92 |
+
passed=passed,
|
| 93 |
+
encouragement=encouragement,
|
| 94 |
+
session_id=body.session_id,
|
| 95 |
+
)
|
backend/services/__init__.py
ADDED
|
File without changes
|
backend/services/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (158 Bytes). View file
|
|
|
backend/services/__pycache__/claude_service.cpython-313.pyc
ADDED
|
Binary file (3.23 kB). View file
|
|
|
backend/services/__pycache__/prompt_templates.cpython-313.pyc
ADDED
|
Binary file (5.31 kB). View file
|
|
|
backend/services/__pycache__/supabase_service.cpython-313.pyc
ADDED
|
Binary file (7.49 kB). View file
|
|
|
backend/services/claude_service.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Claude service — wraps the Anthropic async client.
|
| 3 |
+
Provides two modes:
|
| 4 |
+
- stream() : yields text chunks (for explanations)
|
| 5 |
+
- complete() : returns full text (for JSON outputs)
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import re
|
| 10 |
+
from typing import AsyncIterator
|
| 11 |
+
|
| 12 |
+
import anthropic
|
| 13 |
+
|
| 14 |
+
from backend.core.config import settings
|
| 15 |
+
|
| 16 |
+
MODEL = "claude-sonnet-4-6"
|
| 17 |
+
MAX_TOKENS = 1024
|
| 18 |
+
|
| 19 |
+
_client = anthropic.AsyncAnthropic(api_key=settings.anthropic_api_key)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
async def stream(system: str, user: str) -> AsyncIterator[str]:
|
| 23 |
+
"""Stream response chunks — used for explanation endpoint."""
|
| 24 |
+
async with _client.messages.stream(
|
| 25 |
+
model=MODEL,
|
| 26 |
+
max_tokens=MAX_TOKENS,
|
| 27 |
+
system=system,
|
| 28 |
+
messages=[{"role": "user", "content": user}],
|
| 29 |
+
) as stream:
|
| 30 |
+
async for text in stream.text_stream:
|
| 31 |
+
yield text
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
async def complete(system: str, user: str, max_tokens: int = MAX_TOKENS) -> str:
|
| 35 |
+
"""Return full response text — used for JSON-output endpoints."""
|
| 36 |
+
message = await _client.messages.create(
|
| 37 |
+
model=MODEL,
|
| 38 |
+
max_tokens=max_tokens,
|
| 39 |
+
system=system,
|
| 40 |
+
messages=[{"role": "user", "content": user}],
|
| 41 |
+
)
|
| 42 |
+
return message.content[0].text
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
async def complete_json(system: str, user: str) -> dict | list:
|
| 46 |
+
"""
|
| 47 |
+
Return parsed JSON — retries once if the first response is malformed.
|
| 48 |
+
Strips markdown code fences if present.
|
| 49 |
+
"""
|
| 50 |
+
for attempt in range(2):
|
| 51 |
+
raw = await complete(system, user)
|
| 52 |
+
# Strip ```json ... ``` fences
|
| 53 |
+
cleaned = re.sub(r"^```(?:json)?\s*|\s*```$", "", raw.strip(), flags=re.MULTILINE)
|
| 54 |
+
try:
|
| 55 |
+
return json.loads(cleaned)
|
| 56 |
+
except json.JSONDecodeError:
|
| 57 |
+
if attempt == 1:
|
| 58 |
+
raise ValueError(f"Claude returned invalid JSON after 2 attempts: {raw[:200]}")
|
| 59 |
+
# Retry with an explicit reminder
|
| 60 |
+
user = user + "\n\nIMPORTANT: Return ONLY valid JSON. No markdown."
|
backend/services/prompt_templates.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Prompt templates for each grade band and each AI call type.
|
| 3 |
+
Grade bands: 6-7 (elementary), 8-9 (middle), 10-12 (high school)
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
GRADE_BAND = {
|
| 7 |
+
6: "elementary", 7: "elementary",
|
| 8 |
+
8: "middle", 9: "middle",
|
| 9 |
+
10: "high", 11: "high", 12: "high",
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
GRADE_STYLE = {
|
| 13 |
+
"elementary": (
|
| 14 |
+
"Use very simple, everyday language. Avoid jargon. "
|
| 15 |
+
"Use at most 4 numbered steps. Include a fun real-world example. "
|
| 16 |
+
"Encourage the student warmly."
|
| 17 |
+
),
|
| 18 |
+
"middle": (
|
| 19 |
+
"Use clear language and introduce formal math terms with brief definitions. "
|
| 20 |
+
"Use at most 6 numbered steps with a worked example. "
|
| 21 |
+
"Keep an encouraging but slightly more academic tone."
|
| 22 |
+
),
|
| 23 |
+
"high": (
|
| 24 |
+
"Use precise mathematical language and full algebraic notation. "
|
| 25 |
+
"Use up to 8 numbered steps. Include exam-style worked examples. "
|
| 26 |
+
"Assume the student is preparing for standardised tests."
|
| 27 |
+
),
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def band(grade: int) -> str:
|
| 32 |
+
return GRADE_BAND.get(grade, "middle")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def style(grade: int) -> str:
|
| 36 |
+
return GRADE_STYLE.get(band(grade), GRADE_STYLE["middle"])
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# ── Explanation ────────────────────────────────────────────────────────────────
|
| 40 |
+
def explanation_system(grade: int) -> str:
|
| 41 |
+
return (
|
| 42 |
+
f"You are MathMind AI, an expert mathematics tutor for Grade {grade} students. "
|
| 43 |
+
f"{style(grade)} "
|
| 44 |
+
"Only answer mathematics questions. If the question is off-topic, respond: "
|
| 45 |
+
"'I can only help with math! Try asking me about a specific topic like algebra or fractions.' "
|
| 46 |
+
"Format your response as numbered steps. End with: 'Ready to practise? Type YES!'"
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def explanation_user(query: str) -> str:
|
| 51 |
+
return f"Explain the following math concept or solve this problem:\n\n{query}"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# ── Practice Problems ──────────────────────────────────────────────────────────
|
| 55 |
+
def practice_system(grade: int) -> str:
|
| 56 |
+
return (
|
| 57 |
+
f"You are MathMind AI generating practice problems for a Grade {grade} student. "
|
| 58 |
+
f"{style(grade)} "
|
| 59 |
+
"Respond ONLY with a valid JSON array. No markdown, no preamble. "
|
| 60 |
+
"Each element must have exactly these keys: "
|
| 61 |
+
'"question" (string), "answer" (string), "hint" (string), "difficulty" ("easy"|"medium"|"hard"). '
|
| 62 |
+
"All problems must be solvable with Grade {grade} knowledge."
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def practice_user(topic: str, count: int = 3) -> str:
|
| 67 |
+
return (
|
| 68 |
+
f"Generate {count} practice problems on the topic: {topic}. "
|
| 69 |
+
"Return ONLY the JSON array."
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# ── Test Generation ────────────────────────────────────────────────────────────
|
| 74 |
+
def test_system(grade: int) -> str:
|
| 75 |
+
return (
|
| 76 |
+
f"You are MathMind AI generating a mini-test for a Grade {grade} student. "
|
| 77 |
+
f"{style(grade)} "
|
| 78 |
+
"Respond ONLY with a valid JSON array. No markdown, no preamble. "
|
| 79 |
+
"Each element must have exactly these keys: "
|
| 80 |
+
'"question" (string), "correct_answer" (string), '
|
| 81 |
+
'"solution_steps" (array of strings), "type" ("numerical"|"short_answer"). '
|
| 82 |
+
"Generate exactly 5 questions of increasing difficulty."
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_user(topic: str) -> str:
|
| 87 |
+
return f"Generate a 5-question mini-test on the topic: {topic}. Return ONLY the JSON array."
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# ── Answer Evaluation ──────────────────────────────────────────────────────────
|
| 91 |
+
def evaluate_system() -> str:
|
| 92 |
+
return (
|
| 93 |
+
"You are a math answer evaluator. "
|
| 94 |
+
"You will receive a list of questions with correct answers and student answers. "
|
| 95 |
+
"Be lenient with formatting differences (e.g. '1/2' == '0.5'). "
|
| 96 |
+
"Respond ONLY with a valid JSON object with these keys: "
|
| 97 |
+
'"results" (array of {"question_index": int, "is_correct": bool, "feedback": string}), '
|
| 98 |
+
'"score" (integer 0-100), '
|
| 99 |
+
'"passed" (bool, true if score >= 80), '
|
| 100 |
+
'"encouragement" (string, a short motivating message). '
|
| 101 |
+
"No markdown, no preamble."
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def evaluate_user(qa_pairs: list[dict]) -> str:
|
| 106 |
+
lines = []
|
| 107 |
+
for i, pair in enumerate(qa_pairs):
|
| 108 |
+
lines.append(
|
| 109 |
+
f"Q{i+1}: {pair['question']}\n"
|
| 110 |
+
f" Correct answer: {pair['correct_answer']}\n"
|
| 111 |
+
f" Student answer: {pair['student_answer']}"
|
| 112 |
+
)
|
| 113 |
+
return "Evaluate these answers:\n\n" + "\n\n".join(lines)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# ── Weekly Report (Phase 2 placeholder) ───────────────────────────────────────
|
| 117 |
+
def weekly_report_system() -> str:
|
| 118 |
+
return (
|
| 119 |
+
"You are MathMind AI writing a friendly weekly progress report. "
|
| 120 |
+
"Keep it under 200 words. Be warm, specific, and encouraging."
|
| 121 |
+
)
|
backend/services/supabase_service.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Supabase service — single client instance used by all routers.
|
| 3 |
+
Uses the service role key so it can bypass RLS for server operations.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from supabase import Client, create_client
|
| 7 |
+
from backend.core.config import settings
|
| 8 |
+
|
| 9 |
+
_client: Client = create_client(
|
| 10 |
+
settings.supabase_url,
|
| 11 |
+
settings.supabase_service_role_key,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def db() -> Client:
|
| 16 |
+
"""Return the Supabase client."""
|
| 17 |
+
return _client
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# ── Profiles ───────────────────────────────────────────────────────────────────
|
| 21 |
+
def get_profile(user_id: str) -> dict | None:
|
| 22 |
+
res = _client.table("profiles").select("*").eq("id", user_id).single().execute()
|
| 23 |
+
return res.data
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def upsert_profile(user_id: str, grade: int) -> dict:
|
| 27 |
+
res = (
|
| 28 |
+
_client.table("profiles")
|
| 29 |
+
.upsert({"id": user_id, "grade": grade})
|
| 30 |
+
.execute()
|
| 31 |
+
)
|
| 32 |
+
return res.data[0] if res.data else {}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def update_streak(user_id: str, streak: int) -> None:
|
| 36 |
+
from datetime import date
|
| 37 |
+
_client.table("profiles").update(
|
| 38 |
+
{"streak_count": streak, "last_active": date.today().isoformat()}
|
| 39 |
+
).eq("id", user_id).execute()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# ── Sessions ───────────────────────────────────────────────────────────────────
|
| 43 |
+
def create_session(user_id: str, topic: str, grade: int, explanation: str) -> dict:
|
| 44 |
+
res = (
|
| 45 |
+
_client.table("sessions")
|
| 46 |
+
.insert(
|
| 47 |
+
{
|
| 48 |
+
"user_id": user_id,
|
| 49 |
+
"topic": topic,
|
| 50 |
+
"grade": grade,
|
| 51 |
+
"explanation": explanation,
|
| 52 |
+
}
|
| 53 |
+
)
|
| 54 |
+
.execute()
|
| 55 |
+
)
|
| 56 |
+
return res.data[0]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def get_sessions(user_id: str, limit: int = 10) -> list[dict]:
|
| 60 |
+
res = (
|
| 61 |
+
_client.table("sessions")
|
| 62 |
+
.select("*")
|
| 63 |
+
.eq("user_id", user_id)
|
| 64 |
+
.order("created_at", desc=True)
|
| 65 |
+
.limit(limit)
|
| 66 |
+
.execute()
|
| 67 |
+
)
|
| 68 |
+
return res.data or []
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# ── Practice Attempts ──────────────────────────────────────────────────────────
|
| 72 |
+
def save_practice_attempts(session_id: str, attempts: list[dict]) -> None:
|
| 73 |
+
rows = [
|
| 74 |
+
{
|
| 75 |
+
"session_id": session_id,
|
| 76 |
+
"question": a["question"],
|
| 77 |
+
"student_answer": a.get("student_answer", ""),
|
| 78 |
+
"is_correct": a.get("is_correct", False),
|
| 79 |
+
}
|
| 80 |
+
for a in attempts
|
| 81 |
+
]
|
| 82 |
+
_client.table("practice_attempts").insert(rows).execute()
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
# ── Test Results ───────────────────────────────────────────────────────────────
|
| 86 |
+
def save_test_result(
|
| 87 |
+
session_id: str, user_id: str, score: int, passed: bool, attempt_number: int = 1
|
| 88 |
+
) -> dict:
|
| 89 |
+
res = (
|
| 90 |
+
_client.table("test_results")
|
| 91 |
+
.insert(
|
| 92 |
+
{
|
| 93 |
+
"session_id": session_id,
|
| 94 |
+
"user_id": user_id,
|
| 95 |
+
"score": score,
|
| 96 |
+
"passed": passed,
|
| 97 |
+
"attempts": attempt_number,
|
| 98 |
+
}
|
| 99 |
+
)
|
| 100 |
+
.execute()
|
| 101 |
+
)
|
| 102 |
+
return res.data[0]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def get_test_results(user_id: str) -> list[dict]:
|
| 106 |
+
res = (
|
| 107 |
+
_client.table("test_results")
|
| 108 |
+
.select("*, sessions(topic)")
|
| 109 |
+
.eq("user_id", user_id)
|
| 110 |
+
.order("created_at", desc=True)
|
| 111 |
+
.limit(20)
|
| 112 |
+
.execute()
|
| 113 |
+
)
|
| 114 |
+
return res.data or []
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# ── Badges ─────────────────────────────────────────────────────────────────────
|
| 118 |
+
def get_all_badges() -> list[dict]:
|
| 119 |
+
res = _client.table("badges").select("*").execute()
|
| 120 |
+
return res.data or []
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def get_student_badges(user_id: str) -> list[dict]:
|
| 124 |
+
res = (
|
| 125 |
+
_client.table("student_badges")
|
| 126 |
+
.select("*, badges(name, emoji, description)")
|
| 127 |
+
.eq("user_id", user_id)
|
| 128 |
+
.execute()
|
| 129 |
+
)
|
| 130 |
+
return res.data or []
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def award_badge(user_id: str, badge_id: str) -> dict | None:
|
| 134 |
+
# Check not already awarded
|
| 135 |
+
existing = (
|
| 136 |
+
_client.table("student_badges")
|
| 137 |
+
.select("id")
|
| 138 |
+
.eq("user_id", user_id)
|
| 139 |
+
.eq("badge_id", badge_id)
|
| 140 |
+
.execute()
|
| 141 |
+
)
|
| 142 |
+
if existing.data:
|
| 143 |
+
return None
|
| 144 |
+
res = (
|
| 145 |
+
_client.table("student_badges")
|
| 146 |
+
.insert({"user_id": user_id, "badge_id": badge_id})
|
| 147 |
+
.execute()
|
| 148 |
+
)
|
| 149 |
+
return res.data[0] if res.data else None
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def count_passed_tests(user_id: str) -> int:
|
| 153 |
+
res = (
|
| 154 |
+
_client.table("test_results")
|
| 155 |
+
.select("id", count="exact")
|
| 156 |
+
.eq("user_id", user_id)
|
| 157 |
+
.eq("passed", True)
|
| 158 |
+
.execute()
|
| 159 |
+
)
|
| 160 |
+
return res.count or 0
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def count_sessions(user_id: str) -> int:
|
| 164 |
+
res = (
|
| 165 |
+
_client.table("sessions")
|
| 166 |
+
.select("id", count="exact")
|
| 167 |
+
.eq("user_id", user_id)
|
| 168 |
+
.execute()
|
| 169 |
+
)
|
| 170 |
+
return res.count or 0
|
database/01_schema.sql
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- ============================================================
|
| 2 |
+
-- MathMind AI — Database Schema
|
| 3 |
+
-- Run this in: Supabase Dashboard → SQL Editor
|
| 4 |
+
-- Order: 01_schema.sql → 02_rls.sql → 03_seed.sql
|
| 5 |
+
-- ============================================================
|
| 6 |
+
|
| 7 |
+
-- Enable UUID generation
|
| 8 |
+
create extension if not exists "pgcrypto";
|
| 9 |
+
|
| 10 |
+
-- ── 1. profiles ────────────────────────────────────────────
|
| 11 |
+
-- Extends auth.users — one row per student
|
| 12 |
+
create table if not exists public.profiles (
|
| 13 |
+
id uuid primary key references auth.users(id) on delete cascade,
|
| 14 |
+
grade smallint not null check (grade between 6 and 12),
|
| 15 |
+
streak_count integer not null default 0,
|
| 16 |
+
last_active date,
|
| 17 |
+
created_at timestamptz not null default now(),
|
| 18 |
+
updated_at timestamptz not null default now()
|
| 19 |
+
);
|
| 20 |
+
|
| 21 |
+
comment on table public.profiles is 'Student profile — extends Supabase auth.users';
|
| 22 |
+
|
| 23 |
+
-- Auto-update updated_at
|
| 24 |
+
create or replace function public.set_updated_at()
|
| 25 |
+
returns trigger language plpgsql as $$
|
| 26 |
+
begin
|
| 27 |
+
new.updated_at = now();
|
| 28 |
+
return new;
|
| 29 |
+
end;
|
| 30 |
+
$$;
|
| 31 |
+
|
| 32 |
+
create trigger profiles_updated_at
|
| 33 |
+
before update on public.profiles
|
| 34 |
+
for each row execute function public.set_updated_at();
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
-- ── 2. sessions ────────────────────────────────────────────
|
| 38 |
+
-- One row per tutor session (question + explanation)
|
| 39 |
+
create table if not exists public.sessions (
|
| 40 |
+
id uuid primary key default gen_random_uuid(),
|
| 41 |
+
user_id uuid not null references public.profiles(id) on delete cascade,
|
| 42 |
+
topic text not null,
|
| 43 |
+
grade smallint not null check (grade between 6 and 12),
|
| 44 |
+
explanation text not null,
|
| 45 |
+
created_at timestamptz not null default now()
|
| 46 |
+
);
|
| 47 |
+
|
| 48 |
+
comment on table public.sessions is 'One tutor session per student question';
|
| 49 |
+
|
| 50 |
+
create index if not exists sessions_user_id_idx on public.sessions(user_id);
|
| 51 |
+
create index if not exists sessions_created_at_idx on public.sessions(created_at desc);
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
-- ── 3. practice_attempts ───────────────────────────────────
|
| 55 |
+
-- Practice problem responses within a session
|
| 56 |
+
create table if not exists public.practice_attempts (
|
| 57 |
+
id uuid primary key default gen_random_uuid(),
|
| 58 |
+
session_id uuid not null references public.sessions(id) on delete cascade,
|
| 59 |
+
question text not null,
|
| 60 |
+
student_answer text not null default '',
|
| 61 |
+
is_correct boolean not null default false,
|
| 62 |
+
created_at timestamptz not null default now()
|
| 63 |
+
);
|
| 64 |
+
|
| 65 |
+
comment on table public.practice_attempts is 'Student answers to practice problems';
|
| 66 |
+
|
| 67 |
+
create index if not exists practice_attempts_session_idx on public.practice_attempts(session_id);
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
-- ── 4. test_results ────────────────────────────────────────
|
| 71 |
+
-- Mini-test outcomes per session
|
| 72 |
+
create table if not exists public.test_results (
|
| 73 |
+
id uuid primary key default gen_random_uuid(),
|
| 74 |
+
session_id uuid not null references public.sessions(id) on delete cascade,
|
| 75 |
+
user_id uuid not null references public.profiles(id) on delete cascade,
|
| 76 |
+
score smallint not null check (score between 0 and 100),
|
| 77 |
+
passed boolean not null default false,
|
| 78 |
+
attempts smallint not null default 1,
|
| 79 |
+
created_at timestamptz not null default now()
|
| 80 |
+
);
|
| 81 |
+
|
| 82 |
+
comment on table public.test_results is 'Mini-test results — 80% threshold for pass';
|
| 83 |
+
|
| 84 |
+
create index if not exists test_results_user_id_idx on public.test_results(user_id);
|
| 85 |
+
create index if not exists test_results_session_idx on public.test_results(session_id);
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
-- ── 5. badges ──────────────────────────────────────────────
|
| 89 |
+
-- Badge definitions (populated by 03_seed.sql)
|
| 90 |
+
create table if not exists public.badges (
|
| 91 |
+
id uuid primary key default gen_random_uuid(),
|
| 92 |
+
name text not null unique,
|
| 93 |
+
emoji text not null,
|
| 94 |
+
condition_key text not null unique, -- matched in Python badge engine
|
| 95 |
+
description text not null,
|
| 96 |
+
created_at timestamptz not null default now()
|
| 97 |
+
);
|
| 98 |
+
|
| 99 |
+
comment on table public.badges is 'Badge definitions — condition_key matched by badge engine';
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
-- ── 6. student_badges ──────────────────────────────────────
|
| 103 |
+
-- Badges earned by each student
|
| 104 |
+
create table if not exists public.student_badges (
|
| 105 |
+
id uuid primary key default gen_random_uuid(),
|
| 106 |
+
user_id uuid not null references public.profiles(id) on delete cascade,
|
| 107 |
+
badge_id uuid not null references public.badges(id) on delete cascade,
|
| 108 |
+
earned_at timestamptz not null default now(),
|
| 109 |
+
unique(user_id, badge_id) -- a student earns each badge only once
|
| 110 |
+
);
|
| 111 |
+
|
| 112 |
+
comment on table public.student_badges is 'Badges awarded to students';
|
| 113 |
+
|
| 114 |
+
create index if not exists student_badges_user_idx on public.student_badges(user_id);
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
-- ── Auto-create profile on signup ──────────────────────────
|
| 118 |
+
-- Triggered when a new user signs up via Supabase Auth
|
| 119 |
+
-- Grade defaults to 8 until the student sets it in the app
|
| 120 |
+
create or replace function public.handle_new_user()
|
| 121 |
+
returns trigger language plpgsql security definer as $$
|
| 122 |
+
begin
|
| 123 |
+
insert into public.profiles (id, grade)
|
| 124 |
+
values (new.id, 8)
|
| 125 |
+
on conflict (id) do nothing;
|
| 126 |
+
return new;
|
| 127 |
+
end;
|
| 128 |
+
$$;
|
| 129 |
+
|
| 130 |
+
drop trigger if exists on_auth_user_created on auth.users;
|
| 131 |
+
create trigger on_auth_user_created
|
| 132 |
+
after insert on auth.users
|
| 133 |
+
for each row execute function public.handle_new_user();
|
database/02_rls.sql
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- ============================================================
|
| 2 |
+
-- MathMind AI — Row Level Security (RLS)
|
| 3 |
+
-- Run AFTER 01_schema.sql
|
| 4 |
+
-- ============================================================
|
| 5 |
+
|
| 6 |
+
-- Enable RLS on all student-data tables
|
| 7 |
+
alter table public.profiles enable row level security;
|
| 8 |
+
alter table public.sessions enable row level security;
|
| 9 |
+
alter table public.practice_attempts enable row level security;
|
| 10 |
+
alter table public.test_results enable row level security;
|
| 11 |
+
alter table public.student_badges enable row level security;
|
| 12 |
+
|
| 13 |
+
-- badges table is read-only for all authenticated users (definitions, not student data)
|
| 14 |
+
alter table public.badges enable row level security;
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
-- ── profiles ───────────────────────────────────────────────
|
| 18 |
+
create policy "Students can view own profile"
|
| 19 |
+
on public.profiles for select
|
| 20 |
+
using (auth.uid() = id);
|
| 21 |
+
|
| 22 |
+
create policy "Students can update own profile"
|
| 23 |
+
on public.profiles for update
|
| 24 |
+
using (auth.uid() = id);
|
| 25 |
+
|
| 26 |
+
create policy "Students can insert own profile"
|
| 27 |
+
on public.profiles for insert
|
| 28 |
+
with check (auth.uid() = id);
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
-- ── sessions ───────────────────────────────────────────────
|
| 32 |
+
create policy "Students can view own sessions"
|
| 33 |
+
on public.sessions for select
|
| 34 |
+
using (auth.uid() = user_id);
|
| 35 |
+
|
| 36 |
+
create policy "Students can insert own sessions"
|
| 37 |
+
on public.sessions for insert
|
| 38 |
+
with check (auth.uid() = user_id);
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
-- ── practice_attempts ──────────────────────────────────────
|
| 42 |
+
-- Students access their own attempts via session ownership
|
| 43 |
+
create policy "Students can view own practice attempts"
|
| 44 |
+
on public.practice_attempts for select
|
| 45 |
+
using (
|
| 46 |
+
exists (
|
| 47 |
+
select 1 from public.sessions s
|
| 48 |
+
where s.id = practice_attempts.session_id
|
| 49 |
+
and s.user_id = auth.uid()
|
| 50 |
+
)
|
| 51 |
+
);
|
| 52 |
+
|
| 53 |
+
create policy "Students can insert own practice attempts"
|
| 54 |
+
on public.practice_attempts for insert
|
| 55 |
+
with check (
|
| 56 |
+
exists (
|
| 57 |
+
select 1 from public.sessions s
|
| 58 |
+
where s.id = practice_attempts.session_id
|
| 59 |
+
and s.user_id = auth.uid()
|
| 60 |
+
)
|
| 61 |
+
);
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
-- ── test_results ───────────────────────────────────────────
|
| 65 |
+
create policy "Students can view own test results"
|
| 66 |
+
on public.test_results for select
|
| 67 |
+
using (auth.uid() = user_id);
|
| 68 |
+
|
| 69 |
+
create policy "Students can insert own test results"
|
| 70 |
+
on public.test_results for insert
|
| 71 |
+
with check (auth.uid() = user_id);
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
-- ── badges (definitions — read-only for all auth users) ────
|
| 75 |
+
create policy "All authenticated users can read badges"
|
| 76 |
+
on public.badges for select
|
| 77 |
+
using (auth.role() = 'authenticated');
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
-- ── student_badges ─────────────────────────────────────────
|
| 81 |
+
create policy "Students can view own earned badges"
|
| 82 |
+
on public.student_badges for select
|
| 83 |
+
using (auth.uid() = user_id);
|
| 84 |
+
|
| 85 |
+
create policy "Students can insert own earned badges"
|
| 86 |
+
on public.student_badges for insert
|
| 87 |
+
with check (auth.uid() = user_id);
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
-- ── Service role bypass ────────────────────────────────────
|
| 91 |
+
-- The FastAPI backend uses service_role key which bypasses RLS.
|
| 92 |
+
-- This is intentional — backend does server-side validation before
|
| 93 |
+
-- writing to the DB. Never expose service_role key to the client.
|
database/03_seed.sql
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- ============================================================
|
| 2 |
+
-- MathMind AI — Seed Data
|
| 3 |
+
-- Run AFTER 02_rls.sql
|
| 4 |
+
-- ============================================================
|
| 5 |
+
|
| 6 |
+
-- ── Badge definitions ──────────────────────────────────────
|
| 7 |
+
-- condition_key must match keys in backend/routers/badges.py BADGE_CONDITIONS
|
| 8 |
+
|
| 9 |
+
insert into public.badges (name, emoji, condition_key, description) values
|
| 10 |
+
(
|
| 11 |
+
'First Try Champion',
|
| 12 |
+
'🏆',
|
| 13 |
+
'first_pass',
|
| 14 |
+
'Passed your first mini-test — you''re officially a MathMind champion!'
|
| 15 |
+
),
|
| 16 |
+
(
|
| 17 |
+
'Getting Started',
|
| 18 |
+
'🚀',
|
| 19 |
+
'five_sessions',
|
| 20 |
+
'Completed 5 learning sessions — the journey has begun!'
|
| 21 |
+
),
|
| 22 |
+
(
|
| 23 |
+
'Math Explorer',
|
| 24 |
+
'🌟',
|
| 25 |
+
'ten_sessions',
|
| 26 |
+
'Completed 10 sessions — you are truly exploring mathematics!'
|
| 27 |
+
),
|
| 28 |
+
(
|
| 29 |
+
'On Fire',
|
| 30 |
+
'🔥',
|
| 31 |
+
'streak_5',
|
| 32 |
+
'Maintained a 5-day learning streak — you''re on fire!'
|
| 33 |
+
),
|
| 34 |
+
(
|
| 35 |
+
'Perfect Score',
|
| 36 |
+
'💯',
|
| 37 |
+
'perfect_score',
|
| 38 |
+
'Scored 100% on a mini-test — flawless!'
|
| 39 |
+
)
|
| 40 |
+
on conflict (name) do nothing;
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
-- ── Sample math topics (for reference / future topic picker UI) ─────────────
|
| 44 |
+
-- This is a reference table only — not used by the app logic directly.
|
| 45 |
+
-- Uncomment and extend if you add a topic browser feature.
|
| 46 |
+
|
| 47 |
+
/*
|
| 48 |
+
create table if not exists public.sample_topics (
|
| 49 |
+
id uuid primary key default gen_random_uuid(),
|
| 50 |
+
grade smallint not null,
|
| 51 |
+
topic text not null
|
| 52 |
+
);
|
| 53 |
+
|
| 54 |
+
insert into public.sample_topics (grade, topic) values
|
| 55 |
+
-- Grade 6
|
| 56 |
+
(6, 'Fractions and mixed numbers'),
|
| 57 |
+
(6, 'Ratios and proportions'),
|
| 58 |
+
(6, 'Area and perimeter'),
|
| 59 |
+
(6, 'Introduction to negative numbers'),
|
| 60 |
+
-- Grade 7
|
| 61 |
+
(7, 'Linear equations'),
|
| 62 |
+
(7, 'Percentages and discounts'),
|
| 63 |
+
(7, 'Angles and triangles'),
|
| 64 |
+
(7, 'Introduction to probability'),
|
| 65 |
+
-- Grade 8
|
| 66 |
+
(8, 'Systems of linear equations'),
|
| 67 |
+
(8, 'Pythagorean theorem'),
|
| 68 |
+
(8, 'Functions and graphs'),
|
| 69 |
+
(8, 'Scientific notation'),
|
| 70 |
+
-- Grade 9
|
| 71 |
+
(9, 'Quadratic equations'),
|
| 72 |
+
(9, 'Factoring polynomials'),
|
| 73 |
+
(9, 'Introduction to trigonometry'),
|
| 74 |
+
(9, 'Inequalities'),
|
| 75 |
+
-- Grade 10
|
| 76 |
+
(10, 'Trigonometric ratios'),
|
| 77 |
+
(10, 'Circle theorems'),
|
| 78 |
+
(10, 'Sequences and series'),
|
| 79 |
+
(10, 'Probability and statistics'),
|
| 80 |
+
-- Grade 11
|
| 81 |
+
(11, 'Logarithms and exponentials'),
|
| 82 |
+
(11, 'Binomial theorem'),
|
| 83 |
+
(11, 'Vectors'),
|
| 84 |
+
(11, 'Differentiation introduction'),
|
| 85 |
+
-- Grade 12
|
| 86 |
+
(12, 'Integration'),
|
| 87 |
+
(12, 'Complex numbers'),
|
| 88 |
+
(12, 'Matrices'),
|
| 89 |
+
(12, 'Permutations and combinations');
|
| 90 |
+
*/
|
database/README.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MathMind AI — Database Setup
|
| 2 |
+
|
| 3 |
+
## Steps
|
| 4 |
+
|
| 5 |
+
1. Go to your **Supabase Dashboard → SQL Editor**
|
| 6 |
+
2. Run the scripts **in order**:
|
| 7 |
+
- `01_schema.sql` — creates all 6 tables + triggers
|
| 8 |
+
- `02_rls.sql` — enables Row Level Security
|
| 9 |
+
- `03_seed.sql` — inserts 5 badge definitions
|
| 10 |
+
|
| 11 |
+
## Tables Created
|
| 12 |
+
|
| 13 |
+
| Table | Purpose |
|
| 14 |
+
|-------|---------|
|
| 15 |
+
| `profiles` | Student grade + streak (extends auth.users) |
|
| 16 |
+
| `sessions` | One row per tutor session |
|
| 17 |
+
| `practice_attempts` | Practice problem responses |
|
| 18 |
+
| `test_results` | Mini-test scores and pass/fail |
|
| 19 |
+
| `badges` | Badge definitions |
|
| 20 |
+
| `student_badges` | Badges earned by each student |
|
| 21 |
+
|
| 22 |
+
## Notes
|
| 23 |
+
|
| 24 |
+
- **RLS is enabled** — students can only read/write their own data
|
| 25 |
+
- **Service role key** used by FastAPI backend bypasses RLS (server-side only — never expose to client)
|
| 26 |
+
- **Auto-trigger** creates a `profiles` row (grade=8 default) on every new signup
|
| 27 |
+
- Student must update their grade in the app after signup
|
requirements.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Backend
|
| 2 |
+
fastapi>=0.111.0
|
| 3 |
+
uvicorn[standard]>=0.29.0
|
| 4 |
+
anthropic>=0.25.0
|
| 5 |
+
supabase>=2.4.0
|
| 6 |
+
python-dotenv>=1.0.0
|
| 7 |
+
pydantic-settings>=2.2.0
|
| 8 |
+
pydantic>=2.6.0
|
| 9 |
+
httpx>=0.27.0
|
| 10 |
+
python-jose[cryptography]>=3.3.0
|
| 11 |
+
|
| 12 |
+
# Frontend
|
| 13 |
+
streamlit>=1.35.0
|
streamlit_app/app.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import sys, os
|
| 3 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
| 4 |
+
|
| 5 |
+
st.set_page_config(
|
| 6 |
+
page_title="MathMind AI",
|
| 7 |
+
page_icon="🧮",
|
| 8 |
+
layout="centered",
|
| 9 |
+
initial_sidebar_state="auto",
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
from streamlit_app.utils.auth import is_logged_in
|
| 13 |
+
|
| 14 |
+
# ── Landing page ───────────────────────────────────────────────────────────────
|
| 15 |
+
st.markdown("""
|
| 16 |
+
<style>
|
| 17 |
+
.hero { text-align: center; padding: 3rem 1rem 1rem; }
|
| 18 |
+
.hero h1 { font-size: 3rem; margin-bottom: 0.25rem; }
|
| 19 |
+
.hero p { font-size: 1.2rem; color: #555; margin-bottom: 2rem; }
|
| 20 |
+
.feature-grid { display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap; margin-top: 1.5rem; }
|
| 21 |
+
.feature-card { background: #f0f4ff; border-radius: 12px; padding: 1.2rem 1.5rem;
|
| 22 |
+
width: 200px; text-align: center; }
|
| 23 |
+
.feature-card .icon { font-size: 2rem; }
|
| 24 |
+
.feature-card p { font-size: 0.9rem; margin: 0.5rem 0 0; color: #333; }
|
| 25 |
+
</style>
|
| 26 |
+
|
| 27 |
+
<div class="hero">
|
| 28 |
+
<h1>🧮 MathMind AI</h1>
|
| 29 |
+
<p>Your personal AI math tutor for Grades 6 – 12</p>
|
| 30 |
+
</div>
|
| 31 |
+
""", unsafe_allow_html=True)
|
| 32 |
+
|
| 33 |
+
col1, col2, col3 = st.columns(3)
|
| 34 |
+
with col1:
|
| 35 |
+
st.info("🧠 **Adaptive Explanations**\nGrade-calibrated, step-by-step answers to any math question")
|
| 36 |
+
with col2:
|
| 37 |
+
st.info("📝 **Mini-Tests**\nProve your understanding with a 5-question test and instant feedback")
|
| 38 |
+
with col3:
|
| 39 |
+
st.info("🏆 **Badges & Streaks**\nEarn rewards and track your daily learning streak")
|
| 40 |
+
|
| 41 |
+
st.divider()
|
| 42 |
+
|
| 43 |
+
if is_logged_in():
|
| 44 |
+
st.success(f"Welcome back! You're logged in as **{st.session_state.get('user_email', '')}**")
|
| 45 |
+
col_a, col_b = st.columns(2)
|
| 46 |
+
with col_a:
|
| 47 |
+
st.page_link("pages/2_Tutor.py", label="▶️ Start Learning", use_container_width=True)
|
| 48 |
+
with col_b:
|
| 49 |
+
st.page_link("pages/3_Dashboard.py", label="📊 My Dashboard", use_container_width=True)
|
| 50 |
+
else:
|
| 51 |
+
st.page_link("pages/1_Login.py", label="🚀 Get Started — Login or Sign Up", use_container_width=True)
|
streamlit_app/pages/1_Login.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import sys, os
|
| 3 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
| 4 |
+
|
| 5 |
+
from streamlit_app.utils.auth import login, signup, is_logged_in, logout
|
| 6 |
+
|
| 7 |
+
st.set_page_config(page_title="MathMind AI — Login", page_icon="🔐", layout="centered")
|
| 8 |
+
|
| 9 |
+
# Already logged in
|
| 10 |
+
if is_logged_in():
|
| 11 |
+
st.success(f"✅ Logged in as **{st.session_state.get('user_email')}**")
|
| 12 |
+
st.page_link("pages/2_Tutor.py", label="▶️ Go to Tutor", use_container_width=True)
|
| 13 |
+
if st.button("Log out"):
|
| 14 |
+
logout()
|
| 15 |
+
st.rerun()
|
| 16 |
+
st.stop()
|
| 17 |
+
|
| 18 |
+
st.title("🔐 Login to MathMind AI")
|
| 19 |
+
st.caption("Your personal AI math tutor — Grades 6–12")
|
| 20 |
+
st.divider()
|
| 21 |
+
|
| 22 |
+
tab_login, tab_signup = st.tabs(["Log In", "Sign Up"])
|
| 23 |
+
|
| 24 |
+
# ── Login Tab ──────────────────────────────────────────────────────────────────
|
| 25 |
+
with tab_login:
|
| 26 |
+
st.subheader("Welcome back!")
|
| 27 |
+
email_l = st.text_input("Email", key="login_email", placeholder="you@example.com")
|
| 28 |
+
pass_l = st.text_input("Password", type="password", key="login_pass")
|
| 29 |
+
|
| 30 |
+
if st.button("Log In", type="primary", use_container_width=True, key="btn_login"):
|
| 31 |
+
if not email_l or not pass_l:
|
| 32 |
+
st.error("Please enter your email and password.")
|
| 33 |
+
else:
|
| 34 |
+
with st.spinner("Logging in…"):
|
| 35 |
+
ok, err = login(email_l, pass_l)
|
| 36 |
+
if ok:
|
| 37 |
+
st.success("Logged in! Redirecting…")
|
| 38 |
+
st.page_link("pages/2_Tutor.py", label="▶️ Start Learning")
|
| 39 |
+
st.rerun()
|
| 40 |
+
else:
|
| 41 |
+
st.error(f"Login failed: {err}")
|
| 42 |
+
|
| 43 |
+
# ── Signup Tab ─────────────────────────────────────────────────────────────────
|
| 44 |
+
with tab_signup:
|
| 45 |
+
st.subheader("Create your account")
|
| 46 |
+
email_s = st.text_input("Email", key="signup_email", placeholder="you@example.com")
|
| 47 |
+
pass_s = st.text_input("Password", type="password", key="signup_pass",
|
| 48 |
+
help="Minimum 6 characters")
|
| 49 |
+
pass_s2 = st.text_input("Confirm Password", type="password", key="signup_pass2")
|
| 50 |
+
grade_s = st.selectbox("Your Grade", options=list(range(6, 13)), index=2, key="signup_grade")
|
| 51 |
+
|
| 52 |
+
if st.button("Create Account", type="primary", use_container_width=True, key="btn_signup"):
|
| 53 |
+
if not email_s or not pass_s:
|
| 54 |
+
st.error("Please fill in all fields.")
|
| 55 |
+
elif pass_s != pass_s2:
|
| 56 |
+
st.error("Passwords do not match.")
|
| 57 |
+
elif len(pass_s) < 6:
|
| 58 |
+
st.error("Password must be at least 6 characters.")
|
| 59 |
+
else:
|
| 60 |
+
with st.spinner("Creating your account…"):
|
| 61 |
+
ok, err = signup(email_s, pass_s)
|
| 62 |
+
if ok:
|
| 63 |
+
# Store grade in session state — will be saved to profile by Tutor page
|
| 64 |
+
st.session_state["grade"] = grade_s
|
| 65 |
+
st.success("Account created! Welcome to MathMind AI 🎉")
|
| 66 |
+
st.page_link("pages/2_Tutor.py", label="▶️ Start Learning")
|
| 67 |
+
st.rerun()
|
| 68 |
+
else:
|
| 69 |
+
st.error(f"Signup failed: {err}")
|
streamlit_app/pages/2_Tutor.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import sys, os
|
| 3 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
| 4 |
+
|
| 5 |
+
from streamlit_app.utils.auth import require_login, get_token
|
| 6 |
+
from streamlit_app.utils.state import init_tutor_state, reset_tutor, set_stage, get_stage
|
| 7 |
+
from streamlit_app.utils import api_client
|
| 8 |
+
|
| 9 |
+
st.set_page_config(page_title="MathMind AI — Tutor", page_icon="🧮", layout="centered")
|
| 10 |
+
require_login()
|
| 11 |
+
init_tutor_state()
|
| 12 |
+
|
| 13 |
+
grade = st.session_state.get("grade", 8)
|
| 14 |
+
email = st.session_state.get("user_email", "")
|
| 15 |
+
|
| 16 |
+
# ── Sidebar ────────────────────────────────────────────────────────────────────
|
| 17 |
+
with st.sidebar:
|
| 18 |
+
st.markdown("### 🧮 MathMind AI")
|
| 19 |
+
st.caption(f"Logged in as {email}")
|
| 20 |
+
st.divider()
|
| 21 |
+
grade = st.selectbox(
|
| 22 |
+
"Your Grade",
|
| 23 |
+
options=list(range(6, 13)),
|
| 24 |
+
index=list(range(6, 13)).index(grade),
|
| 25 |
+
key="grade_select",
|
| 26 |
+
)
|
| 27 |
+
st.session_state["grade"] = grade
|
| 28 |
+
st.divider()
|
| 29 |
+
if st.button("🔄 New Question", use_container_width=True):
|
| 30 |
+
reset_tutor()
|
| 31 |
+
st.rerun()
|
| 32 |
+
st.page_link("pages/3_Dashboard.py", label="📊 My Dashboard", use_container_width=True)
|
| 33 |
+
|
| 34 |
+
# ── Header ─────────────────────────────────────────────────────────────────────
|
| 35 |
+
st.title("🧮 Math Tutor")
|
| 36 |
+
st.caption(f"Grade {grade} · Ask me any math question!")
|
| 37 |
+
|
| 38 |
+
stage = get_stage()
|
| 39 |
+
|
| 40 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 41 |
+
# STAGE 1: ASK
|
| 42 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 43 |
+
if stage == "ask":
|
| 44 |
+
st.markdown("### 💬 What would you like to learn?")
|
| 45 |
+
|
| 46 |
+
examples = [
|
| 47 |
+
"How do I solve linear equations?",
|
| 48 |
+
"Explain the Pythagorean theorem",
|
| 49 |
+
"What are fractions and how do I add them?",
|
| 50 |
+
"How does factoring quadratics work?",
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
example_cols = st.columns(2)
|
| 54 |
+
for i, ex in enumerate(examples):
|
| 55 |
+
with example_cols[i % 2]:
|
| 56 |
+
if st.button(ex, use_container_width=True, key=f"ex_{i}"):
|
| 57 |
+
st.session_state["current_query"] = ex
|
| 58 |
+
|
| 59 |
+
query = st.text_area(
|
| 60 |
+
"Or type your own question:",
|
| 61 |
+
value=st.session_state.get("current_query", ""),
|
| 62 |
+
placeholder="e.g. How do I find the area of a circle?",
|
| 63 |
+
height=100,
|
| 64 |
+
key="query_input",
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
if st.button("🚀 Get Explanation", type="primary", use_container_width=True):
|
| 68 |
+
if not query.strip():
|
| 69 |
+
st.error("Please enter a math question first.")
|
| 70 |
+
else:
|
| 71 |
+
st.session_state["current_query"] = query.strip()
|
| 72 |
+
st.session_state["current_topic"] = query.strip()[:80]
|
| 73 |
+
set_stage("explain")
|
| 74 |
+
st.rerun()
|
| 75 |
+
|
| 76 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 77 |
+
# STAGE 2: EXPLAIN (streaming)
|
| 78 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 79 |
+
elif stage == "explain":
|
| 80 |
+
query = st.session_state["current_query"]
|
| 81 |
+
st.markdown(f"### 📖 Explanation for Grade {grade}")
|
| 82 |
+
st.info(f"**Your question:** {query}")
|
| 83 |
+
|
| 84 |
+
if not st.session_state.get("current_explanation"):
|
| 85 |
+
with st.spinner("MathMind AI is thinking…"):
|
| 86 |
+
try:
|
| 87 |
+
explanation_chunks = []
|
| 88 |
+
placeholder = st.empty()
|
| 89 |
+
full_text = ""
|
| 90 |
+
for chunk in api_client.stream_explanation(query, grade):
|
| 91 |
+
full_text += chunk
|
| 92 |
+
placeholder.markdown(full_text + "▌")
|
| 93 |
+
placeholder.markdown(full_text)
|
| 94 |
+
st.session_state["current_explanation"] = full_text
|
| 95 |
+
# Session ID comes back via Supabase — we'll store in next call
|
| 96 |
+
st.session_state["current_session_id"] = "pending"
|
| 97 |
+
except Exception as e:
|
| 98 |
+
st.error(f"Could not get explanation: {e}")
|
| 99 |
+
if st.button("Try Again"):
|
| 100 |
+
reset_tutor()
|
| 101 |
+
st.rerun()
|
| 102 |
+
st.stop()
|
| 103 |
+
else:
|
| 104 |
+
st.markdown(st.session_state["current_explanation"])
|
| 105 |
+
|
| 106 |
+
st.divider()
|
| 107 |
+
col1, col2 = st.columns(2)
|
| 108 |
+
with col1:
|
| 109 |
+
if st.button("📝 Practice Problems", type="primary", use_container_width=True):
|
| 110 |
+
set_stage("practice")
|
| 111 |
+
st.rerun()
|
| 112 |
+
with col2:
|
| 113 |
+
if st.button("⏭️ Skip to Test", use_container_width=True):
|
| 114 |
+
set_stage("test")
|
| 115 |
+
st.rerun()
|
| 116 |
+
|
| 117 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 118 |
+
# STAGE 3: PRACTICE PROBLEMS
|
| 119 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 120 |
+
elif stage == "practice":
|
| 121 |
+
st.markdown("### ✏️ Practice Problems")
|
| 122 |
+
st.caption("Try these problems to reinforce what you just learned.")
|
| 123 |
+
|
| 124 |
+
if not st.session_state.get("practice_problems"):
|
| 125 |
+
with st.spinner("Generating practice problems…"):
|
| 126 |
+
try:
|
| 127 |
+
session_id = st.session_state.get("current_session_id", "temp")
|
| 128 |
+
result = api_client.get_practice(
|
| 129 |
+
topic=st.session_state["current_topic"],
|
| 130 |
+
grade=grade,
|
| 131 |
+
session_id=session_id,
|
| 132 |
+
)
|
| 133 |
+
st.session_state["practice_problems"] = result.get("problems", [])
|
| 134 |
+
except Exception as e:
|
| 135 |
+
st.error(f"Could not generate problems: {e}")
|
| 136 |
+
st.stop()
|
| 137 |
+
|
| 138 |
+
problems = st.session_state["practice_problems"]
|
| 139 |
+
all_answered = True
|
| 140 |
+
|
| 141 |
+
for i, prob in enumerate(problems):
|
| 142 |
+
with st.expander(f"Problem {i+1} — {prob.get('difficulty','').capitalize()}", expanded=True):
|
| 143 |
+
st.markdown(f"**{prob['question']}**")
|
| 144 |
+
answer_key = f"practice_ans_{i}"
|
| 145 |
+
user_ans = st.text_input("Your answer:", key=answer_key)
|
| 146 |
+
|
| 147 |
+
if st.button("Check Answer 💡", key=f"check_{i}"):
|
| 148 |
+
if not user_ans.strip():
|
| 149 |
+
st.warning("Please enter an answer first.")
|
| 150 |
+
else:
|
| 151 |
+
correct_ans = prob.get("answer", "").strip().lower()
|
| 152 |
+
student_ans = user_ans.strip().lower()
|
| 153 |
+
if student_ans == correct_ans or student_ans in correct_ans:
|
| 154 |
+
st.success("✅ Correct! Well done!")
|
| 155 |
+
else:
|
| 156 |
+
st.error(f"❌ Not quite. **Hint:** {prob.get('hint', '')}")
|
| 157 |
+
st.info(f"**Correct answer:** {prob['answer']}")
|
| 158 |
+
|
| 159 |
+
if not user_ans.strip():
|
| 160 |
+
all_answered = False
|
| 161 |
+
|
| 162 |
+
st.divider()
|
| 163 |
+
if st.button("📋 Take Mini-Test", type="primary", use_container_width=True):
|
| 164 |
+
set_stage("test")
|
| 165 |
+
st.rerun()
|
| 166 |
+
|
| 167 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 168 |
+
# STAGE 4: MINI-TEST
|
| 169 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 170 |
+
elif stage == "test":
|
| 171 |
+
st.markdown("### 📋 Mini-Test")
|
| 172 |
+
st.caption("5 questions · Pass mark: 80% · You can retry if you don't pass!")
|
| 173 |
+
|
| 174 |
+
if not st.session_state.get("test_questions"):
|
| 175 |
+
with st.spinner("Generating your mini-test…"):
|
| 176 |
+
try:
|
| 177 |
+
session_id = st.session_state.get("current_session_id", "temp")
|
| 178 |
+
result = api_client.generate_test(
|
| 179 |
+
topic=st.session_state["current_topic"],
|
| 180 |
+
grade=grade,
|
| 181 |
+
session_id=session_id,
|
| 182 |
+
)
|
| 183 |
+
st.session_state["test_questions"] = result.get("questions", [])
|
| 184 |
+
except Exception as e:
|
| 185 |
+
st.error(f"Could not generate test: {e}")
|
| 186 |
+
st.stop()
|
| 187 |
+
|
| 188 |
+
questions = st.session_state["test_questions"]
|
| 189 |
+
answers = st.session_state.get("test_answers", {})
|
| 190 |
+
|
| 191 |
+
with st.form("test_form"):
|
| 192 |
+
for i, q in enumerate(questions):
|
| 193 |
+
st.markdown(f"**Question {i+1}:** {q['question']}")
|
| 194 |
+
ans = st.text_input(f"Your answer:", key=f"test_q_{i}", value=answers.get(str(i), ""))
|
| 195 |
+
answers[str(i)] = ans
|
| 196 |
+
st.divider()
|
| 197 |
+
|
| 198 |
+
submitted = st.form_submit_button("✅ Submit Test", type="primary", use_container_width=True)
|
| 199 |
+
|
| 200 |
+
if submitted:
|
| 201 |
+
st.session_state["test_answers"] = answers
|
| 202 |
+
# Build answers payload
|
| 203 |
+
payload = []
|
| 204 |
+
for i, q in enumerate(questions):
|
| 205 |
+
payload.append({
|
| 206 |
+
"question_index": i,
|
| 207 |
+
"question": q["question"],
|
| 208 |
+
"correct_answer": q["correct_answer"],
|
| 209 |
+
"student_answer": answers.get(str(i), ""),
|
| 210 |
+
})
|
| 211 |
+
|
| 212 |
+
with st.spinner("Evaluating your answers…"):
|
| 213 |
+
try:
|
| 214 |
+
session_id = st.session_state.get("current_session_id", "temp")
|
| 215 |
+
result = api_client.evaluate_test(
|
| 216 |
+
session_id=session_id,
|
| 217 |
+
answers=payload,
|
| 218 |
+
)
|
| 219 |
+
st.session_state["test_result"] = result
|
| 220 |
+
# Check for new badges
|
| 221 |
+
try:
|
| 222 |
+
badge_result = api_client.check_badges(session_id)
|
| 223 |
+
st.session_state["new_badges"] = badge_result.get("newly_awarded", [])
|
| 224 |
+
except Exception:
|
| 225 |
+
st.session_state["new_badges"] = []
|
| 226 |
+
set_stage("result")
|
| 227 |
+
st.rerun()
|
| 228 |
+
except Exception as e:
|
| 229 |
+
st.error(f"Could not evaluate test: {e}")
|
| 230 |
+
|
| 231 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 232 |
+
# STAGE 5: RESULT
|
| 233 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 234 |
+
elif stage == "result":
|
| 235 |
+
result = st.session_state.get("test_result", {})
|
| 236 |
+
score = result.get("score", 0)
|
| 237 |
+
passed = result.get("passed", False)
|
| 238 |
+
encour = result.get("encouragement", "Keep learning!")
|
| 239 |
+
items = result.get("results", [])
|
| 240 |
+
|
| 241 |
+
if passed:
|
| 242 |
+
st.balloons()
|
| 243 |
+
st.success(f"## 🎉 You Passed! Score: {score}%")
|
| 244 |
+
else:
|
| 245 |
+
st.warning(f"## 📚 Score: {score}% — Keep Going!")
|
| 246 |
+
|
| 247 |
+
st.markdown(f"*{encour}*")
|
| 248 |
+
st.divider()
|
| 249 |
+
|
| 250 |
+
# Show question-level feedback
|
| 251 |
+
st.markdown("### 📊 Question Breakdown")
|
| 252 |
+
questions = st.session_state.get("test_questions", [])
|
| 253 |
+
answers = st.session_state.get("test_answers", {})
|
| 254 |
+
for item in items:
|
| 255 |
+
idx = item["question_index"]
|
| 256 |
+
q_text = questions[idx]["question"] if idx < len(questions) else f"Q{idx+1}"
|
| 257 |
+
icon = "✅" if item["is_correct"] else "❌"
|
| 258 |
+
with st.expander(f"{icon} Question {idx+1}: {q_text[:60]}…", expanded=not item["is_correct"]):
|
| 259 |
+
st.write(f"**Your answer:** {answers.get(str(idx), '—')}")
|
| 260 |
+
st.write(f"**Feedback:** {item['feedback']}")
|
| 261 |
+
if not item["is_correct"] and idx < len(questions):
|
| 262 |
+
steps = questions[idx].get("solution_steps", [])
|
| 263 |
+
if steps:
|
| 264 |
+
st.markdown("**Solution steps:**")
|
| 265 |
+
for j, step in enumerate(steps, 1):
|
| 266 |
+
st.markdown(f"{j}. {step}")
|
| 267 |
+
|
| 268 |
+
# New badges
|
| 269 |
+
new_badges = st.session_state.get("new_badges", [])
|
| 270 |
+
if new_badges:
|
| 271 |
+
st.divider()
|
| 272 |
+
st.markdown("### 🏆 New Badges Earned!")
|
| 273 |
+
cols = st.columns(len(new_badges))
|
| 274 |
+
for i, badge in enumerate(new_badges):
|
| 275 |
+
with cols[i]:
|
| 276 |
+
st.markdown(f"## {badge['emoji']}")
|
| 277 |
+
st.markdown(f"**{badge['name']}**")
|
| 278 |
+
st.caption(badge["description"])
|
| 279 |
+
|
| 280 |
+
st.divider()
|
| 281 |
+
col1, col2 = st.columns(2)
|
| 282 |
+
with col1:
|
| 283 |
+
if not passed:
|
| 284 |
+
if st.button("🔄 Retry Test", type="primary", use_container_width=True):
|
| 285 |
+
st.session_state["test_questions"] = []
|
| 286 |
+
st.session_state["test_answers"] = {}
|
| 287 |
+
st.session_state["test_result"] = None
|
| 288 |
+
set_stage("test")
|
| 289 |
+
st.rerun()
|
| 290 |
+
with col2:
|
| 291 |
+
if st.button("🆕 New Question", use_container_width=True):
|
| 292 |
+
reset_tutor()
|
| 293 |
+
st.rerun()
|
streamlit_app/pages/3_Dashboard.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import sys, os
|
| 3 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
| 4 |
+
|
| 5 |
+
from streamlit_app.utils.auth import require_login
|
| 6 |
+
from streamlit_app.utils import api_client
|
| 7 |
+
from streamlit_app.utils.auth import get_supabase, get_user_id
|
| 8 |
+
|
| 9 |
+
st.set_page_config(page_title="MathMind AI — Dashboard", page_icon="📊", layout="centered")
|
| 10 |
+
require_login()
|
| 11 |
+
|
| 12 |
+
email = st.session_state.get("user_email", "")
|
| 13 |
+
user_id = get_user_id()
|
| 14 |
+
|
| 15 |
+
st.title("📊 My Dashboard")
|
| 16 |
+
st.caption(f"Welcome, **{email}**")
|
| 17 |
+
st.divider()
|
| 18 |
+
|
| 19 |
+
# ── Fetch data ─────────────────────────────────────────────────────────────────
|
| 20 |
+
@st.cache_data(ttl=30, show_spinner=False)
|
| 21 |
+
def fetch_dashboard_data(uid: str):
|
| 22 |
+
try:
|
| 23 |
+
sb = get_supabase()
|
| 24 |
+
# Profile (streak)
|
| 25 |
+
profile = sb.table("profiles").select("*").eq("id", uid).single().execute()
|
| 26 |
+
profile_data = profile.data or {}
|
| 27 |
+
|
| 28 |
+
# Recent sessions
|
| 29 |
+
sessions = (
|
| 30 |
+
sb.table("sessions")
|
| 31 |
+
.select("*")
|
| 32 |
+
.eq("user_id", uid)
|
| 33 |
+
.order("created_at", desc=True)
|
| 34 |
+
.limit(10)
|
| 35 |
+
.execute()
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Test results
|
| 39 |
+
results = (
|
| 40 |
+
sb.table("test_results")
|
| 41 |
+
.select("*, sessions(topic)")
|
| 42 |
+
.eq("user_id", uid)
|
| 43 |
+
.order("created_at", desc=True)
|
| 44 |
+
.limit(10)
|
| 45 |
+
.execute()
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
return {
|
| 49 |
+
"profile": profile_data,
|
| 50 |
+
"sessions": sessions.data or [],
|
| 51 |
+
"results": results.data or [],
|
| 52 |
+
}
|
| 53 |
+
except Exception as e:
|
| 54 |
+
return {"profile": {}, "sessions": [], "results": [], "error": str(e)}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@st.cache_data(ttl=30, show_spinner=False)
|
| 58 |
+
def fetch_badges(uid: str):
|
| 59 |
+
try:
|
| 60 |
+
return api_client.get_badges()
|
| 61 |
+
except Exception:
|
| 62 |
+
return []
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
with st.spinner("Loading your progress…"):
|
| 66 |
+
data = fetch_dashboard_data(user_id)
|
| 67 |
+
badges = fetch_badges(user_id)
|
| 68 |
+
|
| 69 |
+
# ── Stats row ──────────────────────────────────────────────────────────────────
|
| 70 |
+
profile = data["profile"]
|
| 71 |
+
sessions = data["sessions"]
|
| 72 |
+
results = data["results"]
|
| 73 |
+
|
| 74 |
+
streak = profile.get("streak_count", 0)
|
| 75 |
+
total_sess = len(sessions)
|
| 76 |
+
passed = sum(1 for r in results if r.get("passed"))
|
| 77 |
+
avg_score = (sum(r.get("score", 0) for r in results) // len(results)) if results else 0
|
| 78 |
+
|
| 79 |
+
col1, col2, col3, col4 = st.columns(4)
|
| 80 |
+
col1.metric("🔥 Streak", f"{streak} days")
|
| 81 |
+
col2.metric("📚 Sessions", total_sess)
|
| 82 |
+
col3.metric("✅ Tests Passed", passed)
|
| 83 |
+
col4.metric("📈 Avg Score", f"{avg_score}%")
|
| 84 |
+
|
| 85 |
+
st.divider()
|
| 86 |
+
|
| 87 |
+
# ── Badges ─────────────────────────────────────────────────────────────────────
|
| 88 |
+
st.markdown("### 🏆 My Badges")
|
| 89 |
+
if badges:
|
| 90 |
+
badge_cols = st.columns(min(len(badges), 5))
|
| 91 |
+
for i, b in enumerate(badges):
|
| 92 |
+
badge_data = b.get("badges") or b
|
| 93 |
+
with badge_cols[i % 5]:
|
| 94 |
+
emoji = badge_data.get("emoji", "🏅")
|
| 95 |
+
name = badge_data.get("name", "Badge")
|
| 96 |
+
desc = badge_data.get("description", "")
|
| 97 |
+
earned_at = b.get("earned_at", "")[:10] if b.get("earned_at") else ""
|
| 98 |
+
st.markdown(
|
| 99 |
+
f"""
|
| 100 |
+
<div style="text-align:center;padding:0.8rem;background:#f0f4ff;
|
| 101 |
+
border-radius:12px;margin-bottom:0.5rem;">
|
| 102 |
+
<div style="font-size:2rem">{emoji}</div>
|
| 103 |
+
<div style="font-weight:600;font-size:0.85rem">{name}</div>
|
| 104 |
+
<div style="font-size:0.75rem;color:#666">{earned_at}</div>
|
| 105 |
+
</div>
|
| 106 |
+
""",
|
| 107 |
+
unsafe_allow_html=True,
|
| 108 |
+
)
|
| 109 |
+
else:
|
| 110 |
+
st.info("No badges yet — complete your first mini-test to earn **🏆 First Try Champion**!")
|
| 111 |
+
|
| 112 |
+
st.divider()
|
| 113 |
+
|
| 114 |
+
# ── Recent test results ────────────────────────────────────────────────────────
|
| 115 |
+
st.markdown("### 📝 Recent Test Results")
|
| 116 |
+
if results:
|
| 117 |
+
for r in results[:5]:
|
| 118 |
+
topic = (r.get("sessions") or {}).get("topic", "Unknown topic") if isinstance(r.get("sessions"), dict) else r.get("topic", "Unknown topic")
|
| 119 |
+
score = r.get("score", 0)
|
| 120 |
+
passed_ = r.get("passed", False)
|
| 121 |
+
date_ = str(r.get("created_at", ""))[:10]
|
| 122 |
+
icon = "✅" if passed_ else "❌"
|
| 123 |
+
st.markdown(
|
| 124 |
+
f"{icon} **{topic[:60]}** — Score: **{score}%** · {date_}"
|
| 125 |
+
)
|
| 126 |
+
else:
|
| 127 |
+
st.info("No test results yet — start a session in the Tutor!")
|
| 128 |
+
|
| 129 |
+
st.divider()
|
| 130 |
+
|
| 131 |
+
# ── Recent sessions ────────��───────────────────────────────────────────────────
|
| 132 |
+
st.markdown("### 💬 Recent Sessions")
|
| 133 |
+
if sessions:
|
| 134 |
+
for s in sessions[:5]:
|
| 135 |
+
topic = s.get("topic", "")[:80]
|
| 136 |
+
grade = s.get("grade", "")
|
| 137 |
+
date_ = str(s.get("created_at", ""))[:10]
|
| 138 |
+
st.markdown(f"📖 **{topic}** · Grade {grade} · {date_}")
|
| 139 |
+
else:
|
| 140 |
+
st.info("No sessions yet — ask your first question in the Tutor!")
|
| 141 |
+
|
| 142 |
+
st.divider()
|
| 143 |
+
st.page_link("pages/2_Tutor.py", label="▶️ Start a New Session", use_container_width=True)
|
streamlit_app/utils/__pycache__/api_client.cpython-313.pyc
ADDED
|
Binary file (4.51 kB). View file
|
|
|