Spaces:
Sleeping
Sleeping
github-actions[bot] commited on
Commit ·
d578716
1
Parent(s): 2d81900
deploy: backend from 2216019
Browse files- main.py +27 -398
- rag/curriculum_rag.py +3 -1
- routes/diagnostic.py +35 -6
- routes/pipeline_routes.py +9 -7
- routes/teacher_materials.py +14 -5
- tests/conftest.py +19 -8
- tests/test_audit_remediation.py +148 -0
main.py
CHANGED
|
@@ -463,6 +463,22 @@ ROLE_POLICIES: Dict[str, Set[str]] = {
|
|
| 463 |
"/api/class-records/upload": TEACHER_OR_ADMIN,
|
| 464 |
}
|
| 465 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
if not os.getenv("DEEPSEEK_API_KEY"):
|
| 467 |
logger.warning(
|
| 468 |
"DEEPSEEK_API_KEY is not set. AI features will fail. "
|
|
@@ -592,6 +608,16 @@ FIRESTORE_SERVER_TIMESTAMP: Any = getattr(cast(Any, firebase_firestore), "SERVER
|
|
| 592 |
FIRESTORE_QUERY_DESCENDING: Any = getattr(getattr(cast(Any, firebase_firestore), "Query", None), "DESCENDING", "DESCENDING")
|
| 593 |
|
| 594 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 595 |
def _snapshot_to_dict(snapshot: Any) -> Dict[str, Any]:
|
| 596 |
data = snapshot.to_dict() if hasattr(snapshot, "to_dict") else {}
|
| 597 |
return data if isinstance(data, dict) else {}
|
|
@@ -1090,7 +1116,7 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
|
| 1090 |
claims=decoded,
|
| 1091 |
)
|
| 1092 |
|
| 1093 |
-
required_roles =
|
| 1094 |
if required_roles and role not in required_roles:
|
| 1095 |
return JSONResponse(status_code=403, content={"detail": "Forbidden for this role"})
|
| 1096 |
|
|
@@ -9191,69 +9217,6 @@ class ImportGroundedAccessAuditResponse(BaseModel):
|
|
| 9191 |
warnings: List[str]
|
| 9192 |
|
| 9193 |
|
| 9194 |
-
# ─── Diagnostic Test Models ────────────────────────────────────
|
| 9195 |
-
|
| 9196 |
-
class DiagnosticGenerateRequest(BaseModel):
|
| 9197 |
-
strand: str = Field(..., description="Student strand: ABM, STEM, HUMSS, GAS, TVL")
|
| 9198 |
-
gradeLevel: str = Field(..., description="Grade level: Grade 11 or Grade 12")
|
| 9199 |
-
numQuestions: int = Field(default=15, ge=5, le=30, description="Number of questions to generate")
|
| 9200 |
-
|
| 9201 |
-
|
| 9202 |
-
class DiagnosticQuestion(BaseModel):
|
| 9203 |
-
question_id: str
|
| 9204 |
-
competency_code: str
|
| 9205 |
-
domain: str
|
| 9206 |
-
topic: str
|
| 9207 |
-
difficulty: str
|
| 9208 |
-
bloom_level: str
|
| 9209 |
-
question_text: str
|
| 9210 |
-
options: Dict[str, str]
|
| 9211 |
-
correct_answer: str
|
| 9212 |
-
solution_hint: str
|
| 9213 |
-
curriculum_reference: str
|
| 9214 |
-
|
| 9215 |
-
|
| 9216 |
-
class DiagnosticGenerateResponse(BaseModel):
|
| 9217 |
-
questions: List[DiagnosticQuestion]
|
| 9218 |
-
test_id: str
|
| 9219 |
-
metadata: Dict[str, Any]
|
| 9220 |
-
|
| 9221 |
-
|
| 9222 |
-
class DiagnosticSubmitRequest(BaseModel):
|
| 9223 |
-
user_id: str
|
| 9224 |
-
test_id: str
|
| 9225 |
-
strand: str
|
| 9226 |
-
grade_level: str
|
| 9227 |
-
responses: List[Dict[str, Any]]
|
| 9228 |
-
|
| 9229 |
-
|
| 9230 |
-
class DiagnosticResult(BaseModel):
|
| 9231 |
-
user_id: str
|
| 9232 |
-
test_id: str
|
| 9233 |
-
taken_at: datetime
|
| 9234 |
-
strand: str
|
| 9235 |
-
grade_level: str
|
| 9236 |
-
total_items: int
|
| 9237 |
-
total_score: int
|
| 9238 |
-
percentage_score: float
|
| 9239 |
-
responses: List[Dict[str, Any]]
|
| 9240 |
-
domain_scores: Dict[str, Dict[str, Any]]
|
| 9241 |
-
risk_profile: Dict[str, Any]
|
| 9242 |
-
|
| 9243 |
-
|
| 9244 |
-
class DiagnosticSubmitResponse(BaseModel):
|
| 9245 |
-
success: bool
|
| 9246 |
-
result: DiagnosticResult
|
| 9247 |
-
risk_profile: Dict[str, Any]
|
| 9248 |
-
domain_scores: Dict[str, Dict[str, Any]]
|
| 9249 |
-
redirect_to: str
|
| 9250 |
-
|
| 9251 |
-
|
| 9252 |
-
class DiagnosticResultsResponse(BaseModel):
|
| 9253 |
-
success: bool
|
| 9254 |
-
results: List[DiagnosticResult]
|
| 9255 |
-
|
| 9256 |
-
|
| 9257 |
# ─── DepEd Curriculum Competency Domains ────────────────────────────
|
| 9258 |
|
| 9259 |
DEPD_ED_COMPETENCY_DOMAINS: Dict[str, Dict[str, List[str]]] = {
|
|
@@ -13237,340 +13200,6 @@ async def automation_content_updated(payload: ContentUpdatePayload):
|
|
| 13237 |
raise HTTPException(status_code=500, detail=f"Automation error: {str(e)}")
|
| 13238 |
|
| 13239 |
|
| 13240 |
-
# ─── Diagnostic Test Endpoints ─────────────────────────────────
|
| 13241 |
-
|
| 13242 |
-
async def _generate_diagnostic_questions(
|
| 13243 |
-
strand: str,
|
| 13244 |
-
grade_level: str,
|
| 13245 |
-
num_questions: int,
|
| 13246 |
-
) -> List[DiagnosticQuestion]:
|
| 13247 |
-
"""Generate diagnostic test questions using LLM based on DepEd curriculum with RAG."""
|
| 13248 |
-
|
| 13249 |
-
topics = DEPD_ED_COMPETENCY_DOMAINS.get(strand, {}).get(grade_level, [])
|
| 13250 |
-
if not topics:
|
| 13251 |
-
topics = DEPD_ED_COMPETENCY_DOMAINS.get("STEM", {}).get("Grade 11", [])
|
| 13252 |
-
|
| 13253 |
-
topic_list = "\n".join([f"- {t}" for t in topics[:10]])
|
| 13254 |
-
|
| 13255 |
-
curriculum_chunks = retrieve_curriculum_context(
|
| 13256 |
-
query=f"{topics[0] if topics else strand} examples problems {grade_level}",
|
| 13257 |
-
subject="General Mathematics",
|
| 13258 |
-
top_k=3,
|
| 13259 |
-
)
|
| 13260 |
-
|
| 13261 |
-
curriculum_context = ""
|
| 13262 |
-
for chunk in curriculum_chunks:
|
| 13263 |
-
source = chunk.get("source_file", "unknown")
|
| 13264 |
-
content = chunk.get("content", "")[:500]
|
| 13265 |
-
curriculum_context += f"[Source: {source}]\n{content}\n\n---\n\n"
|
| 13266 |
-
|
| 13267 |
-
rag_instruction = ""
|
| 13268 |
-
if curriculum_context:
|
| 13269 |
-
rag_instruction = f"""CURRICULUM REFERENCE:
|
| 13270 |
-
{curriculum_context}
|
| 13271 |
-
|
| 13272 |
-
Use these examples as reference. Do not copy directly."""
|
| 13273 |
-
|
| 13274 |
-
prompt = f"""You are MathPulse AI's Diagnostic Test Generator. Generate {num_questions} multiple-choice questions for a Filipino Senior High School student (Strand: {strand}, Grade: {grade_level}).
|
| 13275 |
-
|
| 13276 |
-
Based on these DepEd SHS curriculum competencies:
|
| 13277 |
-
{topic_list}
|
| 13278 |
-
|
| 13279 |
-
{rag_instruction}
|
| 13280 |
-
|
| 13281 |
-
Generate questions in this strict JSON format (no other text):
|
| 13282 |
-
[
|
| 13283 |
-
{{
|
| 13284 |
-
"question_id": "DX-<generate uuid>",
|
| 13285 |
-
"competency_code": "TOPIC-SUBTOPIC-01",
|
| 13286 |
-
"domain": "Domain Name",
|
| 13287 |
-
"topic": "Specific Topic",
|
| 13288 |
-
"difficulty": "easy|medium|hard",
|
| 13289 |
-
"bloom_level": "remembering|understanding|applying|analyzing",
|
| 13290 |
-
"question_text": "Question text in Filipino context",
|
| 13291 |
-
"options": {{"A": "...", "B": "...", "C": "...", "D": "..."}},
|
| 13292 |
-
"correct_answer": "A|B|C|D",
|
| 13293 |
-
"solution_hint": "Brief solution hint (1-2 sentences)",
|
| 13294 |
-
"curriculum_reference": "DepEd SHS [Strand] Q[X] - [Topic]"
|
| 13295 |
-
}}
|
| 13296 |
-
]
|
| 13297 |
-
|
| 13298 |
-
Distribution: 40% easy, 40% medium, 20% hard.
|
| 13299 |
-
Use Filipino real-life context (peso amounts, SSS/PhilHealth/BIR, local scenarios).
|
| 13300 |
-
Distractors must be plausible but clearly wrong.
|
| 13301 |
-
Return ONLY the JSON array, no other text."""
|
| 13302 |
-
|
| 13303 |
-
try:
|
| 13304 |
-
messages = [
|
| 13305 |
-
{"role": "system", "content": "You are a math question generator. Return ONLY valid JSON."},
|
| 13306 |
-
{"role": "user", "content": prompt},
|
| 13307 |
-
]
|
| 13308 |
-
response = await call_hf_chat_async(messages, max_tokens=4096, temperature=0.3, task_type="quiz")
|
| 13309 |
-
|
| 13310 |
-
import re
|
| 13311 |
-
json_match = re.search(r'\[.*\]', response, re.DOTALL)
|
| 13312 |
-
if json_match:
|
| 13313 |
-
questions_data = json.loads(json_match.group())
|
| 13314 |
-
else:
|
| 13315 |
-
questions_data = json.loads(response)
|
| 13316 |
-
|
| 13317 |
-
questions = []
|
| 13318 |
-
for q in questions_data[:num_questions]:
|
| 13319 |
-
questions.append(DiagnosticQuestion(**q))
|
| 13320 |
-
|
| 13321 |
-
return questions
|
| 13322 |
-
except Exception as e:
|
| 13323 |
-
logger.error(f"Diagnostic question generation error: {e}")
|
| 13324 |
-
raise
|
| 13325 |
-
|
| 13326 |
-
|
| 13327 |
-
async def _analyze_diagnostic_risk(
|
| 13328 |
-
responses: List[Dict[str, Any]],
|
| 13329 |
-
total_items: int,
|
| 13330 |
-
total_score: int,
|
| 13331 |
-
) -> Dict[str, Any]:
|
| 13332 |
-
"""Analyze student performance and generate risk profile."""
|
| 13333 |
-
domain_scores: Dict[str, Dict[str, Any]] = {}
|
| 13334 |
-
domain_responses: Dict[str, List[Dict[str, Any]]] = {}
|
| 13335 |
-
|
| 13336 |
-
for resp in responses:
|
| 13337 |
-
domain = resp.get("domain", "Unknown")
|
| 13338 |
-
if domain not in domain_responses:
|
| 13339 |
-
domain_responses[domain] = []
|
| 13340 |
-
domain_responses[domain].append(resp)
|
| 13341 |
-
|
| 13342 |
-
for domain, resp_list in domain_responses.items():
|
| 13343 |
-
correct = sum(1 for r in resp_list if r.get("is_correct", False))
|
| 13344 |
-
total = len(resp_list)
|
| 13345 |
-
pct = (correct / total * 100) if total > 0 else 0
|
| 13346 |
-
|
| 13347 |
-
mastery = "mastered" if pct >= 80 else "developing" if pct >= 60 else "beginning"
|
| 13348 |
-
domain_scores[domain] = {
|
| 13349 |
-
"correct": correct,
|
| 13350 |
-
"total": total,
|
| 13351 |
-
"percentage": round(pct, 1),
|
| 13352 |
-
"mastery_level": mastery,
|
| 13353 |
-
}
|
| 13354 |
-
|
| 13355 |
-
weak_domains = [
|
| 13356 |
-
d for d, data in domain_scores.items()
|
| 13357 |
-
if data["percentage"] < 60
|
| 13358 |
-
]
|
| 13359 |
-
|
| 13360 |
-
critical_gaps = []
|
| 13361 |
-
competency_attempts: Dict[str, List[bool]] = {}
|
| 13362 |
-
for resp in responses:
|
| 13363 |
-
comp_code = resp.get("competency_code", "")
|
| 13364 |
-
if comp_code not in competency_attempts:
|
| 13365 |
-
competency_attempts[comp_code] = []
|
| 13366 |
-
competency_attempts[comp_code].append(resp.get("is_correct", False))
|
| 13367 |
-
|
| 13368 |
-
for comp_code, results in competency_attempts.items():
|
| 13369 |
-
correct_count = sum(1 for r in results if r)
|
| 13370 |
-
if len(results) >= 2 and correct_count == 0:
|
| 13371 |
-
critical_gaps.append(comp_code)
|
| 13372 |
-
|
| 13373 |
-
overall_pct = (total_score / total_items * 100) if total_items > 0 else 0
|
| 13374 |
-
|
| 13375 |
-
if overall_pct >= 75 and len(critical_gaps) == 0:
|
| 13376 |
-
overall_risk = "low"
|
| 13377 |
-
elif overall_pct >= 55 or len(critical_gaps) <= 2:
|
| 13378 |
-
overall_risk = "moderate"
|
| 13379 |
-
elif overall_pct >= 40 or len(critical_gaps) <= 4:
|
| 13380 |
-
overall_risk = "high"
|
| 13381 |
-
else:
|
| 13382 |
-
overall_risk = "critical"
|
| 13383 |
-
|
| 13384 |
-
intervention_messages = {
|
| 13385 |
-
"low": "Great job! You have a solid foundation. Keep practicing to maintain your skills!",
|
| 13386 |
-
"moderate": "You're making good progress. Focus on the topics where you need more practice.",
|
| 13387 |
-
"high": "Don't worry! With focused practice on your weak areas, you'll improve quickly.",
|
| 13388 |
-
"critical": "Let's work on this together. Start with the basics and build up your confidence.",
|
| 13389 |
-
}
|
| 13390 |
-
|
| 13391 |
-
suggested_path = weak_domains[:3] if weak_domains else list(domain_scores.keys())[:3]
|
| 13392 |
-
|
| 13393 |
-
return {
|
| 13394 |
-
"overall_risk": overall_risk,
|
| 13395 |
-
"overall_score_percent": round(overall_pct, 1),
|
| 13396 |
-
"domain_scores": domain_scores,
|
| 13397 |
-
"weak_domains": weak_domains,
|
| 13398 |
-
"critical_gaps": critical_gaps,
|
| 13399 |
-
"recommended_intervention": intervention_messages[overall_risk],
|
| 13400 |
-
"suggested_learning_path": suggested_path,
|
| 13401 |
-
}
|
| 13402 |
-
|
| 13403 |
-
|
| 13404 |
-
def _save_diagnostic_to_firestore(result: DiagnosticResult) -> bool:
|
| 13405 |
-
"""Save diagnostic result to Firestore."""
|
| 13406 |
-
if not HAS_FIREBASE_ADMIN or not firebase_firestore:
|
| 13407 |
-
logger.warning("Firebase not available for diagnostic save")
|
| 13408 |
-
return False
|
| 13409 |
-
|
| 13410 |
-
try:
|
| 13411 |
-
db = firebase_firestore.client()
|
| 13412 |
-
doc_ref = db.collection("diagnosticResults").document(result.user_id).collection("attempts").document(result.test_id)
|
| 13413 |
-
doc_ref.set({
|
| 13414 |
-
"testId": result.test_id,
|
| 13415 |
-
"takenAt": result.taken_at,
|
| 13416 |
-
"strand": result.strand,
|
| 13417 |
-
"gradeLevel": result.grade_level,
|
| 13418 |
-
"totalItems": result.total_items,
|
| 13419 |
-
"totalScore": result.total_score,
|
| 13420 |
-
"percentageScore": result.percentage_score,
|
| 13421 |
-
"responses": result.responses,
|
| 13422 |
-
"domainScores": result.domain_scores,
|
| 13423 |
-
"riskProfile": result.risk_profile,
|
| 13424 |
-
})
|
| 13425 |
-
|
| 13426 |
-
latest_ref = db.collection("users").document(result.user_id)
|
| 13427 |
-
latest_ref.set({"latestDiagnosticTestId": result.test_id}, merge=True)
|
| 13428 |
-
|
| 13429 |
-
return True
|
| 13430 |
-
except Exception as e:
|
| 13431 |
-
logger.error(f"Firestore diagnostic save error: {e}")
|
| 13432 |
-
return False
|
| 13433 |
-
|
| 13434 |
-
|
| 13435 |
-
@app.post("/api/diagnostic/generate", response_model=DiagnosticGenerateResponse)
|
| 13436 |
-
async def generate_diagnostic_test(request: DiagnosticGenerateRequest):
|
| 13437 |
-
"""
|
| 13438 |
-
Generate a personalized diagnostic assessment for a student.
|
| 13439 |
-
Questions are based on DepEd Strengthened SHS Curriculum.
|
| 13440 |
-
"""
|
| 13441 |
-
try:
|
| 13442 |
-
test_id = f"DX-{uuid.uuid4().hex[:12]}"
|
| 13443 |
-
|
| 13444 |
-
questions = await _generate_diagnostic_questions(
|
| 13445 |
-
request.strand,
|
| 13446 |
-
request.gradeLevel,
|
| 13447 |
-
request.numQuestions,
|
| 13448 |
-
)
|
| 13449 |
-
|
| 13450 |
-
stripped_questions = []
|
| 13451 |
-
for q in questions:
|
| 13452 |
-
stripped_questions.append(DiagnosticQuestion(
|
| 13453 |
-
question_id=q.question_id,
|
| 13454 |
-
competency_code=q.competency_code,
|
| 13455 |
-
domain=q.domain,
|
| 13456 |
-
topic=q.topic,
|
| 13457 |
-
difficulty=q.difficulty,
|
| 13458 |
-
bloom_level=q.bloom_level,
|
| 13459 |
-
question_text=q.question_text,
|
| 13460 |
-
options=q.options,
|
| 13461 |
-
correct_answer=q.correct_answer,
|
| 13462 |
-
solution_hint="",
|
| 13463 |
-
curriculum_reference=q.curriculum_reference,
|
| 13464 |
-
))
|
| 13465 |
-
|
| 13466 |
-
metadata = {
|
| 13467 |
-
"strand": request.strand,
|
| 13468 |
-
"grade_level": request.gradeLevel,
|
| 13469 |
-
"num_questions": len(questions),
|
| 13470 |
-
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 13471 |
-
}
|
| 13472 |
-
|
| 13473 |
-
return DiagnosticGenerateResponse(
|
| 13474 |
-
questions=stripped_questions,
|
| 13475 |
-
test_id=test_id,
|
| 13476 |
-
metadata=metadata,
|
| 13477 |
-
)
|
| 13478 |
-
except Exception as e:
|
| 13479 |
-
logger.error(f"Diagnostic generation error: {e}\n{traceback.format_exc()}")
|
| 13480 |
-
raise HTTPException(status_code=500, detail=f"Diagnostic generation error: {str(e)}")
|
| 13481 |
-
|
| 13482 |
-
|
| 13483 |
-
@app.post("/api/diagnostic/submit", response_model=DiagnosticSubmitResponse)
|
| 13484 |
-
async def submit_diagnostic_test(request: DiagnosticSubmitRequest):
|
| 13485 |
-
"""
|
| 13486 |
-
Submit diagnostic test responses, score them, and generate risk profile.
|
| 13487 |
-
Results are saved to Firestore for use by other subsystems.
|
| 13488 |
-
"""
|
| 13489 |
-
try:
|
| 13490 |
-
total_items = len(request.responses)
|
| 13491 |
-
total_score = 0
|
| 13492 |
-
scored_responses = []
|
| 13493 |
-
|
| 13494 |
-
for resp in request.responses:
|
| 13495 |
-
is_correct = resp.get("student_answer", "") == resp.get("correct_answer", "")
|
| 13496 |
-
if is_correct:
|
| 13497 |
-
total_score += 1
|
| 13498 |
-
scored_responses.append({
|
| 13499 |
-
"question_id": resp.get("question_id"),
|
| 13500 |
-
"competency_code": resp.get("competency_code"),
|
| 13501 |
-
"domain": resp.get("domain"),
|
| 13502 |
-
"topic": resp.get("topic"),
|
| 13503 |
-
"difficulty": resp.get("difficulty"),
|
| 13504 |
-
"bloom_level": resp.get("bloom_level"),
|
| 13505 |
-
"student_answer": resp.get("student_answer"),
|
| 13506 |
-
"correct_answer": resp.get("correct_answer"),
|
| 13507 |
-
"is_correct": is_correct,
|
| 13508 |
-
"time_spent_seconds": resp.get("time_spent_seconds", 0),
|
| 13509 |
-
})
|
| 13510 |
-
|
| 13511 |
-
risk_profile = await _analyze_diagnostic_risk(
|
| 13512 |
-
scored_responses,
|
| 13513 |
-
total_items,
|
| 13514 |
-
total_score,
|
| 13515 |
-
)
|
| 13516 |
-
|
| 13517 |
-
domain_scores = risk_profile.get("domain_scores", {})
|
| 13518 |
-
|
| 13519 |
-
result = DiagnosticResult(
|
| 13520 |
-
user_id=request.user_id,
|
| 13521 |
-
test_id=request.test_id,
|
| 13522 |
-
taken_at=datetime.now(timezone.utc),
|
| 13523 |
-
strand=request.strand,
|
| 13524 |
-
grade_level=request.grade_level,
|
| 13525 |
-
total_items=total_items,
|
| 13526 |
-
total_score=total_score,
|
| 13527 |
-
percentage_score=round(total_score / total_items * 100, 1),
|
| 13528 |
-
responses=scored_responses,
|
| 13529 |
-
domain_scores=domain_scores,
|
| 13530 |
-
risk_profile=risk_profile,
|
| 13531 |
-
)
|
| 13532 |
-
|
| 13533 |
-
_save_diagnostic_to_firestore(result)
|
| 13534 |
-
|
| 13535 |
-
return DiagnosticSubmitResponse(
|
| 13536 |
-
success=True,
|
| 13537 |
-
result=result,
|
| 13538 |
-
risk_profile=risk_profile,
|
| 13539 |
-
domain_scores=domain_scores,
|
| 13540 |
-
redirect_to="/dashboard",
|
| 13541 |
-
)
|
| 13542 |
-
except Exception as e:
|
| 13543 |
-
logger.error(f"Diagnostic submit error: {e}\n{traceback.format_exc()}")
|
| 13544 |
-
raise HTTPException(status_code=500, detail=f"Diagnostic submit error: {str(e)}")
|
| 13545 |
-
|
| 13546 |
-
|
| 13547 |
-
@app.get("/api/diagnostic/results/{user_id}", response_model=DiagnosticResultsResponse)
|
| 13548 |
-
async def get_diagnostic_results(user_id: str):
|
| 13549 |
-
"""
|
| 13550 |
-
Fetch diagnostic test results for a student.
|
| 13551 |
-
Returns all attempts with risk profiles.
|
| 13552 |
-
"""
|
| 13553 |
-
if not HAS_FIREBASE_ADMIN or not firebase_firestore:
|
| 13554 |
-
return DiagnosticResultsResponse(success=False, results=[])
|
| 13555 |
-
|
| 13556 |
-
try:
|
| 13557 |
-
db = firebase_firestore.client()
|
| 13558 |
-
docs = db.collection("diagnosticResults").document(user_id).collection("attempts").stream()
|
| 13559 |
-
|
| 13560 |
-
results = []
|
| 13561 |
-
for doc in docs:
|
| 13562 |
-
data = doc.to_dict()
|
| 13563 |
-
if data:
|
| 13564 |
-
results.append(DiagnosticResult(**data))
|
| 13565 |
-
|
| 13566 |
-
results.sort(key=lambda x: x.taken_at, reverse=True)
|
| 13567 |
-
|
| 13568 |
-
return DiagnosticResultsResponse(success=True, results=results)
|
| 13569 |
-
except Exception as e:
|
| 13570 |
-
logger.error(f"Diagnostic results fetch error: {e}")
|
| 13571 |
-
return DiagnosticResultsResponse(success=False, results=[])
|
| 13572 |
-
|
| 13573 |
-
|
| 13574 |
# ─── DepEd Topic Registry for Lessons/Quizzes ─────────────────────────────
|
| 13575 |
|
| 13576 |
DEPD_TOPIC_REGISTRY: Dict[str, Dict[str, str]] = {
|
|
|
|
| 463 |
"/api/class-records/upload": TEACHER_OR_ADMIN,
|
| 464 |
}
|
| 465 |
|
| 466 |
+
_COMPILED_ROLE_PATTERNS: List[Tuple[re.Pattern, Set[str]]] = []
|
| 467 |
+
for _pattern_str, _roles in ROLE_POLICIES.items():
|
| 468 |
+
if "{" in _pattern_str:
|
| 469 |
+
_regex_str = "^" + re.sub(r"\{[a-zA-Z0-9_]+\}", r"[^/]+", _pattern_str) + "$"
|
| 470 |
+
_COMPILED_ROLE_PATTERNS.append((re.compile(_regex_str), _roles))
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def resolve_required_roles(path: str) -> Optional[Set[str]]:
|
| 474 |
+
"""Resolves required roles for a path using exact lookup or compiled pattern matching."""
|
| 475 |
+
if path in ROLE_POLICIES:
|
| 476 |
+
return ROLE_POLICIES[path]
|
| 477 |
+
for pattern_regex, roles in _COMPILED_ROLE_PATTERNS:
|
| 478 |
+
if pattern_regex.match(path):
|
| 479 |
+
return roles
|
| 480 |
+
return None
|
| 481 |
+
|
| 482 |
if not os.getenv("DEEPSEEK_API_KEY"):
|
| 483 |
logger.warning(
|
| 484 |
"DEEPSEEK_API_KEY is not set. AI features will fail. "
|
|
|
|
| 608 |
FIRESTORE_QUERY_DESCENDING: Any = getattr(getattr(cast(Any, firebase_firestore), "Query", None), "DESCENDING", "DESCENDING")
|
| 609 |
|
| 610 |
|
| 611 |
+
def get_firestore_client() -> Any:
|
| 612 |
+
"""Return the initialized Firestore client through the canonical backend seam."""
|
| 613 |
+
if not (_firebase_ready and firebase_firestore):
|
| 614 |
+
raise RuntimeError("Firestore is not initialized")
|
| 615 |
+
try:
|
| 616 |
+
return firebase_firestore.client()
|
| 617 |
+
except Exception as exc:
|
| 618 |
+
raise RuntimeError("Firestore client is unavailable") from exc
|
| 619 |
+
|
| 620 |
+
|
| 621 |
def _snapshot_to_dict(snapshot: Any) -> Dict[str, Any]:
|
| 622 |
data = snapshot.to_dict() if hasattr(snapshot, "to_dict") else {}
|
| 623 |
return data if isinstance(data, dict) else {}
|
|
|
|
| 1116 |
claims=decoded,
|
| 1117 |
)
|
| 1118 |
|
| 1119 |
+
required_roles = resolve_required_roles(path)
|
| 1120 |
if required_roles and role not in required_roles:
|
| 1121 |
return JSONResponse(status_code=403, content={"detail": "Forbidden for this role"})
|
| 1122 |
|
|
|
|
| 9217 |
warnings: List[str]
|
| 9218 |
|
| 9219 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9220 |
# ─── DepEd Curriculum Competency Domains ────────────────────────────
|
| 9221 |
|
| 9222 |
DEPD_ED_COMPETENCY_DOMAINS: Dict[str, Dict[str, List[str]]] = {
|
|
|
|
| 13200 |
raise HTTPException(status_code=500, detail=f"Automation error: {str(e)}")
|
| 13201 |
|
| 13202 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13203 |
# ─── DepEd Topic Registry for Lessons/Quizzes ─────────────────────────────
|
| 13204 |
|
| 13205 |
DEPD_TOPIC_REGISTRY: Dict[str, Dict[str, str]] = {
|
rag/curriculum_rag.py
CHANGED
|
@@ -4,7 +4,7 @@ Updated curriculum RAG with exact match retrieval and 7-section notebook output.
|
|
| 4 |
|
| 5 |
from __future__ import annotations
|
| 6 |
|
| 7 |
-
from typing import Dict, List, Optional, Tuple
|
| 8 |
|
| 9 |
|
| 10 |
def _to_where(
|
|
@@ -56,6 +56,8 @@ def retrieve_curriculum_context(
|
|
| 56 |
competency_code: str | None = None,
|
| 57 |
storage_path: str | None = None,
|
| 58 |
top_k: int = 8,
|
|
|
|
|
|
|
| 59 |
) -> list[dict]:
|
| 60 |
from rag.vectorstore_loader import get_vectorstore_components
|
| 61 |
|
|
|
|
| 4 |
|
| 5 |
from __future__ import annotations
|
| 6 |
|
| 7 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 8 |
|
| 9 |
|
| 10 |
def _to_where(
|
|
|
|
| 56 |
competency_code: str | None = None,
|
| 57 |
storage_path: str | None = None,
|
| 58 |
top_k: int = 8,
|
| 59 |
+
grade_level: str | None = None,
|
| 60 |
+
**kwargs: Any,
|
| 61 |
) -> list[dict]:
|
| 62 |
from rag.vectorstore_loader import get_vectorstore_components
|
| 63 |
|
routes/diagnostic.py
CHANGED
|
@@ -503,7 +503,8 @@ async def generate_diagnostic(request: DiagnosticGenerateRequest, req: Request):
|
|
| 503 |
raise HTTPException(status_code=401, detail="Authentication required")
|
| 504 |
|
| 505 |
try:
|
| 506 |
-
|
|
|
|
| 507 |
test_id, questions = await _generate_questions(
|
| 508 |
request.strand,
|
| 509 |
request.grade_level,
|
|
@@ -740,9 +741,10 @@ async def submit_diagnostic(request: DiagnosticSubmitRequest, req: Request):
|
|
| 740 |
raise HTTPException(status_code=401, detail="Authentication required")
|
| 741 |
|
| 742 |
try:
|
| 743 |
-
|
|
|
|
| 744 |
except Exception as e:
|
| 745 |
-
raise HTTPException(status_code=503, detail="Database unavailable")
|
| 746 |
|
| 747 |
try:
|
| 748 |
session_doc = firestore_client.collection("diagnosticSessions").document(request.test_id).get()
|
|
@@ -817,9 +819,10 @@ async def analyze_diagnostic(request: DiagnosticAnalysisRequest, req: Request):
|
|
| 817 |
raise HTTPException(status_code=401, detail="Authentication required")
|
| 818 |
|
| 819 |
try:
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
|
|
|
| 823 |
|
| 824 |
# Fetch diagnostic results
|
| 825 |
results_doc = firestore_client.collection("diagnosticResults").document(request.user_id).get()
|
|
@@ -1067,3 +1070,29 @@ def _build_fallback_analysis(
|
|
| 1067 |
"hard_performance": pct(hard),
|
| 1068 |
},
|
| 1069 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 503 |
raise HTTPException(status_code=401, detail="Authentication required")
|
| 504 |
|
| 505 |
try:
|
| 506 |
+
from main import get_firestore_client
|
| 507 |
+
firestore_client = get_firestore_client()
|
| 508 |
test_id, questions = await _generate_questions(
|
| 509 |
request.strand,
|
| 510 |
request.grade_level,
|
|
|
|
| 741 |
raise HTTPException(status_code=401, detail="Authentication required")
|
| 742 |
|
| 743 |
try:
|
| 744 |
+
from main import get_firestore_client
|
| 745 |
+
firestore_client = get_firestore_client()
|
| 746 |
except Exception as e:
|
| 747 |
+
raise HTTPException(status_code=503, detail="Database unavailable") from e
|
| 748 |
|
| 749 |
try:
|
| 750 |
session_doc = firestore_client.collection("diagnosticSessions").document(request.test_id).get()
|
|
|
|
| 819 |
raise HTTPException(status_code=401, detail="Authentication required")
|
| 820 |
|
| 821 |
try:
|
| 822 |
+
from main import get_firestore_client
|
| 823 |
+
firestore_client = get_firestore_client()
|
| 824 |
+
except Exception as exc:
|
| 825 |
+
raise HTTPException(status_code=503, detail="Database unavailable") from exc
|
| 826 |
|
| 827 |
# Fetch diagnostic results
|
| 828 |
results_doc = firestore_client.collection("diagnosticResults").document(request.user_id).get()
|
|
|
|
| 1070 |
"hard_performance": pct(hard),
|
| 1071 |
},
|
| 1072 |
}
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
@router.get("/results/{user_id}")
|
| 1076 |
+
async def get_diagnostic_results(user_id: str, req: Request):
|
| 1077 |
+
"""Fetch diagnostic test results for a student."""
|
| 1078 |
+
user = getattr(req.state, "user", None)
|
| 1079 |
+
if not user or not getattr(user, "uid", None):
|
| 1080 |
+
raise HTTPException(status_code=401, detail="Authentication required")
|
| 1081 |
+
if getattr(user, "role", None) == "student" and user.uid != user_id:
|
| 1082 |
+
raise HTTPException(status_code=403, detail="Students can only view their own results")
|
| 1083 |
+
|
| 1084 |
+
try:
|
| 1085 |
+
from main import get_firestore_client
|
| 1086 |
+
firestore_client = get_firestore_client()
|
| 1087 |
+
docs = firestore_client.collection("diagnosticResults").document(user_id).collection("attempts").stream()
|
| 1088 |
+
results = []
|
| 1089 |
+
for doc in docs:
|
| 1090 |
+
data = doc.to_dict()
|
| 1091 |
+
if data:
|
| 1092 |
+
results.append(data)
|
| 1093 |
+
results.sort(key=lambda x: str(x.get("takenAt") or x.get("taken_at") or ""), reverse=True)
|
| 1094 |
+
return {"success": True, "results": results}
|
| 1095 |
+
except Exception as exc:
|
| 1096 |
+
logger.error(f"Diagnostic results fetch error: {exc}")
|
| 1097 |
+
raise HTTPException(status_code=503, detail="Diagnostic results unavailable") from exc
|
| 1098 |
+
|
routes/pipeline_routes.py
CHANGED
|
@@ -69,16 +69,18 @@ async def request_nudge(student_id: str, background_tasks: BackgroundTasks, requ
|
|
| 69 |
@router.get("/profile/{student_id}")
|
| 70 |
async def get_profile(student_id: str, request: Request):
|
| 71 |
"""Get full student profile."""
|
| 72 |
-
_require_auth(request)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
-
_firebase_firestore = None
|
| 75 |
try:
|
| 76 |
-
from
|
| 77 |
-
|
| 78 |
-
except Exception:
|
| 79 |
-
raise HTTPException(status_code=503, detail="Firestore unavailable")
|
| 80 |
|
| 81 |
-
db = _firebase_firestore.client()
|
| 82 |
doc = db.collection("student_profiles").document(student_id).get()
|
| 83 |
if not doc.exists:
|
| 84 |
raise HTTPException(status_code=404, detail="Profile not found")
|
|
|
|
| 69 |
@router.get("/profile/{student_id}")
|
| 70 |
async def get_profile(student_id: str, request: Request):
|
| 71 |
"""Get full student profile."""
|
| 72 |
+
user = _require_auth(request)
|
| 73 |
+
if user.role == "student" and student_id != user.uid:
|
| 74 |
+
raise HTTPException(status_code=403, detail="Students can only access their own profile")
|
| 75 |
+
if user.role not in ("student", "teacher", "admin"):
|
| 76 |
+
raise HTTPException(status_code=403, detail="Forbidden for this role")
|
| 77 |
|
|
|
|
| 78 |
try:
|
| 79 |
+
from main import get_firestore_client
|
| 80 |
+
db = get_firestore_client()
|
| 81 |
+
except Exception as exc:
|
| 82 |
+
raise HTTPException(status_code=503, detail="Firestore unavailable") from exc
|
| 83 |
|
|
|
|
| 84 |
doc = db.collection("student_profiles").document(student_id).get()
|
| 85 |
if not doc.exists:
|
| 86 |
raise HTTPException(status_code=404, detail="Profile not found")
|
routes/teacher_materials.py
CHANGED
|
@@ -197,18 +197,27 @@ def _retrieve_rag_context(
|
|
| 197 |
try:
|
| 198 |
from rag.curriculum_rag import retrieve_curriculum_context
|
| 199 |
|
|
|
|
| 200 |
result = retrieve_curriculum_context(
|
| 201 |
-
query=
|
| 202 |
grade_level=grade_level or "",
|
| 203 |
top_k=top_k,
|
| 204 |
)
|
| 205 |
-
if isinstance(result,
|
| 206 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
chunks = result.get("chunks", [])
|
| 208 |
formatted = []
|
| 209 |
for chunk in chunks:
|
| 210 |
-
src = chunk.get("source", "unknown")
|
| 211 |
-
text = chunk.get("text", "")
|
| 212 |
if text:
|
| 213 |
formatted.append(f"[Source: {src}]\n{text}")
|
| 214 |
return "\n\n---\n\n".join(formatted)
|
|
|
|
| 197 |
try:
|
| 198 |
from rag.curriculum_rag import retrieve_curriculum_context
|
| 199 |
|
| 200 |
+
rag_query = f"{query} {grade_level}".strip() if grade_level else query
|
| 201 |
result = retrieve_curriculum_context(
|
| 202 |
+
query=rag_query,
|
| 203 |
grade_level=grade_level or "",
|
| 204 |
top_k=top_k,
|
| 205 |
)
|
| 206 |
+
if isinstance(result, list):
|
| 207 |
+
formatted = []
|
| 208 |
+
for chunk in result:
|
| 209 |
+
src = chunk.get("source_file") or chunk.get("source", "unknown")
|
| 210 |
+
text = chunk.get("content") or chunk.get("text", "")
|
| 211 |
+
if text:
|
| 212 |
+
formatted.append(f"[Source: {src}]\n{text}")
|
| 213 |
+
return "\n\n---\n\n".join(formatted)
|
| 214 |
+
elif isinstance(result, dict):
|
| 215 |
+
# Dict format with metadata + chunks
|
| 216 |
chunks = result.get("chunks", [])
|
| 217 |
formatted = []
|
| 218 |
for chunk in chunks:
|
| 219 |
+
src = chunk.get("source_file") or chunk.get("source", "unknown")
|
| 220 |
+
text = chunk.get("content") or chunk.get("text", "")
|
| 221 |
if text:
|
| 222 |
formatted.append(f"[Source: {src}]\n{text}")
|
| 223 |
return "\n\n---\n\n".join(formatted)
|
tests/conftest.py
CHANGED
|
@@ -36,28 +36,39 @@ def _get_mock_verify():
|
|
| 36 |
|
| 37 |
|
| 38 |
def _mock_verify_id_token(token: str, *, check_revoked: bool = False) -> dict:
|
| 39 |
-
"""Return fake Firebase claims dict for tokens with 'mock_token_' prefix."""
|
| 40 |
-
if token and token.startswith("mock_token_"):
|
| 41 |
-
uid = token
|
|
|
|
| 42 |
return {
|
| 43 |
-
"uid": uid,
|
| 44 |
-
"sub": uid,
|
| 45 |
-
"email": f"{uid}@test.mathpulse.ai",
|
| 46 |
"email_verified": True,
|
| 47 |
-
"role":
|
| 48 |
}
|
| 49 |
# Non-mock tokens: call the real Firebase implementation
|
| 50 |
real_verify = _get_mock_verify()
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
|
| 54 |
def _apply_firebase_mock():
|
| 55 |
"""Apply the mock to firebase_admin.auth.verify_id_token (idempotent)."""
|
| 56 |
try:
|
| 57 |
import firebase_admin.auth
|
|
|
|
| 58 |
|
| 59 |
current = firebase_admin.auth.verify_id_token
|
| 60 |
if not hasattr(current, "_mathpulse_mock"):
|
|
|
|
| 61 |
firebase_admin.auth.verify_id_token = _mock_verify_id_token
|
| 62 |
firebase_admin.auth.verify_id_token._mathpulse_mock = True
|
| 63 |
except Exception:
|
|
|
|
| 36 |
|
| 37 |
|
| 38 |
def _mock_verify_id_token(token: str, *, check_revoked: bool = False) -> dict:
|
| 39 |
+
"""Return fake Firebase claims dict for tokens with 'mock_token_' or 'test-' prefix."""
|
| 40 |
+
if token and (token.startswith("mock_token_") or token.startswith("test-")):
|
| 41 |
+
uid = token.replace("mock_token_", "").replace("test-", "")
|
| 42 |
+
role = "teacher" if ("teacher" in token or "auth" in token) else "student"
|
| 43 |
return {
|
| 44 |
+
"uid": uid or "test-user-id",
|
| 45 |
+
"sub": uid or "test-user-id",
|
| 46 |
+
"email": f"{uid or 'test'}@test.mathpulse.ai",
|
| 47 |
"email_verified": True,
|
| 48 |
+
"role": role,
|
| 49 |
}
|
| 50 |
# Non-mock tokens: call the real Firebase implementation
|
| 51 |
real_verify = _get_mock_verify()
|
| 52 |
+
if real_verify is not None and real_verify is not _mock_verify_id_token:
|
| 53 |
+
return real_verify(token, check_revoked=check_revoked)
|
| 54 |
+
return {
|
| 55 |
+
"uid": "test-user-id",
|
| 56 |
+
"sub": "test-user-id",
|
| 57 |
+
"email": "test@test.mathpulse.ai",
|
| 58 |
+
"email_verified": True,
|
| 59 |
+
"role": "student",
|
| 60 |
+
}
|
| 61 |
|
| 62 |
|
| 63 |
def _apply_firebase_mock():
|
| 64 |
"""Apply the mock to firebase_admin.auth.verify_id_token (idempotent)."""
|
| 65 |
try:
|
| 66 |
import firebase_admin.auth
|
| 67 |
+
global _mock_orig_verify
|
| 68 |
|
| 69 |
current = firebase_admin.auth.verify_id_token
|
| 70 |
if not hasattr(current, "_mathpulse_mock"):
|
| 71 |
+
_mock_orig_verify = current
|
| 72 |
firebase_admin.auth.verify_id_token = _mock_verify_id_token
|
| 73 |
firebase_admin.auth.verify_id_token._mathpulse_mock = True
|
| 74 |
except Exception:
|
tests/test_audit_remediation.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
backend/tests/test_audit_remediation.py
|
| 3 |
+
|
| 4 |
+
Regression test suite for all fixes from final-audit-report.md:
|
| 5 |
+
1. Dynamic role policies pattern matching in AuthMiddleware (GATE-01)
|
| 6 |
+
2. Pipeline profile ownership verification (GATE-02)
|
| 7 |
+
3. Diagnostic routes deduplication and results handler (GATE-04, GATE-05)
|
| 8 |
+
4. RAG signature acceptance of grade_level (GATE-06)
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import pytest
|
| 12 |
+
from unittest.mock import MagicMock, patch
|
| 13 |
+
from fastapi.testclient import TestClient
|
| 14 |
+
|
| 15 |
+
import main as main_module
|
| 16 |
+
from main import app, resolve_required_roles, ROLE_POLICIES
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestRolePolicyMatching:
|
| 20 |
+
"""Verify GATE-01: parameterized route matching."""
|
| 21 |
+
|
| 22 |
+
def test_literal_routes_resolve_correctly(self):
|
| 23 |
+
assert resolve_required_roles("/api/chat") == {"student", "teacher", "admin"}
|
| 24 |
+
assert resolve_required_roles("/api/predict-risk") == {"teacher", "admin"}
|
| 25 |
+
assert resolve_required_roles("/api/admin/users") == {"admin"}
|
| 26 |
+
|
| 27 |
+
def test_parameterized_routes_resolve_correctly(self):
|
| 28 |
+
assert resolve_required_roles("/api/analytics/class/sec-grade11-stem") == {"teacher", "admin"}
|
| 29 |
+
assert resolve_required_roles("/api/intervention/student-12345") == {"teacher", "admin"}
|
| 30 |
+
assert resolve_required_roles("/api/intervention/student-12345/export-pdf") == {"teacher", "admin"}
|
| 31 |
+
assert resolve_required_roles("/api/pipeline/profile/student-999") == {"student", "teacher", "admin"}
|
| 32 |
+
assert resolve_required_roles("/api/pipeline/profile/student-999/recompute") == {"teacher", "admin"}
|
| 33 |
+
|
| 34 |
+
def test_nonexistent_routes_return_none(self):
|
| 35 |
+
assert resolve_required_roles("/api/nonexistent/unknown") is None
|
| 36 |
+
assert resolve_required_roles("/some/random/path") is None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class TestPipelineProfileOwnership:
|
| 40 |
+
"""Verify GATE-02: student can only access own profile, teacher/admin can access any."""
|
| 41 |
+
|
| 42 |
+
def test_student_cannot_access_other_student_profile(self):
|
| 43 |
+
client = TestClient(app, headers={"Authorization": "Bearer mock_token_student_A"})
|
| 44 |
+
# When token is mock_token_student_A, uid is "student_A" and role is "student"
|
| 45 |
+
with patch.object(main_module.firebase_auth, "verify_id_token", return_value={"uid": "student_A", "role": "student"}):
|
| 46 |
+
response = client.get("/api/pipeline/profile/student_B")
|
| 47 |
+
assert response.status_code == 403
|
| 48 |
+
assert "own profile" in response.json().get("detail", "").lower()
|
| 49 |
+
|
| 50 |
+
def test_student_can_access_own_profile(self):
|
| 51 |
+
client = TestClient(app, headers={"Authorization": "Bearer mock_token_student_A"})
|
| 52 |
+
mock_doc = MagicMock()
|
| 53 |
+
mock_doc.exists = True
|
| 54 |
+
mock_doc.to_dict.return_value = {"student_id": "student_A", "name": "Student A"}
|
| 55 |
+
|
| 56 |
+
mock_db = MagicMock()
|
| 57 |
+
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
| 58 |
+
|
| 59 |
+
with patch.object(main_module, "firebase_firestore", object()), \
|
| 60 |
+
patch.object(main_module, "_firebase_ready", True), \
|
| 61 |
+
patch.object(main_module, "get_firestore_client", return_value=mock_db), \
|
| 62 |
+
patch.object(main_module.firebase_auth, "verify_id_token", return_value={"uid": "student_A", "role": "student"}):
|
| 63 |
+
response = client.get("/api/pipeline/profile/student_A")
|
| 64 |
+
assert response.status_code == 200
|
| 65 |
+
assert response.json()["student_id"] == "student_A"
|
| 66 |
+
|
| 67 |
+
def test_teacher_can_access_any_student_profile(self):
|
| 68 |
+
client = TestClient(app, headers={"Authorization": "Bearer mock_token_teacher_T"})
|
| 69 |
+
mock_doc = MagicMock()
|
| 70 |
+
mock_doc.exists = True
|
| 71 |
+
mock_doc.to_dict.return_value = {"student_id": "student_B", "name": "Student B"}
|
| 72 |
+
|
| 73 |
+
mock_db = MagicMock()
|
| 74 |
+
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
| 75 |
+
|
| 76 |
+
with patch.object(main_module, "firebase_firestore", object()), \
|
| 77 |
+
patch.object(main_module, "_firebase_ready", True), \
|
| 78 |
+
patch.object(main_module, "get_firestore_client", return_value=mock_db), \
|
| 79 |
+
patch.object(main_module.firebase_auth, "verify_id_token", return_value={"uid": "teacher_T", "role": "teacher"}):
|
| 80 |
+
response = client.get("/api/pipeline/profile/student_B")
|
| 81 |
+
assert response.status_code == 200
|
| 82 |
+
assert response.json()["student_id"] == "student_B"
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class TestDiagnosticResultsEndpoint:
|
| 86 |
+
"""Verify GATE-05: /api/diagnostic/results/{user_id} in canonical diagnostic router."""
|
| 87 |
+
|
| 88 |
+
def test_diagnostic_results_rejects_other_student(self):
|
| 89 |
+
client = TestClient(app, headers={"Authorization": "Bearer mock_token_student_1"})
|
| 90 |
+
with patch.object(main_module.firebase_auth, "verify_id_token", return_value={"uid": "student_1", "role": "student"}):
|
| 91 |
+
response = client.get("/api/diagnostic/results/student_2")
|
| 92 |
+
assert response.status_code == 403
|
| 93 |
+
|
| 94 |
+
def test_diagnostic_results_allows_own_student(self):
|
| 95 |
+
client = TestClient(app, headers={"Authorization": "Bearer mock_token_student_1"})
|
| 96 |
+
mock_doc = MagicMock()
|
| 97 |
+
mock_doc.to_dict.return_value = {"testId": "DX-123", "takenAt": "2026-08-16T12:00:00Z"}
|
| 98 |
+
|
| 99 |
+
mock_db = MagicMock()
|
| 100 |
+
mock_db.collection.return_value.document.return_value.collection.return_value.stream.return_value = [mock_doc]
|
| 101 |
+
|
| 102 |
+
with patch.object(main_module, "firebase_firestore", object()), \
|
| 103 |
+
patch.object(main_module, "_firebase_ready", True), \
|
| 104 |
+
patch.object(main_module, "get_firestore_client", return_value=mock_db), \
|
| 105 |
+
patch.object(main_module.firebase_auth, "verify_id_token", return_value={"uid": "student_1", "role": "student"}):
|
| 106 |
+
response = client.get("/api/diagnostic/results/student_1")
|
| 107 |
+
assert response.status_code == 200
|
| 108 |
+
assert response.json()["success"] is True
|
| 109 |
+
assert len(response.json()["results"]) == 1
|
| 110 |
+
|
| 111 |
+
def test_diagnostic_results_reports_firestore_outage(self):
|
| 112 |
+
client = TestClient(app, headers={"Authorization": "Bearer mock_token_student_1"})
|
| 113 |
+
|
| 114 |
+
with patch.object(main_module, "firebase_firestore", object()), \
|
| 115 |
+
patch.object(main_module, "_firebase_ready", True), \
|
| 116 |
+
patch.object(main_module, "get_firestore_client", side_effect=RuntimeError("unavailable")), \
|
| 117 |
+
patch.object(main_module.firebase_auth, "verify_id_token", return_value={"uid": "student_1", "role": "student"}):
|
| 118 |
+
response = client.get("/api/diagnostic/results/student_1")
|
| 119 |
+
|
| 120 |
+
assert response.status_code == 503
|
| 121 |
+
assert response.json()["detail"] == "Diagnostic results unavailable"
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class TestCurriculumRAGSignature:
|
| 125 |
+
"""Verify GATE-06: retrieve_curriculum_context signature."""
|
| 126 |
+
|
| 127 |
+
def test_retrieve_curriculum_context_accepts_grade_level(self):
|
| 128 |
+
from rag.curriculum_rag import retrieve_curriculum_context
|
| 129 |
+
|
| 130 |
+
mock_collection = MagicMock()
|
| 131 |
+
mock_collection.query.return_value = {
|
| 132 |
+
"documents": [["Quadratic functions concept"]],
|
| 133 |
+
"metadatas": [[{"source_file": "GenMath_Q1.pdf", "subject": "General Mathematics", "quarter": 1}]],
|
| 134 |
+
"distances": [[0.1]],
|
| 135 |
+
}
|
| 136 |
+
mock_embedder = MagicMock()
|
| 137 |
+
mock_embedder.encode.return_value.tolist.return_value = [0.1] * 384
|
| 138 |
+
|
| 139 |
+
with patch("rag.vectorstore_loader.get_vectorstore_components", return_value=(None, mock_collection, mock_embedder)):
|
| 140 |
+
results = retrieve_curriculum_context(
|
| 141 |
+
query="quadratic functions",
|
| 142 |
+
grade_level="Grade 11",
|
| 143 |
+
top_k=3,
|
| 144 |
+
extra_future_param="ok",
|
| 145 |
+
)
|
| 146 |
+
assert len(results) == 1
|
| 147 |
+
assert results[0]["source_file"] == "GenMath_Q1.pdf"
|
| 148 |
+
assert "Quadratic functions" in results[0]["content"]
|