Spaces:
Running
Running
github-actions[bot] commited on
Commit ·
394b734
1
Parent(s): 3d1319b
deploy: backend from 99b3c80
Browse filesFiles changed (17)
- config/env.sample+1
- main.py+20-105
- routes/admin_routes.py+3-2
- routes/class_analytics_routes.py+3-1
- routes/diagnostic.py+18-21
- routes/practice.py+14-22
- routes/quiz_generation_routes.py+12-25
- routes/rag_routes.py+5-11
- routes/tutor_checkin.py+14-11
- services/class_analytics_engine.py+13-15
- services/intervention_engine.py+5-12
- services/llm_json.pyAdded+195
- services/student_intelligence_pipeline.py+4-3
- services/tutor_nudge_service.py+3-1
- services/wri_service.py+40-15
- tests/conftest.py+3-35
- tests/test_llm_json.pyAdded+142
2 unmodified lines3456782 unmodified linesDEEPSEEK_BASE_URL=https://api.deepseek.comDEEPSEEK_MODEL=deepseek-chatDEEPSEEK_REASONER_MODEL=deepseek-reasoner# Inference provider selection# CI trigger marker: keep this file touchable to force backend deploy workflow runs when needed.2 unmodified lines34567892 unmodified linesDEEPSEEK_BASE_URL=https://api.deepseek.comDEEPSEEK_MODEL=deepseek-chatDEEPSEEK_REASONER_MODEL=deepseek-reasonerDEEPSEEK_ENABLED=true# Inference provider selection# CI trigger marker: keep this file touchable to force backend deploy workflow runs when needed.
83 unmodified lines84858687888910689 unmodified lines1077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801 unmodified line10882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090283 unmodified lines)from services.deterministic_cache import DeterministicResponseCachefrom services.logging_utils import log_model_callfrom services.email_service import create_email_service_from_env, EmailMessagePayloadfrom services.user_provisioning_service import (AdminCreateUserInput,10689 unmodified linesdef _parse_quiz_json(raw: str) -> List[Dict[str, Any]]:"""Robustly extract a JSON array of quiz questions from LLM output."""cleaned = raw.strip()# Remove markdown fencescleaned = re.sub(r"^```(?:json)?\s*\n?", "", cleaned, flags=re.IGNORECASE)cleaned = re.sub(r"\n?```\s*$", "", cleaned)cleaned = cleaned.strip()# Remove known reasoning wrappers and preambles that can precede JSON.cleaned = re.sub(r"<think>[\s\S]*?</think>", "", cleaned, flags=re.IGNORECASE)# Remove common reasoning preambles before JSON output.cleaned = re.sub(r"^\s*thinking\s*process\s*:\s*", "", cleaned, flags=re.IGNORECASE)cleaned = re.sub(r"^\s*json\s*[:\-]?\s*", "", cleaned, flags=re.IGNORECASE)def _extract_json_blocks(text: str) -> List[str]:blocks: List[str] = []starts = [i for i, ch in enumerate(text) if ch in "[{"]for start in starts:opener = text[start]closer = "]" if opener == "[" else "}"depth = 0in_string = Falseescaped = Falsefor idx in range(start, len(text)):ch = text[idx]if in_string:if escaped:escaped = Falseelif ch == "\\":escaped = Trueelif ch == '"':in_string = Falsecontinueif ch == '"':in_string = Truecontinueif ch == opener:depth += 1elif ch == closer:depth -= 1if depth == 0:blocks.append(text[start : idx + 1])breakreturn blocksdef _normalize_candidate(candidate: str) -> str:normalized = candidate.strip().lstrip("\ufeff")normalized = (normalized.replace("\u201c", '"').replace("\u201d", '"').replace("\u2018", "'").replace("\u2019", "'"))# Remove trailing commas before object/array closers.normalized = re.sub(r",(\s*[}\]])", r"\1", normalized)return normalizeddef _jsonish_loads(candidate: str) -> Any:normalized = _normalize_candidate(candidate)try:return json.loads(normalized)except json.JSONDecodeError:pass# Fallback for Python-literal style payloads using single quotes / True / None.python_like = re.sub(r"\btrue\b", "True", normalized, flags=re.IGNORECASE)python_like = re.sub(r"\bfalse\b", "False", python_like, flags=re.IGNORECASE)python_like = re.sub(r"\bnull\b", "None", python_like, flags=re.IGNORECASE)try:return ast.literal_eval(python_like)except (ValueError, SyntaxError):return Nonedef _coerce_question_list(value: Any) -> List[Dict[str, Any]]:if not isinstance(value, list):return []return [item for item in value if isinstance(item, dict)]def _extract_question_list(payload: Any) -> List[Dict[str, Any]]:if isinstance(payload, list):return _coerce_question_list(payload)if isinstance(payload, dict):for key in ("questions", "quiz", "items", "data"):nested = payload.get(key)if isinstance(nested, list):return _coerce_question_list(nested)return []# Try every balanced JSON-ish block and accept known payload wrappers.for candidate in _extract_json_blocks(cleaned):parsed = _jsonish_loads(candidate)extracted = _extract_question_list(parsed)if extracted:return extracted1 unmodified linearr_start = cleaned.find("[")arr_end = cleaned.rfind("]") + 1if arr_start >= 0 and arr_end > arr_start:parsed = _jsonish_loads(cleaned[arr_start:arr_end])extracted = _extract_question_list(parsed)if extracted:return extracted# Fallback: salvage individually parseable question-like objects.objects: List[Dict[str, Any]] = []for candidate in _extract_json_blocks(cleaned):if not candidate.lstrip().startswith("{"):continueparsed = _jsonish_loads(candidate)if isinstance(parsed, dict) and str(parsed.get("question") or "").strip():objects.append(parsed)return objectsasync def _repair_quiz_json_with_llm(83 unmodified lines8485868788899091929394959610689 unmodified lines1078610787107881078910790107911079210793107941079510796107971079810799108001 unmodified line1080210803108041080510806108071080810809108101081110812108131081410815108161081783 unmodified lines)from services.deterministic_cache import DeterministicResponseCachefrom services.logging_utils import log_model_callfrom services.llm_json import (collect_dict_objects,extract_dict_list,extract_json_blocks,loads_jsonish,strip_reasoning,)from services.email_service import create_email_service_from_env, EmailMessagePayloadfrom services.user_provisioning_service import (AdminCreateUserInput,10689 unmodified linesdef _parse_quiz_json(raw: str) -> List[Dict[str, Any]]:"""Extract a JSON array of quiz questions from LLM output.Extraction and recovery live in services.llm_json so every route acceptsthe same model-produced envelope shapes."""cleaned = strip_reasoning(raw)for candidate in extract_json_blocks(cleaned):extracted = extract_dict_list(loads_jsonish(candidate))if extracted:return extracted1 unmodified linearr_start = cleaned.find("[")arr_end = cleaned.rfind("]") + 1if arr_start >= 0 and arr_end > arr_start:extracted = extract_dict_list(loads_jsonish(cleaned[arr_start:arr_end]))if extracted:return extracted# Fallback: salvage individually parseable question-like objects.return [parsedfor parsed in collect_dict_objects(cleaned)if str(parsed.get("question") or "").strip()]async def _repair_quiz_json_with_llm(
9 unmodified lines101112131415426 unmodified lines44244344444544644744834 unmodified lines4834844854864874884899 unmodified linesfrom rag.firebase_storage_loader import _init_firebase_storage, PDF_METADATAfrom scripts.ingest_from_storage import ingest_from_firebase_storage# Lazy import for audit_logger to prevent ModuleNotFoundError during test collection_audit_logger = Nonedef _get_audit_logger():426 unmodified linesprofiles = list(db.collection("managedStudents").stream())total = len(profiles)wri_dist = {"safe": 0, "watch": 0, "intervene": 0, "critical": 0, "at_risk": 0, "pending_assessment": 0}wri_values = []grade_wri: dict = defaultdict(list)class_wri: dict = defaultdict(list)34 unmodified lines# Recent escalations (last 24h)updated = data.get("wri_updated_at") or data.get("riskUpdatedAt")if updated and status in ("critical", "at_risk"):try:if hasattr(updated, "seconds"):dt = datetime.fromtimestamp(updated.seconds, tz=timezone.utc)9 unmodified lines10111213141516426 unmodified lines44344444544644744844934 unmodified lines4844854864874884894909 unmodified linesfrom rag.firebase_storage_loader import _init_firebase_storage, PDF_METADATAfrom scripts.ingest_from_storage import ingest_from_firebase_storagefrom services.wri_service import ESCALATION_RISK_STATUSES, empty_risk_distribution# Lazy import for audit_logger to prevent ModuleNotFoundError during test collection_audit_logger = Nonedef _get_audit_logger():426 unmodified linesprofiles = list(db.collection("managedStudents").stream())total = len(profiles)wri_dist = empty_risk_distribution()wri_values = []grade_wri: dict = defaultdict(list)class_wri: dict = defaultdict(list)34 unmodified lines# Recent escalations (last 24h)updated = data.get("wri_updated_at") or data.get("riskUpdatedAt")if updated and status in ESCALATION_RISK_STATUSES:try:if hasattr(updated, "seconds"):dt = datetime.fromtimestamp(updated.seconds, tz=timezone.utc)
4 unmodified lines567891042 unmodified lines535455565758594 unmodified linesfrom typing import Optionalfrom fastapi import APIRouter, HTTPException, Requestlogger = logging.getLogger("mathpulse.class_analytics_routes")router = APIRouter(prefix="/api/analytics/class", tags=["class-analytics"])42 unmodified lines)[:10]elif filter == "needs_attention":students = sorted([s for s in students if s.risk_level in ("intervene", "critical", "at_risk")],key=lambda s: s.avg_score,)4 unmodified lines5678910111242 unmodified lines555657585960614 unmodified linesfrom typing import Optionalfrom fastapi import APIRouter, HTTPException, Requestfrom services.wri_service import ATTENTION_RISK_STATUSESlogger = logging.getLogger("mathpulse.class_analytics_routes")router = APIRouter(prefix="/api/analytics/class", tags=["class-analytics"])42 unmodified lines)[:10]elif filter == "needs_attention":students = sorted([s for s in students if s.risk_level in ATTENTION_RISK_STATUSES],key=lambda s: s.avg_score,)
19 unmodified lines202122232425346 unmodified lines37237337437537637737837938038138238338438538638738838939039139239339439539639739819 unmodified linesfrom pydantic import BaseModel, Fieldfrom services.ai_client import CHAT_MODEL, get_deepseek_clientfrom rag.curriculum_rag import retrieve_curriculum_contextimport firebase_adminfrom firebase_admin import firestore as fs346 unmodified linesdef _parse_questions_response(raw_response: str) -> List[Dict[str, Any]]:try:data = json.loads(raw_response)if isinstance(data, dict):for key in ("questions", "items", "data", "results"):if key in data and isinstance(data[key], list):return data[key]for key, value in data.items():if isinstance(value, list) and len(value) > 0 and isinstance(value[0], dict):if "question_text" in value[0]:return valueif isinstance(data, list):return dataexcept json.JSONDecodeError:passimport rematch = re.search(r'\[.*\]', raw_response, re.DOTALL)if match:try:return json.loads(match.group())except json.JSONDecodeError:passraise ValueError("Could not parse questions from AI response")19 unmodified lines20212223242526346 unmodified lines37337437537637737837938038138238338438538638738838939039139239339439519 unmodified linesfrom pydantic import BaseModel, Fieldfrom services.ai_client import CHAT_MODEL, get_deepseek_clientfrom services.llm_json import LLMJsonError, extract_json_value, extract_dict_listfrom rag.curriculum_rag import retrieve_curriculum_contextimport firebase_adminfrom firebase_admin import firestore as fs346 unmodified linesdef _parse_questions_response(raw_response: str) -> List[Dict[str, Any]]:try:payload = extract_json_value(raw_response, preferred=(dict, list))except LLMJsonError as exc:raise ValueError("Could not parse questions from AI response") from excquestions = extract_dict_list(payload)if questions:return questions# Envelope object whose list lives under a non-standard key.if isinstance(payload, dict):for value in payload.values():if isinstance(value, list) and value and isinstance(value[0], dict):if "question_text" in value[0]:return valueif isinstance(payload, list):return payloadraise ValueError("Could not parse questions from AI response")
18 unmodified lines192021222324135 unmodified lines16016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219318 unmodified linesfrom pydantic import BaseModel, Fieldfrom services.ai_client import CHAT_MODEL, get_deepseek_clientimport firebase_adminfrom firebase_admin import firestore as fs135 unmodified linesdef _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 = Noneif isinstance(data, dict):for key in ("questions", "items", "data", "results", "practice_questions"):if key in data and isinstance(data[key], list):questions = data[key]breakif 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 = vbreakelif isinstance(data, list):questions = dataif not questions:raise HTTPException(status_code=500, detail="AI response missing questions. Please try again.")# Ensure we have exactly `count` questionsquestions = questions[:count]return questionsdef _build_question_prompt(subject: str, competency: str, difficulty: str, count: int) -> tuple[str, str]:18 unmodified lines19202122232425135 unmodified lines16116216316416516616716816917017117217317417517617717817918018118218318418518 unmodified linesfrom pydantic import BaseModel, Fieldfrom services.ai_client import CHAT_MODEL, get_deepseek_clientfrom services.llm_json import LLMJsonError, extract_dict_list, extract_json_valueimport firebase_adminfrom firebase_admin import firestore as fs135 unmodified linesdef _parse_questions_response(raw: str, count: int) -> List[Dict[str, Any]]:"""Extract the question list from an AI JSON response."""try:payload = extract_json_value(raw, preferred=(dict, list))except LLMJsonError as exc:raise HTTPException(status_code=500, detail="Failed to parse AI response. Please try again.") from excquestions = extract_dict_list(payload)if not questions and isinstance(payload, dict):for value in payload.values():if isinstance(value, list) and value and isinstance(value[0], dict):questions = valuebreakif not questions:raise HTTPException(status_code=500, detail="AI response missing questions. Please try again.")return questions[:count]def _build_question_prompt(subject: str, competency: str, difficulty: str, count: int) -> tuple[str, str]:
9 unmodified lines101112131415161718198 unmodified lines282930313233190 unmodified lines2242252262272282292302312322332342352362372382392402412422432442452462472482492502512522539 unmodified linesfrom __future__ import annotationsimport jsonimport loggingimport randomimport refrom typing import Any, Dict, List, Optionalfrom fastapi import APIRouter, HTTPException, Request8 unmodified linescreate_default_client,get_model_for_task,)logger = logging.getLogger("mathpulse.quiz_generation")router = APIRouter(prefix="/api/quiz", tags=["quiz-generation"])190 unmodified linesdef _parse_quiz_response(text: str, expected_count: int) -> List[Dict[str, Any]]:"""Parse and validate QuizForge quiz generation response."""cleaned = text.strip()# Strip markdown fencescleaned = re.sub(r"^```json\s*", "", cleaned, flags=re.IGNORECASE)cleaned = re.sub(r"^```\s*", "", cleaned)cleaned = re.sub(r"\s*```$", "", cleaned)cleaned = cleaned.strip()try:questions = json.loads(cleaned)except json.JSONDecodeError as e:logger.error(f"Failed to parse quiz response as JSON: {e}")# Try to extract JSON array from textmatch = re.search(r"\[.*\]", cleaned, re.DOTALL)if match:try:questions = json.loads(match.group())except json.JSONDecodeError:raise ValueError(f"Invalid JSON in quiz response: {e}")else:raise ValueError(f"No JSON array found in quiz response")if not isinstance(questions, list):raise ValueError("Quiz response is not a JSON array")validated = []for i, q in enumerate(questions):9 unmodified lines10111213141516178 unmodified lines26272829303132190 unmodified lines2232242252262272282292302312322332342352362372382392409 unmodified linesfrom __future__ import annotationsimport loggingimport randomfrom typing import Any, Dict, List, Optionalfrom fastapi import APIRouter, HTTPException, Request8 unmodified linescreate_default_client,get_model_for_task,)from services.llm_json import LLMJsonError, extract_dict_list, extract_json_valuelogger = logging.getLogger("mathpulse.quiz_generation")router = APIRouter(prefix="/api/quiz", tags=["quiz-generation"])190 unmodified linesdef _parse_quiz_response(text: str, expected_count: int) -> List[Dict[str, Any]]:"""Parse and validate QuizForge quiz generation response."""try:payload = extract_json_value(text, preferred=(list, dict))except LLMJsonError as exc:logger.error("Failed to parse quiz response as JSON: %s", exc)raise ValueError(f"No JSON array found in quiz response: {exc}") from excif isinstance(payload, list):questions = payloadelse:questions = extract_dict_list(payload)if not questions:raise ValueError("Quiz response is not a JSON array")validated = []for i, q in enumerate(questions):
10 unmodified lines11121314151687 unmodified lines10410510610710810911011111211311411511611711811912010 unmodified linesfrom fastapi import APIRouter, HTTPException, Requestfrom pydantic import BaseModel, Field, field_validatorfrom services.inference_client import (InferenceRequest,create_default_client,87 unmodified linesdef _strip_thinking_and_parse(text: str) -> dict:cleaned = text.strip()cleaned = re.sub(r" </think>", "", cleaned, flags=re.DOTALL).strip()if "{" in cleaned and "}" in cleaned:try:start = cleaned.find("{")end = cleaned.rfind("}") + 1parsed = json.loads(cleaned[start:end])if isinstance(parsed, dict):return parsedexcept Exception:passreturn {"explanation": text}10 unmodified lines111213141516171887 unmodified lines10610710810911011111211311410 unmodified linesfrom fastapi import APIRouter, HTTPException, Requestfrom pydantic import BaseModel, Field, field_validatorfrom services.llm_json import extract_json_objectfrom services.inference_client import (InferenceRequest,create_default_client,87 unmodified linesdef _strip_thinking_and_parse(text: str) -> dict:parsed = extract_json_object(text)if parsed is not None:return parsedreturn {"explanation": text}
6 unmodified lines789101112131415161717 unmodified lines353637383940414243444546474844 unmodified lines939495969798993 unmodified lines1031041051061071081099 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421436 unmodified linesimport loggingimport osfrom typing import Optionalfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModellogger = logging.getLogger("mathpulse.tutor_checkin")router = APIRouter(prefix="/api/tutor-checkin", tags=["tutor-checkin"])17 unmodified linesdef _build_checkin_prompt(req: TutorCheckinRequest) -> str:"""Build a contextual prompt for DeepSeek to generate a tutor check-in."""name = req.student_name or "Student"status = req.risk_status or "unknown"wri = req.wriweak = req.weak_topics or []activity = req.recent_activity or "No recent activity recorded."weak_topics_str = ", ".join(weak) if weak else "none identified"tone_map = {"safe": "encouraging and celebratory","watch": "gentle and supportive","intervene": "caring but firm",44 unmodified linesmessage = response.strip() if response else _fallback_message(req.risk_status)tone_map = {"safe": "encouraging","watch": "supportive","intervene": "caring-but-firm",3 unmodified linesreturn TutorCheckinResponse(message=message,tone=tone_map.get(req.risk_status or "", "supportive"),suggested_action=_suggest_action(req.risk_status, req.weak_topics),)9 unmodified linesdef _fallback_message(risk_status: Optional[str]) -> str:"""Template-based fallback when DeepSeek is unavailable."""fallbacks = {"safe": "Great work! You're on track. Keep up the momentum with today's practice.","watch": "I noticed you've been working hard. Let's take a moment to review any tricky concepts together.","intervene": "Your teacher and I are here to help. Let's focus on one topic at a time — you've got this.","critical": "I'm worried about your progress. Please reach out to your teacher or start a remedial module today.","at_risk": "Your learning path is paused until your teacher reviews your progress. In the meantime, review your completed lessons.",}return fallbacks.get(risk_status or "", "Keep going! Every problem you solve makes you stronger.")def _suggest_action(risk_status: Optional[str], weak_topics: Optional[list]) -> Optional[str]:"""Suggest a concrete next action based on status."""if risk_status == "safe":return "Try a bonus challenge to stretch your skills."if risk_status == "watch":return "Review the hint for your last incorrect answer."if risk_status == "intervene":topic = weak_topics[0] if weak_topics else "your weakest topic"return f"Start the remedial module on {topic}."if risk_status in ("critical", "at_risk"):return "Contact your teacher or start a 1-on-1 review session."return None6 unmodified lines7891011121314151617181917 unmodified lines373839404142434445464748495044 unmodified lines95969798991001013 unmodified lines1051061071081091101119 unmodified lines1211221231241251261271281291301311321331341351361371381391401411421431441451466 unmodified linesimport loggingimport osfrom typing import Dict, Optionalfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModelfrom services.wri_service import ESCALATION_RISK_STATUSES, RiskLevel, normalize_risk_bandlogger = logging.getLogger("mathpulse.tutor_checkin")router = APIRouter(prefix="/api/tutor-checkin", tags=["tutor-checkin"])17 unmodified linesdef _build_checkin_prompt(req: TutorCheckinRequest) -> str:"""Build a contextual prompt for DeepSeek to generate a tutor check-in."""name = req.student_name or "Student"status: RiskLevel = normalize_risk_band(req.risk_status)wri = req.wriweak = req.weak_topics or []activity = req.recent_activity or "No recent activity recorded."weak_topics_str = ", ".join(weak) if weak else "none identified"tone_map: Dict[RiskLevel, str] = {"safe": "encouraging and celebratory","watch": "gentle and supportive","intervene": "caring but firm",44 unmodified linesmessage = response.strip() if response else _fallback_message(req.risk_status)tone_map: Dict[RiskLevel, str] = {"safe": "encouraging","watch": "supportive","intervene": "caring-but-firm",3 unmodified linesreturn TutorCheckinResponse(message=message,tone=tone_map.get(normalize_risk_band(req.risk_status), "supportive"),suggested_action=_suggest_action(req.risk_status, req.weak_topics),)9 unmodified linesdef _fallback_message(risk_status: Optional[str]) -> str:"""Template-based fallback when DeepSeek is unavailable."""fallbacks: Dict[RiskLevel, str] = {"safe": "Great work! You're on track. Keep up the momentum with today's practice.","watch": "I noticed you've been working hard. Let's take a moment to review any tricky concepts together.","intervene": "Your teacher and I are here to help. Let's focus on one topic at a time — you've got this.","critical": "I'm worried about your progress. Please reach out to your teacher or start a remedial module today.","at_risk": "Your learning path is paused until your teacher reviews your progress. In the meantime, review your completed lessons.",}return fallbacks.get(normalize_risk_band(risk_status), "Keep going! Every problem you solve makes you stronger.")def _suggest_action(risk_status: Optional[str], weak_topics: Optional[list]) -> Optional[str]:"""Suggest a concrete next action based on status."""band = normalize_risk_band(risk_status)if band == "safe":return "Try a bonus challenge to stretch your skills."if band == "watch":return "Review the hint for your last incorrect answer."if band == "intervene":topic = weak_topics[0] if weak_topics else "your weakest topic"return f"Start the remedial module on {topic}."if band in ESCALATION_RISK_STATUSES:return "Contact your teacher or start a 1-on-1 review session."return None
13 unmodified lines14151617181926 unmodified lines4647484950515236 unmodified lines899091929394959697989910010110210310410510610710873 unmodified lines18218318418518618718818919019119219319419513 unmodified linesfrom pydantic import BaseModel, Fieldlogger = logging.getLogger("mathpulse.class_analytics")# ─── Firestore helper ──────────────────────────────────────────────────────26 unmodified linesavg_score: float = 0.0quiz_attempt_count: int = 0last_active: Optional[str] = Nonerisk_level: Literal["safe", "watch", "intervene", "critical", "at_risk", "pending_assessment"] = "pending_assessment"engagement_level: Literal["Low", "Medium", "High"] = "Low"weakest_topic: Optional[str] = Noneaccuracy_by_topic: Dict[str, float] = Field(default_factory=dict)36 unmodified lines# ─── Risk & Engagement Classification ─────────────────────────────────────def classify_risk(avg_score: float, quiz_count: int, days_since_active: Optional[int]) -> str:"""Map to WRI status bands. When no WRI is available, estimate from avg_score."""if quiz_count == 0:return "pending_assessment"# Approximate WRI bands from avg_score (actual WRI uses D, G, P weights)if avg_score >= 88:return "safe"if avg_score >= 80:return "watch"if avg_score >= 75:return "intervene"if avg_score >= 68:return "critical"return "at_risk"def classify_engagement(days_since_active: Optional[int], recent_quiz_count: int) -> str:73 unmodified linesparticipation_rate = (active_count / student_count * 100) if student_count > 0 else 0.0# Attention = intervene + critical + at_riskattention_count = sum(1 for s in student_summaries if s.risk_level in ("intervene", "critical", "at_risk"))# Topic performancetopic_perf = self._compute_topic_performance(student_summaries)# Risk distributionfrom services.wri_service import normalize_risk_bandrisk_dist = {"safe": 0, "watch": 0, "intervene": 0, "critical": 0, "at_risk": 0, "pending_assessment": 0}for s in student_summaries:# Prefer stored WRI status from managedStudents if availablestored_status = None13 unmodified lines141516171819202122232425262726 unmodified lines5455565758596036 unmodified lines97989910010110210310410510610773 unmodified lines18118218318418518618718818919019119219313 unmodified linesfrom pydantic import BaseModel, Fieldfrom services.wri_service import (ATTENTION_RISK_STATUSES,RiskLevel,band_for_score,empty_risk_distribution,normalize_risk_band,)logger = logging.getLogger("mathpulse.class_analytics")# ─── Firestore helper ──────────────────────────────────────────────────────26 unmodified linesavg_score: float = 0.0quiz_attempt_count: int = 0last_active: Optional[str] = Nonerisk_level: RiskLevel = "pending_assessment"engagement_level: Literal["Low", "Medium", "High"] = "Low"weakest_topic: Optional[str] = Noneaccuracy_by_topic: Dict[str, float] = Field(default_factory=dict)36 unmodified lines# ─── Risk & Engagement Classification ─────────────────────────────────────def classify_risk(avg_score: float, quiz_count: int, days_since_active: Optional[int]) -> RiskLevel:"""Map to WRI status bands. When no WRI is available, estimate from avg_score."""if quiz_count == 0:return "pending_assessment"return band_for_score(avg_score)def classify_engagement(days_since_active: Optional[int], recent_quiz_count: int) -> str:73 unmodified linesparticipation_rate = (active_count / student_count * 100) if student_count > 0 else 0.0# Attention = intervene + critical + at_riskattention_count = sum(1 for s in student_summaries if s.risk_level in ATTENTION_RISK_STATUSES)# Topic performancetopic_perf = self._compute_topic_performance(student_summaries)# Risk distributionrisk_dist = empty_risk_distribution()for s in student_summaries:# Prefer stored WRI status from managedStudents if availablestored_status = None
12 unmodified lines13141516171848 unmodified lines676869707172739 unmodified lines8384858687888990919293949596979899100101140 unmodified lines24224324424524624724812 unmodified linesfrom pydantic import BaseModel, Fieldlogger = logging.getLogger("mathpulse.intervention_engine")# ─── Firestore helper ──────────────────────────────────────────────────────48 unmodified linesstudent_name: str = ""grade_level: str = ""section: str = ""risk_level: str = "pending_assessment"avg_score: float = 0.0engagement_level: Literal["Low", "Medium", "High"] = "Low"last_active: Optional[str] = None9 unmodified lines# ─── Risk & Engagement Classification ─────────────────────────────────────def _classify_risk(avg_score: float, quiz_count: int, days_since_active: Optional[int] = None) -> str:"""Canonical 5-band DepEd classification when WRI is not directly available."""if quiz_count == 0:return "pending_assessment"if avg_score >= 88:return "safe"if avg_score >= 80:return "watch"if avg_score >= 75:return "intervene"if avg_score >= 68:return "critical"return "at_risk"def _classify_engagement(days_since_active: Optional[int], recent_quiz_count: int, lessons_completed: int = 0) -> str:140 unmodified linesor student_data.get("wriRiskBand"))if raw_risk:from services.wri_service import normalize_risk_bandrisk_level = normalize_risk_band(raw_risk)else:risk_level = _classify_risk(avg_score, quiz_count, days_since_active)12 unmodified lines131415161718192048 unmodified lines697071727374759 unmodified lines8586878889909192939495140 unmodified lines23623723823924024112 unmodified linesfrom pydantic import BaseModel, Fieldfrom services.wri_service import RiskLevel, band_for_score, normalize_risk_bandlogger = logging.getLogger("mathpulse.intervention_engine")# ─── Firestore helper ──────────────────────────────────────────────────────48 unmodified linesstudent_name: str = ""grade_level: str = ""section: str = ""risk_level: RiskLevel = "pending_assessment"avg_score: float = 0.0engagement_level: Literal["Low", "Medium", "High"] = "Low"last_active: Optional[str] = None9 unmodified lines# ─── Risk & Engagement Classification ─────────────────────────────────────def _classify_risk(avg_score: float, quiz_count: int, days_since_active: Optional[int] = None) -> RiskLevel:"""Canonical 5-band DepEd classification when WRI is not directly available."""if quiz_count == 0:return "pending_assessment"return band_for_score(avg_score)def _classify_engagement(days_since_active: Optional[int], recent_quiz_count: int, lessons_completed: int = 0) -> str:140 unmodified linesor student_data.get("wriRiskBand"))if raw_risk:risk_level = normalize_risk_band(raw_risk)else:risk_level = _classify_risk(avg_score, quiz_count, days_since_active)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195"""Shared extraction of JSON payloads from LLM responses.
LLM providers wrap structured output in prose, markdown fences, thinkingblocks, smart quotes, trailing commas, or Python-literal syntax. Every routethat consumes model-produced JSON needs the same recovery ladder; this moduleis the single implementation so a payload that parses on one route parses onall of them.
Callers keep their own error type: this module raises ``LLMJsonError`` and eachroute translates it into its existing ``HTTPException``/``ValueError``."""
from __future__ import annotations
import astimport jsonimport refrom typing import Any, Dict, Iterable, List, Optional
__all__ = [ "LLMJsonError", "strip_reasoning", "extract_json_blocks", "normalize_candidate", "loads_jsonish", "extract_json_value", "extract_json_object", "extract_json_list", "coerce_dict_list", "extract_dict_list", "collect_dict_objects",]
# Wrapper keys models use when they nest a list inside an envelope object._LIST_WRAPPER_KEYS = ("questions", "items", "data", "results", "quiz", "practice_questions")
class LLMJsonError(ValueError): """Raised when no parseable JSON payload can be recovered from model output."""
_THINKING_PATTERNS = ( re.compile(r"<think(?:ing)?>[\s\S]*?</think(?:ing)?>", re.IGNORECASE), re.compile(r"</think(?:ing)?>", re.IGNORECASE), re.compile(r"^\s*thinking\s*process\s*:\s*", re.IGNORECASE), re.compile(r"^\s*json\s*[:\-]?\s*", re.IGNORECASE),)
def strip_reasoning(text: str) -> str: """Remove thinking blocks and reasoning preambles that precede JSON.""" cleaned = (text or "").strip() for pattern in _THINKING_PATTERNS: cleaned = pattern.sub("", cleaned) return cleaned.strip()
def extract_json_blocks(text: str) -> List[str]: """Return every balanced ``{...}``/``[...]`` span, ignoring brackets inside strings.""" blocks: List[str] = [] starts = [index for index, char in enumerate(text) if char in "[{"] for start in starts: opener = text[start] closer = "]" if opener == "[" else "}" depth = 0 in_string = False escaped = False for index in range(start, len(text)): char = text[index] if in_string: if escaped: escaped = False elif char == "\\": escaped = True elif char == '"': in_string = False continue if char == '"': in_string = True continue if char == opener: depth += 1 elif char == closer: depth -= 1 if depth == 0: blocks.append(text[start : index + 1]) break return blocks
def normalize_candidate(candidate: str) -> str: """Repair the defects models introduce into otherwise valid JSON.""" normalized = candidate.strip().lstrip("\ufeff") # Drop markdown code fences that wrap the payload. normalized = re.sub(r"^```[a-zA-Z0-9_-]*\s*\n?", "", normalized) normalized = re.sub(r"\n?\s*```\s*$", "", normalized) normalized = ( normalized.replace("\u201c", '"') .replace("\u201d", '"') .replace("\u2018", "'") .replace("\u2019", "'") ) # Drop trailing commas before an object/array closer. return re.sub(r",(\s*[}\]])", r"\1", normalized)
def loads_jsonish(candidate: str) -> Any: """Parse a candidate as JSON, falling back to a Python-literal payload.""" normalized = normalize_candidate(candidate) try: return json.loads(normalized) except json.JSONDecodeError: pass
python_like = re.sub(r"\btrue\b", "True", normalized, flags=re.IGNORECASE) python_like = re.sub(r"\bfalse\b", "False", python_like, flags=re.IGNORECASE) python_like = re.sub(r"\bnull\b", "None", python_like, flags=re.IGNORECASE) try: return ast.literal_eval(python_like) except (ValueError, SyntaxError): return None
def extract_json_value(raw: str, *, preferred: type | tuple[type, ...] | None = None) -> Any: """Recover the first parseable JSON value from a raw model response.
``preferred`` restricts acceptance to a JSON type (``dict``/``list``); when omitted, the first successfully parsed block wins. Raises ``LLMJsonError`` if nothing parses. """ cleaned = strip_reasoning(raw)
for candidate in extract_json_blocks(cleaned): parsed = loads_jsonish(candidate) if parsed is None: continue if preferred is None or isinstance(parsed, preferred): return parsed
# Models sometimes emit bare JSON with no envelope; try the whole text. parsed = loads_jsonish(cleaned) if parsed is not None and (preferred is None or isinstance(parsed, preferred)): return parsed
raise LLMJsonError("No parseable JSON payload found in model response")
def extract_json_object(raw: str) -> Optional[Dict[str, Any]]: """Recover a JSON object, or ``None`` when the response holds no object.""" try: parsed = extract_json_value(raw, preferred=dict) except LLMJsonError: return None return parsed
def extract_json_list(raw: str) -> Optional[List[Any]]: """Recover a JSON array, or ``None`` when the response holds no array.""" try: parsed = extract_json_value(raw, preferred=list) except LLMJsonError: return None return parsed
def coerce_dict_list(value: Any) -> List[Dict[str, Any]]: """Keep only the mapping entries of a list.""" if not isinstance(value, list): return [] return [item for item in value if isinstance(item, dict)]
def extract_dict_list(payload: Any, wrapper_keys: Iterable[str] = _LIST_WRAPPER_KEYS) -> List[Dict[str, Any]]: """Unwrap a list of objects from either a bare array or an envelope object.""" if isinstance(payload, list): return coerce_dict_list(payload) if isinstance(payload, dict): for key in wrapper_keys: nested = payload.get(key) if isinstance(nested, list): return coerce_dict_list(nested) return []
def collect_dict_objects(raw: str) -> List[Dict[str, Any]]: """Salvage every individually parseable object, for truncated responses.""" cleaned = strip_reasoning(raw) objects: List[Dict[str, Any]] = [] for candidate in extract_json_blocks(cleaned): if not candidate.lstrip().startswith("{"): continue parsed = loads_jsonish(candidate) if isinstance(parsed, dict): objects.append(parsed) return objects17 unmodified lines181920212223101 unmodified lines12512612712812913013125 unmodified lines157158159160161162163299 unmodified lines46346446546646746846917 unmodified linesfrom pydantic import BaseModel, Fieldlogger = logging.getLogger("mathpulse.pipeline")# ─── Firestore ─────────────────────────────────────────────────────────────101 unmodified linesweights = managed.get("weights") or profile.get("wri_weights") or {"w1": 0.30, "w2": 0.40, "w3": 0.30}if d is not None and event.event_type != "session":from services.wri_service import compute_wriwri_result = compute_wri(d=d, g=g, p=new_p, weights=weights)previous_status = profile.get("risk_status", "pending_assessment")25 unmodified lines# 6b. Proactive tutor nudge (fire-and-forget, non-blocking)new_status = profile.get("risk_status", "safe")if new_status in ("watch", "intervene", "critical", "at_risk"):weak_topics = (profile.get("quiz_performance", {}).get("lowest_accuracy_topics", [])or profile.get("diagnostic", {}).get("weak_topics", [])299 unmodified linesreturn Falseexcept Exception:passreturn event.event_type in ("quiz", "battle") and result.new_risk_status in ("critical", "at_risk")async def _generate_ai_context(self, profile: Dict, event: StudentActivityEvent) -> Optional[Dict]:"""Call DeepSeek for AI context generation."""17 unmodified lines1819202122232425101 unmodified lines12712812913013113225 unmodified lines158159160161162163164299 unmodified lines46446546646746846947017 unmodified linesfrom pydantic import BaseModel, Fieldfrom services.wri_service import ESCALATION_RISK_STATUSES, FLAGGED_RISK_STATUSES, compute_wrilogger = logging.getLogger("mathpulse.pipeline")# ─── Firestore ─────────────────────────────────────────────────────────────101 unmodified linesweights = managed.get("weights") or profile.get("wri_weights") or {"w1": 0.30, "w2": 0.40, "w3": 0.30}if d is not None and event.event_type != "session":wri_result = compute_wri(d=d, g=g, p=new_p, weights=weights)previous_status = profile.get("risk_status", "pending_assessment")25 unmodified lines# 6b. Proactive tutor nudge (fire-and-forget, non-blocking)new_status = profile.get("risk_status", "safe")if new_status in FLAGGED_RISK_STATUSES:weak_topics = (profile.get("quiz_performance", {}).get("lowest_accuracy_topics", [])or profile.get("diagnostic", {}).get("weak_topics", [])299 unmodified linesreturn Falseexcept Exception:passreturn event.event_type in ("quiz", "battle") and result.new_risk_status in ESCALATION_RISK_STATUSESasync def _generate_ai_context(self, profile: Dict, event: StudentActivityEvent) -> Optional[Dict]:"""Call DeepSeek for AI context generation."""
7 unmodified lines8910111213119 unmodified lines1331341351361371381397 unmodified linesimport loggingfrom datetime import datetime, timezonelogger = logging.getLogger("mathpulse.tutor_nudge")NUDGE_COOLDOWN_HOURS = 24119 unmodified linesdata = managed_snap.to_dict() or {}risk_status = data.get("riskStatus")if risk_status not in ("watch", "intervene", "critical", "at_risk"):return None# Get weak topics from student_profiles7 unmodified lines89101112131415119 unmodified lines1351361371381391401417 unmodified linesimport loggingfrom datetime import datetime, timezonefrom services.wri_service import FLAGGED_RISK_STATUSESlogger = logging.getLogger("mathpulse.tutor_nudge")NUDGE_COOLDOWN_HOURS = 24119 unmodified linesdata = managed_snap.to_dict() or {}risk_status = data.get("riskStatus")if risk_status not in FLAGGED_RISK_STATUSES:return None# Get weak topics from student_profiles
17 unmodified lines1819202122232425262728293031323371 unmodified lines10510610710810911011111211311411511611711811912012117 unmodified lineswith official DepEd grading policies."""from typing import OptionalDEFAULT_WEIGHTS = {"w1": 0.30, "w2": 0.40, "w3": 0.30}WEIGHT_TOLERANCE = 0.001CANONICAL_RISK_BANDS = ("safe", "watch", "intervene", "critical", "at_risk")CANONICAL_RISK_STATUSES = ("safe", "watch", "intervene", "critical", "at_risk", "pending_assessment")def normalize_risk_band(band: Optional[str]) -> str:"""Normalize legacy or mixed-case risk status strings to canonical 5-band WRI format."""if not band:return "pending_assessment"71 unmodified lines# Compute WRIwri = round((w1 * d) + (w2 * g_val) + (w3 * p_val), 2)# 5-band prevention-first classificationif wri >= 88:status = "safe"elif wri >= 80:status = "watch"elif wri >= 75:status = "intervene"elif wri >= 68:status = "critical"else:status = "at_risk"return {"wri": wri,17 unmodified lines181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666771 unmodified lines13914014114214314414514617 unmodified lineswith official DepEd grading policies."""from typing import Dict, Literal, Optional, get_argsDEFAULT_WEIGHTS = {"w1": 0.30, "w2": 0.40, "w3": 0.30}WEIGHT_TOLERANCE = 0.001# ─── Canonical risk vocabulary ────────────────────────────────────────────# Single owner. Every module that needs the bands, one of the subsets below,# or a zeroed distribution imports from here instead of re-transcribing the# closed set. Drift here previously left stale counters compiling silently.RiskLevel = Literal["safe", "watch", "intervene", "critical", "at_risk", "pending_assessment"]CANONICAL_RISK_STATUSES: tuple = get_args(RiskLevel)CANONICAL_RISK_BANDS: tuple = tuple(status for status in CANONICAL_RISK_STATUSES if status != "pending_assessment")# Above the DepEd floor — the system adjusts difficulty or nudges the student.FLAGGED_RISK_STATUSES: tuple = ("watch", "intervene", "critical", "at_risk")# Approaching or below the DepEd passing mark — the teacher is notified.ATTENTION_RISK_STATUSES: tuple = ("intervene", "critical", "at_risk")# Escalation-worthy — structured intervention or teacher review required.ESCALATION_RISK_STATUSES: tuple = ("critical", "at_risk")# DepEd DO No. 8, s. 2015 — prevention-first bands. See the module docstring._BAND_THRESHOLDS: tuple = ((88.0, "safe"),(80.0, "watch"),(75.0, "intervene"),(68.0, "critical"),)def band_for_score(score: float) -> RiskLevel:"""Classify a 0-100 WRI score into the canonical 5-band DepEd scale."""for threshold, band in _BAND_THRESHOLDS:if score >= threshold:return bandreturn "at_risk"def empty_risk_distribution() -> Dict[str, int]:"""Zeroed counter keyed by every canonical risk status."""return dict.fromkeys(CANONICAL_RISK_STATUSES, 0)def normalize_risk_band(band: Optional[str]) -> RiskLevel:"""Normalize legacy or mixed-case risk status strings to canonical 5-band WRI format."""if not band:return "pending_assessment"71 unmodified lines# Compute WRIwri = round((w1 * d) + (w2 * g_val) + (w3 * p_val), 2)# 5-band prevention-first classification (thresholds owned by band_for_score)status = band_for_score(wri)return {"wri": wri,
1234567891011121373 unmodified lines87888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""pytest conftest: force backend/ to sys.path[0] and prevent stale services shadow.Project root has stale services/ dir (with __init__.py) that shadowsbackend/services/ and lacks several service modules needed by routes/tests.This conftest:1. Ensures backend/ is at sys.path[0]2. Evicts any stale 'services' package from sys.modules so subsequentimports resolve to backend/services/ instead of the project-root copy.3. Mocks Firebase Admin auth so test tokens (Bearer mock_token_<uid>)work without real Firebase credentials."""73 unmodified linessys.path.remove(_backend_dir)sys.path.insert(0, _backend_dir)# 2. Evict stale 'services' package from import cache.# The project root services/ has __init__.py making it a regular package,# and it shadows backend/services/ in sys.path resolution._keys_to_evict = [k for k in sys.modules if k == "services" or k.startswith("services.")]for k in _keys_to_evict:del sys.modules[k]def _evict_stale_services():"""Remove stale 'services' entry from sys.modules if it exists."""for k in list(sys.modules.keys()):if k == "services" or k.startswith("services."):# Only evict if it's NOT the backend/services/* versionmod = sys.modules[k]mod_file = getattr(mod, "__file__", "") or ""if _backend_dir in mod_file:continue # keep backend/services/* entriesdel sys.modules[k]@pytest.fixture(autouse=True)def _auto_evict_stale_services():"""Re-evict stale services before every test to prevent cross-file pollution."""_evict_stale_services()yield@pytest.fixture(autouse=True)def _mock_firebase_auth():"""Re-apply Firebase auth mock before every test.1234567873 unmodified lines828384858687"""pytest conftest: force backend/ to sys.path[0] and mock Firebase Admin auth.This conftest:1. Ensures backend/ is at sys.path[0] so `services.*` resolves to backend/services/.2. Mocks Firebase Admin auth so test tokens (Bearer mock_token_<uid>)work without real Firebase credentials."""73 unmodified linessys.path.remove(_backend_dir)sys.path.insert(0, _backend_dir)@pytest.fixture(autouse=True)def _mock_firebase_auth():"""Re-apply Firebase auth mock before every test.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142"""Tests for the shared LLM JSON envelope recovery used by every AI route."""
from __future__ import annotations
import pytest
from services.llm_json import ( LLMJsonError, coerce_dict_list, collect_dict_objects, extract_dict_list, extract_json_blocks, extract_json_list, extract_json_object, extract_json_value, loads_jsonish, normalize_candidate, strip_reasoning,)
class TestStripReasoning: def test_removes_think_blocks(self) -> None: assert strip_reasoning("<think>hmm</think>{\"a\": 1}") == '{"a": 1}'
def test_removes_unpaired_closing_tag(self) -> None: assert strip_reasoning('</think>{"a": 1}') == '{"a": 1}'
def test_removes_reasoning_preamble(self) -> None: assert strip_reasoning('Thinking process: {"a": 1}') == '{"a": 1}'
def test_plain_text_is_unchanged(self) -> None: assert strip_reasoning(" plain ") == "plain"
class TestExtractJsonBlocks: def test_finds_outer_and_nested_blocks(self) -> None: # The scanner starts at every opener; callers take the first usable block. blocks = extract_json_blocks('pre {"a": {"b": 1}} post') assert blocks[0] == '{"a": {"b": 1}}' assert '{"b": 1}' in blocks
def test_ignores_brackets_inside_strings(self) -> None: assert extract_json_blocks('{"a": "}"}') == ['{"a": "}"}']
def test_finds_array(self) -> None: assert extract_json_blocks("see [1, 2] now") == ["[1, 2]"]
def test_returns_empty_for_no_json(self) -> None: assert extract_json_blocks("no json here") == []
class TestNormalizeCandidate: def test_replaces_smart_quotes(self) -> None: assert normalize_candidate('{\u201ca\u201d: 1}') == '{"a": 1}'
def test_drops_trailing_comma(self) -> None: assert normalize_candidate('{"a": 1,}') == '{"a": 1}'
def test_strips_bom(self) -> None: assert normalize_candidate("\ufeff{}") == "{}"
class TestLoadsJsonish: def test_parses_valid_json(self) -> None: assert loads_jsonish('{"a": 1}') == {"a": 1}
def test_parses_fenced_json(self) -> None: assert loads_jsonish('```json\n{"a": 1}\n```') == {"a": 1}
def test_parses_python_literals(self) -> None: assert loads_jsonish("{'a': True, 'b': None}") == {"a": True, "b": None}
def test_returns_none_for_garbage(self) -> None: assert loads_jsonish("not json at all") is None
class TestExtractJsonValue: def test_prefers_first_parseable_object(self) -> None: assert extract_json_value('{"a": 1} trailing {"b": 2}', preferred=dict) == {"a": 1}
def test_recovers_from_prose_wrapper(self) -> None: prose = 'Sure! Here is the payload:\n```json\n{"a": 1}\n```\nHope that helps.' assert extract_json_value(prose, preferred=dict) == {"a": 1}
def test_recovers_from_thinking_block(self) -> None: assert extract_json_value('<think>...</think>\n[{"q": 1}]', preferred=list) == [{"q": 1}]
def test_raises_when_nothing_parses(self) -> None: with pytest.raises(LLMJsonError): extract_json_value("no json here")
def test_raises_when_type_not_preferred(self) -> None: with pytest.raises(LLMJsonError): extract_json_value("[1, 2]", preferred=dict)
class TestTypedHelpers: def test_extract_json_object_returns_none_on_array(self) -> None: assert extract_json_object("[1]") is None
def test_extract_json_list_returns_none_on_object(self) -> None: assert extract_json_list('{"a": 1}') is None
def test_extract_json_object_parses(self) -> None: assert extract_json_object('{"a": 1}') == {"a": 1}
class TestDictListExtraction: def test_coerce_filters_non_dicts(self) -> None: assert coerce_dict_list([{"a": 1}, "x", 2, None]) == [{"a": 1}]
def test_coerce_rejects_non_list(self) -> None: assert coerce_dict_list({"a": 1}) == []
def test_extract_dict_list_from_bare_array(self) -> None: assert extract_dict_list([{"a": 1}]) == [{"a": 1}]
def test_extract_dict_list_unwraps_questions_key(self) -> None: assert extract_dict_list({"questions": [{"q": 1}]}) == [{"q": 1}]
def test_extract_dict_list_unwraps_practice_questions_key(self) -> None: assert extract_dict_list({"practice_questions": [{"q": 1}]}) == [{"q": 1}]
def test_extract_dict_list_prefers_questions_over_data(self) -> None: payload = {"data": [{"d": 1}], "questions": [{"q": 1}]} assert extract_dict_list(payload) == [{"q": 1}]
def test_extract_dict_list_returns_empty_for_unknown_envelope(self) -> None: assert extract_dict_list({"unknown": [{"q": 1}]}) == []
class TestCollectDictObjects: def test_salvages_multiple_objects_from_truncated_output(self) -> None: truncated = '{"question": "a", "correct": "A"} {"question": "b", "correct": "B"}' assert collect_dict_objects(truncated) == [ {"question": "a", "correct": "A"}, {"question": "b", "correct": "B"}, ]
def test_ignores_arrays(self) -> None: assert collect_dict_objects("[1, 2]") == []config/env.sample+1
main.py+20-105
routes/admin_routes.py+3-2
routes/class_analytics_routes.py+3-1
routes/diagnostic.py+18-21
routes/practice.py+14-22
routes/quiz_generation_routes.py+12-25
routes/rag_routes.py+5-11
routes/tutor_checkin.py+14-11
services/class_analytics_engine.py+13-15
services/intervention_engine.py+5-12
services/llm_json.pyAdded+195
services/student_intelligence_pipeline.py+4-3
services/tutor_nudge_service.py+3-1
services/wri_service.py+40-15
tests/conftest.py+3-35
tests/test_llm_json.pyAdded+142