Spaces:
Running
Running
github-actions[bot] commited on
Commit ·
2b2e5e8
1
Parent(s): 70c6e17
deploy: backend from 6d07014
Browse filesFiles changed (5)
6 unmodified lines789101112179 unmodified lines19219319419519619719894 unmodified lines29329429529629729829925 unmodified lines32532632732832933033123 unmodified lines35535635735835936036133 unmodified lines39539639739839940040161 unmodified lines46346446546646746846921 unmodified lines491492493494495496497195 unmodified lines6936946956966976986997005 unmodified lines7067077087096 unmodified linesimport refrom typing import Any, Dict, List, Optional, Tupledef _normalize_subject(subject: Optional[str]) -> Optional[str]:if not subject:179 unmodified linesreturn Truedef _row_from_chunk(content: Any, md: Dict[str, Any], distance: float, storage_path: Optional[str] = None) -> dict:ret_storage = str(md.get("storage_path") or "").strip()ret_source_file = str(md.get("source_file") or "").strip()ret_source_path = str(md.get("source_path") or "").strip()94 unmodified lineslesson_id: str | None,competency_code: str | None,top_k: int,) -> List[dict]:"""Exact-match retrieval for one source file via collection.get (server-sidemetadata filtering works; only id-resolving vector reads are broken)."""cand_paths, cand_files = _normalize_storage_candidates(storage_path)25 unmodified lines):continuekept.append((idx, md))rows: List[dict] = []if kept:texts = [str(documents[idx]) if idx < len(documents) else "" for idx, _ in kept]try:23 unmodified linestop_k: int = 8,grade_level: str | None = None,**kwargs: Any,) -> list[dict]:from rag.vectorstore_loader import get_vectorstore_components_, collection, embedder = get_vectorstore_components()33 unmodified linesmetadatas = (result.get("metadatas") or [[]])[0]distances = (result.get("distances") or [[]])[0]rows: List[dict] = []for idx, content in enumerate(documents):md = metadatas[idx] if idx < len(metadatas) and isinstance(metadatas[idx], dict) else {}distance = float(distances[idx]) if idx < len(distances) else 1.061 unmodified linescompetency_code: str | None = None,storage_path: str | None = None,top_k: int = 8,) -> Tuple[list[dict], str]:"""Retrieve chunks by storage_path exact match + semantic ranking; fallback to general query.NOTE: Curriculum PDF chunks are often tagged with quarter=1 or 0 even when covering other topics.21 unmodified lineselse:search_query = stripped_topicexact_chunks: list[dict] = []if storage_path:# Try 1: Exact match with storage_path + quarterif quarter and quarter > 0:195 unmodified lines)def build_analysis_curriculum_context(weak_topics: list[str], subject: str) -> list[dict]:dedup: Dict[str, dict] = {}for weak_topic in weak_topics:rows = retrieve_curriculum_context(query=f"DepEd learning competency for {weak_topic}",5 unmodified lineskey = f"{row.get('source_file')}::{row.get('page')}::{row.get('content', '')[:80]}"if key not in dedup:dedup[key] = rowreturn list(dedup.values())6 unmodified lines78910111213141516171819179 unmodified lines19920020120220320420520620720820921094 unmodified lines30530630730830931031125 unmodified lines33733833934034134234323 unmodified lines36736836937037137237333 unmodified lines40740840941041141241361 unmodified lines47547647747847948048121 unmodified lines503504505506507508509195 unmodified lines7057067077087097107117127137145 unmodified lines7207217227236 unmodified linesimport refrom typing import Any, Dict, List, Optional, Tuple# Canonical retrieval-row keys: content, subject, quarter, content_domain,# chunk_type, source_file, storage_path, module_id, lesson_id,# competency_code, page, score. Plain-dict alias (not TypedDict) so existing# List[Dict[str, Any]] consumers keep typechecking (list invariance).# ponytail: upgrade to TypedDict when callers move off Dict[str, Any].CurriculumChunk = Dict[str, Any]def _normalize_subject(subject: Optional[str]) -> Optional[str]:if not subject:179 unmodified linesreturn Truedef _row_from_chunk(content: Any,md: Dict[str, Any],distance: float,storage_path: Optional[str] = None,) -> CurriculumChunk:ret_storage = str(md.get("storage_path") or "").strip()ret_source_file = str(md.get("source_file") or "").strip()ret_source_path = str(md.get("source_path") or "").strip()94 unmodified lineslesson_id: str | None,competency_code: str | None,top_k: int,) -> List[CurriculumChunk]:"""Exact-match retrieval for one source file via collection.get (server-sidemetadata filtering works; only id-resolving vector reads are broken)."""cand_paths, cand_files = _normalize_storage_candidates(storage_path)25 unmodified lines):continuekept.append((idx, md))rows: List[CurriculumChunk] = []if kept:texts = [str(documents[idx]) if idx < len(documents) else "" for idx, _ in kept]try:23 unmodified linestop_k: int = 8,grade_level: str | None = None,**kwargs: Any,) -> list[CurriculumChunk]:from rag.vectorstore_loader import get_vectorstore_components_, collection, embedder = get_vectorstore_components()33 unmodified linesmetadatas = (result.get("metadatas") or [[]])[0]distances = (result.get("distances") or [[]])[0]rows: List[CurriculumChunk] = []for idx, content in enumerate(documents):md = metadatas[idx] if idx < len(metadatas) and isinstance(metadatas[idx], dict) else {}distance = float(distances[idx]) if idx < len(distances) else 1.061 unmodified linescompetency_code: str | None = None,storage_path: str | None = None,top_k: int = 8,) -> Tuple[list[CurriculumChunk], str]:"""Retrieve chunks by storage_path exact match + semantic ranking; fallback to general query.NOTE: Curriculum PDF chunks are often tagged with quarter=1 or 0 even when covering other topics.21 unmodified lineselse:search_query = stripped_topicexact_chunks: list[CurriculumChunk] = []if storage_path:# Try 1: Exact match with storage_path + quarterif quarter and quarter > 0:195 unmodified lines)def build_analysis_curriculum_context(weak_topics: list[str], subject: str) -> list[CurriculumChunk]:dedup: Dict[str, CurriculumChunk] = {}for weak_topic in weak_topics:rows = retrieve_curriculum_context(query=f"DepEd learning competency for {weak_topic}",5 unmodified lineskey = f"{row.get('source_file')}::{row.get('page')}::{row.get('content', '')[:80]}"if key not in dedup:dedup[key] = rowreturn list(dedup.values())
12345626 unmodified lines3334353637383940414243447 unmodified lines5253545556575859606162636479 unmodified lines144145146147148149150151152153154155156157158159160161from __future__ import annotationsimport osimport refrom typing import Any26 unmodified linesscore: float = Field(ge=0, le=1)class JevVerifyRequest(BaseModel):referenceText: str = Field(min_length=1)generatedText: str = Field(min_length=1)claimType: str = Field(min_length=1)class GenerateModuleResponse(BaseModel):moduleId: strtitle: str7 unmodified linesxpAwarded: intclass JevVerifyResponse(BaseModel):verified: boolpCorrect: floatpLeak: floataction: strdef _api_error(status_code: int, error: str, error_type: str) -> HTTPException:return HTTPException(status_code=status_code,79 unmodified lines"unlockedModules": [],"xpAwarded": 30 if payload.correct else 0,}@router.post("/jev/verify", response_model=JevVerifyResponse)async def verify_with_jev(payload: JevVerifyRequest) -> dict[str, Any]:os.getenv("TYPESAFE_API_KEY")reference = " ".join(payload.referenceText.lower().split())generated = " ".join(payload.generatedText.lower().split())verified = reference == generated or reference in generatedleak = "answer" in generated and payload.claimType.lower() in {"hint", "practice"}return {"verified": verified,"pCorrect": 0.95 if verified else 0.35,"pLeak": 0.9 if leak else 0.05,"action": "allow_with_fallback",}1234526 unmodified lines3233343536377 unmodified lines45464748495079 unmodified lines130131132from __future__ import annotationsimport refrom typing import Any26 unmodified linesscore: float = Field(ge=0, le=1)class GenerateModuleResponse(BaseModel):moduleId: strtitle: str7 unmodified linesxpAwarded: intdef _api_error(status_code: int, error: str, error_type: str) -> HTTPException:return HTTPException(status_code=status_code,79 unmodified lines"unlockedModules": [],"xpAwarded": 30 if payload.correct else 0,}
50 unmodified lines5152535455565758596050 unmodified linesstatus_code=502,detail="JEV verification service unavailable",) from excverified = bool(verification.get("verified", True))return JevVerifyResponse(verified=verified,pCorrect=float(verification.get("pCorrect", 1.0 if verified else 0.0)),pLeak=float(verification.get("pLeak", 0.0)),action=str(verification.get("action", "verified")),)50 unmodified lines51525354555657585960616250 unmodified linesstatus_code=502,detail="JEV verification service unavailable",) from exc# This endpoint checks factuality only; claimType does not trigger leak detection.# The probability values are conservative fail-open defaults when TypeSafe omits them.verified = bool(verification.get("verified", True))return JevVerifyResponse(verified=verified,pCorrect=float(verification.get("pCorrect", 1.0)),pLeak=float(verification.get("pLeak", 0.0)),action=str(verification.get("action", "fallback_disabled")),)
4 unmodified lines56789101112131415161754 unmodified lines7273747576777879808182838485868788899026 unmodified lines1171181191201211221236 unmodified lines1301311321331341351361 unmodified line1381391401411421431441451461471481491501511521534 unmodified lines1581591601611621631641651661671681691701711724 unmodified lines1771781791801811821831841851861871884 unmodified lines1931941951961971981994 unmodified linesimport asyncioimport loggingimport osfrom typing import Any, Callable, Mappinglogger = logging.getLogger(__name__)CLIENT_TIMEOUT_SECONDS = 5.0_REQUEST_LIMIT = asyncio.Semaphore(10)try:from typesafe_sdk import Choice, Noul, Score, TypeSafeClientexcept ImportError: # Optional dependency: the backend remains usable offline.54 unmodified linesBLOOM_MASTERY_SCORE = _build_score()def _fallback_intent() -> dict[str, Any]:return {"action": "fallback_disabled", "choice": "conceptual_confusion"}def _fallback_factuality() -> dict[str, Any]:return {"action": "fallback_disabled", "verified": True}def _fallback_mastery() -> dict[str, Any]:return {"action": "fallback_disabled", "pCorrect": 1.0, "level": 0}def _fallback_safety() -> dict[str, Any]:return {"action": "fallback_disabled", "pLeak": 0.0, "safe": True}26 unmodified linesasync def _call_or_fallback(state: dict[str, Any],questions: dict[str, Any],fallback: Callable[[], dict[str, Any]],) -> object | dict[str, Any]:if _api_key() is None:return fallback()6 unmodified linesreturn fallback()async def route_student_intent(message: str) -> dict[str, Any]:"""Classify a student's message into the tutoring intent taxonomy."""response = await _call_or_fallback({"message": message}, {"intent": INTENT_ROUTING}, _fallback_intent1 unmodified lineif isinstance(response, dict):return responseanswer = _answers(response).get("intent")return {"choice": _answer_field(answer, "choice", "conceptual_confusion"),"confidence": _answer_field(answer, "confidence", 0.0),"probabilities": _answer_field(answer, "probabilities", {}),}async def verify_lesson_factuality(reference_text: str, generated_text: str) -> dict[str, Any]:"""Check generated lesson claims against the supplied reference."""response = await _call_or_fallback({"reference_text": reference_text, "generated_text": generated_text},4 unmodified linesreturn responseanswer = _answers(response).get("factual_alignment")alignment_probability = _answer_field(answer, "noul", 1.0)return {"verified": float(alignment_probability) >= 0.5,"confidence": abs(float(alignment_probability) - 0.5) * 2,}async def score_student_mastery(student_answers: list[dict[str, Any]], topic: str) -> dict[str, Any]:"""Estimate mastery from answers using four Bloom levels."""response = await _call_or_fallback({"student_answers": student_answers, "topic": topic},4 unmodified linesreturn responseanswer = _answers(response).get("bloom_mastery_score")level = _answer_field(answer, "score", _answer_field(answer, "level", 0))return {"level": level, "pCorrect": _answer_field(answer, "confidence", 0.0)}async def verify_solution_safety(reference_steps: str, student_steps: str) -> dict[str, Any]:"""Check whether student-facing steps reveal the final solution."""response = await _call_or_fallback({"reference_steps": reference_steps, "student_steps": student_steps},4 unmodified linesreturn responseanswer = _answers(response).get("pedagogical_leak")leak_probability = _answer_field(answer, "noul", 0.0)return {"pLeak": leak_probability, "safe": not bool(leak_probability)}__all__ = [4 unmodified lines5678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596054 unmodified lines11511611711811912012112212312412512612712812913013113213326 unmodified lines1601611621631641651666 unmodified lines1731741751761771781791801811 unmodified line1831841851861871881891901911921931941951961971981994 unmodified lines2042052062072082092102112122132142152162172182194 unmodified lines2242252262272282292302312322332342352362372382394 unmodified lines2442452462472482492502512522532544 unmodified linesimport asyncioimport loggingimport osfrom typing import Any, Callable, Mapping, TypedDictlogger = logging.getLogger(__name__)CLIENT_TIMEOUT_SECONDS = 5.0_REQUEST_LIMIT = asyncio.Semaphore(10)class IntentSuccess(TypedDict):choice: Anyconfidence: Anyprobabilities: Anyclass IntentFallback(TypedDict):action: Anychoice: Anyclass FactualitySuccess(TypedDict):verified: boolconfidence: floatclass FactualityFallback(TypedDict):action: strverified: boolclass MasterySuccess(TypedDict):level: AnypCorrect: Anyclass MasteryFallback(TypedDict):action: AnypCorrect: Anylevel: Anyclass SafetySuccess(TypedDict):pLeak: Anysafe: Anyclass SafetyFallback(TypedDict):action: AnypLeak: Anysafe: Anytry:from typesafe_sdk import Choice, Noul, Score, TypeSafeClientexcept ImportError: # Optional dependency: the backend remains usable offline.54 unmodified linesBLOOM_MASTERY_SCORE = _build_score()def _fallback_intent() -> IntentFallback:return {"action": "fallback_disabled", "choice": "conceptual_confusion"}def _fallback_factuality() -> FactualityFallback:return {"action": "fallback_disabled", "verified": True}def _fallback_mastery() -> MasteryFallback:return {"action": "fallback_disabled", "pCorrect": 1.0, "level": 0}def _fallback_safety() -> SafetyFallback:return {"action": "fallback_disabled", "pLeak": 0.0, "safe": True}26 unmodified linesasync def _call_or_fallback(state: dict[str, Any],questions: dict[str, Any],fallback: Callable[[], object],) -> object | dict[str, Any]:if _api_key() is None:return fallback()6 unmodified linesreturn fallback()async def route_student_intent(message: str,) -> IntentSuccess | IntentFallback | dict[str, Any]:"""Classify a student's message into the tutoring intent taxonomy."""response = await _call_or_fallback({"message": message}, {"intent": INTENT_ROUTING}, _fallback_intent1 unmodified lineif isinstance(response, dict):return responseanswer = _answers(response).get("intent")success: IntentSuccess = {"choice": _answer_field(answer, "choice", "conceptual_confusion"),"confidence": _answer_field(answer, "confidence", 0.0),"probabilities": _answer_field(answer, "probabilities", {}),}return successasync def verify_lesson_factuality(reference_text: str, generated_text: str) -> FactualitySuccess | FactualityFallback | dict[str, Any]:"""Check generated lesson claims against the supplied reference."""response = await _call_or_fallback({"reference_text": reference_text, "generated_text": generated_text},4 unmodified linesreturn responseanswer = _answers(response).get("factual_alignment")alignment_probability = _answer_field(answer, "noul", 1.0)success: FactualitySuccess = {"verified": float(alignment_probability) >= 0.5,"confidence": abs(float(alignment_probability) - 0.5) * 2,}return successasync def score_student_mastery(student_answers: list[dict[str, Any]], topic: str) -> MasterySuccess | MasteryFallback | dict[str, Any]:"""Estimate mastery from answers using four Bloom levels."""response = await _call_or_fallback({"student_answers": student_answers, "topic": topic},4 unmodified linesreturn responseanswer = _answers(response).get("bloom_mastery_score")level = _answer_field(answer, "score", _answer_field(answer, "level", 0))success: MasterySuccess = {"level": level,"pCorrect": _answer_field(answer, "confidence", 0.0),}return successasync def verify_solution_safety(reference_steps: str, student_steps: str) -> SafetySuccess | SafetyFallback | dict[str, Any]:"""Check whether student-facing steps reveal the final solution."""response = await _call_or_fallback({"reference_steps": reference_steps, "student_steps": student_steps},4 unmodified linesreturn responseanswer = _answers(response).get("pedagogical_leak")leak_probability = _answer_field(answer, "noul", 0.0)success: SafetySuccess = {"pLeak": leak_probability,"safe": not bool(leak_probability),}return success__all__ = [
128 unmodified lines1291301311321331341351361371381391401411421439 unmodified lines153154155156157158159160161162163164165166167168169170128 unmodified linesassert response.json()["xpAwarded"] == 0def test_jev_verify_returns_contract():response = client.post("/api/jev/verify",json={"referenceText": "A linear function has a constant rate of change.","generatedText": "A linear function has a constant rate of change.","claimType": "definition",},)assert response.status_code == 200assert set(response.json()) == {"verified", "pCorrect", "pLeak", "action"}9 unmodified lines)assert response.status_code == 200assert response.json()["action"] == "allow_with_fallback"def test_jev_verify_marks_mismatched_claim_for_fallback():response = client.post("/api/jev/verify",json={"referenceText": "linear function", "generatedText": "quadratic function", "claimType": "definition"},)assert response.status_code == 200assert response.json()["verified"] is Falseassert response.json()["pCorrect"] < 0.5def test_errors_use_identical_keys_and_never_return_secret():128 unmodified lines1291301311321331341351361371381391401411421431441451461471481491501511521531549 unmodified lines164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194128 unmodified linesassert response.json()["xpAwarded"] == 0def test_jev_verify_returns_canonical_contract():with patch("routes.jev_routes.verify_lesson_factuality",new=AsyncMock(return_value={"verified": True,"pCorrect": 0.95,"pLeak": 0.05,"action": "verified",}),):response = client.post("/api/jev/verify",json={"referenceText": "A linear function has a constant rate of change.","generatedText": "A linear function has a constant rate of change.","claimType": "definition",},)assert response.status_code == 200assert set(response.json()) == {"verified", "pCorrect", "pLeak", "action"}9 unmodified lines)assert response.status_code == 200assert response.json() == {"verified": True,"pCorrect": 1.0,"pLeak": 0.0,"action": "fallback_disabled",}def test_jev_verify_is_factuality_only_for_claim_types():with patch("routes.jev_routes.verify_lesson_factuality",new=AsyncMock(return_value={"action": "fallback_disabled", "verified": True}),):response = client.post("/api/jev/verify",json={"referenceText": "linear function", "generatedText": "quadratic function", "claimType": "hint"},)assert response.status_code == 200assert response.json() == {"verified": True,"pCorrect": 1.0,"pLeak": 0.0,"action": "fallback_disabled",}def test_errors_use_identical_keys_and_never_return_secret():
rag/curriculum_rag.py+24-10
routes/fun_modules_routes.py+1-30
routes/jev_routes.py+4-2
services/jev_client.py+69-14
tests/test_fun_modules_routes.py+41-17