github-actions[bot] commited on
Commit
394b734
·
1 Parent(s): 3d1319b

deploy: backend from 99b3c80

Browse files
config/env.sample CHANGED
@@ -3,6 +3,7 @@ DEEPSEEK_API_KEY=your_deepseek_api_key_here
3
  DEEPSEEK_BASE_URL=https://api.deepseek.com
4
  DEEPSEEK_MODEL=deepseek-chat
5
  DEEPSEEK_REASONER_MODEL=deepseek-reasoner
 
6
 
7
  # Inference provider selection
8
  # CI trigger marker: keep this file touchable to force backend deploy workflow runs when needed.
 
3
  DEEPSEEK_BASE_URL=https://api.deepseek.com
4
  DEEPSEEK_MODEL=deepseek-chat
5
  DEEPSEEK_REASONER_MODEL=deepseek-reasoner
6
+ DEEPSEEK_ENABLED=true
7
 
8
  # Inference provider selection
9
  # CI trigger marker: keep this file touchable to force backend deploy workflow runs when needed.
main.py CHANGED
@@ -84,6 +84,13 @@ from services.inference_client import (
84
  )
85
  from services.deterministic_cache import DeterministicResponseCache
86
  from services.logging_utils import log_model_call
 
 
 
 
 
 
 
87
  from services.email_service import create_email_service_from_env, EmailMessagePayload
88
  from services.user_provisioning_service import (
89
  AdminCreateUserInput,
@@ -10779,102 +10786,15 @@ def _distribute_questions(
10779
 
10780
 
10781
  def _parse_quiz_json(raw: str) -> List[Dict[str, Any]]:
10782
- """Robustly extract a JSON array of quiz questions from LLM output."""
10783
- cleaned = raw.strip()
10784
- # Remove markdown fences
10785
- cleaned = re.sub(r"^```(?:json)?\s*\n?", "", cleaned, flags=re.IGNORECASE)
10786
- cleaned = re.sub(r"\n?```\s*$", "", cleaned)
10787
- cleaned = cleaned.strip()
10788
-
10789
- # Remove known reasoning wrappers and preambles that can precede JSON.
10790
- cleaned = re.sub(r"<think>[\s\S]*?</think>", "", cleaned, flags=re.IGNORECASE)
10791
- # Remove common reasoning preambles before JSON output.
10792
- cleaned = re.sub(r"^\s*thinking\s*process\s*:\s*", "", cleaned, flags=re.IGNORECASE)
10793
- cleaned = re.sub(r"^\s*json\s*[:\-]?\s*", "", cleaned, flags=re.IGNORECASE)
10794
-
10795
- def _extract_json_blocks(text: str) -> List[str]:
10796
- blocks: List[str] = []
10797
- starts = [i for i, ch in enumerate(text) if ch in "[{"]
10798
- for start in starts:
10799
- opener = text[start]
10800
- closer = "]" if opener == "[" else "}"
10801
- depth = 0
10802
- in_string = False
10803
- escaped = False
10804
- for idx in range(start, len(text)):
10805
- ch = text[idx]
10806
- if in_string:
10807
- if escaped:
10808
- escaped = False
10809
- elif ch == "\\":
10810
- escaped = True
10811
- elif ch == '"':
10812
- in_string = False
10813
- continue
10814
-
10815
- if ch == '"':
10816
- in_string = True
10817
- continue
10818
-
10819
- if ch == opener:
10820
- depth += 1
10821
- elif ch == closer:
10822
- depth -= 1
10823
- if depth == 0:
10824
- blocks.append(text[start : idx + 1])
10825
- break
10826
- return blocks
10827
-
10828
- def _normalize_candidate(candidate: str) -> str:
10829
- normalized = candidate.strip().lstrip("\ufeff")
10830
- normalized = (
10831
- normalized
10832
- .replace("\u201c", '"')
10833
- .replace("\u201d", '"')
10834
- .replace("\u2018", "'")
10835
- .replace("\u2019", "'")
10836
- )
10837
- # Remove trailing commas before object/array closers.
10838
- normalized = re.sub(r",(\s*[}\]])", r"\1", normalized)
10839
- return normalized
10840
-
10841
- def _jsonish_loads(candidate: str) -> Any:
10842
- normalized = _normalize_candidate(candidate)
10843
- try:
10844
- return json.loads(normalized)
10845
- except json.JSONDecodeError:
10846
- pass
10847
-
10848
- # Fallback for Python-literal style payloads using single quotes / True / None.
10849
- python_like = re.sub(r"\btrue\b", "True", normalized, flags=re.IGNORECASE)
10850
- python_like = re.sub(r"\bfalse\b", "False", python_like, flags=re.IGNORECASE)
10851
- python_like = re.sub(r"\bnull\b", "None", python_like, flags=re.IGNORECASE)
10852
- try:
10853
- return ast.literal_eval(python_like)
10854
- except (ValueError, SyntaxError):
10855
- return None
10856
-
10857
- def _coerce_question_list(value: Any) -> List[Dict[str, Any]]:
10858
- if not isinstance(value, list):
10859
- return []
10860
- return [item for item in value if isinstance(item, dict)]
10861
-
10862
- def _extract_question_list(payload: Any) -> List[Dict[str, Any]]:
10863
- if isinstance(payload, list):
10864
- return _coerce_question_list(payload)
10865
 
10866
- if isinstance(payload, dict):
10867
- for key in ("questions", "quiz", "items", "data"):
10868
- nested = payload.get(key)
10869
- if isinstance(nested, list):
10870
- return _coerce_question_list(nested)
10871
-
10872
- return []
10873
 
10874
- # Try every balanced JSON-ish block and accept known payload wrappers.
10875
- for candidate in _extract_json_blocks(cleaned):
10876
- parsed = _jsonish_loads(candidate)
10877
- extracted = _extract_question_list(parsed)
10878
  if extracted:
10879
  return extracted
10880
 
@@ -10882,21 +10802,16 @@ def _parse_quiz_json(raw: str) -> List[Dict[str, Any]]:
10882
  arr_start = cleaned.find("[")
10883
  arr_end = cleaned.rfind("]") + 1
10884
  if arr_start >= 0 and arr_end > arr_start:
10885
- parsed = _jsonish_loads(cleaned[arr_start:arr_end])
10886
- extracted = _extract_question_list(parsed)
10887
  if extracted:
10888
  return extracted
10889
 
10890
  # Fallback: salvage individually parseable question-like objects.
10891
- objects: List[Dict[str, Any]] = []
10892
- for candidate in _extract_json_blocks(cleaned):
10893
- if not candidate.lstrip().startswith("{"):
10894
- continue
10895
- parsed = _jsonish_loads(candidate)
10896
- if isinstance(parsed, dict) and str(parsed.get("question") or "").strip():
10897
- objects.append(parsed)
10898
-
10899
- return objects
10900
 
10901
 
10902
  async def _repair_quiz_json_with_llm(
 
84
  )
85
  from services.deterministic_cache import DeterministicResponseCache
86
  from services.logging_utils import log_model_call
87
+ from services.llm_json import (
88
+ collect_dict_objects,
89
+ extract_dict_list,
90
+ extract_json_blocks,
91
+ loads_jsonish,
92
+ strip_reasoning,
93
+ )
94
  from services.email_service import create_email_service_from_env, EmailMessagePayload
95
  from services.user_provisioning_service import (
96
  AdminCreateUserInput,
 
10786
 
10787
 
10788
  def _parse_quiz_json(raw: str) -> List[Dict[str, Any]]:
10789
+ """Extract a JSON array of quiz questions from LLM output.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10790
 
10791
+ Extraction and recovery live in services.llm_json so every route accepts
10792
+ the same model-produced envelope shapes.
10793
+ """
10794
+ cleaned = strip_reasoning(raw)
 
 
 
10795
 
10796
+ for candidate in extract_json_blocks(cleaned):
10797
+ extracted = extract_dict_list(loads_jsonish(candidate))
 
 
10798
  if extracted:
10799
  return extracted
10800
 
 
10802
  arr_start = cleaned.find("[")
10803
  arr_end = cleaned.rfind("]") + 1
10804
  if arr_start >= 0 and arr_end > arr_start:
10805
+ extracted = extract_dict_list(loads_jsonish(cleaned[arr_start:arr_end]))
 
10806
  if extracted:
10807
  return extracted
10808
 
10809
  # Fallback: salvage individually parseable question-like objects.
10810
+ return [
10811
+ parsed
10812
+ for parsed in collect_dict_objects(cleaned)
10813
+ if str(parsed.get("question") or "").strip()
10814
+ ]
 
 
 
 
10815
 
10816
 
10817
  async def _repair_quiz_json_with_llm(
routes/admin_routes.py CHANGED
@@ -10,6 +10,7 @@ from pydantic import BaseModel
10
 
11
  from rag.firebase_storage_loader import _init_firebase_storage, PDF_METADATA
12
  from scripts.ingest_from_storage import ingest_from_firebase_storage
 
13
  # Lazy import for audit_logger to prevent ModuleNotFoundError during test collection
14
  _audit_logger = None
15
  def _get_audit_logger():
@@ -442,7 +443,7 @@ def get_school_analytics(request: Request):
442
  profiles = list(db.collection("managedStudents").stream())
443
  total = len(profiles)
444
 
445
- wri_dist = {"safe": 0, "watch": 0, "intervene": 0, "critical": 0, "at_risk": 0, "pending_assessment": 0}
446
  wri_values = []
447
  grade_wri: dict = defaultdict(list)
448
  class_wri: dict = defaultdict(list)
@@ -483,7 +484,7 @@ def get_school_analytics(request: Request):
483
 
484
  # Recent escalations (last 24h)
485
  updated = data.get("wri_updated_at") or data.get("riskUpdatedAt")
486
- if updated and status in ("critical", "at_risk"):
487
  try:
488
  if hasattr(updated, "seconds"):
489
  dt = datetime.fromtimestamp(updated.seconds, tz=timezone.utc)
 
10
 
11
  from rag.firebase_storage_loader import _init_firebase_storage, PDF_METADATA
12
  from scripts.ingest_from_storage import ingest_from_firebase_storage
13
+ from services.wri_service import ESCALATION_RISK_STATUSES, empty_risk_distribution
14
  # Lazy import for audit_logger to prevent ModuleNotFoundError during test collection
15
  _audit_logger = None
16
  def _get_audit_logger():
 
443
  profiles = list(db.collection("managedStudents").stream())
444
  total = len(profiles)
445
 
446
+ wri_dist = empty_risk_distribution()
447
  wri_values = []
448
  grade_wri: dict = defaultdict(list)
449
  class_wri: dict = defaultdict(list)
 
484
 
485
  # Recent escalations (last 24h)
486
  updated = data.get("wri_updated_at") or data.get("riskUpdatedAt")
487
+ if updated and status in ESCALATION_RISK_STATUSES:
488
  try:
489
  if hasattr(updated, "seconds"):
490
  dt = datetime.fromtimestamp(updated.seconds, tz=timezone.utc)
routes/class_analytics_routes.py CHANGED
@@ -5,6 +5,8 @@ import logging
5
  from typing import Optional
6
  from fastapi import APIRouter, HTTPException, Request
7
 
 
 
8
  logger = logging.getLogger("mathpulse.class_analytics_routes")
9
 
10
  router = APIRouter(prefix="/api/analytics/class", tags=["class-analytics"])
@@ -53,7 +55,7 @@ async def get_class_students(
53
  )[:10]
54
  elif filter == "needs_attention":
55
  students = sorted(
56
- [s for s in students if s.risk_level in ("intervene", "critical", "at_risk")],
57
  key=lambda s: s.avg_score,
58
  )
59
 
 
5
  from typing import Optional
6
  from fastapi import APIRouter, HTTPException, Request
7
 
8
+ from services.wri_service import ATTENTION_RISK_STATUSES
9
+
10
  logger = logging.getLogger("mathpulse.class_analytics_routes")
11
 
12
  router = APIRouter(prefix="/api/analytics/class", tags=["class-analytics"])
 
55
  )[:10]
56
  elif filter == "needs_attention":
57
  students = sorted(
58
+ [s for s in students if s.risk_level in ATTENTION_RISK_STATUSES],
59
  key=lambda s: s.avg_score,
60
  )
61
 
routes/diagnostic.py CHANGED
@@ -20,6 +20,7 @@ from fastapi import APIRouter, HTTPException, Request
20
  from pydantic import BaseModel, Field
21
 
22
  from services.ai_client import CHAT_MODEL, get_deepseek_client
 
23
  from rag.curriculum_rag import retrieve_curriculum_context
24
  import firebase_admin
25
  from firebase_admin import firestore as fs
@@ -372,27 +373,23 @@ async def _call_deepseek(system_prompt: str, user_message: str, temperature: flo
372
 
373
  def _parse_questions_response(raw_response: str) -> List[Dict[str, Any]]:
374
  try:
375
- data = json.loads(raw_response)
376
- if isinstance(data, dict):
377
- for key in ("questions", "items", "data", "results"):
378
- if key in data and isinstance(data[key], list):
379
- return data[key]
380
- for key, value in data.items():
381
- if isinstance(value, list) and len(value) > 0 and isinstance(value[0], dict):
382
- if "question_text" in value[0]:
383
- return value
384
- if isinstance(data, list):
385
- return data
386
- except json.JSONDecodeError:
387
- pass
388
-
389
- import re
390
- match = re.search(r'\[.*\]', raw_response, re.DOTALL)
391
- if match:
392
- try:
393
- return json.loads(match.group())
394
- except json.JSONDecodeError:
395
- pass
396
 
397
  raise ValueError("Could not parse questions from AI response")
398
 
 
20
  from pydantic import BaseModel, Field
21
 
22
  from services.ai_client import CHAT_MODEL, get_deepseek_client
23
+ from services.llm_json import LLMJsonError, extract_json_value, extract_dict_list
24
  from rag.curriculum_rag import retrieve_curriculum_context
25
  import firebase_admin
26
  from firebase_admin import firestore as fs
 
373
 
374
  def _parse_questions_response(raw_response: str) -> List[Dict[str, Any]]:
375
  try:
376
+ payload = extract_json_value(raw_response, preferred=(dict, list))
377
+ except LLMJsonError as exc:
378
+ raise ValueError("Could not parse questions from AI response") from exc
379
+
380
+ questions = extract_dict_list(payload)
381
+ if questions:
382
+ return questions
383
+
384
+ # Envelope object whose list lives under a non-standard key.
385
+ if isinstance(payload, dict):
386
+ for value in payload.values():
387
+ if isinstance(value, list) and value and isinstance(value[0], dict):
388
+ if "question_text" in value[0]:
389
+ return value
390
+
391
+ if isinstance(payload, list):
392
+ return payload
 
 
 
 
393
 
394
  raise ValueError("Could not parse questions from AI response")
395
 
routes/practice.py CHANGED
@@ -19,6 +19,7 @@ from fastapi import APIRouter, HTTPException, Request
19
  from pydantic import BaseModel, Field
20
 
21
  from services.ai_client import CHAT_MODEL, get_deepseek_client
 
22
  import firebase_admin
23
  from firebase_admin import firestore as fs
24
 
@@ -160,34 +161,25 @@ async def _call_deepseek(system_prompt: str, user_message: str, temperature: flo
160
 
161
 
162
  def _parse_questions_response(raw: str, count: int) -> List[Dict[str, Any]]:
163
- """Extract question list from AI JSON response."""
164
- cleaned = raw.strip()
165
- cleaned = cleaned.replace("```json", "").replace("```", "").strip()
166
  try:
167
- data = json.loads(cleaned)
168
- except json.JSONDecodeError:
169
- raise HTTPException(status_code=500, detail="Failed to parse AI response. Please try again.")
170
-
171
- questions = None
172
- if isinstance(data, dict):
173
- for key in ("questions", "items", "data", "results", "practice_questions"):
174
- if key in data and isinstance(data[key], list):
175
- questions = data[key]
 
 
176
  break
177
- if questions is None and len(data) > 0:
178
- for v in data.values():
179
- if isinstance(v, list) and len(v) > 0 and isinstance(v[0], dict):
180
- questions = v
181
- break
182
- elif isinstance(data, list):
183
- questions = data
184
 
185
  if not questions:
186
  raise HTTPException(status_code=500, detail="AI response missing questions. Please try again.")
187
 
188
- # Ensure we have exactly `count` questions
189
- questions = questions[:count]
190
- return questions
191
 
192
 
193
  def _build_question_prompt(subject: str, competency: str, difficulty: str, count: int) -> tuple[str, str]:
 
19
  from pydantic import BaseModel, Field
20
 
21
  from services.ai_client import CHAT_MODEL, get_deepseek_client
22
+ from services.llm_json import LLMJsonError, extract_dict_list, extract_json_value
23
  import firebase_admin
24
  from firebase_admin import firestore as fs
25
 
 
161
 
162
 
163
  def _parse_questions_response(raw: str, count: int) -> List[Dict[str, Any]]:
164
+ """Extract the question list from an AI JSON response."""
 
 
165
  try:
166
+ payload = extract_json_value(raw, preferred=(dict, list))
167
+ except LLMJsonError as exc:
168
+ raise HTTPException(
169
+ status_code=500, detail="Failed to parse AI response. Please try again."
170
+ ) from exc
171
+
172
+ questions = extract_dict_list(payload)
173
+ if not questions and isinstance(payload, dict):
174
+ for value in payload.values():
175
+ if isinstance(value, list) and value and isinstance(value[0], dict):
176
+ questions = value
177
  break
 
 
 
 
 
 
 
178
 
179
  if not questions:
180
  raise HTTPException(status_code=500, detail="AI response missing questions. Please try again.")
181
 
182
+ return questions[:count]
 
 
183
 
184
 
185
  def _build_question_prompt(subject: str, competency: str, difficulty: str, count: int) -> tuple[str, str]:
routes/quiz_generation_routes.py CHANGED
@@ -10,10 +10,8 @@ picks up the new content via RAG retrieval.
10
 
11
  from __future__ import annotations
12
 
13
- import json
14
  import logging
15
  import random
16
- import re
17
  from typing import Any, Dict, List, Optional
18
 
19
  from fastapi import APIRouter, HTTPException, Request
@@ -28,6 +26,7 @@ from services.inference_client import (
28
  create_default_client,
29
  get_model_for_task,
30
  )
 
31
 
32
  logger = logging.getLogger("mathpulse.quiz_generation")
33
  router = APIRouter(prefix="/api/quiz", tags=["quiz-generation"])
@@ -224,30 +223,18 @@ IMPORTANT:
224
 
225
  def _parse_quiz_response(text: str, expected_count: int) -> List[Dict[str, Any]]:
226
  """Parse and validate QuizForge quiz generation response."""
227
- cleaned = text.strip()
228
-
229
- # Strip markdown fences
230
- cleaned = re.sub(r"^```json\s*", "", cleaned, flags=re.IGNORECASE)
231
- cleaned = re.sub(r"^```\s*", "", cleaned)
232
- cleaned = re.sub(r"\s*```$", "", cleaned)
233
- cleaned = cleaned.strip()
234
-
235
  try:
236
- questions = json.loads(cleaned)
237
- except json.JSONDecodeError as e:
238
- logger.error(f"Failed to parse quiz response as JSON: {e}")
239
- # Try to extract JSON array from text
240
- match = re.search(r"\[.*\]", cleaned, re.DOTALL)
241
- if match:
242
- try:
243
- questions = json.loads(match.group())
244
- except json.JSONDecodeError:
245
- raise ValueError(f"Invalid JSON in quiz response: {e}")
246
- else:
247
- raise ValueError(f"No JSON array found in quiz response")
248
-
249
- if not isinstance(questions, list):
250
- raise ValueError("Quiz response is not a JSON array")
251
 
252
  validated = []
253
  for i, q in enumerate(questions):
 
10
 
11
  from __future__ import annotations
12
 
 
13
  import logging
14
  import random
 
15
  from typing import Any, Dict, List, Optional
16
 
17
  from fastapi import APIRouter, HTTPException, Request
 
26
  create_default_client,
27
  get_model_for_task,
28
  )
29
+ from services.llm_json import LLMJsonError, extract_dict_list, extract_json_value
30
 
31
  logger = logging.getLogger("mathpulse.quiz_generation")
32
  router = APIRouter(prefix="/api/quiz", tags=["quiz-generation"])
 
223
 
224
  def _parse_quiz_response(text: str, expected_count: int) -> List[Dict[str, Any]]:
225
  """Parse and validate QuizForge quiz generation response."""
 
 
 
 
 
 
 
 
226
  try:
227
+ payload = extract_json_value(text, preferred=(list, dict))
228
+ except LLMJsonError as exc:
229
+ logger.error("Failed to parse quiz response as JSON: %s", exc)
230
+ raise ValueError(f"No JSON array found in quiz response: {exc}") from exc
231
+
232
+ if isinstance(payload, list):
233
+ questions = payload
234
+ else:
235
+ questions = extract_dict_list(payload)
236
+ if not questions:
237
+ raise ValueError("Quiz response is not a JSON array")
 
 
 
 
238
 
239
  validated = []
240
  for i, q in enumerate(questions):
routes/rag_routes.py CHANGED
@@ -11,6 +11,8 @@ from typing import Any, Dict, List, Optional
11
  from fastapi import APIRouter, HTTPException, Request
12
  from pydantic import BaseModel, Field, field_validator
13
 
 
 
14
  from services.inference_client import (
15
  InferenceRequest,
16
  create_default_client,
@@ -104,17 +106,9 @@ def _log_rag_usage(
104
 
105
 
106
  def _strip_thinking_and_parse(text: str) -> dict:
107
- cleaned = text.strip()
108
- cleaned = re.sub(r" </think>", "", cleaned, flags=re.DOTALL).strip()
109
- if "{" in cleaned and "}" in cleaned:
110
- try:
111
- start = cleaned.find("{")
112
- end = cleaned.rfind("}") + 1
113
- parsed = json.loads(cleaned[start:end])
114
- if isinstance(parsed, dict):
115
- return parsed
116
- except Exception:
117
- pass
118
  return {"explanation": text}
119
 
120
 
 
11
  from fastapi import APIRouter, HTTPException, Request
12
  from pydantic import BaseModel, Field, field_validator
13
 
14
+ from services.llm_json import extract_json_object
15
+
16
  from services.inference_client import (
17
  InferenceRequest,
18
  create_default_client,
 
106
 
107
 
108
  def _strip_thinking_and_parse(text: str) -> dict:
109
+ parsed = extract_json_object(text)
110
+ if parsed is not None:
111
+ return parsed
 
 
 
 
 
 
 
 
112
  return {"explanation": text}
113
 
114
 
routes/tutor_checkin.py CHANGED
@@ -7,11 +7,13 @@ based on their recent activity, weak topics, and current risk status.
7
 
8
  import logging
9
  import os
10
- from typing import Optional
11
 
12
  from fastapi import APIRouter, HTTPException
13
  from pydantic import BaseModel
14
 
 
 
15
  logger = logging.getLogger("mathpulse.tutor_checkin")
16
 
17
  router = APIRouter(prefix="/api/tutor-checkin", tags=["tutor-checkin"])
@@ -35,14 +37,14 @@ class TutorCheckinResponse(BaseModel):
35
  def _build_checkin_prompt(req: TutorCheckinRequest) -> str:
36
  """Build a contextual prompt for DeepSeek to generate a tutor check-in."""
37
  name = req.student_name or "Student"
38
- status = req.risk_status or "unknown"
39
  wri = req.wri
40
  weak = req.weak_topics or []
41
  activity = req.recent_activity or "No recent activity recorded."
42
 
43
  weak_topics_str = ", ".join(weak) if weak else "none identified"
44
 
45
- tone_map = {
46
  "safe": "encouraging and celebratory",
47
  "watch": "gentle and supportive",
48
  "intervene": "caring but firm",
@@ -93,7 +95,7 @@ def generate_tutor_checkin(req: TutorCheckinRequest):
93
 
94
  message = response.strip() if response else _fallback_message(req.risk_status)
95
 
96
- tone_map = {
97
  "safe": "encouraging",
98
  "watch": "supportive",
99
  "intervene": "caring-but-firm",
@@ -103,7 +105,7 @@ def generate_tutor_checkin(req: TutorCheckinRequest):
103
 
104
  return TutorCheckinResponse(
105
  message=message,
106
- tone=tone_map.get(req.risk_status or "", "supportive"),
107
  suggested_action=_suggest_action(req.risk_status, req.weak_topics),
108
  )
109
 
@@ -119,25 +121,26 @@ def generate_tutor_checkin(req: TutorCheckinRequest):
119
 
120
  def _fallback_message(risk_status: Optional[str]) -> str:
121
  """Template-based fallback when DeepSeek is unavailable."""
122
- fallbacks = {
123
  "safe": "Great work! You're on track. Keep up the momentum with today's practice.",
124
  "watch": "I noticed you've been working hard. Let's take a moment to review any tricky concepts together.",
125
  "intervene": "Your teacher and I are here to help. Let's focus on one topic at a time — you've got this.",
126
  "critical": "I'm worried about your progress. Please reach out to your teacher or start a remedial module today.",
127
  "at_risk": "Your learning path is paused until your teacher reviews your progress. In the meantime, review your completed lessons.",
128
  }
129
- return fallbacks.get(risk_status or "", "Keep going! Every problem you solve makes you stronger.")
130
 
131
 
132
  def _suggest_action(risk_status: Optional[str], weak_topics: Optional[list]) -> Optional[str]:
133
  """Suggest a concrete next action based on status."""
134
- if risk_status == "safe":
 
135
  return "Try a bonus challenge to stretch your skills."
136
- if risk_status == "watch":
137
  return "Review the hint for your last incorrect answer."
138
- if risk_status == "intervene":
139
  topic = weak_topics[0] if weak_topics else "your weakest topic"
140
  return f"Start the remedial module on {topic}."
141
- if risk_status in ("critical", "at_risk"):
142
  return "Contact your teacher or start a 1-on-1 review session."
143
  return None
 
7
 
8
  import logging
9
  import os
10
+ from typing import Dict, Optional
11
 
12
  from fastapi import APIRouter, HTTPException
13
  from pydantic import BaseModel
14
 
15
+ from services.wri_service import ESCALATION_RISK_STATUSES, RiskLevel, normalize_risk_band
16
+
17
  logger = logging.getLogger("mathpulse.tutor_checkin")
18
 
19
  router = APIRouter(prefix="/api/tutor-checkin", tags=["tutor-checkin"])
 
37
  def _build_checkin_prompt(req: TutorCheckinRequest) -> str:
38
  """Build a contextual prompt for DeepSeek to generate a tutor check-in."""
39
  name = req.student_name or "Student"
40
+ status: RiskLevel = normalize_risk_band(req.risk_status)
41
  wri = req.wri
42
  weak = req.weak_topics or []
43
  activity = req.recent_activity or "No recent activity recorded."
44
 
45
  weak_topics_str = ", ".join(weak) if weak else "none identified"
46
 
47
+ tone_map: Dict[RiskLevel, str] = {
48
  "safe": "encouraging and celebratory",
49
  "watch": "gentle and supportive",
50
  "intervene": "caring but firm",
 
95
 
96
  message = response.strip() if response else _fallback_message(req.risk_status)
97
 
98
+ tone_map: Dict[RiskLevel, str] = {
99
  "safe": "encouraging",
100
  "watch": "supportive",
101
  "intervene": "caring-but-firm",
 
105
 
106
  return TutorCheckinResponse(
107
  message=message,
108
+ tone=tone_map.get(normalize_risk_band(req.risk_status), "supportive"),
109
  suggested_action=_suggest_action(req.risk_status, req.weak_topics),
110
  )
111
 
 
121
 
122
  def _fallback_message(risk_status: Optional[str]) -> str:
123
  """Template-based fallback when DeepSeek is unavailable."""
124
+ fallbacks: Dict[RiskLevel, str] = {
125
  "safe": "Great work! You're on track. Keep up the momentum with today's practice.",
126
  "watch": "I noticed you've been working hard. Let's take a moment to review any tricky concepts together.",
127
  "intervene": "Your teacher and I are here to help. Let's focus on one topic at a time — you've got this.",
128
  "critical": "I'm worried about your progress. Please reach out to your teacher or start a remedial module today.",
129
  "at_risk": "Your learning path is paused until your teacher reviews your progress. In the meantime, review your completed lessons.",
130
  }
131
+ return fallbacks.get(normalize_risk_band(risk_status), "Keep going! Every problem you solve makes you stronger.")
132
 
133
 
134
  def _suggest_action(risk_status: Optional[str], weak_topics: Optional[list]) -> Optional[str]:
135
  """Suggest a concrete next action based on status."""
136
+ band = normalize_risk_band(risk_status)
137
+ if band == "safe":
138
  return "Try a bonus challenge to stretch your skills."
139
+ if band == "watch":
140
  return "Review the hint for your last incorrect answer."
141
+ if band == "intervene":
142
  topic = weak_topics[0] if weak_topics else "your weakest topic"
143
  return f"Start the remedial module on {topic}."
144
+ if band in ESCALATION_RISK_STATUSES:
145
  return "Contact your teacher or start a 1-on-1 review session."
146
  return None
services/class_analytics_engine.py CHANGED
@@ -14,6 +14,14 @@ from typing import Any, Dict, List, Literal, Optional
14
 
15
  from pydantic import BaseModel, Field
16
 
 
 
 
 
 
 
 
 
17
  logger = logging.getLogger("mathpulse.class_analytics")
18
 
19
  # ─── Firestore helper ──────────────────────────────────────────────────────
@@ -46,7 +54,7 @@ class StudentAnalyticsSummary(BaseModel):
46
  avg_score: float = 0.0
47
  quiz_attempt_count: int = 0
48
  last_active: Optional[str] = None
49
- risk_level: Literal["safe", "watch", "intervene", "critical", "at_risk", "pending_assessment"] = "pending_assessment"
50
  engagement_level: Literal["Low", "Medium", "High"] = "Low"
51
  weakest_topic: Optional[str] = None
52
  accuracy_by_topic: Dict[str, float] = Field(default_factory=dict)
@@ -89,20 +97,11 @@ class ClassAnalyticsReport(BaseModel):
89
 
90
  # ─── Risk & Engagement Classification ─────────────────────────────────────
91
 
92
- def classify_risk(avg_score: float, quiz_count: int, days_since_active: Optional[int]) -> str:
93
  """Map to WRI status bands. When no WRI is available, estimate from avg_score."""
94
  if quiz_count == 0:
95
  return "pending_assessment"
96
- # Approximate WRI bands from avg_score (actual WRI uses D, G, P weights)
97
- if avg_score >= 88:
98
- return "safe"
99
- if avg_score >= 80:
100
- return "watch"
101
- if avg_score >= 75:
102
- return "intervene"
103
- if avg_score >= 68:
104
- return "critical"
105
- return "at_risk"
106
 
107
 
108
  def classify_engagement(days_since_active: Optional[int], recent_quiz_count: int) -> str:
@@ -182,14 +181,13 @@ class ClassAnalyticsEngine:
182
  participation_rate = (active_count / student_count * 100) if student_count > 0 else 0.0
183
 
184
  # Attention = intervene + critical + at_risk
185
- attention_count = sum(1 for s in student_summaries if s.risk_level in ("intervene", "critical", "at_risk"))
186
 
187
  # Topic performance
188
  topic_perf = self._compute_topic_performance(student_summaries)
189
 
190
  # Risk distribution
191
- from services.wri_service import normalize_risk_band
192
- risk_dist = {"safe": 0, "watch": 0, "intervene": 0, "critical": 0, "at_risk": 0, "pending_assessment": 0}
193
  for s in student_summaries:
194
  # Prefer stored WRI status from managedStudents if available
195
  stored_status = None
 
14
 
15
  from pydantic import BaseModel, Field
16
 
17
+ from services.wri_service import (
18
+ ATTENTION_RISK_STATUSES,
19
+ RiskLevel,
20
+ band_for_score,
21
+ empty_risk_distribution,
22
+ normalize_risk_band,
23
+ )
24
+
25
  logger = logging.getLogger("mathpulse.class_analytics")
26
 
27
  # ─── Firestore helper ──────────────────────────────────────────────────────
 
54
  avg_score: float = 0.0
55
  quiz_attempt_count: int = 0
56
  last_active: Optional[str] = None
57
+ risk_level: RiskLevel = "pending_assessment"
58
  engagement_level: Literal["Low", "Medium", "High"] = "Low"
59
  weakest_topic: Optional[str] = None
60
  accuracy_by_topic: Dict[str, float] = Field(default_factory=dict)
 
97
 
98
  # ─── Risk & Engagement Classification ─────────────────────────────────────
99
 
100
+ def classify_risk(avg_score: float, quiz_count: int, days_since_active: Optional[int]) -> RiskLevel:
101
  """Map to WRI status bands. When no WRI is available, estimate from avg_score."""
102
  if quiz_count == 0:
103
  return "pending_assessment"
104
+ return band_for_score(avg_score)
 
 
 
 
 
 
 
 
 
105
 
106
 
107
  def classify_engagement(days_since_active: Optional[int], recent_quiz_count: int) -> str:
 
181
  participation_rate = (active_count / student_count * 100) if student_count > 0 else 0.0
182
 
183
  # Attention = intervene + critical + at_risk
184
+ attention_count = sum(1 for s in student_summaries if s.risk_level in ATTENTION_RISK_STATUSES)
185
 
186
  # Topic performance
187
  topic_perf = self._compute_topic_performance(student_summaries)
188
 
189
  # Risk distribution
190
+ risk_dist = empty_risk_distribution()
 
191
  for s in student_summaries:
192
  # Prefer stored WRI status from managedStudents if available
193
  stored_status = None
services/intervention_engine.py CHANGED
@@ -13,6 +13,8 @@ from typing import Any, Dict, List, Literal, Optional
13
 
14
  from pydantic import BaseModel, Field
15
 
 
 
16
  logger = logging.getLogger("mathpulse.intervention_engine")
17
 
18
  # ─── Firestore helper ──────────────────────────────────────────────────────
@@ -67,7 +69,7 @@ class InterventionPlan(BaseModel):
67
  student_name: str = ""
68
  grade_level: str = ""
69
  section: str = ""
70
- risk_level: str = "pending_assessment"
71
  avg_score: float = 0.0
72
  engagement_level: Literal["Low", "Medium", "High"] = "Low"
73
  last_active: Optional[str] = None
@@ -83,19 +85,11 @@ class InterventionPlan(BaseModel):
83
 
84
  # ─── Risk & Engagement Classification ─────────────────────────────────────
85
 
86
- def _classify_risk(avg_score: float, quiz_count: int, days_since_active: Optional[int] = None) -> str:
87
  """Canonical 5-band DepEd classification when WRI is not directly available."""
88
  if quiz_count == 0:
89
  return "pending_assessment"
90
- if avg_score >= 88:
91
- return "safe"
92
- if avg_score >= 80:
93
- return "watch"
94
- if avg_score >= 75:
95
- return "intervene"
96
- if avg_score >= 68:
97
- return "critical"
98
- return "at_risk"
99
 
100
 
101
  def _classify_engagement(days_since_active: Optional[int], recent_quiz_count: int, lessons_completed: int = 0) -> str:
@@ -242,7 +236,6 @@ class InterventionEngine:
242
  or student_data.get("wriRiskBand")
243
  )
244
  if raw_risk:
245
- from services.wri_service import normalize_risk_band
246
  risk_level = normalize_risk_band(raw_risk)
247
  else:
248
  risk_level = _classify_risk(avg_score, quiz_count, days_since_active)
 
13
 
14
  from pydantic import BaseModel, Field
15
 
16
+ from services.wri_service import RiskLevel, band_for_score, normalize_risk_band
17
+
18
  logger = logging.getLogger("mathpulse.intervention_engine")
19
 
20
  # ─── Firestore helper ──────────────────────────────────────────────────────
 
69
  student_name: str = ""
70
  grade_level: str = ""
71
  section: str = ""
72
+ risk_level: RiskLevel = "pending_assessment"
73
  avg_score: float = 0.0
74
  engagement_level: Literal["Low", "Medium", "High"] = "Low"
75
  last_active: Optional[str] = None
 
85
 
86
  # ─── Risk & Engagement Classification ─────────────────────────────────────
87
 
88
+ def _classify_risk(avg_score: float, quiz_count: int, days_since_active: Optional[int] = None) -> RiskLevel:
89
  """Canonical 5-band DepEd classification when WRI is not directly available."""
90
  if quiz_count == 0:
91
  return "pending_assessment"
92
+ return band_for_score(avg_score)
 
 
 
 
 
 
 
 
93
 
94
 
95
  def _classify_engagement(days_since_active: Optional[int], recent_quiz_count: int, lessons_completed: int = 0) -> str:
 
236
  or student_data.get("wriRiskBand")
237
  )
238
  if raw_risk:
 
239
  risk_level = normalize_risk_band(raw_risk)
240
  else:
241
  risk_level = _classify_risk(avg_score, quiz_count, days_since_active)
services/llm_json.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared extraction of JSON payloads from LLM responses.
2
+
3
+ LLM providers wrap structured output in prose, markdown fences, thinking
4
+ blocks, smart quotes, trailing commas, or Python-literal syntax. Every route
5
+ that consumes model-produced JSON needs the same recovery ladder; this module
6
+ is the single implementation so a payload that parses on one route parses on
7
+ all of them.
8
+
9
+ Callers keep their own error type: this module raises ``LLMJsonError`` and each
10
+ route translates it into its existing ``HTTPException``/``ValueError``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import ast
16
+ import json
17
+ import re
18
+ from typing import Any, Dict, Iterable, List, Optional
19
+
20
+ __all__ = [
21
+ "LLMJsonError",
22
+ "strip_reasoning",
23
+ "extract_json_blocks",
24
+ "normalize_candidate",
25
+ "loads_jsonish",
26
+ "extract_json_value",
27
+ "extract_json_object",
28
+ "extract_json_list",
29
+ "coerce_dict_list",
30
+ "extract_dict_list",
31
+ "collect_dict_objects",
32
+ ]
33
+
34
+ # Wrapper keys models use when they nest a list inside an envelope object.
35
+ _LIST_WRAPPER_KEYS = ("questions", "items", "data", "results", "quiz", "practice_questions")
36
+
37
+
38
+ class LLMJsonError(ValueError):
39
+ """Raised when no parseable JSON payload can be recovered from model output."""
40
+
41
+
42
+ _THINKING_PATTERNS = (
43
+ re.compile(r"<think(?:ing)?>[\s\S]*?</think(?:ing)?>", re.IGNORECASE),
44
+ re.compile(r"</think(?:ing)?>", re.IGNORECASE),
45
+ re.compile(r"^\s*thinking\s*process\s*:\s*", re.IGNORECASE),
46
+ re.compile(r"^\s*json\s*[:\-]?\s*", re.IGNORECASE),
47
+ )
48
+
49
+
50
+ def strip_reasoning(text: str) -> str:
51
+ """Remove thinking blocks and reasoning preambles that precede JSON."""
52
+ cleaned = (text or "").strip()
53
+ for pattern in _THINKING_PATTERNS:
54
+ cleaned = pattern.sub("", cleaned)
55
+ return cleaned.strip()
56
+
57
+
58
+ def extract_json_blocks(text: str) -> List[str]:
59
+ """Return every balanced ``{...}``/``[...]`` span, ignoring brackets inside strings."""
60
+ blocks: List[str] = []
61
+ starts = [index for index, char in enumerate(text) if char in "[{"]
62
+ for start in starts:
63
+ opener = text[start]
64
+ closer = "]" if opener == "[" else "}"
65
+ depth = 0
66
+ in_string = False
67
+ escaped = False
68
+ for index in range(start, len(text)):
69
+ char = text[index]
70
+ if in_string:
71
+ if escaped:
72
+ escaped = False
73
+ elif char == "\\":
74
+ escaped = True
75
+ elif char == '"':
76
+ in_string = False
77
+ continue
78
+ if char == '"':
79
+ in_string = True
80
+ continue
81
+ if char == opener:
82
+ depth += 1
83
+ elif char == closer:
84
+ depth -= 1
85
+ if depth == 0:
86
+ blocks.append(text[start : index + 1])
87
+ break
88
+ return blocks
89
+
90
+
91
+ def normalize_candidate(candidate: str) -> str:
92
+ """Repair the defects models introduce into otherwise valid JSON."""
93
+ normalized = candidate.strip().lstrip("\ufeff")
94
+ # Drop markdown code fences that wrap the payload.
95
+ normalized = re.sub(r"^```[a-zA-Z0-9_-]*\s*\n?", "", normalized)
96
+ normalized = re.sub(r"\n?\s*```\s*$", "", normalized)
97
+ normalized = (
98
+ normalized.replace("\u201c", '"')
99
+ .replace("\u201d", '"')
100
+ .replace("\u2018", "'")
101
+ .replace("\u2019", "'")
102
+ )
103
+ # Drop trailing commas before an object/array closer.
104
+ return re.sub(r",(\s*[}\]])", r"\1", normalized)
105
+
106
+
107
+ def loads_jsonish(candidate: str) -> Any:
108
+ """Parse a candidate as JSON, falling back to a Python-literal payload."""
109
+ normalized = normalize_candidate(candidate)
110
+ try:
111
+ return json.loads(normalized)
112
+ except json.JSONDecodeError:
113
+ pass
114
+
115
+ python_like = re.sub(r"\btrue\b", "True", normalized, flags=re.IGNORECASE)
116
+ python_like = re.sub(r"\bfalse\b", "False", python_like, flags=re.IGNORECASE)
117
+ python_like = re.sub(r"\bnull\b", "None", python_like, flags=re.IGNORECASE)
118
+ try:
119
+ return ast.literal_eval(python_like)
120
+ except (ValueError, SyntaxError):
121
+ return None
122
+
123
+
124
+ def extract_json_value(raw: str, *, preferred: type | tuple[type, ...] | None = None) -> Any:
125
+ """Recover the first parseable JSON value from a raw model response.
126
+
127
+ ``preferred`` restricts acceptance to a JSON type (``dict``/``list``); when
128
+ omitted, the first successfully parsed block wins. Raises ``LLMJsonError``
129
+ if nothing parses.
130
+ """
131
+ cleaned = strip_reasoning(raw)
132
+
133
+ for candidate in extract_json_blocks(cleaned):
134
+ parsed = loads_jsonish(candidate)
135
+ if parsed is None:
136
+ continue
137
+ if preferred is None or isinstance(parsed, preferred):
138
+ return parsed
139
+
140
+ # Models sometimes emit bare JSON with no envelope; try the whole text.
141
+ parsed = loads_jsonish(cleaned)
142
+ if parsed is not None and (preferred is None or isinstance(parsed, preferred)):
143
+ return parsed
144
+
145
+ raise LLMJsonError("No parseable JSON payload found in model response")
146
+
147
+
148
+ def extract_json_object(raw: str) -> Optional[Dict[str, Any]]:
149
+ """Recover a JSON object, or ``None`` when the response holds no object."""
150
+ try:
151
+ parsed = extract_json_value(raw, preferred=dict)
152
+ except LLMJsonError:
153
+ return None
154
+ return parsed
155
+
156
+
157
+ def extract_json_list(raw: str) -> Optional[List[Any]]:
158
+ """Recover a JSON array, or ``None`` when the response holds no array."""
159
+ try:
160
+ parsed = extract_json_value(raw, preferred=list)
161
+ except LLMJsonError:
162
+ return None
163
+ return parsed
164
+
165
+
166
+ def coerce_dict_list(value: Any) -> List[Dict[str, Any]]:
167
+ """Keep only the mapping entries of a list."""
168
+ if not isinstance(value, list):
169
+ return []
170
+ return [item for item in value if isinstance(item, dict)]
171
+
172
+
173
+ def extract_dict_list(payload: Any, wrapper_keys: Iterable[str] = _LIST_WRAPPER_KEYS) -> List[Dict[str, Any]]:
174
+ """Unwrap a list of objects from either a bare array or an envelope object."""
175
+ if isinstance(payload, list):
176
+ return coerce_dict_list(payload)
177
+ if isinstance(payload, dict):
178
+ for key in wrapper_keys:
179
+ nested = payload.get(key)
180
+ if isinstance(nested, list):
181
+ return coerce_dict_list(nested)
182
+ return []
183
+
184
+
185
+ def collect_dict_objects(raw: str) -> List[Dict[str, Any]]:
186
+ """Salvage every individually parseable object, for truncated responses."""
187
+ cleaned = strip_reasoning(raw)
188
+ objects: List[Dict[str, Any]] = []
189
+ for candidate in extract_json_blocks(cleaned):
190
+ if not candidate.lstrip().startswith("{"):
191
+ continue
192
+ parsed = loads_jsonish(candidate)
193
+ if isinstance(parsed, dict):
194
+ objects.append(parsed)
195
+ return objects
services/student_intelligence_pipeline.py CHANGED
@@ -18,6 +18,8 @@ from typing import Any, Dict, List, Literal, Optional
18
 
19
  from pydantic import BaseModel, Field
20
 
 
 
21
  logger = logging.getLogger("mathpulse.pipeline")
22
 
23
  # ─── Firestore ─────────────────────────────────────────────────────────────
@@ -125,7 +127,6 @@ class StudentIntelligencePipeline:
125
  weights = managed.get("weights") or profile.get("wri_weights") or {"w1": 0.30, "w2": 0.40, "w3": 0.30}
126
 
127
  if d is not None and event.event_type != "session":
128
- from services.wri_service import compute_wri
129
  wri_result = compute_wri(d=d, g=g, p=new_p, weights=weights)
130
 
131
  previous_status = profile.get("risk_status", "pending_assessment")
@@ -157,7 +158,7 @@ class StudentIntelligencePipeline:
157
 
158
  # 6b. Proactive tutor nudge (fire-and-forget, non-blocking)
159
  new_status = profile.get("risk_status", "safe")
160
- if new_status in ("watch", "intervene", "critical", "at_risk"):
161
  weak_topics = (
162
  profile.get("quiz_performance", {}).get("lowest_accuracy_topics", [])
163
  or profile.get("diagnostic", {}).get("weak_topics", [])
@@ -463,7 +464,7 @@ class StudentIntelligencePipeline:
463
  return False
464
  except Exception:
465
  pass
466
- return event.event_type in ("quiz", "battle") and result.new_risk_status in ("critical", "at_risk")
467
 
468
  async def _generate_ai_context(self, profile: Dict, event: StudentActivityEvent) -> Optional[Dict]:
469
  """Call DeepSeek for AI context generation."""
 
18
 
19
  from pydantic import BaseModel, Field
20
 
21
+ from services.wri_service import ESCALATION_RISK_STATUSES, FLAGGED_RISK_STATUSES, compute_wri
22
+
23
  logger = logging.getLogger("mathpulse.pipeline")
24
 
25
  # ─── Firestore ─────────────────────────────────────────────────────────────
 
127
  weights = managed.get("weights") or profile.get("wri_weights") or {"w1": 0.30, "w2": 0.40, "w3": 0.30}
128
 
129
  if d is not None and event.event_type != "session":
 
130
  wri_result = compute_wri(d=d, g=g, p=new_p, weights=weights)
131
 
132
  previous_status = profile.get("risk_status", "pending_assessment")
 
158
 
159
  # 6b. Proactive tutor nudge (fire-and-forget, non-blocking)
160
  new_status = profile.get("risk_status", "safe")
161
+ if new_status in FLAGGED_RISK_STATUSES:
162
  weak_topics = (
163
  profile.get("quiz_performance", {}).get("lowest_accuracy_topics", [])
164
  or profile.get("diagnostic", {}).get("weak_topics", [])
 
464
  return False
465
  except Exception:
466
  pass
467
+ return event.event_type in ("quiz", "battle") and result.new_risk_status in ESCALATION_RISK_STATUSES
468
 
469
  async def _generate_ai_context(self, profile: Dict, event: StudentActivityEvent) -> Optional[Dict]:
470
  """Call DeepSeek for AI context generation."""
services/tutor_nudge_service.py CHANGED
@@ -8,6 +8,8 @@ then writes them to Firestore for the floating tutor to surface.
8
  import logging
9
  from datetime import datetime, timezone
10
 
 
 
11
  logger = logging.getLogger("mathpulse.tutor_nudge")
12
 
13
  NUDGE_COOLDOWN_HOURS = 24
@@ -133,7 +135,7 @@ async def check_and_generate_nudge(student_id: str) -> dict | None:
133
 
134
  data = managed_snap.to_dict() or {}
135
  risk_status = data.get("riskStatus")
136
- if risk_status not in ("watch", "intervene", "critical", "at_risk"):
137
  return None
138
 
139
  # Get weak topics from student_profiles
 
8
  import logging
9
  from datetime import datetime, timezone
10
 
11
+ from services.wri_service import FLAGGED_RISK_STATUSES
12
+
13
  logger = logging.getLogger("mathpulse.tutor_nudge")
14
 
15
  NUDGE_COOLDOWN_HOURS = 24
 
135
 
136
  data = managed_snap.to_dict() or {}
137
  risk_status = data.get("riskStatus")
138
+ if risk_status not in FLAGGED_RISK_STATUSES:
139
  return None
140
 
141
  # Get weak topics from student_profiles
services/wri_service.py CHANGED
@@ -18,16 +18,50 @@ Final academic decisions must still be made by the teacher in accordance
18
  with official DepEd grading policies.
19
  """
20
 
21
- from typing import Optional
22
 
23
  DEFAULT_WEIGHTS = {"w1": 0.30, "w2": 0.40, "w3": 0.30}
24
  WEIGHT_TOLERANCE = 0.001
25
 
26
- CANONICAL_RISK_BANDS = ("safe", "watch", "intervene", "critical", "at_risk")
27
- CANONICAL_RISK_STATUSES = ("safe", "watch", "intervene", "critical", "at_risk", "pending_assessment")
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
 
 
 
 
 
 
 
29
 
30
- def normalize_risk_band(band: Optional[str]) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  """Normalize legacy or mixed-case risk status strings to canonical 5-band WRI format."""
32
  if not band:
33
  return "pending_assessment"
@@ -105,17 +139,8 @@ def compute_wri(
105
  # Compute WRI
106
  wri = round((w1 * d) + (w2 * g_val) + (w3 * p_val), 2)
107
 
108
- # 5-band prevention-first classification
109
- if wri >= 88:
110
- status = "safe"
111
- elif wri >= 80:
112
- status = "watch"
113
- elif wri >= 75:
114
- status = "intervene"
115
- elif wri >= 68:
116
- status = "critical"
117
- else:
118
- status = "at_risk"
119
 
120
  return {
121
  "wri": wri,
 
18
  with official DepEd grading policies.
19
  """
20
 
21
+ from typing import Dict, Literal, Optional, get_args
22
 
23
  DEFAULT_WEIGHTS = {"w1": 0.30, "w2": 0.40, "w3": 0.30}
24
  WEIGHT_TOLERANCE = 0.001
25
 
26
+ # ─── Canonical risk vocabulary ────────────────────────────────────────────
27
+ # Single owner. Every module that needs the bands, one of the subsets below,
28
+ # or a zeroed distribution imports from here instead of re-transcribing the
29
+ # closed set. Drift here previously left stale counters compiling silently.
30
+ RiskLevel = Literal["safe", "watch", "intervene", "critical", "at_risk", "pending_assessment"]
31
+ CANONICAL_RISK_STATUSES: tuple = get_args(RiskLevel)
32
+ CANONICAL_RISK_BANDS: tuple = tuple(
33
+ status for status in CANONICAL_RISK_STATUSES if status != "pending_assessment"
34
+ )
35
+ # Above the DepEd floor — the system adjusts difficulty or nudges the student.
36
+ FLAGGED_RISK_STATUSES: tuple = ("watch", "intervene", "critical", "at_risk")
37
+ # Approaching or below the DepEd passing mark — the teacher is notified.
38
+ ATTENTION_RISK_STATUSES: tuple = ("intervene", "critical", "at_risk")
39
+ # Escalation-worthy — structured intervention or teacher review required.
40
+ ESCALATION_RISK_STATUSES: tuple = ("critical", "at_risk")
41
 
42
+ # DepEd DO No. 8, s. 2015 — prevention-first bands. See the module docstring.
43
+ _BAND_THRESHOLDS: tuple = (
44
+ (88.0, "safe"),
45
+ (80.0, "watch"),
46
+ (75.0, "intervene"),
47
+ (68.0, "critical"),
48
+ )
49
 
50
+
51
+ def band_for_score(score: float) -> RiskLevel:
52
+ """Classify a 0-100 WRI score into the canonical 5-band DepEd scale."""
53
+ for threshold, band in _BAND_THRESHOLDS:
54
+ if score >= threshold:
55
+ return band
56
+ return "at_risk"
57
+
58
+
59
+ def empty_risk_distribution() -> Dict[str, int]:
60
+ """Zeroed counter keyed by every canonical risk status."""
61
+ return dict.fromkeys(CANONICAL_RISK_STATUSES, 0)
62
+
63
+
64
+ def normalize_risk_band(band: Optional[str]) -> RiskLevel:
65
  """Normalize legacy or mixed-case risk status strings to canonical 5-band WRI format."""
66
  if not band:
67
  return "pending_assessment"
 
139
  # Compute WRI
140
  wri = round((w1 * d) + (w2 * g_val) + (w3 * p_val), 2)
141
 
142
+ # 5-band prevention-first classification (thresholds owned by band_for_score)
143
+ status = band_for_score(wri)
 
 
 
 
 
 
 
 
 
144
 
145
  return {
146
  "wri": wri,
tests/conftest.py CHANGED
@@ -1,13 +1,8 @@
1
- """pytest conftest: force backend/ to sys.path[0] and prevent stale services shadow.
2
-
3
- Project root has stale services/ dir (with __init__.py) that shadows
4
- backend/services/ and lacks several service modules needed by routes/tests.
5
 
6
  This conftest:
7
- 1. Ensures backend/ is at sys.path[0]
8
- 2. Evicts any stale 'services' package from sys.modules so subsequent
9
- imports resolve to backend/services/ instead of the project-root copy.
10
- 3. Mocks Firebase Admin auth so test tokens (Bearer mock_token_<uid>)
11
  work without real Firebase credentials.
12
  """
13
 
@@ -87,33 +82,6 @@ while _backend_dir in sys.path:
87
  sys.path.remove(_backend_dir)
88
  sys.path.insert(0, _backend_dir)
89
 
90
- # 2. Evict stale 'services' package from import cache.
91
- # The project root services/ has __init__.py making it a regular package,
92
- # and it shadows backend/services/ in sys.path resolution.
93
- _keys_to_evict = [k for k in sys.modules if k == "services" or k.startswith("services.")]
94
- for k in _keys_to_evict:
95
- del sys.modules[k]
96
-
97
-
98
- def _evict_stale_services():
99
- """Remove stale 'services' entry from sys.modules if it exists."""
100
- for k in list(sys.modules.keys()):
101
- if k == "services" or k.startswith("services."):
102
- # Only evict if it's NOT the backend/services/* version
103
- mod = sys.modules[k]
104
- mod_file = getattr(mod, "__file__", "") or ""
105
- if _backend_dir in mod_file:
106
- continue # keep backend/services/* entries
107
- del sys.modules[k]
108
-
109
-
110
- @pytest.fixture(autouse=True)
111
- def _auto_evict_stale_services():
112
- """Re-evict stale services before every test to prevent cross-file pollution."""
113
- _evict_stale_services()
114
- yield
115
-
116
-
117
  @pytest.fixture(autouse=True)
118
  def _mock_firebase_auth():
119
  """Re-apply Firebase auth mock before every test.
 
1
+ """pytest conftest: force backend/ to sys.path[0] and mock Firebase Admin auth.
 
 
 
2
 
3
  This conftest:
4
+ 1. Ensures backend/ is at sys.path[0] so `services.*` resolves to backend/services/.
5
+ 2. Mocks Firebase Admin auth so test tokens (Bearer mock_token_<uid>)
 
 
6
  work without real Firebase credentials.
7
  """
8
 
 
82
  sys.path.remove(_backend_dir)
83
  sys.path.insert(0, _backend_dir)
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  @pytest.fixture(autouse=True)
86
  def _mock_firebase_auth():
87
  """Re-apply Firebase auth mock before every test.
tests/test_llm_json.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the shared LLM JSON envelope recovery used by every AI route."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+
7
+ from services.llm_json import (
8
+ LLMJsonError,
9
+ coerce_dict_list,
10
+ collect_dict_objects,
11
+ extract_dict_list,
12
+ extract_json_blocks,
13
+ extract_json_list,
14
+ extract_json_object,
15
+ extract_json_value,
16
+ loads_jsonish,
17
+ normalize_candidate,
18
+ strip_reasoning,
19
+ )
20
+
21
+
22
+ class TestStripReasoning:
23
+ def test_removes_think_blocks(self) -> None:
24
+ assert strip_reasoning("<think>hmm</think>{\"a\": 1}") == '{"a": 1}'
25
+
26
+ def test_removes_unpaired_closing_tag(self) -> None:
27
+ assert strip_reasoning('</think>{"a": 1}') == '{"a": 1}'
28
+
29
+ def test_removes_reasoning_preamble(self) -> None:
30
+ assert strip_reasoning('Thinking process: {"a": 1}') == '{"a": 1}'
31
+
32
+ def test_plain_text_is_unchanged(self) -> None:
33
+ assert strip_reasoning(" plain ") == "plain"
34
+
35
+
36
+ class TestExtractJsonBlocks:
37
+ def test_finds_outer_and_nested_blocks(self) -> None:
38
+ # The scanner starts at every opener; callers take the first usable block.
39
+ blocks = extract_json_blocks('pre {"a": {"b": 1}} post')
40
+ assert blocks[0] == '{"a": {"b": 1}}'
41
+ assert '{"b": 1}' in blocks
42
+
43
+ def test_ignores_brackets_inside_strings(self) -> None:
44
+ assert extract_json_blocks('{"a": "}"}') == ['{"a": "}"}']
45
+
46
+ def test_finds_array(self) -> None:
47
+ assert extract_json_blocks("see [1, 2] now") == ["[1, 2]"]
48
+
49
+ def test_returns_empty_for_no_json(self) -> None:
50
+ assert extract_json_blocks("no json here") == []
51
+
52
+
53
+ class TestNormalizeCandidate:
54
+ def test_replaces_smart_quotes(self) -> None:
55
+ assert normalize_candidate('{\u201ca\u201d: 1}') == '{"a": 1}'
56
+
57
+ def test_drops_trailing_comma(self) -> None:
58
+ assert normalize_candidate('{"a": 1,}') == '{"a": 1}'
59
+
60
+ def test_strips_bom(self) -> None:
61
+ assert normalize_candidate("\ufeff{}") == "{}"
62
+
63
+
64
+ class TestLoadsJsonish:
65
+ def test_parses_valid_json(self) -> None:
66
+ assert loads_jsonish('{"a": 1}') == {"a": 1}
67
+
68
+ def test_parses_fenced_json(self) -> None:
69
+ assert loads_jsonish('```json\n{"a": 1}\n```') == {"a": 1}
70
+
71
+ def test_parses_python_literals(self) -> None:
72
+ assert loads_jsonish("{'a': True, 'b': None}") == {"a": True, "b": None}
73
+
74
+ def test_returns_none_for_garbage(self) -> None:
75
+ assert loads_jsonish("not json at all") is None
76
+
77
+
78
+ class TestExtractJsonValue:
79
+ def test_prefers_first_parseable_object(self) -> None:
80
+ assert extract_json_value('{"a": 1} trailing {"b": 2}', preferred=dict) == {"a": 1}
81
+
82
+ def test_recovers_from_prose_wrapper(self) -> None:
83
+ prose = 'Sure! Here is the payload:\n```json\n{"a": 1}\n```\nHope that helps.'
84
+ assert extract_json_value(prose, preferred=dict) == {"a": 1}
85
+
86
+ def test_recovers_from_thinking_block(self) -> None:
87
+ assert extract_json_value('<think>...</think>\n[{"q": 1}]', preferred=list) == [{"q": 1}]
88
+
89
+ def test_raises_when_nothing_parses(self) -> None:
90
+ with pytest.raises(LLMJsonError):
91
+ extract_json_value("no json here")
92
+
93
+ def test_raises_when_type_not_preferred(self) -> None:
94
+ with pytest.raises(LLMJsonError):
95
+ extract_json_value("[1, 2]", preferred=dict)
96
+
97
+
98
+ class TestTypedHelpers:
99
+ def test_extract_json_object_returns_none_on_array(self) -> None:
100
+ assert extract_json_object("[1]") is None
101
+
102
+ def test_extract_json_list_returns_none_on_object(self) -> None:
103
+ assert extract_json_list('{"a": 1}') is None
104
+
105
+ def test_extract_json_object_parses(self) -> None:
106
+ assert extract_json_object('{"a": 1}') == {"a": 1}
107
+
108
+
109
+ class TestDictListExtraction:
110
+ def test_coerce_filters_non_dicts(self) -> None:
111
+ assert coerce_dict_list([{"a": 1}, "x", 2, None]) == [{"a": 1}]
112
+
113
+ def test_coerce_rejects_non_list(self) -> None:
114
+ assert coerce_dict_list({"a": 1}) == []
115
+
116
+ def test_extract_dict_list_from_bare_array(self) -> None:
117
+ assert extract_dict_list([{"a": 1}]) == [{"a": 1}]
118
+
119
+ def test_extract_dict_list_unwraps_questions_key(self) -> None:
120
+ assert extract_dict_list({"questions": [{"q": 1}]}) == [{"q": 1}]
121
+
122
+ def test_extract_dict_list_unwraps_practice_questions_key(self) -> None:
123
+ assert extract_dict_list({"practice_questions": [{"q": 1}]}) == [{"q": 1}]
124
+
125
+ def test_extract_dict_list_prefers_questions_over_data(self) -> None:
126
+ payload = {"data": [{"d": 1}], "questions": [{"q": 1}]}
127
+ assert extract_dict_list(payload) == [{"q": 1}]
128
+
129
+ def test_extract_dict_list_returns_empty_for_unknown_envelope(self) -> None:
130
+ assert extract_dict_list({"unknown": [{"q": 1}]}) == []
131
+
132
+
133
+ class TestCollectDictObjects:
134
+ def test_salvages_multiple_objects_from_truncated_output(self) -> None:
135
+ truncated = '{"question": "a", "correct": "A"} {"question": "b", "correct": "B"}'
136
+ assert collect_dict_objects(truncated) == [
137
+ {"question": "a", "correct": "A"},
138
+ {"question": "b", "correct": "B"},
139
+ ]
140
+
141
+ def test_ignores_arrays(self) -> None:
142
+ assert collect_dict_objects("[1, 2]") == []