Spaces:
Running
Running
File size: 21,887 Bytes
65ba59e 01e41e5 65ba59e 01e41e5 65ba59e 01e41e5 65ba59e 01e41e5 65ba59e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 | """
MathPulse AI - Practice Center Router
POST /api/practice/generate - Generate MCQ practice session via AI
POST /api/practice/submit - Score session, persist result, update XP
GET /api/practice/stats/{userId} - Aggregated stats + recent sessions
GET /api/practice/history/{userId} - Paginated session history
"""
from __future__ import annotations
import json
import logging
import uuid
from collections import defaultdict
from datetime import datetime, timezone
from typing import Any, Dict, List, Literal, Optional
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field
from services.ai_client import CHAT_MODEL, get_deepseek_client
import firebase_admin
from firebase_admin import firestore as fs
logger = logging.getLogger("mathpulse.practice")
router = APIRouter(prefix="/api/practice", tags=["practice"])
# In-memory fallback if Firestore unavailable
_in_memory_sessions: Dict[str, Dict[str, Any]] = defaultdict(dict)
_in_memory_results: Dict[str, Dict[str, Any]] = defaultdict(dict)
# โโโ Request Models โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class PracticeGenerateRequest(BaseModel):
userId: str
subject: str
competency: str
difficulty: Literal["Practice", "Challenge", "Mastery"] = "Practice"
count: int = Field(default=5, ge=1, le=20)
class AnswerItem(BaseModel):
question_id: str
selected_index: int
class PracticeSubmitRequest(BaseModel):
session_id: str
userId: str
answers: List[AnswerItem]
# โโโ Response Models โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class PracticeQuestion(BaseModel):
id: str
question: str
options: List[str]
correct_index: int
explanation: str
competency: str
difficulty: str
bloomsLevel: str
class PracticeGenerateResponse(BaseModel):
session_id: str
questions: List[PracticeQuestion]
generated_at: str
class PerQuestionFeedback(BaseModel):
question_id: str
selected_index: int
correct_index: int
is_correct: bool
explanation: str
class UpdatedStats(BaseModel):
totalXP: int
quizzesCompleted: int
averageScore: float
class PracticeSubmitResponse(BaseModel):
score_percent: float
correct_count: int
total: int
xp_earned: int
per_question_feedback: List[PerQuestionFeedback]
updated_stats: UpdatedStats
class RecentSession(BaseModel):
session_id: str
score_percent: float
subject: str
difficulty: str
timestamp: str
class CompetencyBreakdownEntry(BaseModel):
total: int
correct: int
percent: float
class PracticeStatsResponse(BaseModel):
quizzesCompleted: int
totalXPEarned: int
averageScore: float
recentSessions: List[RecentSession]
competencyBreakdown: Dict[str, CompetencyBreakdownEntry]
class HistoryItem(BaseModel):
session_id: str
score_percent: float
subject: str
difficulty: str
submitted_at: str
class PracticeHistoryResponse(BaseModel):
page: int
limit: int
hasMore: bool
total: int
items: List[HistoryItem]
# โโโ Helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _get_firestore():
if firebase_admin._apps:
return firebase_admin.firestore.client()
return None
async def _call_deepseek(system_prompt: str, user_message: str, temperature: float = 0.7) -> str:
"""Call DeepSeek with JSON mode for structured output."""
try:
client = get_deepseek_client()
response = client.chat.completions.create(
model=CHAT_MODEL,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_message},
],
temperature=temperature,
response_format={"type": "json_object"},
)
return response.choices[0].message.content or ""
except Exception as e:
logger.error(f"DeepSeek API error: {e}")
raise HTTPException(status_code=500, detail="AI model unavailable. Please try again later.")
def _parse_questions_response(raw: str, count: int) -> List[Dict[str, Any]]:
"""Extract question list from AI JSON response."""
cleaned = raw.strip()
cleaned = cleaned.replace("```json", "").replace("```", "").strip()
try:
data = json.loads(cleaned)
except json.JSONDecodeError:
raise HTTPException(status_code=500, detail="Failed to parse AI response. Please try again.")
questions = None
if isinstance(data, dict):
for key in ("questions", "items", "data", "results", "practice_questions"):
if key in data and isinstance(data[key], list):
questions = data[key]
break
if questions is None and len(data) > 0:
for v in data.values():
if isinstance(v, list) and len(v) > 0 and isinstance(v[0], dict):
questions = v
break
elif isinstance(data, list):
questions = data
if not questions:
raise HTTPException(status_code=500, detail="AI response missing questions. Please try again.")
# Ensure we have exactly `count` questions
questions = questions[:count]
return questions
def _build_question_prompt(subject: str, competency: str, difficulty: str, count: int) -> tuple[str, str]:
system_prompt = (
"You are a math question generator. "
"IMPORTANT: Write EVERYTHING in English. Do NOT use Tagalog, Filipino, or any other language. "
"Generate exactly " + str(count) + " multiple-choice math questions "
"for the subject \"" + subject + "\" focused on competency: \"" + competency + "\". "
"Difficulty level: " + difficulty + ". "
"Return ONLY valid JSON with this exact structure: "
"{ \"questions\": [{ \"id\": \"q1\", \"question\": \"...\", "
"\"options\": [\"A: ...\", \"B: ...\", \"C: ...\", \"D: ...\"], "
"\"correct_index\": 0-3, \"explanation\": \"...\", "
"\"competency\": \"...\", \"difficulty\": \"...\", "
"\"bloomsLevel\": \"Remember|Understand|Apply|Analyze|Evaluate|Create\" }] }. "
"All text must be in English only."
)
user_message = (
f"Generate {count} multiple-choice math questions in English for {subject}, "
f"competency: {competency}, difficulty: {difficulty}. "
f"Write all questions, options, and explanations in English. Return only the JSON."
)
return system_prompt, user_message
def _authenticate(request: Request, userId: str) -> None:
"""Verify the requesting user matches the userId in the payload."""
user = getattr(request.state, "user", None)
if not user:
raise HTTPException(status_code=401, detail="Authentication required")
uid = getattr(user, "uid", None)
if uid != userId:
raise HTTPException(status_code=403, detail="Not authorized for this user")
# โโโ Endpoints โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@router.post("/generate", response_model=PracticeGenerateResponse)
async def generate_practice(request: Request, body: PracticeGenerateRequest):
"""
Generate a practice session with count MCQ questions aligned to
subject, competency, and difficulty.
"""
# Auth check
_authenticate(request, body.userId)
system_prompt, user_message = _build_question_prompt(
body.subject, body.competency, body.difficulty, body.count
)
# Call AI
raw_response = await _call_deepseek(system_prompt, user_message, temperature=0.7)
# Parse questions
raw_questions = _parse_questions_response(raw_response, body.count)
# Normalize into PracticeQuestion list
questions: List[PracticeQuestion] = []
for i, q in enumerate(raw_questions):
q_id = q.get("id") or f"q{i+1}"
correct_idx = int(q.get("correct_index", 0))
questions.append(
PracticeQuestion(
id=q_id,
question=q.get("question", ""),
options=q.get("options", ["", "", "", ""]),
correct_index=correct_idx,
explanation=q.get("explanation", "No explanation available."),
competency=q.get("competency", body.competency),
difficulty=q.get("difficulty", body.difficulty),
bloomsLevel=q.get("bloomsLevel", "Apply"),
)
)
session_id = str(uuid.uuid4())
generated_at = datetime.now(timezone.utc).isoformat()
# Build Firestore document
session_doc = {
"session_id": session_id,
"userId": body.userId,
"subject": body.subject,
"competency": body.competency,
"difficulty": body.difficulty,
"questions": [q.model_dump() for q in questions],
"generated_at": generated_at,
}
# Store in Firestore (fallback to in-memory)
db = _get_firestore()
if db:
try:
db.collection("practice_sessions").document(session_id).set(session_doc)
except Exception as e:
logger.warning("Firestore write failed for session %s: %s", session_id, e)
_in_memory_sessions[session_id] = session_doc
else:
_in_memory_sessions[session_id] = session_doc
return PracticeGenerateResponse(
session_id=session_id,
questions=questions,
generated_at=generated_at,
)
@router.post("/submit", response_model=PracticeSubmitResponse)
async def submit_practice(request: Request, body: PracticeSubmitRequest):
"""
Score a practice session, compute XP, persist result, update user stats.
XP formula: 10 XP per correct answer + 50 XP bonus if score >= 80%.
"""
_authenticate(request, body.userId)
session_id = body.session_id
userId = body.userId
# Retrieve session
db = _get_firestore()
questions_data: List[Dict[str, Any]] = []
session_subject = ""
session_difficulty = ""
session_competency = ""
if db:
try:
doc = db.collection("practice_sessions").document(session_id).get()
if doc.exists:
data = doc.to_dict()
questions_data = data.get("questions", [])
session_subject = data.get("subject", "")
session_difficulty = data.get("difficulty", "")
session_competency = data.get("competency", "")
except Exception as e:
logger.warning("Firestore read failed for session %s: %s", session_id, e)
else:
sess = _in_memory_sessions.get(session_id, {})
questions_data = sess.get("questions", [])
session_subject = sess.get("subject", "")
session_difficulty = sess.get("difficulty", "")
session_competency = sess.get("competency", "")
if not questions_data:
raise HTTPException(status_code=404, detail="Session not found or expired.")
# Build question lookup
q_lookup: Dict[str, Dict[str, Any]] = {q["id"]: q for q in questions_data}
# Score
correct_count = 0
total = len(body.answers)
per_question_feedback: List[PerQuestionFeedback] = []
for answer in body.answers:
q = q_lookup.get(answer.question_id, {})
correct_idx = int(q.get("correct_index", -1))
is_correct = answer.selected_index == correct_idx
if is_correct:
correct_count += 1
per_question_feedback.append(
PerQuestionFeedback(
question_id=answer.question_id,
selected_index=answer.selected_index,
correct_index=correct_idx,
is_correct=is_correct,
explanation=q.get("explanation", ""),
)
)
score_percent = round((correct_count / total) * 100, 1) if total > 0 else 0.0
xp_earned = correct_count * 10 + (50 if score_percent >= 80 else 0)
submitted_at = datetime.now(timezone.utc).isoformat()
# Build result doc
result_doc = {
"session_id": session_id,
"userId": userId,
"score_percent": score_percent,
"correct_count": correct_count,
"total": total,
"xp_earned": xp_earned,
"subject": session_subject,
"competency": session_competency,
"difficulty": session_difficulty,
"answers": [a.model_dump() for a in body.answers],
"per_question_feedback": [f.model_dump() for f in per_question_feedback],
"submitted_at": submitted_at,
}
# Store result
if db:
try:
db.collection("practice_results").document(userId).collection("sessions").document(session_id).set(result_doc)
except Exception as e:
logger.warning("Firestore write failed for result %s: %s", session_id, e)
_in_memory_results[f"{userId}:{session_id}"] = result_doc
else:
_in_memory_results[f"{userId}:{session_id}"] = result_doc
# Update user stats atomically
if db:
try:
user_ref = db.collection("users").document(userId)
user_doc = user_ref.get()
if user_doc.exists:
current = user_doc.to_dict()
current_quizzes = current.get("quizzesCompleted", 0) or 0
current_avg = current.get("averageScore", 0.0) or 0.0
new_quizzes = current_quizzes + 1
new_avg = round((current_avg * current_quizzes + score_percent) / new_quizzes, 1)
user_ref.update({
"totalXP": fs.Increment(xp_earned),
"quizzesCompleted": fs.Increment(1),
"averageScore": new_avg,
})
updated_total_xp = (current.get("totalXP", 0) or 0) + xp_earned
updated_stats = UpdatedStats(
totalXP=updated_total_xp,
quizzesCompleted=new_quizzes,
averageScore=new_avg,
)
else:
updated_stats = UpdatedStats(
totalXP=xp_earned,
quizzesCompleted=1,
averageScore=score_percent,
)
except Exception as e:
logger.warning("User stats update failed: %s", e)
updated_stats = UpdatedStats(
totalXP=xp_earned,
quizzesCompleted=1,
averageScore=score_percent,
)
else:
updated_stats = UpdatedStats(
totalXP=xp_earned,
quizzesCompleted=1,
averageScore=score_percent,
)
return PracticeSubmitResponse(
score_percent=score_percent,
correct_count=correct_count,
total=total,
xp_earned=xp_earned,
per_question_feedback=per_question_feedback,
updated_stats=updated_stats,
)
@router.get("/stats/{userId}", response_model=PracticeStatsResponse)
async def get_practice_stats(request: Request, userId: str):
"""
Return aggregated stats for a user:
quizzesCompleted, totalXPEarned, averageScore, recentSessions (last 10),
competencyBreakdown.
"""
_authenticate(request, userId)
db = _get_firestore()
# Read user doc
total_xp = 0
quizzes_completed = 0
average_score = 0.0
if db:
try:
user_doc = db.collection("users").document(userId).get()
if user_doc.exists:
d = user_doc.to_dict()
total_xp = d.get("totalXP", 0) or 0
quizzes_completed = d.get("quizzesCompleted", 0) or 0
average_score = d.get("averageScore", 0.0) or 0.0
except Exception as e:
logger.warning("Error reading user stats for %s: %s", userId, e)
else:
# Fallback: sum from in-memory results
for key, val in _in_memory_results.items():
if key.startswith(f"{userId}:"):
quizzes_completed += 1
total_xp += val.get("xp_earned", 0)
# Read recent sessions from practice_results
recent_sessions: List[RecentSession] = []
competency_breakdown: Dict[str, Dict[str, Any]] = defaultdict(lambda: {"total": 0, "correct": 0})
if db:
try:
results_ref = db.collection("practice_results").document(userId).collection("sessions")
all_results = results_ref.order_by("submitted_at", direction=fs.Query.DESCENDING).limit(50).get()
for doc in all_results:
d = doc.to_dict()
score = d.get("score_percent", 0)
total = d.get("total", 1)
correct = d.get("correct_count", 0)
submitted = d.get("submitted_at", "")
subject = d.get("subject", "")
difficulty = d.get("difficulty", "")
competency = d.get("competency", "")
# Recent sessions (last 10)
if len(recent_sessions) < 10:
recent_sessions.append(RecentSession(
session_id=d.get("session_id", ""),
score_percent=score,
subject=subject,
difficulty=difficulty,
timestamp=submitted,
))
# Competency breakdown
if competency:
competency_breakdown[competency]["total"] += total
competency_breakdown[competency]["correct"] += correct
except Exception as e:
logger.warning("Error reading practice results for %s: %s", userId, e)
else:
# Fallback from in-memory
for key, val in _in_memory_results.items():
if key.startswith(f"{userId}:"):
if len(recent_sessions) < 10:
recent_sessions.append(RecentSession(
session_id=val.get("session_id", ""),
score_percent=val.get("score_percent", 0),
subject=val.get("subject", ""),
difficulty=val.get("difficulty", ""),
timestamp=val.get("submitted_at", ""),
))
# Compute competency percentages
competency_result: Dict[str, CompetencyBreakdownEntry] = {}
for comp, vals in competency_breakdown.items():
total_q = vals["total"]
correct_q = vals["correct"]
pct = round((correct_q / total_q) * 100, 1) if total_q > 0 else 0.0
competency_result[comp] = CompetencyBreakdownEntry(
total=total_q,
correct=correct_q,
percent=pct,
)
return PracticeStatsResponse(
quizzesCompleted=quizzes_completed,
totalXPEarned=total_xp,
averageScore=average_score,
recentSessions=recent_sessions,
competencyBreakdown=competency_result,
)
@router.get("/history/{userId}", response_model=PracticeHistoryResponse)
async def get_practice_history(
request: Request,
userId: str,
page: int = 1,
limit: int = 10,
):
"""
Return paginated practice history for a user, sorted by submitted_at DESC.
"""
_authenticate(request, userId)
page = max(1, page)
limit = max(1, min(50, limit))
offset = (page - 1) * limit
db = _get_firestore()
items: List[HistoryItem] = []
total = 0
has_more = False
if db:
try:
results_ref = db.collection("practice_results").document(userId).collection("sessions")
# Get total count
all_docs = results_ref.order_by("submitted_at", direction=fs.Query.DESCENDING).get()
total = len(all_docs)
# Get page
page_docs = (
results_ref
.order_by("submitted_at", direction=fs.Query.DESCENDING)
.offset(offset)
.limit(limit)
.get()
)
for doc in page_docs:
d = doc.to_dict()
items.append(HistoryItem(
session_id=d.get("session_id", ""),
score_percent=d.get("score_percent", 0),
subject=d.get("subject", ""),
difficulty=d.get("difficulty", ""),
submitted_at=d.get("submitted_at", ""),
))
has_more = offset + len(items) < total
except Exception as e:
logger.warning("Error reading practice history for %s: %s", userId, e)
else:
# Fallback: filter in-memory
all_results = [
v for k, v in _in_memory_results.items() if k.startswith(f"{userId}:")
]
all_results.sort(key=lambda x: x.get("submitted_at", ""), reverse=True)
total = len(all_results)
paginated = all_results[offset:offset + limit]
for v in paginated:
items.append(HistoryItem(
session_id=v.get("session_id", ""),
score_percent=v.get("score_percent", 0),
subject=v.get("subject", ""),
difficulty=v.get("difficulty", ""),
submitted_at=v.get("submitted_at", ""),
))
has_more = offset + len(items) < total
return PracticeHistoryResponse(
page=page,
limit=limit,
hasMore=has_more,
total=total,
items=items,
) |