Spaces:
Build error
Build error
anwarKXC commited on
Commit ·
0850a3f
1
Parent(s): 6868c87
feat: Implement passage groups and associated tests for exam structure
Browse filesFiles changed (10)
- app/config.py+23
- app/models/structured_schemas.py+56
- app/services/gateway.py+1242-39
- app/services/pdf_export.py+38
- app/templates/answer_key.html+3-1
- app/templates/exam.html+30-1
- tests/test_exam_measured_difficulty.pyAdded+188
- tests/test_exam_passage_groups.pyAdded+157
- tests/test_exam_question_integrity.pyAdded+267
- tests/test_exam_red_team.pyAdded+83
284 unmodified lines285286287288289290284 unmodified lines# ── Auth ──────────────────────────────────────────────────────────────────API_KEY: str = "changeme"# ── Cache ─────────────────────────────────────────────────────────────────CACHE_ENABLED: bool = TrueCACHE_TASK_TYPE: str = "CURRICULUM_QUESTION" # must match NestJS exactly284 unmodified lines285286287288289290291292293294295296297298299300301302303304305306307308309310311312313284 unmodified lines# ── Auth ──────────────────────────────────────────────────────────────────API_KEY: str = "changeme"# ── Exam passage groups ───────────────────────────────────────────────────# One block of book text (lifted verbatim from the retrieved chunks, never# written by the model) followed by several questions built on it, each# assigned a different reasoning family. Off switch kept because this# changes what a printed exam looks like, not just how it's scored.EXAM_PASSAGE_GROUPS_ENABLED: bool = True# Minimum questions in a batch before it's worth spending a passage on —# below this the group can't cover enough distinct reasoning families to# be more than a normal batch with a preamble.EXAM_PASSAGE_MIN_QUESTIONS: int = 4# ── Exam red team ─────────────────────────────────────────────────────────# An LLM pass that attacks hard questions the deterministic checks can't# judge: is this answerable without having read the lesson, can three# options be dismissed on general knowledge, is the wording ambiguous.# Costs one extra cheap-tier call per section, plus at most one extra# reroll round for the questions that fail — turn off if exam latency# matters more than hard-question quality on a given deployment.EXAM_RED_TEAM_ENABLED: bool = True# Never attack more than this many questions per section: the call is# batched, but its output tokens still scale with the count.EXAM_RED_TEAM_MAX_QUESTIONS: int = 12# ── Cache ─────────────────────────────────────────────────────────────────CACHE_ENABLED: bool = TrueCACHE_TASK_TYPE: str = "CURRICULUM_QUESTION" # must match NestJS exactly
52 unmodified lines535455565758596061626335 unmodified lines9910010110210310410510610710843 unmodified lines15215315415515615752 unmodified linesreason: Optional[str] = Field(default=None, description="Second statement (Reason)")# true_false_correction-specific: required (non-null) when answer is false.correction: Optional[str] = Field(default=None, description="Corrected statement when answer is false")class ExamSection(BaseModel):title: strquestions: list[ExamQuestion]class ExamMetadata(BaseModel):35 unmodified linesclass QualitySubscores(BaseModel):"""0-100 normalized, question-count-weighted across sections."""coverage: floatdifficulty_balance: floatbloom_balance: floatconcept_uniqueness: floatstem_balance: floatclass LowestSection(BaseModel):43 unmodified linesoverall: floatweighted_overall: floatsubscores: QualitySubscoreslowest_section: Optional[LowestSection] = Nonewarnings: list[str] = Field(default_factory=list)retrieval_confidence: float52 unmodified lines53545556575859606162636465666768697071727374757677787980818283848586878835 unmodified lines12412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216343 unmodified lines20720820921021121221352 unmodified linesreason: Optional[str] = Field(default=None, description="Second statement (Reason)")# true_false_correction-specific: required (non-null) when answer is false.correction: Optional[str] = Field(default=None, description="Corrected statement when answer is false")# Set when this question belongs to a passage group — matches an id in its# section's `passages`. Renderers print the passage above the first# question carrying its id; every other consumer can ignore this field.passage_id: Optional[str] = Field(default=None, description="Id of the ExamPassage this question is built on")class ExamPassage(BaseModel):"""A block of book text several questions are built on.Lifted verbatim from the retrieved chunks, never written by the model —an invented passage produces convincing questions about text that isn't inthe teacher's book, which is strictly worse than no passage at all. See`_extract_passage`."""id: strtext: str# Exact chunks the sentences came from — this is what makes "view source"# able to open the right page of the original PDF.source_chunk_ids: list[str] = Field(default_factory=list)page_range: Optional[list[int]] = Field(default=None, description="[min_page, max_page]")class ExamSection(BaseModel):title: strquestions: list[ExamQuestion]# Questions stay in one flat list even when grouped: numbering, marks,# the answer key, export and grading all iterate `questions`, and splitting# it would mean changing every one of them. Grouping is expressed by# `ExamQuestion.passage_id` pointing back into this list.passages: list[ExamPassage] = Field(default_factory=list)class ExamMetadata(BaseModel):35 unmodified linesclass QualitySubscores(BaseModel):"""0-100 normalized, question-count-weighted across sections."""coverage: float# Label compliance: did the model apply the easy/medium/hard mix it was# asked for. Retained for continuity (and because obeying the teacher's# request is worth something) but no longer the headline — it scored# 100/94/100 on three exams whose "hard" questions were medium questions# with a clause appended. Read it against difficulty_fidelity below; a# high balance next to a low fidelity is the signature of that failure.difficulty_balance: floatbloom_balance: floatconcept_uniqueness: floatstem_balance: float# Measured difficulty: of the slots the teacher asked to be hard, how many# hold questions that actually demand hard reasoning (see# `_measured_difficulty`). None when no difficulty target was requested —# there is nothing to be faithful to, which is not the same as scoring 0.difficulty_fidelity: Optional[float] = None# Grounding: how much of each question's vocabulary is attested in the# retrieved book context. Answers "is this testing the selected lesson or# the model's general knowledge of the topic". None when the section had# too little source vocabulary for the comparison to mean anything.content_fidelity: Optional[float] = Noneclass AuthenticDifficulty(BaseModel):"""Descriptive shares of the exam by *measured* difficulty, not by label.Deliberately separate from QualitySubscores: these are percentages of theexam, not 0-100 quality scores, and folding them in would invite averagingthem together with things that aren't comparable."""# Share of questions measuring >= 56 (the "hard" band floor).authentic_hard_pct: float = 0.0# Share measuring >= 86 — the "6/5" tier tracked separately on request.exceptional_pct: float = 0.0mean_measured_difficulty: float = 0.0class LowestSection(BaseModel):43 unmodified linesoverall: floatweighted_overall: floatsubscores: QualitySubscoresauthentic_difficulty: AuthenticDifficulty = Field(default_factory=AuthenticDifficulty)lowest_section: Optional[LowestSection] = Nonewarnings: list[str] = Field(default_factory=list)retrieval_confidence: float
30 unmodified lines313233343536331 unmodified lines368369370371372373238 unmodified lines61261361461561661752 unmodified lines67067167267367467567639 unmodified lines7167177187197207215 unmodified lines7277287297307317327335 unmodified lines73974074174274374467 unmodified lines81281381481581681759 unmodified lines87787887988088188234 unmodified lines91791891992092192292392492592692792813 unmodified lines94294394494594694794894995095195286 unmodified lines1039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106113 unmodified lines1075107610771078107910807 unmodified lines108810891090109110921093124 unmodified lines121812191220122112221223146 unmodified lines1370137113721373137413756 unmodified lines1382138313841385138613877 unmodified lines139513961397139813991400140125 unmodified lines1427142814291430143114321415 unmodified lines28482849285028512852285380 unmodified lines293429352936293729382939294029412942294329442945294629472948294929502951295221 unmodified lines297429752976297729782979298029812982298329842 unmodified lines29872988298929902991299215 unmodified lines3008300930103011301230133014579 unmodified lines359435953596359735983599360057 unmodified lines3658365936603661366236633664366551 unmodified lines3717371837193720372137229 unmodified lines373237333734373537363737373831 unmodified lines37703771377237733774377553 unmodified lines38293830383138323833383488 unmodified lines39233924392539263927392839293930393139323933393439353936393739383939394013 unmodified lines3954395539563957395839593960396139623963396457 unmodified lines40224023402440254026402710 unmodified lines4038403940404041404240434044404540464047404840494050405140524053405440553 unmodified lines40594060406140624063406440654066406760 unmodified lines41284129413041314132413341344135426 unmodified lines45624563456445654566456730 unmodified linesfrom app.services.retrieval_cache import RetrievalCacheServicefrom app.services.retrieval import RetrievalService, MIN_USABLE_CONTEXT_CHARS, usable_context_charsfrom app.services.router import QueryRouter# All modes now use cloud LLM; tier is determined dynamically by _pick_model_tier()_CLOUD_MODES = {"exam", "assignment", "qa", "lesson_prep"}331 unmodified linesq["choices"] = new_choices[:len(choices)]# Subjects whose exam questions should be computational (solve/calculate/derive)# rather than definitional — keyword match is deliberately simple, same style# as ContentTypeDetector, since the subject name always arrives as free text238 unmodified lines)def _build_exam_review_prompt(language: str) -> str:review_lang_directive = _review_output_language_directive(language)return (52 unmodified lines# Above this overlap, two questions are treated as testing the same concept._DUPLICATE_CONCEPT_THRESHOLD = 0.6_REROLL_HINTS = {"duplicate_concept": ("هذا السؤال يكرر مفهومًا مغطى بالفعل في سؤال آخر بنفس القسم — أنشئ سؤالًا ""بديلاً عن جانب مختلف تمامًا من المحتوى المصدر."39 unmodified linesflagged: list[int] = []reasons: dict[int, str] = {}# 1. Duplicate-concept clustering — keep the first occurrence, flag later ones.# Terms shared by most of the section (e.g. the organism/topic name# appearing in nearly every question) are discounted first — otherwise5 unmodified linesterm_doc_freq = _Counter(w for k in keys for w in k)common_terms = {w for w, c in term_doc_freq.items() if c > max(2, n // 2)}keys = [k - common_terms for k in keys]already = set()for i in range(n):if i in already:continue5 unmodified linesflagged.append(j)reasons[j] = "duplicate_concept"# 2. "hard"-labeled questions that read as plain recall.# Two independent checks, either one is enough to flag: (a) the phrasing# itself reads as recall (no scenario/comparison/reason marker), or67 unmodified linesreturn {"flagged": flagged, "reasons": reasons}def _apply_source_chunk_ids(questions: list[dict],chunk_ids: list[str],59 unmodified linesquestions: list[dict], stype: str, *, retrieval_confidence: float = 1.0,source_pool_size: Optional[int] = None,difficulty_target: Optional[dict[str, int]] = None,) -> dict:"""Structured quality telemetry for one finished section (post-reroll).34 unmodified linesbloom_balance, stem_balance, difficulty_balance = _quality_subscores(bloom_counts, category_counts, difficulty_counts, n, difficulty_target,)quality_index = _composite_quality_index(concept_uniqueness=concept_uniqueness,coverage_ratio=coverage_ratio,bloom_balance=bloom_balance,stem_balance=stem_balance,difficulty_balance=difficulty_balance,)return {13 unmodified lines# without recomputing anything from the raw percentages above."bloom_balance": bloom_balance,"stem_balance": stem_balance,"difficulty_balance": difficulty_balance,# Which of the two difficulty_balance definitions produced the number# above — the two are not comparable, so a dashboard mixing exams with# and without an AssessmentIntent target needs to split on this."difficulty_scored_against": "target" if difficulty_target else "spread",# 0-100, monitoring only — never shown to teachers. Named "index" not# "score" deliberately: it's a relative signal for comparing exams to# each other over time, not a claim of objective exam quality.86 unmodified lines# always rewarding spread via entropy — which scored an exam 0.0 for delivering# exactly the single difficulty it was asked for. Falls back to entropy when no# target was given; `difficulty_scored_against` says which was used._QUALITY_HEURISTIC_VERSION = "2026-08.3"# Mirrors the weighting scheme: concept uniqueness and source coverage matter# most (both are grounded in retrieval evidence, not text heuristics), Bloom# balance next, stem/difficulty balance least (softest signals)._QUALITY_INDEX_WEIGHTS = {"concept_uniqueness": 0.25,"coverage": 0.25,"bloom_balance": 0.20,"stem_balance": 0.15,"difficulty_balance": 0.15,}def _composite_quality_index(*, concept_uniqueness: float, coverage_ratio: float | None,bloom_balance: float, stem_balance: float, difficulty_balance: float,) -> float:"""Weighted 0-100 monitoring index — never used to drive rerolls, andnever shown to teachers. Purely for comparing prompt/model revisions and13 unmodified lines}if coverage_ratio is not None:components["coverage"] = min(1.0, coverage_ratio)total_weight = sum(_QUALITY_INDEX_WEIGHTS[k] for k in components)index = sum(_QUALITY_INDEX_WEIGHTS[k] * v for k, v in components.items()) / total_weight7 unmodified lines# Human-readable reason shown when a section's weakest subscore explains why# it dragged the exam average down — keyed the same as QualitySubscores._QUALITY_SUBSCORE_REASONS = {"concept_uniqueness": "بعض الأسئلة تختبر نفس الفكرة تقريبًا (تكرار مفاهيمي)","coverage": "الأسئلة مبنية على جزء محدود من المحتوى المصدر (تغطية ضعيفة)","bloom_balance": "أغلب الأسئلة استرجاعية ولا تتطلب تحليلاً أو تطبيقًا كافيًا",124 unmodified linesreturn sum(v * w for v, w in usable) / total_wdef _confidence_label(score: float) -> str:if score >= 85:return "very_high"146 unmodified lines[(m["concept_uniqueness"], m["count"]) for _, m in scored_sections]), 1),"stem_balance": round(100 * _weighted_avg([(m["stem_balance"], m["count"]) for _, m in scored_sections]), 1),}retrieval_confidence = round(100 * _weighted_avg([(m["retrieval_confidence"], m["count"]) for _, m in scored_sections]), 1)6 unmodified lines"stem_balance": subscores["stem_balance"] - 100 * lowest_metrics["stem_balance"],"difficulty_balance": subscores["difficulty_balance"] - 100 * lowest_metrics["difficulty_balance"],}weakest_key = max(sub_gaps, key=lambda k: sub_gaps[k])reason = _QUALITY_SUBSCORE_REASONS[weakest_key]lowest_section = {7 unmodified lineselse:weighted_overall = 0.0subscores = {"coverage": 0.0, "difficulty_balance": 0.0, "bloom_balance": 0.0,"concept_uniqueness": 0.0, "stem_balance": 0.0}retrieval_confidence = 0.0lowest_section = Nonewarnings = []25 unmodified lines"overall": weighted_overall,"weighted_overall": weighted_overall,"subscores": subscores,"lowest_section": lowest_section,"warnings": warnings,"retrieval_confidence": retrieval_confidence,1415 unmodified lines# rule 5 below falls back to its original generic instruction,# unchanged from before this parameter existed.difficulty_target: dict[str, int] | None = None,) -> str:"""Build a focused system prompt for generating a single exam section."""language_directive = _exam_language_directive(language)80 unmodified lines# With a resolved AssessmentIntent target, name exact counts instead of# the generic "vary difficulty" instruction — otherwise (None) this is# the original sentence, unchanged.if difficulty_target:difficulty_rule = ("- وزّع الأسئلة على مستويات الصعوبة بالضبط كالتالي: "f"{difficulty_target.get('easy', 0)} سهل (easy)، "f"{difficulty_target.get('medium', 0)} متوسط (medium)، "f"{difficulty_target.get('hard', 0)} صعب (hard) — من أصل {count} سؤالاً. ""أسئلة hard يجب أن تربط بين فكرتين أو أكثر من ""النص (مثال: نتيجة سريرية + سبب + علاج) بدلاً من استرجاع حقيقة واحدة معزولة.\n")else:difficulty_rule = ("- نوّع مستوى الصعوبة: easy, medium, hard. أسئلة hard يجب أن تربط بين فكرتين أو أكثر من ""النص (مثال: نتيجة سريرية + سبب + علاج) بدلاً من استرجاع حقيقة واحدة معزولة.\n")# Ordered most-stable-first so the prompt has a long, byte-identical21 unmodified lines"مباشر عنها.\n""4. لكل سؤال اختيار من متعدد، اجعل الاختيارات الخاطئة (المشتتات) من نفس الفئة أو الموضوع ""الفرعي للإجابة الصحيحة (مثال: أطوار دورة حياة أخرى، أنواع أخرى من نفس الجنس، مصطلحات ""متشابهة) وليست خيارات غير منطقية يسهل استبعادها بالحدس.\n""5. لا ترتّب الأسئلة بنفس تسلسل المواضيع كما وردت في المصدر — نوّع/اخلط بين المواضيع ""الفرعية عبر أسئلة هذا القسم بدلاً من تغطيتها بنفس الترتيب الخطي للنص.\n")section_spec = ("\n=== مواصفات هذا القسم ===\n"f"- نوع الأسئلة: {section_type}\n"2 unmodified linesf"- {extra_note}")batch_spec = ("\n=== تعليمات هذه الدفعة ===\n"f"- أنشئ بالضبط {count} أسئلة — لا أكثر ولا أقل.\n"15 unmodified linesreturn (general_rules+ section_spec+ batch_spec# Deliberately outside the numbered rule list and stated last: this# is the one field the model has no prior instinct for, and burying579 unmodified lines# actually drives wall-clock here — sections run concurrently, so# the slowest section's serial chain is the exam's floor.timings = {"retrieval_ms": 0.0, "generate_ms": 0.0, "topup_ms": 0.0,"reroll_ms": 0.0, "calls": 0}def _elapsed_ms(started: float) -> float:return (time.perf_counter() - started) * 100057 unmodified lines# — a thin source caps how spread-out coverage can realistically be.context_batches_total = 0context_batches_ok = 0for batch_idx, batch_count in enumerate(batches):# Open a fresh session only for the DB read, then close it before# the LLM call (which may take 60+ s and would hold the connection idle).batch_figure_urls: list[str] = []51 unmodified lineslast_chunk_ids = batch_chunk_ids or last_chunk_idslast_figure_urls = batch_figure_urls or last_figure_urlslast_block_chunk_ids = batch_block_chunk_ids or last_block_chunk_idssection_user_msg = (f"السؤال: {question_text}\n\n"f"النص من الكتاب المدرسي:\n\n{assembled.text}\n\n"9 unmodified lineshas_figures=bool(batch_figure_urls),language=exam_language,difficulty_target=_difficulty_counts_for_section(batch_count, difficulty_target),source_block_count=len(batch_block_chunk_ids) if batch_has_context else 0,)try:_t_llm = time.perf_counter()31 unmodified lines_apply_source_chunk_ids(normalized_questions, batch_chunk_ids, batch_block_chunk_ids,)added = _append_unique_questions(all_questions, normalized_questions)logger.info("Section %d/%d (%s) batch %d/%d: %d questions",53 unmodified lines)if retry_has_context:last_context_text = assembled.text or last_context_textlast_image_urls = retry_image_urls or last_image_urlslast_chunk_ids = retry_chunk_ids or last_chunk_idslast_figure_urls = retry_figure_urls or last_figure_urls88 unmodified linesall_questions, stype, retrieval_confidence=retrieval_confidence,source_pool_size=section_pool_size,)# Bounded reroll budget: capping to ~1/4 of the section keeps# the fix targeted at the worst offenders (the flagged list is# already priority-ordered — duplicates first, then fake-hard,# then stem repetition) rather than rewriting half the exam.reroll_budget = max(2, len(all_questions) // 4)reroll_indices = review["flagged"][:reroll_budget]if reroll_indices:logger.info("Section %d/%d (%s) quality review: %d/%d flagged (%s) — rerolling %d",idx + 1, total_sections, stype, len(review["flagged"]),len(all_questions), review["reasons"], len(reroll_indices),)# One call for the whole reroll set, not one per question.# These are independent replacements — nothing in a reroll# depends on the previous reroll's output — so running them13 unmodified lines# ask for, so slot j's instruction lands on the question# that actually had that defect.reasons_in_order = [review["reasons"].get(r_idx, "default") for r_idx in reroll_indices]hint_lines = [f"- البديل رقم {slot + 1}: {_REROLL_HINTS.get(reason, _REROLL_HINTS['default'])}"for slot, reason in enumerate(reasons_in_order)]hint = (f"أنشئ {len(reroll_indices)} سؤالاً بديلاً بالترتيب، كل بديل يعالج المشكلة "57 unmodified linesstype, len(reroll_indices), reasons_in_order, e,)_shuffle_mcq_answer_positions(all_questions)section_quality_metrics: Optional[dict] = None10 unmodified linesdifficulty_target=_difficulty_counts_for_section(len(all_questions), difficulty_target,),)# Structured + greppable: one line per finished section, meant# to be aggregated across exams over time (recall vs.# application mix, coverage, concept uniqueness) rather than# read one-off — the "teacher analytics" telemetry request.logger.info("Exam section quality metrics: %s", json.dumps(section_quality_metrics, ensure_ascii=False))timings["total_ms"] = round(timings["retrieval_ms"] + timings["generate_ms"]+ timings["topup_ms"] + timings["reroll_ms"], 1,)for _k in ("retrieval_ms", "generate_ms", "topup_ms", "reroll_ms"):timings[_k] = round(timings[_k], 1)logger.info("Section %d/%d (%s): %d total questions — timings %s",3 unmodified lines# `quality_metrics` rides along on the section result so the# exam-level `generation_insights` aggregation below can reuse it# without recomputing anything — see GenerationInsights.return {"title": title,"questions": all_questions,"quality_metrics": section_quality_metrics,"timings": timings,}60 unmodified lines}, ensure_ascii=False),)all_sections = [{"title": sec.get("title"), "questions": sec.get("questions", [])}for sec in all_sections]426 unmodified linesreview = ExamReview(overall=50.0, summary="", findings=[], missing_topics=[])return review.model_dump()async def improve_single_question(self, question: dict, *, client: httpx.AsyncClient, focus: Optional[str] = None,language: str = "AR",30 unmodified lines31323334353637331 unmodified lines369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418238 unmodified lines65765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873952 unmodified lines79279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295339 unmodified lines99399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610275 unmodified lines1033103410351036103710381039104010415 unmodified lines10471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111267 unmodified lines11801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156359 unmodified lines162316241625162616271628162934 unmodified lines166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169113 unmodified lines1705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173386 unmodified lines182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185913 unmodified lines187318741875187618771878187918801881188218831884188518867 unmodified lines189418951896189718981899190019011902190319041905124 unmodified lines20302031203220332034203520362037203820392040204120422043204420452046204720482049146 unmodified lines2196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122226 unmodified lines22292230223122322233223422352236223722382239224022417 unmodified lines224922502251225222532254225522562257225825 unmodified lines228422852286228722882289229022912292229322941415 unmodified lines3710371137123713371437153716371737183719372080 unmodified lines38013802380338043805380638073808380938103811381238133814381538163817381838193820382121 unmodified lines38433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939002 unmodified lines390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393615 unmodified lines395239533954395539563957395839593960579 unmodified lines454045414542454345444545454645474548454957 unmodified lines46074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463051 unmodified lines4682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447059 unmodified lines47154716471747184719472047214722472347244725472647274728472931 unmodified lines4761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478353 unmodified lines483748384839484048414842484388 unmodified lines49324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498213 unmodified lines49964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501957 unmodified lines5077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513510 unmodified lines5146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151723 unmodified lines517651775178517951805181518251835184518551865187518851895190519160 unmodified lines52525253525452555256525752585259526052615262526352645265526652675268426 unmodified lines569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577030 unmodified linesfrom app.services.retrieval_cache import RetrievalCacheServicefrom app.services.retrieval import RetrievalService, MIN_USABLE_CONTEXT_CHARS, usable_context_charsfrom app.services.router import QueryRouterfrom app.services.text_quality import normalize_arabic# All modes now use cloud LLM; tier is determined dynamically by _pick_model_tier()_CLOUD_MODES = {"exam", "assignment", "qa", "lesson_prep"}331 unmodified linesq["choices"] = new_choices[:len(choices)]# The same class of leak as answer *position*, on the length axis — and the# one _shuffle_mcq_answer_positions can't fix, because reordering options# doesn't change how long they are.## A model writing four options spends its effort on the one it knows is# correct and discards the other three, so the correct option comes out# visibly longer and more qualified. Measured over three generated exams of# the same blueprint, the correct option was the longest one in 14/20, 12/20# and 19/20 MCQs, averaging 1.4x the length of its distractors — meaning a# student who never reads a single stem and always picks the longest option# scores up to 95% on section one. That is an exam-integrity defect, not a# style preference, so it's treated as blocking (see _INTEGRITY_REASONS).## Threshold is "strictly longest AND meaningfully longer": a correct answer# that happens to win by two characters is noise, not a cue a student can# actually exploit._LENGTH_LEAK_RATIO = 1.25def _mcq_length_leak(question: dict) -> bool:"""True when an MCQ's correct option is guessable from its length alone."""if question.get("type") != "mcq":return Falsechoices = question.get("choices")answer = str(question.get("answer", "")).strip()if not isinstance(choices, list) or len(choices) < 3 or not answer:return Falsetexts = [str(c).strip() for c in choices]if answer not in texts:return False # answer doesn't match a choice verbatim — nothing to comparedistractors = [t for t in texts if t != answer]if not distractors:return Falseanswer_len = len(answer)if answer_len <= max(len(d) for d in distractors):return False # not the longest — no length cuemean_distractor = sum(len(d) for d in distractors) / len(distractors)if mean_distractor <= 0:return Falsereturn answer_len >= _LENGTH_LEAK_RATIO * mean_distractor# Subjects whose exam questions should be computational (solve/calculate/derive)# rather than definitional — keyword match is deliberately simple, same style# as ContentTypeDetector, since the subject name always arrives as free text238 unmodified lines)# ── Red team ────────────────────────────────────────────────────────────────## The deterministic checks in `_review_section_quality` can see structure (does# this question have a task shape, are the options guessable by length, does it# duplicate another). They cannot see meaning — whether a question is actually# answerable without having read the lesson, or whether three of its four# options can be dismissed on general knowledge. Those need a reader.## So this is the one place an LLM judgment is bought, and it is bought# narrowly: one batched call per section, over hard-labeled questions only,# asking five yes/no questions that each have a defensible right answer. It is# explicitly *not* asked "is this hard?" — a model asked that grades its own# homework and says yes._RED_TEAM_SCHEMA_HINT = ('أرجع النتيجة كـ JSON فقط بدون أي نص إضافي بهذا الهيكل بالضبط:\n''{"verdicts": [{"n": رقم السؤال كما أُعطي لك, ''"answerable_without_lesson": true أو false, ''"solvable_by_general_logic": true أو false, ''"distractors_eliminable": true أو false, ''"needs_multiple_evidence": true أو false, ''"clear": true أو false, ''"note": "سبب قصير جدًا للحكم السلبي الأهم، أو نص فارغ"}]}\n''أعطِ حكمًا لكل سؤال أُعطي لك، بنفس أرقامه، ولا تضف أسئلة من عندك.')def _build_red_team_prompt(language: str) -> str:"""Rubric for attacking hard questions, not for admiring them.Each field is phrased so that `true` is the *bad* answer wherever a defectis being probed, except `needs_multiple_evidence` and `clear` — statedpositively because a negative-only schema made the model drift towardanswering everything `false`."""review_lang_directive = _review_output_language_directive(language)return ("أنت ممتحِن خبير مهمتك مهاجمة أسئلة الامت��ان لا مدحها. افترض أنك طالب ذكي ""لم يدرس هذا الدرس إطلاقًا، وحاول الوصول إلى الإجابة الصحيحة بأي وسيلة.\n""لكل سؤال، أجب عن خمسة أحكام:\n""1. answerable_without_lesson: هل يمكن لطالب لم يقرأ نص هذا الدرس تحديدًا أن ""يجيب إجابة صحيحة؟ (true = عيب في السؤال)\n""2. solvable_by_general_logic: هل يمكن الوصول للإجابة بالمنطق العام أو الثقافة ""العامة دون معرفة المحتوى؟ (true = عيب)\n""3. distractors_eliminable: في أسئلة الاختيار من متعدد، هل يمكن استبعاد ثلاثة ""خيارات دون فهم المادة (لأنها غير منطقية، أو مبالغ فيها، أو أقصر/أطول بشكل ""لافت)؟ (true = عيب. في غير الاختيار من متعدد ضع false)\n""4. needs_multiple_evidence: هل تتطلب الإجابة الجمع بين معلومتين أو تفاعل ""قاعدتين، بدل معلومة واحدة معزولة؟ (false = السؤال ليس صعبًا فعليًا)\n""5. clear: هل السؤال مفهوم فورًا وله معنى واحد فقط؟ (false = صياغة غامضة أو ""معقدة بلا داعٍ)\n""احكم على السؤال كما هو مكتوب، لا على ما تظن أنه يقصده. لا تجامل.\n"f"{review_lang_directive}\n\n{_RED_TEAM_SCHEMA_HINT}")# Verdict -> reroll reason. Ordered by severity: a question answerable without# the lesson isn't testing the lesson at all, which outranks it merely being# guessable or shallow._RED_TEAM_FAILURES: list[tuple[str, bool, str]] = [("answerable_without_lesson", True, "not_source_dependent"),("distractors_eliminable", True, "weak_distractors"),("solvable_by_general_logic", True, "solvable_without_content"),("clear", False, "unclear_wording"),("needs_multiple_evidence", False, "single_evidence"),]def _red_team_failures(verdict: dict) -> list[str]:"""Reasons this question failed the attack, worst first."""out = []for field, bad_value, reason in _RED_TEAM_FAILURES:value = verdict.get(field)if isinstance(value, bool) and value is bad_value:out.append(reason)return outdef _build_exam_review_prompt(language: str) -> str:review_lang_directive = _review_output_language_directive(language)return (52 unmodified lines# Above this overlap, two questions are treated as testing the same concept._DUPLICATE_CONCEPT_THRESHOLD = 0.6# Reasoning families a genuinely hard question is expected to belong to —# the review's §22 "controlled family" list, reduced to the markers that# actually survive Arabic paraphrase. The point is the distinction the review# draws in §1: a hard question should be hard to *answer*, not hard to *read*.## What made the measured exams fake-hard is that "hard" was produced by# appending a clause to a medium question ("...وكيف يعكس ذلك فهمه لطبيعة# الصراع؟"), which reads as analysis to any marker-based Bloom heuristic —# _bloom_level_heuristic classifies anything containing "لماذا" as analysis,# so the existing hard_but_recall check could never fire on it. These markers# are deliberately narrower than _REASON_MARKERS: they describe a *task# structure* (diagnose an error, resolve a conflict between two rules,# transform and re-derive, compare a minimal pair) rather than an# interrogative mood._ERROR_DIAGNOSIS_MARKERS = ["أخطأ", "خطأ الطالب", "حدّد موضع الخطأ", "حدد موضع الخطأ", "قال طالب","كتب أحد الطلاب", "ما الخطأ", "أين الخطأ", "هل يصح حكمه", "صحّح التحليل","error in", "what is wrong with", "identify the mistake",]_RULE_CONFLICT_MARKERS = ["أيهما تنطبق", "أي القاعدتين", "هل تنطبق القاعدة", "لا يكفي أن نقول","لا يكفي الشكل", "ما الدليل الذي يستبعد", "التعميم", "بصورتها المطلقة","which rule applies", "why is the generalization",]_TRANSFORMATION_MARKERS = ["أعد صياغة", "لو استبدلنا", "إذا استبدلنا", "لو غُيّر", "لو غيرنا","بحيث تصبح", "أعد كتابة", "ماذا يحدث لو", "rewrite", "if we replaced",]_MINIMAL_PAIR_MARKERS = ["في الموضعين", "في الحالتين", "في الجملتين", "الفرق بين الجملتين","رغم ثبات", "مع أنها الكلمة نفسها", "سبب اختلاف",]_TRANSFER_MARKERS = ["من إنشائك", "في مثال جديد", "طبّق القاعدة نفسها", "طبق القاعدة نفسها","مثال من عندك", "your own example",]_MULTI_EVIDENCE_MARKERS = ["صنّف الجمل", "صنف الجمل", "أي الجمل", "بالاعتماد على الفقرتين","من خلال الموضعين", "ثم فسّر", "ثم بيّن", "ثم حدّد", "ثم اذكر",]# One flat lookup — a hard question needs at least one of these to count as# structurally hard. Kept as a tuple of (family, markers) so Phase 2's# difficulty scoring can report *which* family a question belongs to rather# than just a boolean._HARD_FAMILY_MARKERS: list[tuple[str, list[str]]] = [("error_diagnosis", _ERROR_DIAGNOSIS_MARKERS),("rule_conflict", _RULE_CONFLICT_MARKERS),("transformation", _TRANSFORMATION_MARKERS),("minimal_pair", _MINIMAL_PAIR_MARKERS),("transfer", _TRANSFER_MARKERS),("multi_evidence", _MULTI_EVIDENCE_MARKERS),]def _hard_family(question_text: str) -> Optional[str]:"""Which reasoning family a question's task structure belongs to, if any."""t = (question_text or "").strip().lower()for family, markers in _HARD_FAMILY_MARKERS:if any(m in t for m in markers):return familyreturn None# How much of the smaller question's concept set has to sit inside the larger# one before the pair is treated as the same question at two difficulties.# Containment rather than Jaccard on purpose: "medium + one extra clause" is# asymmetric by construction, so Jaccard (which the existing duplicate check# uses) is diluted by the added words and stays under its 0.6 bar — the# measured pair below scores Jaccard 0.22, which is why check 1 never saw it.## Thresholds are tuned against the one confirmed real instance, a medium/hard# pair from the same MCQ section of a generated exam:# medium: ما السبب الذي دفع صلاح الدين للبدء بفتح المدن الساحلية قبل القدس؟# hard: لماذا أصر صلاح الدين على تحرير المدن الساحلية قبل التوجه لتحرير# القدس، وكيف يعكس ذلك فهمه لطبيعة الصراع؟# which scores stem containment 0.54 and answer containment 0.50. At these# values the check fires on exactly that pair and nothing else across the 183# questions of three measured exams. Caveat worth knowing before retuning:# that is one positive example, so the thresholds are set to catch it without# false positives on the sample available, not validated on a broad corpus.# The conjunction (strictly higher difficulty label AND stem containment AND# answer containment) is what makes a value this loose selective._DIFFICULTY_EQUIVALENCE_CONTAINMENT = 0.5# ...and the two must also be asking for the same thing, not merely sharing# vocabulary — checked on the answers, which is where "same question" really# shows up. Containment again rather than Jaccard: generated variants# paraphrase their answers ("لحرمان الصليبيين من قواعدهم البحرية" vs "لقطع# خطوط الإمداد البحرية التي تربط الصليبيين بأوروبا"), which scores Jaccard# 0.15 — same answer, different words._DIFFICULTY_EQUIVALENCE_ANSWER_OVERLAP = 0.5_DIFFICULTY_RANK = {"easy": 0, "medium": 1, "hard": 2}def _containment(a: set[str], b: set[str]) -> float:"""Fraction of the smaller set contained in the larger one."""if not a or not b:return 0.0return len(a & b) / min(len(a), len(b))# Defects that are exam-integrity bugs rather than style preferences: a# student can exploit these without knowing any of the material. They jump the# reroll queue and get budget of their own (see the reroll block), because# capping them under the same ~1/4 style budget meant a section with 19 leaked# MCQs could only ever have 5 of them fixed._INTEGRITY_REASONS = frozenset({"option_length_leak", "answer_leakage"})_REROLL_HINTS = {"option_length_leak": ("الإجابة الصحيحة في هذا السؤال أطول بوضوح من باقي الخيارات، فيستطيع الطالب ""تخمينها دون قراءة السؤال. أعد كتابة السؤال بحيث تكون الخيارات الأربعة ""متقاربة في الطول وفي مستوى التفصيل، ولا تجعل الإجابة الصحيحة أطولها."),"answer_leakage": ("إجابة هذا السؤال مذكورة نصًا داخل صياغة سؤال آخر في نفس القسم — أنشئ سؤالًا ""بديلاً عن جانب آخر من المحتوى لا تكشفه صياغة أي سؤال موجود."),"inflated_difficulty": ("هذا السؤال هو نفسه سؤال آخر في القسم بعد إضافة عبارة زائدة (مثل «وكيف يعكس ""ذلك...؟») — الإجابة والدليل المطلوبان لم يتغيرا. الصعوبة تأتي من صعوبة الوصول ""إلى الإجابة، لا من طول الجملة: أنشئ سؤالًا يطلب خطوة استدلالية إضافية حقيقية ""(تشخيص خطأ، أو تعارض قاعدتين، أو تحويل الجملة، أو مقارنة زوج متقارب)."),# Red-team verdicts (see _build_red_team_prompt). These come from a reader,# not a heuristic, so the hints can be specific about what to change."not_source_dependent": ("طالب لم يقرأ هذا الدرس يستطيع الإجابة عن هذا السؤال — إذن السؤال لا يختبر ""الدرس. أنشئ سؤالًا بديلاً لا يمكن الإجابة عنه إلا بمعلومة أو قاعدة وردت في ""النص المرفق تحديدًا."),"weak_distractors": ("يمكن استبعاد ثلاثة من خيارات هذا السؤال دون فهم المادة. اجعل كل خيار خاطئ ""خطأً شائعًا يقع فيه طالب فعلًا، ومتقاربًا مع الإجابة الصحيحة في الطول ومستوى ""التفصيل ودرجة المعقولية."),"solvable_without_content": ("يمكن الوصول لإجابة هذا السؤال بالمنطق العام دون معرفة المحتوى. اجعل الإجابة ""متوقفة على تفصيل محدد من النص لا يمكن تخمينه."),"unclear_wording": ("صياغة هذا السؤال غامضة أو تحتمل أكثر من معنى. أعد صياغته بجملة قصيرة واضحة ""لها معنى واحد فقط — مع الإبقاء على صعوبة الاستدلال المطلوب كما هي أو أعلى."),"single_evidence": ("هذا السؤال يعتمد على معلومة واحدة معزولة. اجعله يتطلب الجمع بين موضعين من ""النص أو تفاعل قاعدتين للوصول إلى الإجابة."),"shallow_hard": ("هذا السؤال مصنّف صعبًا لكن بنيته بنية سؤال مباشر. أعد بناءه على هيئة واحدة من ""الأنماط التالية: (1) طالب أخطأ في التحليل — أين الخطأ ولماذا؟ ""(2) قاعدتان تبدوان ممكنتين — أيهما تنطبق وما الدليل الذي يستبعد الأخرى؟ ""(3) حوّل الجملة ثم فسّر سبب تغيّر الحكم. (4) موضعان متقاربان — لماذا اختلف ""الحكم فيهما؟ اجعل الصياغة قصيرة وواضحة، والصعوبة في الاستدلال لا في اللغة."),"duplicate_concept": ("هذا السؤال يكرر مفهومًا مغطى بالفعل في سؤال آخر بنفس القسم — أنشئ سؤالًا ""بديلاً عن جانب مختلف تمامًا من المحتوى المصدر."39 unmodified linesflagged: list[int] = []reasons: dict[int, str] = {}# 0a. Integrity: MCQ answer guessable from option length alone. Checked# before anything else because it's the one defect here a student can# exploit while knowing none of the material — see _mcq_length_leak.already_integrity: set[int] = set()for i, q in enumerate(questions):if _mcq_length_leak(q):already_integrity.add(i)flagged.append(i)reasons[i] = "option_length_leak"# 0b. Integrity: one question's answer printed verbatim inside another# question's stem, within this section. The exam-level pass# (_cross_section_findings) already detects this, but only after all# rerolls are spent — so it could report the defect and never fix it.# Same normalization and minimum length as that pass, so the two agree on# what counts as a leak; the difference is purely that this one is# actionable while the reroll budget is still open.stems = [_normalize_query(str(q.get("question", "") or "")) for q in questions]for i, q in enumerate(questions):if i in already_integrity:continueanswer = _normalize_query(str(q.get("answer", "") or ""))if len(answer) < _ANSWER_LEAKAGE_MIN_CHARS:continueif any(answer in stem for j, stem in enumerate(stems) if j != i):already_integrity.add(i)flagged.append(i)reasons[i] = "answer_leakage"# 1. Duplicate-concept clustering — keep the first occurrence, flag later ones.# Terms shared by most of the section (e.g. the organism/topic name# appearing in nearly every question) are discounted first — otherwise5 unmodified linesterm_doc_freq = _Counter(w for k in keys for w in k)common_terms = {w for w, c in term_doc_freq.items() if c > max(2, n // 2)}keys = [k - common_terms for k in keys]# Seeded with the integrity flags above so a question already queued for# replacement isn't flagged twice under a second, weaker reason.already = set(already_integrity)for i in range(n):if i in already:continue5 unmodified linesflagged.append(j)reasons[j] = "duplicate_concept"# 1b. Difficulty inflation — the same question at two difficulty labels,# the harder one being the easier one plus a clause. Measured example from# one generated exam, both in the same MCQ section:# medium: ما السبب الذي دفع صلاح الدين للبدء بفتح المدن الساحلية قبل القدس؟# hard: لماذا أصر صلاح الدين على تحرير المدن الساحلية قبل التوجه لتحرير# القدس، وكيف يعكس ذلك فهمه لطبيعة الصراع؟# Same fact, same answer, one clause longer. Check 1 above cannot see this:# the added words dilute Jaccard below its 0.6 bar, which is exactly why# containment is used here instead (see _DIFFICULTY_EQUIVALENCE_*). Only# the higher-labeled question is flagged — the easier one is fine as it is,# and it's the "hard" slot that isn't earning its label.for i in range(n):for j in range(n):# Only `i` (the harder-labeled question, the one that would be# replaced) has to be unflagged. `j` is read as evidence, not# rewritten, so it being queued for its own reroll is irrelevant —# requiring it to be clean is what let the measured pair slip# through, since its easier half was already flagged for a length# leak.if i == j or i in already:continuerank_i = _DIFFICULTY_RANK.get(str(questions[i].get("difficulty", "")).lower(), -1)rank_j = _DIFFICULTY_RANK.get(str(questions[j].get("difficulty", "")).lower(), -1)if rank_i <= rank_j:continue # only flag the strictly-harder-labeled one of a pairif _containment(keys[i], keys[j]) < _DIFFICULTY_EQUIVALENCE_CONTAINMENT:continueans_i = _concept_key({"question": str(questions[i].get("answer", "") or "")})ans_j = _concept_key({"question": str(questions[j].get("answer", "") or "")})if _containment(ans_i, ans_j) < _DIFFICULTY_EQUIVALENCE_ANSWER_OVERLAP:continuealready.add(i)flagged.append(i)reasons[i] = "inflated_difficulty"break# 1c. "hard" questions with no hard task structure at all. Distinct from# check 2 below, which asks whether the phrasing reads as recall: this asks# whether the question belongs to any of the reasoning families a hard# question is supposed to come from (error diagnosis, rule conflict,# transformation, minimal pair, transfer, multi-evidence — see# _HARD_FAMILY_MARKERS). A question can pass the Bloom heuristic purely by# containing "لماذا" and still be a one-step lookup; this is the check that# notices, and it's the reason the measured exams could report# difficulty_balance = 100 while nothing about the questions got harder.## Only applied where the section type has room for a task structure —# true_false and fill_blank are single-proposition formats by construction,# so demanding a reasoning family from them would flag every question.if stype in {"mcq", "short_answer", "essay", "compare"}:for i, q in enumerate(questions):if i in already:continueif str(q.get("difficulty", "")).lower() != "hard":continueif _hard_family(_question_review_text(q)) is None:already.add(i)flagged.append(i)reasons[i] = "shallow_hard"# 2. "hard"-labeled questions that read as plain recall.# Two independent checks, either one is enough to flag: (a) the phrasing# itself reads as recall (no scenario/comparison/reason marker), or67 unmodified linesreturn {"flagged": flagged, "reasons": reasons}# ── Measured difficulty (what a question actually demands) ───────────────────## `difficulty_balance` scores whether the model applied the difficulty *labels*# it was told to apply. That is a real thing to measure, but it is not# difficulty, and treating it as the headline number is how three measured# exams could report difficulty_balance = 100 / 94 / 100 while the only# property that changed between a medium and a hard question was stem length# (mean 73 -> 122 characters). A metric that scores the model's own# self-assessment can never notice that the self-assessment is wrong.## This scores the question instead of the label, from signals that are# decidable in code and that a model cannot satisfy by writing a longer# sentence. Bands follow the ones the difficulty review proposed:## 0-20 trivial 21-40 basic 41-55 medium# 56-70 hard 71-85 very hard 86-100 exceptional## It is an approximation and is not trying to be a grader — its job is to make# the *gap* between requested difficulty and delivered difficulty visible, so# "we asked for 100% hard and got 61% authentically hard" is a number the# system reports rather than something only a human reading the exam notices._DIFFICULTY_BANDS: list[tuple[int, str]] = [(86, "exceptional"),(71, "very_hard"),(56, "hard"),(41, "medium"),(21, "basic"),(0, "trivial"),]# Minimum measured score a question must reach to count as authentically# filling a slot of each requested level._AUTHENTIC_FLOOR = {"easy": 21, "medium": 41, "hard": 56}# A stem this long with nothing structural to show for it is the exact failure# mode being corrected: difficulty performed through wording._VERBOSE_STEM_CHARS = 110def _difficulty_band(score: int) -> str:for floor, name in _DIFFICULTY_BANDS:if score >= floor:return namereturn "trivial"def _measured_difficulty(question: dict, source_terms: Optional[set[str]] = None) -> int:"""Approximate how much a question actually demands, 0-100.Deliberately free and deterministic — this runs on every question of everyexam, so it cannot afford a model call. `source_terms`, when given, is thebag of significant words from the section's retrieved book context; it isused only to notice questions that don't appear to be grounded in it."""text = _question_review_text(question)# Calibration anchors — real questions, with the score this function# actually produces for them (see tests/test_exam_measured_difficulty.py,# which pins these so a weight change can't silently drift the scale):# "ما الاسم الذي أطلقه الكنعانيون على القدس؟" 24 basic# "ما السبب الذي دفع صلاح الدين لفتح المدن الساحلية؟" 39 basic# ...same question with "وكيف يعكس ذلك فهمه؟" appended 31 basic# "قال طالب إن 'مدارس' تُجر بالكسرة. أين الخطأ؟" 57 hard# ...the same, over two sources with worked steps 75 very hard# The third anchor is the load-bearing one: appending a clause must not# raise the score. It in fact lowers it (the verbosity penalty fires),# which is the intended direction — inflation should cost, not pay.# The scale deliberately errs low: this metric exists to stop the system# over-claiming difficulty, so a borderline question reading one band# cooler is the safe direction for it to be wrong in.score = 15 # a well-formed, on-topic question is not a zero# 1. Task structure — the dominant term, and the one that can't be faked by# phrasing. A reasoning family means the student has to *do* something# (diagnose, resolve, transform, compare); a "why" is just a mood.if _hard_family(text):score += 30else:bucket = _question_stem_bucket(text)if bucket in ("scenario", "exception"):score += 18elif bucket in ("comparison", "reason"):score += 12# 2. Conceptual breadth — how many distinct ideas the question touches.concept_terms = len(_concept_key(question))score += min(12, max(0, int((concept_terms - 4) * 1.5)))# 3. Multiple evidence points. A question written from two source blocks# needs both to answer; one written from a single block usually doesn't.if len(question.get("source_chunk_ids") or []) > 1:score += 10# 4. Solution depth, where the model volunteered it.steps = question.get("solution_steps")if isinstance(steps, list) and len(steps) >= 2:score += 8# 5. MCQ option quality. Both directions matter: plausible distractors make# a question genuinely harder, and a length tell makes it trivially easy no# matter what the stem asks.if question.get("type") == "mcq" and isinstance(question.get("choices"), list):choices = [str(c).strip() for c in question["choices"]]answer = str(question.get("answer", "")).strip()distractors = [c for c in choices if c != answer]if _mcq_length_leak(question):score -= 22if distractors and answer:# Distractors drawn from the same conceptual space as the answer# can't be eliminated on sight. Measured as vocabulary overlap,# which is coarse but catches the "obviously absurd option" case# the measured exams were full of.answer_key = _concept_key({"question": answer})overlaps = [_jaccard(answer_key, _concept_key({"question": d})) for d in distractors]mean_overlap = sum(overlaps) / len(overlaps)# Only judged when the options are long enough for vocabulary# overlap to mean anything. A set of one- or two-word proper nouns# ("إيلياء" / "أورشليم" / "أورسالم") shares no tokens by nature and# is a perfectly good distractor set — penalizing it for that was# scoring correct recall questions below trivial.judgeable = all(len(c.split()) >= 3 for c in [answer, *distractors])if mean_overlap >= 0.15:score += 10elif judgeable and mean_overlap < 0.05:score -= 8# Keyword matching: if the correct option shares more vocabulary# with the stem than every distractor does, the question is# answerable by word-matching without understanding it.stem_key = _concept_key({"question": str(question.get("question", ""))})answer_hit = _jaccard(stem_key, answer_key)if distractors and all(answer_hit > _jaccard(stem_key, _concept_key({"question": d}))for d in distractors) and answer_hit > 0:score -= 10# 6. Verbosity penalty — a long stem with no task structure and one source# is difficulty performed rather than difficulty present.if (len(text) > _VERBOSE_STEM_CHARSand not _hard_family(text)and len(question.get("source_chunk_ids") or []) <= 1):score -= 8# 7. Grounding — a question whose vocabulary barely appears in the book# context it was supposedly written from is not testing the lesson,# however hard it looks. Only applied when there's enough source# vocabulary for the comparison to mean anything.if source_terms and len(source_terms) >= 50:if _content_grounding(question, source_terms) < 0.3:score -= 15return max(0, min(100, score))# Single-letter clitics Arabic glues onto the front of a word (و/ف conjunctions,# ب/ك/ل prepositions) plus the definite article. Stripped for grounding# comparison only: the book writes "ورفض" where the question writes "رفض", and# on exact-token matching a perfectly grounded question scored 0.56 purely# because of that. Deliberately not applied to `_concept_key`, whose Jaccard# thresholds elsewhere in this file are tuned against un-stripped tokens._AR_PREFIX_RE = re.compile(r"^(?:وال|فال|بال|كال|لل|ال|و|ف|ب|ك|ل)")def _grounding_token(word: str) -> str:"""Fold one word to the form used for source-grounding comparison."""folded = normalize_arabic(word)stripped = _AR_PREFIX_RE.sub("", folded)# Never strip a word down to nothing meaningful — "ال" alone isn't a stem.return stripped if len(stripped) > 2 else foldeddef _grounding_terms(text: str) -> set[str]:words = re.findall(r"[\w-ۿ]+", (text or "").lower())return {_grounding_token(w) for w in wordsif w not in _STOPWORDS and len(w) > 2}def _content_grounding(question: dict, source_terms: set[str]) -> float:"""Fraction of a question's significant vocabulary attested in the source.The signal behind `content_fidelity`: whether the question was writtenfrom the retrieved book material or from the model's own knowledge of thetopic. Both produce plausible Arabic about the right subject; only one istesting the lesson the teacher selected.Both sides go through `_grounding_terms`, so the comparison is on foldedstems rather than surface forms."""key = _grounding_terms(_question_review_text(question) + " " + str(question.get("answer", "") or ""))if not key:return 0.0return len(key & source_terms) / len(key)def _source_terms(context_text: str) -> set[str]:"""Bag of significant words from assembled book context, for grounding."""return _grounding_terms(context_text)def _difficulty_fidelity(questions: list[dict],difficulty_target: Optional[dict[str, int]],source_terms: Optional[set[str]] = None,) -> dict:"""Requested difficulty vs. difficulty actually delivered.Slots are filled hardest-measured-first: the top `hard` questions bymeasured score are the ones filling the hard slots, and the metric asks howmany of them actually clear the hard floor. That deliberately gives thegenerator the benefit of the doubt about *which* questions were meant to behard — the number still comes out low when nothing is hard, and there's noway to game it by relabeling.Returns the fidelity fraction plus the raw band distribution, because thedistribution is what makes the number actionable ("61% of the hard slotsare actually medium")."""scores = sorted(((_measured_difficulty(q, source_terms), q) for q in questions),key=lambda pair: pair[0],reverse=True,)n = len(scores)band_counts: dict[str, int] = {}for score, _ in scores:band = _difficulty_band(score)band_counts[band] = band_counts.get(band, 0) + 1result = {"measured_bands": band_counts,"mean_measured_difficulty": round(sum(s for s, _ in scores) / n, 1) if n else 0.0,# The "6/5" share the difficulty review asked to track separately."exceptional_pct": round(100 * sum(1 for s, _ in scores if s >= 86) / n, 1) if n else 0.0,"authentic_hard_pct": round(100 * sum(1 for s, _ in scores if s >= 56) / n, 1) if n else 0.0,}if not difficulty_target or not n or sum(difficulty_target.values()) <= 0:result["difficulty_fidelity"] = Nonereturn resultcursor = 0met = 0for level in ("hard", "medium", "easy"):want = difficulty_target.get(level, 0)floor = _AUTHENTIC_FLOOR[level]for score, _ in scores[cursor:cursor + want]:if score >= floor:met += 1cursor += wantresult["difficulty_fidelity"] = round(met / min(n, cursor or n), 3)return result# ── Source-grounded passages ────────────────────────────────────────────────## A passage is 4-5 sentences of book text that several questions are then# written from, so the exam can test transfer and rule interaction instead of# isolated recall.## Critically, the passage is *lifted from the retrieved chunks*, never written# by the model. An invented passage is worse than no passage: it reads as# perfectly good Arabic on the right topic, the questions written from it are# genuinely hard, and none of it is in the book the teacher selected — which# is exactly the "questions aren't about the lesson" failure this is supposed# to fix. Every sentence here traces to a chunk id and a page._SENTENCE_SPLIT_RE = re.compile(r"(?<=[.؟!؛])\s+|\n+")# Lines the assembler injects that are not prose (figure captions, embedded# OCR, markdown tables, source markers) — never part of a reading passage._NON_PROSE_RE = re.compile(r"^\s*(?:\[\[?المصدر|\[تسمية:|\[المعادلة:|\[نص داخل الصورة:|\||-{3,})")_PASSAGE_MIN_SENTENCES = 4_PASSAGE_MAX_SENTENCES = 5# Below this a "sentence" is a heading, a page number or a fragment, not prose._PASSAGE_MIN_SENTENCE_CHARS = 40_PASSAGE_MAX_SENTENCE_CHARS = 400def _prose_sentences(text: str) -> list[str]:"""Split chunk text into usable prose sentences, dropping non-prose lines."""out: list[str] = []for raw in _SENTENCE_SPLIT_RE.split(text or ""):sentence = " ".join(raw.split())if not sentence or _NON_PROSE_RE.match(sentence):continueif not (_PASSAGE_MIN_SENTENCE_CHARS <= len(sentence) <= _PASSAGE_MAX_SENTENCE_CHARS):continueout.append(sentence)return outdef _extract_passage(chunks: list) -> Optional[dict]:"""Build one source-grounded passage from retrieved chunks, or None.Prefers a run of consecutive sentences from a *single* chunk: that keepsthe passage coherent (it was written as continuous prose) and makes itsprovenance exact. Falls back to stitching the opening sentences of severalchunks that share a section title — still entirely book text, still fullyattributed, just assembled.Returns None when the retrieved material has no continuous prose to buildfrom (a page of tables, formulas or headings), in which case the callergenerates ungrouped questions exactly as before. Passage mode is anenhancement to reach for, never a requirement to satisfy."""if not chunks:return Nonedef _page_range(used: list) -> Optional[list[int]]:pages = [p for p in (getattr(c, "page_number", None) for c in used) if p]return [min(pages), max(pages)] if pages else None# 1. A single chunk with enough continuous prose.for chunk in chunks:sentences = _prose_sentences(getattr(chunk, "content", "") or "")if len(sentences) >= _PASSAGE_MIN_SENTENCES:picked = sentences[:_PASSAGE_MAX_SENTENCES]return {"text": " ".join(picked),"source_chunk_ids": [str(chunk.id)] if getattr(chunk, "id", None) else [],"page_range": _page_range([chunk]),"section_title": getattr(chunk, "section_title", None),"assembled": False,}# 2. Stitched from several chunks of the same lesson. Grouped by# section_title so the result reads as one topic rather than a collage.by_section: dict[str, list] = {}for chunk in chunks:by_section.setdefault(str(getattr(chunk, "section_title", "") or ""), []).append(chunk)for _title, group in sorted(by_section.items(), key=lambda kv: -len(kv[1])):picked: list[str] = []used: list = []for chunk in group:sentences = _prose_sentences(getattr(chunk, "content", "") or "")if not sentences:continuepicked.extend(sentences[:2])used.append(chunk)if len(picked) >= _PASSAGE_MAX_SENTENCES:breakif len(picked) >= _PASSAGE_MIN_SENTENCES:return {"text": " ".join(picked[:_PASSAGE_MAX_SENTENCES]),"source_chunk_ids": [str(c.id) for c in used if getattr(c, "id", None)],"page_range": _page_range(used),"section_title": _title or None,"assembled": True,}return None# Families dealt out across a passage group's questions, in this order. The# point of a group is that one context gets attacked from several angles — six# "why" questions about one paragraph is just recall six times — so the# families are assigned per slot rather than left to the model, which# otherwise converges on whichever pattern it wrote first._PASSAGE_FAMILY_CYCLE = [("application", "تطبيق مباشر لقاعدة أو فكرة وردت في النص على موضع محدد فيه"),("minimal_pair", "موضعان متشابهان في النص اختلف الحكم فيهما — ما سبب الاختلاف؟"),("error_diagnosis", "طالب حلّل أحد المواضع في النص تحليلًا خاطئًا — أين الخطأ ولماذا؟"),("transformation", "غيّر عنصرًا في إحدى جمل النص، ثم بيّن ما الذي تغيّر في الحكم وما الذي ثبت"),("multi_evidence", "إجابة تتطلب الجمع بين موضعين مختلفين من النص، لا يكفي فيها موضع واحد"),("rule_conflict", "قاعدتان تبدوان منطبقتين على موضع في النص — أيهما تنطبق وما الدليل المستبعد للأخرى؟"),("transfer", "طبّق القاعدة المستخلصة من النص على مثال جديد من إنشائك لم يرد فيه"),("comparison", "قارن بين موقفين أو فكرتين وردتا في النص، وبيّن أثر الفرق بينهما"),]def _apply_source_chunk_ids(questions: list[dict],chunk_ids: list[str],59 unmodified linesquestions: list[dict], stype: str, *, retrieval_confidence: float = 1.0,source_pool_size: Optional[int] = None,difficulty_target: Optional[dict[str, int]] = None,source_terms: Optional[set[str]] = None,) -> dict:"""Structured quality telemetry for one finished section (post-reroll).34 unmodified linesbloom_balance, stem_balance, difficulty_balance = _quality_subscores(bloom_counts, category_counts, difficulty_counts, n, difficulty_target,)# Measured difficulty, independent of the labels the model assigned — see# _measured_difficulty. `difficulty_balance` above answers "did it apply# the labels it was asked for"; this answers "are the questions actually# that hard", and the gap between the two is the diagnostic.fidelity = _difficulty_fidelity(questions, difficulty_target, source_terms)difficulty_fidelity = fidelity.get("difficulty_fidelity")content_fidelity: Optional[float] = Noneif source_terms and len(source_terms) >= 50:content_fidelity = round(sum(_content_grounding(q, source_terms) for q in questions) / n, 3)quality_index = _composite_quality_index(concept_uniqueness=concept_uniqueness,coverage_ratio=coverage_ratio,bloom_balance=bloom_balance,stem_balance=stem_balance,difficulty_balance=difficulty_balance,difficulty_fidelity=difficulty_fidelity,content_fidelity=content_fidelity,)return {13 unmodified lines# without recomputing anything from the raw percentages above."bloom_balance": bloom_balance,"stem_balance": stem_balance,# Retained, but no longer the headline: this is label compliance, not# difficulty. Kept because the *gap* between it and difficulty_fidelity# is the single most useful diagnostic here — a section scoring 1.0 on# this and 0.4 on fidelity has obediently labelled easy questions# "hard", which is precisely the failure it used to hide."difficulty_balance": difficulty_balance,# Which of the two difficulty_balance definitions produced the number# above — the two are not comparable, so a dashboard mixing exams with# and without an AssessmentIntent target needs to split on this."difficulty_scored_against": "target" if difficulty_target else "spread",# Measured difficulty (see _measured_difficulty / _difficulty_fidelity).# None for difficulty_fidelity means no target was requested, so there# was nothing to be faithful *to* — not a score of zero."difficulty_fidelity": difficulty_fidelity,"measured_difficulty_bands": fidelity["measured_bands"],"mean_measured_difficulty": fidelity["mean_measured_difficulty"],"authentic_hard_pct": fidelity["authentic_hard_pct"],"exceptional_pct": fidelity["exceptional_pct"],# Mean fraction of each question's vocabulary attested in the retrieved# book context — "is this question testing the selected lesson, or the# model's own knowledge of the topic". None when there wasn't enough# source vocabulary for the comparison to mean anything."content_fidelity": content_fidelity,# 0-100, monitoring only — never shown to teachers. Named "index" not# "score" deliberately: it's a relative signal for comparing exams to# each other over time, not a claim of objective exam quality.86 unmodified lines# always rewarding spread via entropy — which scored an exam 0.0 for delivering# exactly the single difficulty it was asked for. Falls back to entropy when no# target was given; `difficulty_scored_against` says which was used.# 2026-08.4: difficulty_balance demoted from a 0.15 weight to 0.05 and joined# by difficulty_fidelity (0.20) and content_fidelity (0.15), which measure the# questions rather than the labels on them. Motivating measurement: three exams# generated from one blueprint at three difficulty targets scored# difficulty_balance 100 / 94 / 100 while the only property that actually# changed between a medium and a hard question was stem length. quality_index# before and after this version is not comparable — the old number could not# go down when the questions were fake-hard, and the new one can._QUALITY_HEURISTIC_VERSION = "2026-08.4"# Mirrors the weighting scheme: concept uniqueness, source coverage and# measured difficulty matter most (all grounded in retrieval evidence or in# properties of the question itself, not in the model's self-assessment),# Bloom balance next, stem balance and label compliance least.## difficulty_balance keeps a small non-zero weight rather than being deleted:# obeying the teacher's requested mix is still worth something, it just isn't# worth what it was being paid._QUALITY_INDEX_WEIGHTS = {"concept_uniqueness": 0.20,"coverage": 0.20,"difficulty_fidelity": 0.20,"content_fidelity": 0.15,"bloom_balance": 0.15,"stem_balance": 0.05,"difficulty_balance": 0.05,}def _composite_quality_index(*, concept_uniqueness: float, coverage_ratio: float | None,bloom_balance: float, stem_balance: float, difficulty_balance: float,difficulty_fidelity: float | None = None,content_fidelity: float | None = None,) -> float:"""Weighted 0-100 monitoring index — never used to drive rerolls, andnever shown to teachers. Purely for comparing prompt/model revisions and13 unmodified lines}if coverage_ratio is not None:components["coverage"] = min(1.0, coverage_ratio)# Both fidelity terms are None-able for legitimate reasons (no difficulty# target requested; too little source vocabulary to judge grounding), and# are dropped-and-renormalized exactly like coverage rather than being# scored as zero — a missing measurement is not a bad measurement.if difficulty_fidelity is not None:components["difficulty_fidelity"] = min(1.0, difficulty_fidelity)if content_fidelity is not None:components["content_fidelity"] = min(1.0, content_fidelity)total_weight = sum(_QUALITY_INDEX_WEIGHTS[k] for k in components)index = sum(_QUALITY_INDEX_WEIGHTS[k] * v for k, v in components.items()) / total_weight7 unmodified lines# Human-readable reason shown when a section's weakest subscore explains why# it dragged the exam average down — keyed the same as QualitySubscores._QUALITY_SUBSCORE_REASONS = {"difficulty_fidelity": ("الأسئلة المصنّفة صعبة في هذا القسم أسهل فعليًا مما يوحي به تصنيفها"),"content_fidelity": ("بعض أسئلة هذا القسم لا تستن�� بوضوح إلى نص الدرس المختار"),"concept_uniqueness": "بعض الأسئلة تختبر نفس الفكرة تقريبًا (تكرار مفاهيمي)","coverage": "الأسئلة مبنية على جزء محدود من المحتوى المصدر (تغطية ضعيفة)","bloom_balance": "أغلب الأسئلة استرجاعية ولا تتطلب تحليلاً أو تطبيقًا كافيًا",124 unmodified linesreturn sum(v * w for v, w in usable) / total_wdef _optional_subscore(pairs: list[tuple[Optional[float], int]]) -> Optional[float]:"""Weighted 0-100 subscore, or None when nothing in `pairs` was scorable.`_weighted_avg` returns 0.0 for "no usable values", which reads as a scoreof zero everywhere it's displayed. For the fidelity subscores thatdistinction matters: an exam generated without a difficulty target has nodifficulty fidelity to report, and showing the teacher a red 0 for itwould be a lie about their exam."""if all(v is None for v, _ in pairs):return Nonereturn round(100 * _weighted_avg(pairs), 1)def _confidence_label(score: float) -> str:if score >= 85:return "very_high"146 unmodified lines[(m["concept_uniqueness"], m["count"]) for _, m in scored_sections]), 1),"stem_balance": round(100 * _weighted_avg([(m["stem_balance"], m["count"]) for _, m in scored_sections]), 1),# Measured difficulty and grounding. `_weighted_avg` skips None# entries, so sections that legitimately couldn't be scored (no# difficulty target, too little source vocabulary) drop out of the# average — but if *every* section was unscorable the result would# be a bare 0.0, i.e. "terrible" instead of "not measured". The# helper below keeps that distinction."difficulty_fidelity": _optional_subscore([(m.get("difficulty_fidelity"), m["count"]) for _, m in scored_sections]),"content_fidelity": _optional_subscore([(m.get("content_fidelity"), m["count"]) for _, m in scored_sections]),}# Reported next to the subscores rather than inside them: these are# descriptive shares of the exam, not 0-100 "how good" scores, and# averaging them as if they were would misrepresent both.authentic_difficulty = {"authentic_hard_pct": round(_weighted_avg([(m.get("authentic_hard_pct"), m["count"]) for _, m in scored_sections]), 1),"exceptional_pct": round(_weighted_avg([(m.get("exceptional_pct"), m["count"]) for _, m in scored_sections]), 1),"mean_measured_difficulty": round(_weighted_avg([(m.get("mean_measured_difficulty"), m["count"]) for _, m in scored_sections]), 1),}retrieval_confidence = round(100 * _weighted_avg([(m["retrieval_confidence"], m["count"]) for _, m in scored_sections]), 1)6 unmodified lines"stem_balance": subscores["stem_balance"] - 100 * lowest_metrics["stem_balance"],"difficulty_balance": subscores["difficulty_balance"] - 100 * lowest_metrics["difficulty_balance"],}# Only comparable where both the exam average and this section have a# value — a section with no measurable fidelity isn't the weakest one,# it's an unscored one.for _key, _metric in (("difficulty_fidelity", "difficulty_fidelity"),("content_fidelity", "content_fidelity")):if subscores[_key] is not None and lowest_metrics.get(_metric) is not None:sub_gaps[_key] = subscores[_key] - 100 * lowest_metrics[_metric]weakest_key = max(sub_gaps, key=lambda k: sub_gaps[k])reason = _QUALITY_SUBSCORE_REASONS[weakest_key]lowest_section = {7 unmodified lineselse:weighted_overall = 0.0subscores = {"coverage": 0.0, "difficulty_balance": 0.0, "bloom_balance": 0.0,"concept_uniqueness": 0.0, "stem_balance": 0.0,"difficulty_fidelity": None, "content_fidelity": None}authentic_difficulty = {"authentic_hard_pct": 0.0, "exceptional_pct": 0.0,"mean_measured_difficulty": 0.0}retrieval_confidence = 0.0lowest_section = Nonewarnings = []25 unmodified lines"overall": weighted_overall,"weighted_overall": weighted_overall,"subscores": subscores,# Descriptive shares, not scores — "how much of this exam is# actually hard", reported next to (not folded into) the subscores# so the requested-vs-delivered comparison the difficulty review# asked for is readable straight off the summary."authentic_difficulty": authentic_difficulty,"lowest_section": lowest_section,"warnings": warnings,"retrieval_confidence": retrieval_confidence,1415 unmodified lines# rule 5 below falls back to its original generic instruction,# unchanged from before this parameter existed.difficulty_target: dict[str, int] | None = None,# A source-grounded passage (see _extract_passage) that every question# in this batch must be written from, turning the batch into a passage# group. None keeps the prompt byte-identical to the ungrouped path.passage: dict | None = None,passage_families: list[tuple[str, str]] | None = None,) -> str:"""Build a focused system prompt for generating a single exam section."""language_directive = _exam_language_directive(language)80 unmodified lines# With a resolved AssessmentIntent target, name exact counts instead of# the generic "vary difficulty" instruction — otherwise (None) this is# the original sentence, unchanged.# Counts only — what "hard" *means* is defined once in# `difficulty_contract` above, inside the cacheable prefix, instead of# being restated (and previously under-specified) in this per-batch# tier.if difficulty_target:difficulty_rule = ("- وزّع الأسئلة على مستويات الصعوبة بالضبط كالتالي: "f"{difficulty_target.get('easy', 0)} سهل (easy)، "f"{difficulty_target.get('medium', 0)} متوسط (medium)، "f"{difficulty_target.get('hard', 0)} صعب (hard) — من أصل {count} سؤالاً، ""بحسب تعريف المستويات المذكور أعلاه.\n")else:difficulty_rule = ("- نوّع مستوى الصعوبة: easy, medium, hard، بحسب تعريف المستويات المذكور أعلاه.\n")# Ordered most-stable-first so the prompt has a long, byte-identical21 unmodified lines"مباشر عنها.\n""4. لكل سؤال اختيار من متعدد، اجعل الاختيارات الخاطئة (المشتتات) من نفس الفئة أو الموضوع ""الفرعي للإجابة الصحيحة (مثال: أطوار دورة حياة أخرى، أنواع أخرى من نفس الجنس، مصطلحات ""متشابهة) وليست خيارات غير منطقية يسهل استبعادها بالحدس. كل مشتّت يجب أن يمثل خطأً ""شائعًا يقع فيه طالب فعلًا، لا عبارة يعرف الجميع أنها غير صحيحة.\n""5. الخيارات الأربعة يجب أن تكون متقاربة في الطول وفي مستوى التفصيل. ممنوع أن تكون ""الإجابة الصحيحة أطول الخيارات أو أكثرها تفصيلًا أو الوحيدة التي تحمل تعليلًا — الطالب ""الذي لا يعرف الإجابة يختار الخيار الأطول، فيحصل على الدرجة دون فهم. إن احتاجت الإجابة ""الصحيحة إلى تعليل، فأضف تعليلًا مماثلًا في الطول لكل مشتّت.\n""6. لا ترتّب الأسئلة بنفس تسلسل المواضيع كما وردت في المصدر — نوّع/اخلط بين المواضيع ""الفرعية عبر أسئلة هذا القسم بدلاً من تغطيتها بنفس الترتيب الخطي للنص.\n")# The difficulty contract, stated once and kept out of the interpolated# tiers so it stays inside the cacheable prefix.## This replaces a single sentence ("أسئلة hard يجب أن تربط بين فكرتين# أو أكثر") that measurably did not work: across three generated exams# the only property that changed between a medium and a hard question# was length (mean stem 73 -> 122 characters), because "link two ideas"# is satisfiable by appending a clause to a medium question. The# measured example, both questions in the same section:# medium: ما السبب الذي دفع صلاح الدين للبدء بفتح المدن الساحلية...؟# hard: لماذا أصر صلاح الدين... وكيف يعكس ذلك فهمه لطبيعة الصراع؟# Same answer, one clause longer. Naming the forbidden move explicitly# and requiring a task structure from a closed list is the fix: a# family is something the model has to *build*, not phrasing it can# append. The families mirror what _hard_family checks for after# generation, so the prompt and the reroll heuristic agree on what# "hard" means.difficulty_contract = ("\n=== معنى مستويات الصعوبة (مهم جدًا) ===\n""الصعوبة تعني صعوبة الوصول إلى الإجابة، لا صعوبة قراءة السؤال.\n""- الصياغة يجب أن تبقى واضحة وقصيرة ومباشرة في كل المستويات، ولها معنى واحد فقط لا ""يحتمل التأويل. ممنوع رفع الصعوبة بجملة طويلة أو مصطلحات معقدة أو تراكيب متشابكة.\n""- ممنوع منعًا باتًا أن تجعل السؤال «صعبًا» بإضافة عبارة زائدة إلى سؤال أسهل (مثل ""«... وكيف يعكس ذلك ...؟» أو «... وما دلالة ذلك؟») بينما تبقى الإجابة والدليل المطلوبان ""كما هما. هذا سؤال متوسط بصياغة أطول، وليس سؤالًا صعبًا.\n""- easy: تطبيق قاعدة أو معلومة واحدة من النص تطبيقًا مباشرًا وصحيحًا.\n""- medium: خطوتان من الاستدلال، أو مقارنة بين حالتين، أو تطبيق يحتاج ربط معلومتين.\n""- hard: يجب أن يُبنى على واحد من الأنماط التالية حصرًا:\n"" • تشخيص خطأ: طالب حلّل أو أعرب أو فسّر بشكل خاطئ — أين الخطأ في تحليله ولماذا؟\n"" • تعارض قاعدتين: قاعدتان تبدوان منطبقتين — أيهما تنطبق هنا، وما الدليل الذي ""يستبعد الأخرى؟\n"" • تحويل: غيّر عنصرًا في الجملة أو الموقف، ثم فسّر ما الذي تغيّر في الحكم وما الذي ""لم يتغيّر ولماذا.\n"" • زوج متقارب: موضعان شديدا التشابه اختلف الحكم فيهما — ما سبب الاختلاف؟\n"" • أدلة متعددة: الإجابة تتطلب الجمع بين موضعين مختلفين من النص، ولا تكفي فيها ""معلومة واحدة.\n"" • نقل: طبّق القاعدة نفسها على مثال جديد لم يرد في النص.\n""- كل سؤال hard يجب ألا يكون قابلًا للحل بالذكاء العام أو المعرفة العامة أو بمطابقة ""الكلمات المشتركة بين السؤال والخيارات — من لم يدرس هذا الدرس تحديدًا لا يستطيع ""الإجابة.\n")section_spec = ("\n=== مواصفات هذا القسم ===\n"f"- نوع الأسئلة: {section_type}\n"2 unmodified linesf"- {extra_note}")# Passage groups: one block of book text, several questions written# from it, each assigned a different reasoning family. The passage is# quoted here verbatim from the retrieved chunks — the model is# explicitly forbidden from rewriting it, because an invented passage# would produce excellent questions about text that isn't in the# teacher's book (see _extract_passage).passage_spec = ""if passage:family_lines = "\n".join(f" {slot + 1}. {label} — {description}"for slot, (label, description) in enumerate((passage_families or _PASSAGE_FAMILY_CYCLE)[:count]))passage_spec = ("\n=== القطعة المرفقة (نص من الكتاب) ===\n"f"{passage['text']}\n""\n=== تعليمات أسئلة القطعة ===\n""- كل الأسئلة في هذه الدفعة تُبنى على القطعة أعلاه وحدها، ويجب أن يكون النص ""المرفق كافيًا للإجابة عنها جميعًا.\n""- لا تعد كتابة القطعة ولا تلخّصها ولا تضف إليها جملًا من عندك — هي نص الكتاب ""كما هو، والطالب يقرؤها كما وردت.\n""- لا تكرر نص القطعة داخل صياغة أي سؤال؛ أشر إلى مواضعها بالاقتباس القصير فقط.\n""- وزّع الأسئلة على أنماط تفكير مختلفة بالترتيب التالي، سؤال واحد لكل نمط:\n"f"{family_lines}\n""- الصياغة قصيرة وواضحة في كل الأسئلة؛ التعقيد في الاستدلال المطلوب لا في اللغة.\n")batch_spec = ("\n=== تعليمات هذه الدفعة ===\n"f"- أنشئ بالضبط {count} أسئلة — لا أكثر ولا أقل.\n"15 unmodified linesreturn (general_rules+ difficulty_contract+ section_spec+ passage_spec+ batch_spec# Deliberately outside the numbered rule list and stated last: this# is the one field the model has no prior instinct for, and burying579 unmodified lines# actually drives wall-clock here — sections run concurrently, so# the slowest section's serial chain is the exam's floor.timings = {"retrieval_ms": 0.0, "generate_ms": 0.0, "topup_ms": 0.0,"reroll_ms": 0.0, "red_team_ms": 0.0, "calls": 0}# Summary of the red-team pass for this section, or None when it# didn't run (disabled, no context, or no hard questions to attack).red_team_stats: Optional[dict] = Nonedef _elapsed_ms(started: float) -> float:return (time.perf_counter() - started) * 100057 unmodified lines# — a thin source caps how spread-out coverage can realistically be.context_batches_total = 0context_batches_ok = 0# Union of significant vocabulary across every batch of book# context this section was shown — the reference set# `content_fidelity` scores each question against. Accumulated# across batches rather than taken from `last_context_text`,# because a question written from batch 1 must not be judged# ungrounded just because batch 4 was the last one seen.section_source_terms: set[str] = set()# Passage groups produced by this section. Questions stay in one# flat `questions` list (every existing consumer — numbering,# metrics, answer key, export, grading — depends on that); a# question that belongs to a group carries `passage_id`, and# renderers print the passage above the first question bearing it.section_passages: list[dict] = []for batch_idx, batch_count in enumerate(batches):# Reset per batch: only the batch that built a passage is a# group, and only its questions inherit the passage.batch_passage: Optional[dict] = None# Open a fresh session only for the DB read, then close it before# the LLM call (which may take 60+ s and would hold the connection idle).batch_figure_urls: list[str] = []51 unmodified lineslast_chunk_ids = batch_chunk_ids or last_chunk_idslast_figure_urls = batch_figure_urls or last_figure_urlslast_block_chunk_ids = batch_block_chunk_ids or last_block_chunk_idssection_source_terms |= _source_terms(assembled.text or "")# Passage group: the first batch of a section that has# enough questions and enough continuous prose to build# one. Deliberately one group per section rather than# every batch — a whole exam of passage-bound questions# would collapse source coverage onto a handful of# chunks, which is the defect `coverage_gap` exists to# catch. `matching` is excluded: its column/answer shape# has nowhere to put a reading passage.if (settings.EXAM_PASSAGE_GROUPS_ENABLEDand batch_passage is Noneand not section_passagesand stype != "matching"and batch_has_contextand batch_count >= settings.EXAM_PASSAGE_MIN_QUESTIONS):batch_passage = _extract_passage(batch_chunks or [])section_user_msg = (f"السؤال: {question_text}\n\n"f"النص من الكتاب المدرسي:\n\n{assembled.text}\n\n"9 unmodified lineshas_figures=bool(batch_figure_urls),language=exam_language,difficulty_target=_difficulty_counts_for_section(batch_count, difficulty_target),# A passage group's questions all come from the passage, so# per-question `source_index` attribution would be asking# the model to pick among blocks it was told not to use.# They inherit the passage's own chunk ids instead.source_block_count=(0 if batch_passageelse (len(batch_block_chunk_ids) if batch_has_context else 0)),passage=batch_passage,)try:_t_llm = time.perf_counter()31 unmodified lines_apply_source_chunk_ids(normalized_questions, batch_chunk_ids, batch_block_chunk_ids,)# Register the group only once questions actually came back# — a passage with no questions under it would render as a# stray block of book text in the printed exam.if batch_passage and normalized_questions:passage_id = f"p{idx + 1}-{batch_idx + 1}"for q in normalized_questions:q["passage_id"] = passage_id# Provenance is the passage's, not the batch's: these# questions were written from those exact sentences.if batch_passage["source_chunk_ids"]:q["source_chunk_ids"] = list(batch_passage["source_chunk_ids"])section_passages.append({"id": passage_id,"text": batch_passage["text"],"source_chunk_ids": batch_passage["source_chunk_ids"],"page_range": batch_passage["page_range"],})added = _append_unique_questions(all_questions, normalized_questions)logger.info("Section %d/%d (%s) batch %d/%d: %d questions",53 unmodified lines)if retry_has_context:last_context_text = assembled.text or last_context_textsection_source_terms |= _source_terms(assembled.text or "")last_image_urls = retry_image_urls or last_image_urlslast_chunk_ids = retry_chunk_ids or last_chunk_idslast_figure_urls = retry_figure_urls or last_figure_urls88 unmodified linesall_questions, stype, retrieval_confidence=retrieval_confidence,source_pool_size=section_pool_size,)# Two budgets, because the flags are two different kinds of# problem.## Integrity defects (option_length_leak, answer_leakage) let a# student score without knowing the material, so they get their# own allowance ahead of everything else. A single ~1/4 budget# shared with style flags meant a 20-question MCQ section with# 11 length-leaked options could have at most 5 of them fixed,# and only if no duplicate outranked them in the queue.## Style/difficulty defects keep the original ~1/4 cap. That cap# is deliberate and is *not* raised to cover shallow_hard: on# the measured exams shallow_hard flags most of a hard section,# and rerolling 10 questions through the same prompt that wrote# them just buys 10 more of the same. The generation prompt is# the fix there (see the reasoning-families rule in# _build_section_prompt); the flag's job past this cap is to be# reported honestly by the quality metrics, not silently# papered over.n_q = len(all_questions)style_budget = max(2, n_q // 4)integrity_budget = max(4, n_q // 2)# Passage-group questions are excluded from rerolling: the# reroll prompt is built from the section's last batch context,# not from the group's passage, so a replacement would be a# question printed under a passage it wasn't written from —# worse than the defect it fixes. Their defects still surface# in the quality metrics rather than being silently dropped.# (The group prompt carries the same distractor and difficulty# rules, so it should produce fewer of them to begin with.)flagged = [i for i in review["flagged"]if not all_questions[i].get("passage_id")]integrity = [i for i in flaggedif review["reasons"].get(i) in _INTEGRITY_REASONS]style = [i for i in flaggedif review["reasons"].get(i) not in _INTEGRITY_REASONS]reroll_indices = integrity[:integrity_budget] + style[:style_budget]async def _run_reroll(reroll_indices: list[int], reasons: dict[int, str]) -> None:"""Replace the named questions in one batched call.Extracted so the deterministic pass and the red-team passbelow share it — they differ only in how they decided whatto replace, not in how replacement works."""# One call for the whole reroll set, not one per question.# These are independent replacements — nothing in a reroll# depends on the previous reroll's output — so running them13 unmodified lines# ask for, so slot j's instruction lands on the question# that actually had that defect.reasons_in_order = [reasons.get(r_idx, "default") for r_idx in reroll_indices]# Each slot also names the difficulty it has to come back# at. Previously the reroll prompt carried no difficulty# information at all, so replacements were free to land# anywhere — which quietly eroded the section's requested# mix every time the review pass fired. Naming it per slot# (rather than re-deriving a section-level target, which# would fight the distribution already in place) keeps the# replacement in the same slot it's filling.hint_lines = [f"- البديل رقم {slot + 1}"+ (f" (المستوى المطلوب: {all_questions[r_idx].get('difficulty')})"if all_questions[r_idx].get("difficulty") else "")+ f": {_REROLL_HINTS.get(reason, _REROLL_HINTS['default'])}"for slot, (r_idx, reason) in enumerate(zip(reroll_indices, reasons_in_order))]hint = (f"أنشئ {len(reroll_indices)} سؤالاً بديلاً بالترتيب، كل بديل يعالج المشكلة "57 unmodified linesstype, len(reroll_indices), reasons_in_order, e,)if reroll_indices:logger.info("Section %d/%d (%s) quality review: %d/%d flagged (%s) — rerolling %d",idx + 1, total_sections, stype, len(review["flagged"]),len(all_questions), review["reasons"], len(reroll_indices),)await _run_reroll(reroll_indices, review["reasons"])# ── Red team ──────────────────────────────────────────────# The checks above see structure; this one sees meaning. It# runs after them so it judges the questions that will# actually ship, and only over hard-labeled ones — the# questions whose label is a promise worth verifying.if settings.EXAM_RED_TEAM_ENABLED and last_context_text:attackable = [i for i, q in enumerate(all_questions)if str(q.get("difficulty", "")).lower() == "hard"and not q.get("passage_id") # same exclusion as above][:settings.EXAM_RED_TEAM_MAX_QUESTIONS]if attackable:_t_rt = time.perf_counter()rt_failures = await self._red_team_section(all_questions, attackable,context_text=last_context_text, client=client,language=exam_language,)timings["red_team_ms"] += _elapsed_ms(_t_rt)timings["calls"] += 1from collections import Counter as _RTCounterred_team_stats = {"attacked": len(attackable),"failed": len(rt_failures),"reasons": dict(_RTCounter(r[0] for r in rt_failures.values() if r)),}logger.info("Section %d/%d (%s) red team: %d/%d failed (%s)",idx + 1, total_sections, stype, len(rt_failures),len(attackable), red_team_stats["reasons"],)# One extra round only, and bounded by the same style# budget — a red team that triggers an unbounded# rewrite loop would cost more latency than the# quality it buys. Whatever isn't fixed here stays# flagged in the metrics rather than being hidden.rt_indices = sorted(rt_failures)[:style_budget]if rt_indices:await _run_reroll(rt_indices,{i: rt_failures[i][0] for i in rt_indices},)_shuffle_mcq_answer_positions(all_questions)section_quality_metrics: Optional[dict] = None10 unmodified linesdifficulty_target=_difficulty_counts_for_section(len(all_questions), difficulty_target,),source_terms=section_source_terms,)# Structured + greppable: one line per finished section, meant# to be aggregated across exams over time (recall vs.# application mix, coverage, concept uniqueness) rather than# read one-off — the "teacher analytics" telemetry request.# Attached rather than computed inside the metrics function:# that function is pure over the questions, and this is the# outcome of an external call. Reported even when the reroll# budget couldn't fix everything it found — a red team whose# findings vanish when they're inconvenient isn't one.if red_team_stats:section_quality_metrics["red_team"] = red_team_statslogger.info("Exam section quality metrics: %s", json.dumps(section_quality_metrics, ensure_ascii=False))timings["total_ms"] = round(timings["retrieval_ms"] + timings["generate_ms"]+ timings["topup_ms"] + timings["reroll_ms"]+ timings["red_team_ms"], 1,)for _k in ("retrieval_ms", "generate_ms", "topup_ms", "reroll_ms", "red_team_ms"):timings[_k] = round(timings[_k], 1)logger.info("Section %d/%d (%s): %d total questions — timings %s",3 unmodified lines# `quality_metrics` rides along on the section result so the# exam-level `generation_insights` aggregation below can reuse it# without recomputing anything — see GenerationInsights.# Passages are dropped if the reroll/top-up churn left no question# referencing them — `_append_unique_questions` can discard a# duplicate, and a passage with nothing under it must not print.live_passage_ids = {q.get("passage_id") for q in all_questions if q.get("passage_id")}return {"title": title,"questions": all_questions,"passages": [p for p in section_passages if p["id"] in live_passage_ids],"quality_metrics": section_quality_metrics,"timings": timings,}60 unmodified lines}, ensure_ascii=False),)# Strips the generation-only keys (quality_metrics, timings) that were# already consumed above. `passages` stays: it's exam content, not# telemetry — the printed paper needs it. Omitted entirely when a# section has none, so exams generated before passage groups (and# sections that couldn't build one) keep their exact previous shape.all_sections = [{"title": sec.get("title"),"questions": sec.get("questions", []),**({"passages": sec["passages"]} if sec.get("passages") else {}),}for sec in all_sections]426 unmodified linesreview = ExamReview(overall=50.0, summary="", findings=[], missing_topics=[])return review.model_dump()async def _red_team_section(self, questions: list[dict], indices: list[int], *,context_text: str, client: httpx.AsyncClient, language: str = "AR",) -> dict[int, list[str]]:"""Attack the named questions and report which failed, and how.One batched call for the whole set — the deterministic reroll passlearned this lesson already (per-question calls serialized into thelatency that pushed large exams past 100s), and the same applies here.Returns {question_index: [reason, ...]} containing only failures, so anempty dict means everything survived. Any error returns an empty dict:a red team that fails to respond must never block an exam or silentlymark good questions bad."""settings = get_settings()if not indices:return {}# Numbered 1..N over the *attacked subset*, not the section, so the# model's `n` maps back unambiguously without it having to reason about# gaps in the numbering.slot_to_index = {slot + 1: q_idx for slot, q_idx in enumerate(indices)}trimmed = [{"n": slot,"type": questions[q_idx].get("type"),"question": questions[q_idx].get("question"),"choices": questions[q_idx].get("choices"),"answer": questions[q_idx].get("answer"),}for slot, q_idx in slot_to_index.items()]user_msg = (# The lesson text is included because the first verdict# ("answerable without the lesson") is meaningless without it —# the judge has to know what the lesson actually said to decide# whether the question depends on it.(f"نص الدرس:\n\n{context_text}\n\n" if context_text else "")+ "هاجم الأسئلة التالية وأرجع الأحكام بصيغة JSON فقط:\n\n"+ json.dumps(trimmed, ensure_ascii=False))try:raw = await self._pick_llm("exam").generate(_build_red_team_prompt(language),[{"role": "user", "content": user_msg}],client=client,json_format=True,max_tokens=settings.LLM_MAX_TOKENS_STRUCTURED,model_tier="cheap",)from json_repair import repair_jsonrepaired = repair_json(raw)data = json.loads(repaired) if isinstance(repaired, str) else repairedexcept Exception as exc:logger.warning("Red team call failed (%d questions): %s", len(indices), exc)return {}failures: dict[int, list[str]] = {}for verdict in (data or {}).get("verdicts", []) or []:if not isinstance(verdict, dict):continueq_idx = slot_to_index.get(verdict.get("n"))if q_idx is None:continuereasons = _red_team_failures(verdict)if reasons:failures[q_idx] = reasonsreturn failuresasync def improve_single_question(self, question: dict, *, client: httpx.AsyncClient, focus: Optional[str] = None,language: str = "AR",
180 unmodified lines18118218318418518669 unmodified lines256257258259260261180 unmodified linesreturn defaultdef _calc_total_marks(data: dict) -> int:"""Sum all question marks across all sections."""total = 069 unmodified lines_jinja_env.filters["visible_blocks"] = _visible_blocks_jinja_env.filters["text_dir"] = _text_dir_jinja_env.globals["calc_total_marks"] = _calc_total_marks_jinja_env.globals["matching_answer_cells"] = _matching_answer_cells_jinja_env.globals["to_arabic_indic"] = _to_arabic_indic_jinja_env.globals["to_arabic_letter"] = _to_arabic_letter180 unmodified lines18118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222369 unmodified lines293294295296297298299180 unmodified linesreturn default# ── Redundant question stem detection ─────────────────────────────────────# Generators routinely echo the section instruction as the question stem —# section "السؤال السادس: وصّل من العمود (أ) ما يناسبه من العمود (ب)" followed# by a question reading "وصّل من العمود (أ) ما يناسبه من العمود (ب)". The# instruction then prints twice, two lines apart. Comparison is done on a# normalized form (diacritics/tatweel stripped, alef/ya/ta-marbuta folded,# punctuation and whitespace collapsed) so cosmetic differences — a shadda on# وصّل, a trailing colon, "(أ)" vs "( أ )" — don't hide the duplicate._ARABIC_DIACRITICS_RE = re.compile(r"[ً-ْٰـ]")_STEM_NOISE_RE = re.compile(r"[^\w-ۿ]+")_ARABIC_FOLD = str.maketrans({"أ": "ا", "إ": "ا", "آ": "ا", "ٱ": "ا","ى": "ي", "ئ": "ي", "ؤ": "و", "ة": "ه",})def _normalize_stem(text: Any) -> str:s = _ARABIC_DIACRITICS_RE.sub("", str(text or "")).translate(_ARABIC_FOLD)return " ".join(_STEM_NOISE_RE.sub(" ", s).split())def _stem_is_redundant(question: Any, section_title: Any) -> bool:"""True when a question's stem adds nothing over its section heading.Substring (not equality) because the heading carries an ordinal prefix thestem never has ("السؤال السادس: ..."). The length floor keeps a genuinelyshort stem that happens to appear inside a long heading from being dropped."""q = _normalize_stem(question)if not q:return Truetitle = _normalize_stem(section_title)if not title:return Falsereturn q == title or (len(q) >= 12 and q in title)def _calc_total_marks(data: dict) -> int:"""Sum all question marks across all sections."""total = 069 unmodified lines_jinja_env.filters["visible_blocks"] = _visible_blocks_jinja_env.filters["text_dir"] = _text_dir_jinja_env.globals["calc_total_marks"] = _calc_total_marks_jinja_env.globals["stem_is_redundant"] = _stem_is_redundant_jinja_env.globals["matching_answer_cells"] = _matching_answer_cells_jinja_env.globals["to_arabic_indic"] = _to_arabic_indic_jinja_env.globals["to_arabic_letter"] = _to_arabic_letter
195 unmodified lines196197198199200201202195 unmodified lines<div class="ak-body">{# Brief question text for context #}<div class="ak-question-text" dir="{{ q.question | text_dir }}">{% if q.type == 'fill_blank' %}{{ q.question | replace('___', '____') | replace('....', '____') | replace('____________','____') }}{% else %}195 unmodified lines196197198199200201202203204195 unmodified lines<div class="ak-body">{# Brief question text for context #}<div class="ak-question-text" dir="{{ q.question | text_dir }}">{# Stem that only repeats the section heading adds no context here #}{% if q.type != 'fill_blank' and stem_is_redundant(q.question, section.title) %}{% elif q.type == 'fill_blank' %}{{ q.question | replace('___', '____') | replace('....', '____') | replace('____________','____') }}{% else %}
336 unmodified lines337338339340341342190 unmodified lines53353453553653753812 unmodified lines551552553554555556557558336 unmodified lines}/* ── Reading passage ─────────────────────────────── */.reading-passage {font-size: 0.92em;line-height: 1.75;190 unmodified lines<div class="reading-passage" dir="{{ q.passage | text_dir }}">{{ q.passage }}</div>{% endif %}<div class="question-main{% if q_image %} with-image{% endif %}"><div class="question-body"><div class="question-header">12 unmodified lines{# ── Question marker ────────────────────── #}{% if qm == 'bullet' %}<span class="q-marker">•</span>{% elif qm == 'dash' %}<spanclass="q-marker">—</span>{% endif %}<div class="question-text" dir="{{ q.question | text_dir }}">{% if q.type == 'fill_blank' %}{{ q.question | replace('___', '<span class="fill-blank"> </span>') |replace('....', '<span class="fill-blank"> </span>') | replace('____________','<span class="fill-blank"> </span>') | safe }}336 unmodified lines337338339340341342343344345346347348349350190 unmodified lines54154254354454554654754854955055155255355455555655755855956012 unmodified lines573574575576577578579580581582583584585586587336 unmodified lines}/* ── Reading passage ─────────────────────────────── *//* Instruction line above a passage group's shared text. Small and quiet —it's a signpost, not a heading, and it must not compete with the sectiontitle directly above it. */.passage-group-lead {font-size: 0.9em;font-weight: 600;margin: 4pt 0 2pt;}.reading-passage {font-size: 0.92em;line-height: 1.75;190 unmodified lines<div class="reading-passage" dir="{{ q.passage | text_dir }}">{{ q.passage }}</div>{% endif %}{# ── Passage group ───────────────────────────────A source-grounded block of book text shared by the next fewquestions. Printed above the FIRST question carrying thispassage_id only — questions stay a single flat list, so "is thisthe start of a group" is decided by comparing with the previousquestion rather than by any nesting in the data. ───────────── #}{% if q.passage_id and (loop.first or loop.previtem.passage_id != q.passage_id) %}{% set group_passage = (section.passages | selectattr('id', 'equalto', q.passage_id) | first) %}{% if group_passage %}<div class="passage-group-lead">اقرأ النص الآتي ثم أجب عن الأسئلة التي تليه:</div><div class="reading-passage" dir="{{ group_passage.text | text_dir }}">{{ group_passage.text }}</div>{% endif %}{% endif %}<div class="question-main{% if q_image %} with-image{% endif %}"><div class="question-body"><div class="question-header">12 unmodified lines{# ── Question marker ────────────────────── #}{% if qm == 'bullet' %}<span class="q-marker">•</span>{% elif qm == 'dash' %}<spanclass="q-marker">—</span>{% endif %}{# A stem that only repeats the section heading is dropped — theinstruction already prints above, in the heading. Types whose stemcarries a rendered extra (answer box, blank, assertion/reason) areexcluded so suppressing the text can't take that extra with it. #}{% set drop_stem = q.type not in ('fill_blank', 'true_false', 'true_false_correction','assertion_reason') and stem_is_redundant(q.question, section.title) %}<div class="question-text" dir="{{ q.question | text_dir }}">{% if drop_stem %}{% elif q.type == 'fill_blank' %}{{ q.question | replace('___', '<span class="fill-blank"> </span>') |replace('....', '<span class="fill-blank"> </span>') | replace('____________','<span class="fill-blank"> </span>') | safe }}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188"""Measured difficulty — scoring the question instead of its label.
`difficulty_balance` scores whether the model applied the easy/medium/hard mixit was told to apply. Three exams generated from one blueprint at threedifficulty targets scored 100 / 90 / 100 on it, while the only property thatactually changed between a medium and a hard question was stem length. A metricbuilt on the model's own self-assessment cannot notice that the self-assessmentis wrong, so `_measured_difficulty` scores properties of the question that alonger sentence cannot buy.
The anchor test below pins the calibration: these are the reference points theweights were tuned against, and a weight change that moves them is a change towhat every band in the system means."""import pytest
from app.services.gateway import ( _content_grounding, _difficulty_band, _difficulty_fidelity, _measured_difficulty, _source_terms,)
_RECALL_MCQ = { "type": "mcq", "question": "ما الاسم الذي أطلقه العرب الكنعانيون على مدينة القدس قديماً؟", "learning_objective": "معرفة الحقائق التاريخية", "choices": ["إيلياء", "أورشليم", "دار السلام", "أورسالم"], "answer": "أورسالم", "source_chunk_ids": ["a"],}_ONE_STEP_REASON = { "type": "short_answer", "question": "ما السبب الذي دفع صلاح الدين الأيوبي للبدء بفتح المدن الساحلية قبل القدس؟", "learning_objective": "تحليل الاستراتيجية العسكرية", "answer": "لحرمان الصليبيين من قواعدهم البحرية", "source_chunk_ids": ["a"],}_SAME_PLUS_CLAUSE = { "type": "short_answer", "question": ( "لماذا أصر صلاح الدين الأيوبي على تحرير المدن الساحلية قبل التوجه لتحرير " "القدس، وكيف يعكس ذلك فهمه لطبيعة الصراع؟" ), "learning_objective": "تحليل الاستراتيجية العسكرية", "answer": "لقطع خطوط الإمداد البحرية عن الصليبيين", "source_chunk_ids": ["a"],}_ERROR_DIAGNOSIS = { "type": "short_answer", "question": ( "كتب أحد الطلاب: «زاروا مدارسِ قديمةٍ» وقال إن الكسرة صحيحة لأن «مدارس» " "اسم مجرور. حدّد موضع الخطأ في تحليله." ), "learning_objective": "الممنوع من الصرف", "answer": "الخطأ أنه خلط بين الوظيفة الإعرابية وعلامة الإعراب", "source_chunk_ids": ["a"],}_ERROR_DIAGNOSIS_RICH = { **_ERROR_DIAGNOSIS, "question": ( "كتب أحد الطلاب: «زاروا مدارسِ قديمةٍ» وقال إن الكسرة صحيحة لأن «مدارس» " "اسم مجرور. حدّد موضع الخطأ، ثم بيّن الفرق بين معرفة الوظيفة وتحديد العلامة." ), "learning_objective": "الممنوع من الصرف والإضافة", "answer": "الوظيفة مجرور لكن العلامة فتحة لأن الكلمة ممنوعة من الصرف وغير مضافة", "solution_steps": ["تحديد نوع الكلمة", "تحديد الوظيفة", "تحديد العلامة"], "source_chunk_ids": ["a", "b"],}
@pytest.mark.parametrize("question,expected_band", [ (_RECALL_MCQ, "basic"), (_ONE_STEP_REASON, "basic"), (_ERROR_DIAGNOSIS, "hard"), (_ERROR_DIAGNOSIS_RICH, "very_hard"),])def test_calibration_anchors_land_in_their_bands(question, expected_band): assert _difficulty_band(_measured_difficulty(question)) == expected_band
def test_appending_a_clause_does_not_raise_the_score(): """The load-bearing property. This is the exact move that produced "hard" questions in the measured exams, and it must not pay.""" base = _measured_difficulty(_ONE_STEP_REASON) inflated = _measured_difficulty(_SAME_PLUS_CLAUSE)
assert inflated <= base
def test_a_length_leaked_mcq_scores_below_its_stem(): """A guessable option set caps a question however analytical the stem reads.""" leaked = { "type": "mcq", "question": "لماذا اعتبر الكاتب أن 'إرادة التغيير' هي ذاتها 'إرادة العمل'؟", "learning_objective": "تحليل الأفكار", "choices": [ "لأن التغيير لا يحتاج لعمل", "لأن الفعل لا يحتاج لإرادة", "لأن الإرادة هي مجرد قول", "لأن الإرادة بدون فعل هي مجرد أمنية لا تُحدث تغييرًا في الواقع", ], "answer": "لأن الإرادة بدون فعل هي مجرد أمنية لا تُحدث تغييرًا في الواقع", "source_chunk_ids": ["a"], }
assert _difficulty_band(_measured_difficulty(leaked)) in {"trivial", "basic"}
def test_short_proper_noun_options_are_not_penalized_for_low_overlap(): """Regression: judging distractor quality by vocabulary overlap pushed correct recall questions with proper-noun options below "trivial".""" assert _measured_difficulty(_RECALL_MCQ) >= 21
def test_scores_are_clamped_to_the_band_range(): assert 0 <= _measured_difficulty({"question": "", "type": "essay"}) <= 100
# ── Fidelity ──────────────────────────────────────────────────────────────────
def test_fidelity_is_low_when_hard_slots_hold_easy_questions(): """The measured case: a section labelled all-hard, made of recall questions.""" questions = [{**_RECALL_MCQ, "difficulty": "hard"} for _ in range(8)]
result = _difficulty_fidelity(questions, {"easy": 0, "medium": 0, "hard": 8})
assert result["difficulty_fidelity"] == 0.0 assert result["authentic_hard_pct"] == 0.0
def test_fidelity_is_high_when_hard_slots_hold_hard_questions(): questions = [{**_ERROR_DIAGNOSIS_RICH, "difficulty": "hard"} for _ in range(4)]
result = _difficulty_fidelity(questions, {"easy": 0, "medium": 0, "hard": 4})
assert result["difficulty_fidelity"] == 1.0 assert result["authentic_hard_pct"] == 100.0
def test_no_target_means_no_fidelity_rather_than_zero(): """An exam generated without an AssessmentIntent has nothing to be faithful to — reporting 0 there would be a lie about the exam, not a measurement.""" result = _difficulty_fidelity([_RECALL_MCQ], None)
assert result["difficulty_fidelity"] is None # ...but the descriptive numbers are still reported. assert result["mean_measured_difficulty"] > 0
def test_relabelling_cannot_improve_fidelity(): """Slots are filled by measured score, so calling everything hard doesn't help.""" honest = [{**_RECALL_MCQ, "difficulty": "easy"} for _ in range(6)] relabelled = [{**_RECALL_MCQ, "difficulty": "hard"} for _ in range(6)] target = {"easy": 0, "medium": 0, "hard": 6}
assert (_difficulty_fidelity(honest, target)["difficulty_fidelity"] == _difficulty_fidelity(relabelled, target)["difficulty_fidelity"])
# ── Content grounding ─────────────────────────────────────────────────────────
def test_a_question_written_from_the_source_is_grounded(): context = ( "كان أبو الريحان البيروني عالمًا موسوعيًا ولد في خوارزم، ورفض جوائز " "السلطان المسعودي زهدًا في المال والسلطان، وألّف كتاب تحقيق ما للهند من مقولة." ) question = { "question": "لماذا رفض البيروني جوائز السلطان المسعودي؟", "answer": "زهدًا في المال والسلطان", }
assert _content_grounding(question, _source_terms(context)) > 0.6
def test_a_question_from_general_knowledge_is_not_grounded(): """Plausible Arabic about the right subject, written from outside the lesson.""" context = ( "كان أبو الريحان البيروني عالمًا موسوعيًا ولد في خوارزم، ورفض جوائز " "السلطان المسعودي زهدًا في المال والسلطان." ) question = { "question": "ما أثر الثورة الصناعية على حركة التجارة الدولية في أوروبا؟", "answer": "ازدهرت المصانع وتوسعت الأسواق الاستعمارية", }
assert _content_grounding(question, _source_terms(context)) < 0.3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157"""Source-grounded passage groups.
One block of book text, several questions built on it, each assigned adifferent reasoning family — so a topic can be tested for transfer and ruleinteraction instead of six isolated recalls.
The load-bearing property is that the passage is *lifted from the retrievedchunks*, never written by the model. An invented passage reads as perfectlygood Arabic on the right topic and yields genuinely hard questions about textthat is not in the teacher's book, which is strictly worse than no passage.Every test here exists to keep that true."""import pytest
from app.services.gateway import ( GatewayService, _PASSAGE_FAMILY_CYCLE, _extract_passage, _prose_sentences,)
class _Chunk: def __init__(self, id, content, page_number=None, section_title=None): self.id = id self.content = content self.page_number = page_number self.section_title = section_title
_PROSE = ( "الممنوع من الصرف هو الاسم الذي لا يقبل التنوين ولا الكسر في حالة الجر، ويُجر " "بالفتحة نيابة عن الكسرة. ومن أشهر صوره صيغة منتهى الجموع مثل مساجد ومدارس " "ومصابيح، وهي التي جاءت على وزن مفاعل أو مفاعيل. فإذا قلت: صليت في مساجدَ " "أثرية، كانت مساجد مجرورة وعلامة جرها الفتحة لأنها ممنوعة من الصرف. غير أن " "هذا الحكم يتغير إذا اقترن الاسم بأل أو أضيف إلى ما بعده، فيعود إلى الجر " "بالكسرة. ولذلك تقول: صليت في مساجدِ المدينةِ، فتجر مساجد بالكسرة لأنها أضيفت.")
def test_passage_is_lifted_verbatim_from_the_chunk(): """Every sentence must be findable in the source. This is the whole point.""" chunk = _Chunk("c1", _PROSE, page_number=203, section_title="الممنوع من الصرف")
passage = _extract_passage([chunk])
assert passage is not None for sentence in passage["text"].split(". "): assert sentence.strip(" .") in _PROSE
def test_passage_carries_exact_provenance(): chunk = _Chunk("c1", _PROSE, page_number=203, section_title="الممنوع من الصرف")
passage = _extract_passage([chunk])
assert passage["source_chunk_ids"] == ["c1"] assert passage["page_range"] == [203, 203]
def test_tables_captions_and_ocr_lines_are_not_passage_material(): """The assembler injects these; none of them are prose a student reads.""" noisy = _Chunk("t1", ( "[[المصدر 1]]\n" "[تسمية: جدول يوضح أنواع الممنوع من الصرف]\n" "| النوع | المثال |\n" "| --- | --- |\n" "[نص داخل الصورة: مساجد]\n" ), page_number=10)
assert _extract_passage([noisy]) is None
def test_returns_none_when_there_is_no_continuous_prose(): """Passage mode is an enhancement to reach for, never a requirement — the caller falls back to ungrouped generation.""" headings = _Chunk("h1", "الوحدة الأولى\nالدرس الثاني\nتدريبات\nأسئلة", page_number=1)
assert _extract_passage([headings]) is None
def test_prefers_a_single_chunk_over_stitching(): """Continuous prose was written as continuous prose — it reads better and its provenance is exact.""" fragment = _Chunk("f1", "ومن أشهر صور الممنوع من الصرف صيغة منتهى الجموع في اللغة العربية.", section_title="أ") whole = _Chunk("c1", _PROSE, page_number=203, section_title="ب")
passage = _extract_passage([fragment, whole])
assert passage["assembled"] is False assert passage["source_chunk_ids"] == ["c1"]
def test_stitches_across_chunks_of_one_lesson_when_no_single_chunk_suffices(): lesson = "الممنوع من الصرف" chunks = [ _Chunk(f"c{i}", ( f"الجملة رقم {i} في هذا الدرس تشرح حكمًا من أحكام الممنوع من الصرف بشيء من التفصيل. " f"والجملة الثانية رقم {i} تضيف مثالًا تطبيقيًا على القاعدة السابقة بوضوح تام." ), page_number=200 + i, section_title=lesson) for i in range(3) ]
passage = _extract_passage(chunks)
assert passage["assembled"] is True assert len(passage["source_chunk_ids"]) >= 2 assert passage["page_range"] == [200, 202]
def test_passage_length_stays_within_bounds(): chunk = _Chunk("c1", _PROSE, page_number=203)
passage = _extract_passage([chunk])
assert 4 <= len(_prose_sentences(passage["text"])) <= 5
# ── Prompt ──────────────────────────────────────────��─────────────────────────
def _passage_prompt(count=5): return GatewayService._build_section_prompt( None, "short_answer", count, "السؤال الخامس", 3, "", True, language="AR", source_block_count=0, passage={"text": _PROSE, "source_chunk_ids": ["c1"], "page_range": [203, 203]}, )
def test_prompt_quotes_the_passage_and_forbids_rewriting_it(): prompt = _passage_prompt()
assert _PROSE in prompt assert "لا تعد كتابة القطعة" in prompt
def test_prompt_assigns_a_different_family_per_question(): prompt = _passage_prompt(count=5)
for family, _description in _PASSAGE_FAMILY_CYCLE[:5]: assert family in prompt
def test_prompt_requests_only_as_many_families_as_there_are_questions(): prompt = _passage_prompt(count=3)
assert _PASSAGE_FAMILY_CYCLE[3][0] not in prompt
def test_ungrouped_prompt_is_unchanged_by_the_feature(): """No passage means the prompt must not mention one at all.""" prompt = GatewayService._build_section_prompt( None, "short_answer", 5, "السؤال الخامس", 3, "", True, language="AR", source_block_count=4, )
assert "القطعة المرفقة" not in prompt assert "=== إسناد المصدر (إلزامي) ===" in prompt # normal attribution still on123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267"""Exam-integrity and fake-difficulty detection in the per-section review.
These checks come from measuring three real generated exams built from thesame 61-question blueprint over the same Arabic textbook, at three difficultytargets (25% / 50% / 100% hard). Two defects showed up that the review passcould not see at all:
1. The correct MCQ option was the longest one in 14/20, 12/20 and 19/20 questions, averaging 1.4x its distractors' length — a student who never reads a stem and always picks the longest option scores up to 95%.2. The only property that reliably changed between a medium and a hard question was length (mean stem 73 -> 122 characters). "Hard" was being produced by appending a clause to a medium question, which every marker-based Bloom heuristic reads as analysis.
The cases below are taken from that measured data rather than invented, so aregression here means the specific behavior that shipped has come back."""import pytest
from app.services.gateway import ( _containment, _hard_family, _mcq_length_leak, _review_section_quality, _INTEGRITY_REASONS,)
def _mcq(question, choices, answer, difficulty="hard", objective="هدف"): return { "type": "mcq", "difficulty": difficulty, "learning_objective": objective, "question": question, "choices": choices, "answer": answer, "marks": 2, }
# ── Option-length leakage ─────────────────────────────────────────────────────
def test_longest_most_qualified_option_is_flagged_as_a_leak(): """The measured shape: three curt distractors, one long reasoned answer.""" q = _mcq( "لماذا اعتبر الكاتب أن 'إرادة التغيير' هي ذاتها 'إرادة العمل'؟", [ "لأن التغيير لا يحتاج لعمل", "لأن الفعل لا يحتاج لإرادة", "لأن الإرادة هي مجرد قول", "لأن الإرادة بدون فعل هي مجرد أمنية لا تُحدث تغييرًا في الواقع", ], "لأن الإرادة بدون فعل هي مجرد أمنية لا تُحدث تغييرًا في الواقع", )
assert _mcq_length_leak(q) is True
def test_options_of_comparable_length_are_not_flagged(): q = _mcq( "ما الاسم الذي أطلقه الكنعانيون على القدس؟", ["إيلياء", "أورشليم", "دار السلام", "أورسالم"], "أورسالم", )
assert _mcq_length_leak(q) is False
def test_marginally_longest_answer_is_not_flagged(): """Winning by a couple of characters is noise, not a cue a student can use.""" q = _mcq( "ما عاصمة الدولة الأموية؟", ["مدينة الإسكندرية", "مدينة بغداد الكبرى", "مدينة القيروان", "مدينة دمشق الشامية"], "مدينة دمشق الشامية", )
# Longest, but only by ~1.13x the mean distractor — under the 1.25 bar. assert _mcq_length_leak(q) is False
def test_non_mcq_questions_are_never_length_flagged(): assert _mcq_length_leak({ "type": "essay", "question": "حلل العلاقة بين الغربة والحنين في أدب المهاجر.", "answer": "إجابة مطولة جدًا تشرح العلاقة بتفصيل كبير ولا معنى لمقارنتها بخيارات", }) is False
def test_length_leak_is_treated_as_an_integrity_defect(): """Integrity reasons get their own reroll budget ahead of style flags.""" assert "option_length_leak" in _INTEGRITY_REASONS assert "answer_leakage" in _INTEGRITY_REASONS
# ── Difficulty inflation ──────────────────────────────────────────────────────
# The real medium/hard pair, from the same MCQ section of one generated exam._MEDIUM_TWIN = { "type": "short_answer", "difficulty": "medium", "learning_objective": "تحليل الأفكار", "question": "ما السبب الذي دفع صلاح الدين الأيوبي للبدء بفتح المدن الساحلية قبل القدس؟", "answer": "لحرمان الصليبيين من قواعدهم البحرية",}_HARD_TWIN = { "type": "short_answer", "difficulty": "hard", "learning_objective": "تحليل العلاقة بين التخطيط الاستراتيجي والنتائج العسكرية", "question": ( "لماذا أصر صلاح الدين الأيوبي على تحرير المدن الساحلية قبل التوجه لتحرير " "القدس، وكيف يعكس ذلك فهمه لطبيعة الصراع؟" ), "answer": "لقطع خطوط الإمداد البحرية التي تربط الصليبيين بأوروبا لضمان عدم وصول تعزيزات",}_FILLER = [ {"type": "short_answer", "difficulty": "easy", "question": "متى وُلد البيروني؟", "learning_objective": "حقائق تاريخية", "answer": "سنة ٣٦٢ هجرية في خوارزم"}, {"type": "short_answer", "difficulty": "medium", "question": "ما أهم مؤلفات البيروني عن الهند؟", "learning_objective": "مؤلفات البيروني", "answer": "كتاب تحقيق ما للهند من مقولة"},]
def test_a_medium_question_plus_a_clause_is_flagged_as_inflated(): questions = [_MEDIUM_TWIN, _HARD_TWIN, *_FILLER]
review = _review_section_quality(questions, "short_answer", retrieval_confidence=1.0)
assert review["reasons"].get(1) == "inflated_difficulty"
def test_only_the_harder_half_of_the_pair_is_flagged(): """The medium question is fine as it is — it's the hard slot that isn't earning its label.""" questions = [_MEDIUM_TWIN, _HARD_TWIN, *_FILLER]
review = _review_section_quality(questions, "short_answer", retrieval_confidence=1.0)
assert review["reasons"].get(0) != "inflated_difficulty"
def test_the_pair_is_invisible_to_plain_jaccard_duplicate_detection(): """Why containment is used here: the added clause dilutes Jaccard below 0.6.""" from app.services.gateway import _concept_key, _jaccard
a, b = _concept_key(_HARD_TWIN), _concept_key(_MEDIUM_TWIN)
assert _jaccard(a, b) < 0.6 # the existing duplicate check can't see it assert _containment(a, b) >= 0.5 # this one can
# ── Reasoning families ────────────────────────────────────────────────────────
@pytest.mark.parametrize("text,family", [ ("كتب أحد الطلاب: 'زاروا مدارسِ قديمةٍ' وقال إن الكسرة صحيحة. حدّد موضع الخطأ.", "error_diagnosis"), ("قاعدتان تبدوان ممكنتين هنا — ما الدليل الذي يستبعد الأخرى؟", "rule_conflict"), ("لو استبدلنا 'مدارسَ قديمةً' بـ'مدارسِ المدينةِ'، فما الذي يتغير؟", "transformation"), ("ما سبب اختلاف صورة الاسم في الموضعين؟", "minimal_pair"), ("طبّق القاعدة نفسها على كلمة 'مساجد' في مثال من إنشائك.", "transfer"),])def test_hard_families_are_recognized(text, family): assert _hard_family(text) == family
def test_a_why_question_alone_is_not_a_hard_family(): """The core miss: "لماذا" reads as analysis to the Bloom heuristic, but it's a mood, not a task structure — this is what let fake-hard questions pass.""" assert _hard_family("لماذا اعتبر الكاتب أن إرادة التغيير هي ذاتها إرادة العمل؟") is None
def test_hard_question_without_a_family_is_flagged_shallow(): questions = [ _mcq("لماذا اعتبر الكاتب أن 'إرادة التغيير' هي ذاتها 'إرادة العمل'؟", ["أ الخيار", "ب الخيار", "ج الخيار", "د الخيار"], "أ الخيار"), _mcq("ما الرابط بين 'العهدة العمرية' و'تسامح الإسلام'؟", ["أ خيار", "ب خيار", "ج خيار", "د خيار"], "ب خيار"), _mcq("ما معنى 'نير' في العبارة؟", ["قيد", "طريق", "جبل", "نهر"], "قيد", difficulty="easy"), _mcq("متى وُلد البيروني؟", ["٣٦٢ هـ", "٤٠٠ هـ", "٣٠٠ هـ", "٤٥٠ هـ"], "٣٦٢ هـ", difficulty="easy"), ]
review = _review_section_quality(questions, "mcq", retrieval_confidence=1.0)
assert review["reasons"].get(0) == "shallow_hard"
def test_hard_question_built_on_a_family_is_not_flagged_shallow(): questions = [ _mcq( "قال طالب إن 'مدارس' تُجر بالكسرة لأنها اسم مجرور. حدّد موضع الخطأ في تحليله.", ["خلط بين الوظيفة والعلامة", "أخطأ في تحديد الوظيفة", "أخطأ في نوع الكلمة", "أخطأ في موقع الجملة"], "خلط بين الوظيفة والعلامة", ), _mcq("ما معنى 'نير'؟", ["قيد", "طريق", "جبل", "نهر"], "قيد", difficulty="easy"), _mcq("متى وُلد البيروني؟", ["٣٦٢ هـ", "٤٠٠ هـ", "٣٠٠ هـ", "٤٥٠ هـ"], "٣٦٢ هـ", difficulty="easy"), _mcq("أين نشأ البيروني؟", ["خوارزم", "بغداد", "دمشق", "قرطبة"], "خوارزم", difficulty="easy"), ]
review = _review_section_quality(questions, "mcq", retrieval_confidence=1.0)
assert review["reasons"].get(0) != "shallow_hard"
def test_true_false_sections_are_exempt_from_the_family_requirement(): """Single-proposition formats have no room for a task structure, so demanding a reasoning family from them would flag every question.""" questions = [ {"type": "true_false", "difficulty": "hard", "learning_objective": "هدف", "question": "كان البيروني يرفض جوائز السلطان المسعودي.", "answer": "صح"}, {"type": "true_false", "difficulty": "hard", "learning_objective": "هدف آخر", "question": "أُطلق على القدس اسم أورسالم عند الكنعانيين.", "answer": "صح"}, {"type": "true_false", "difficulty": "easy", "learning_objective": "ثالث", "question": "وُلد البيروني في بغداد.", "answer": "خطأ"}, {"type": "true_false", "difficulty": "easy", "learning_objective": "رابع", "question": "فتح صلاح الدين عكا قبل القدس.", "answer": "صح"}, ]
review = _review_section_quality(questions, "true_false", retrieval_confidence=1.0)
assert "shallow_hard" not in review["reasons"].values()
# ── Intra-section answer leakage ──────────────────────────────────────────────
def test_answer_printed_in_another_stem_is_flagged_during_review(): """Previously only reported at exam level, after the reroll budget was spent.""" leaked = "قطع خطوط الإمداد البحرية عن الصليبيين في الشام" questions = [ {"type": "short_answer", "difficulty": "medium", "learning_objective": "أ", "question": "ما هدف صلاح الدين من فتح المدن الساحلية؟", "answer": leaked}, {"type": "short_answer", "difficulty": "easy", "learning_objective": "ب", "question": f"بعد {leaked}، ما الذي تغير في موازين القوى؟", "answer": "ضعف الصليبيين"}, {"type": "short_answer", "difficulty": "easy", "learning_objective": "ج", "question": "متى وُلد البيروني؟", "answer": "سنة ٣٦٢ هجرية"}, {"type": "short_answer", "difficulty": "medium", "learning_objective": "د", "question": "ما أشهر مؤلفات البيروني؟", "answer": "كتاب تحقيق ما للهند"}, ]
review = _review_section_quality(questions, "short_answer", retrieval_confidence=1.0)
assert review["reasons"].get(0) == "answer_leakage"
def test_short_answers_do_not_count_as_leakage(): """"صح"/"10"/a single term collide by coincidence constantly.""" questions = [ {"type": "short_answer", "difficulty": "easy", "learning_objective": "أ", "question": "ما عاصمة الأمويين؟", "answer": "دمشق"}, {"type": "short_answer", "difficulty": "easy", "learning_objective": "ب", "question": "متى فُتحت دمشق؟", "answer": "سنة ١٤ هجرية"}, {"type": "short_answer", "difficulty": "easy", "learning_objective": "ج", "question": "متى وُلد البيروني؟", "answer": "سنة ٣٦٢ هجرية"}, {"type": "short_answer", "difficulty": "medium", "learning_objective": "د", "question": "ما أشهر مؤلفات البيروني؟", "answer": "كتاب تحقيق ما للهند"}, ]
review = _review_section_quality(questions, "short_answer", retrieval_confidence=1.0)
assert "answer_leakage" not in review["reasons"].values()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""The red-team pass — the one place an LLM judgment is bought.
The deterministic checks see structure: does a question have a task shape, areits options guessable by length, does it duplicate another. They cannot seemeaning — whether a question is answerable without having read the lesson, orwhether three of four options fall to general knowledge. Those need a reader.
The rubric is deliberately five yes/no judgments with defensible answers, not"is this hard?" — a model asked that grades its own homework and says yes."""import pytest
from app.services.gateway import ( _RED_TEAM_FAILURES, _build_red_team_prompt, _red_team_failures,)
_CLEAN = { "answerable_without_lesson": False, "solvable_by_general_logic": False, "distractors_eliminable": False, "needs_multiple_evidence": True, "clear": True,}
def test_a_question_that_survives_the_attack_has_no_failures(): assert _red_team_failures(_CLEAN) == []
@pytest.mark.parametrize("field,value,reason", [ ("answerable_without_lesson", True, "not_source_dependent"), ("solvable_by_general_logic", True, "solvable_without_content"), ("distractors_eliminable", True, "weak_distractors"), ("needs_multiple_evidence", False, "single_evidence"), ("clear", False, "unclear_wording"),])def test_each_verdict_maps_to_its_reason(field, value, reason): assert reason in _red_team_failures({**_CLEAN, field: value})
def test_failures_come_back_worst_first(): """Not testing the lesson at all outranks merely being guessable.""" everything_wrong = { "answerable_without_lesson": True, "solvable_by_general_logic": True, "distractors_eliminable": True, "needs_multiple_evidence": False, "clear": False, }
reasons = _red_team_failures(everything_wrong)
assert reasons[0] == "not_source_dependent" assert reasons == [r for _f, _v, r in _RED_TEAM_FAILURES]
def test_missing_and_non_boolean_verdicts_are_ignored(): """A judge that answers "maybe" must not be read as a failure — the reroll budget is finite and spending it on a non-answer is worse than not acting.""" assert _red_team_failures({}) == [] assert _red_team_failures({"answerable_without_lesson": "نعم"}) == [] assert _red_team_failures({"clear": None}) == []
def test_every_mapped_field_appears_in_the_prompt(): """The schema and the rubric must agree, or the model answers a different set of questions than the code reads.""" prompt = _build_red_team_prompt("AR")
for field, _value, _reason in _RED_TEAM_FAILURES: assert field in prompt
def test_prompt_frames_the_task_as_an_attack_not_an_assessment(): prompt = _build_red_team_prompt("AR")
assert "مهاجمة" in prompt assert "لم يدرس هذا الدرس" in prompt # It must never simply ask "is this hard" — that's the question the whole # measured failure came from the model answering optimistically. assert "هل هذا السؤال صعب" not in promptapp/config.py+23
app/models/structured_schemas.py+56
app/services/gateway.py+1242-39
app/services/pdf_export.py+38
app/templates/answer_key.html+3-1
app/templates/exam.html+30-1
tests/test_exam_measured_difficulty.pyAdded+188
tests/test_exam_passage_groups.pyAdded+157
tests/test_exam_question_integrity.pyAdded+267
tests/test_exam_red_team.pyAdded+83