Spaces:
Build error
Build error
anwarKXC commited on
Commit ·
355cf7a
1
Parent(s): e30e684
feat: Add live progress tracking for exam generation with multilingual phase labels
Browse filesFiles changed (2)
29 unmodified lines3031323334353637383929 unmodified linesclass StreamProgressEvent(BaseModel):"""Progress update during multi-section exam generation."""progress: strsection: inttotal_sections: intclass StreamErrorEvent(BaseModel):29 unmodified lines30313233343536373839404142434445464748495051525329 unmodified linesclass StreamProgressEvent(BaseModel):"""Progress update during multi-section exam generation.One event per phase transition of one section, streamed live while thesection runs — `section` identifies the row to update in place rather thana new line to append.Completion travels as `step_done`, never `done`: both the NestJS proxy andthe browser normalizer match a bare `done: true` as the TERMINAL streamevent before they look at `progress`, so reusing `done` here would end thestream mid-generation."""progress: strsection: inttotal_sections: inttitle: Optional[str] = Nonephase: Optional[str] = Nonedetail: Optional[str] = Nonestep_done: bool = Falseclass StreamErrorEvent(BaseModel):
367 unmodified lines368369370371372373602 unmodified lines97697797897998098198298398422 unmodified lines1007100810091010101110121013101410151016101710181019242 unmodified lines1262126312641265126612671268146 unmodified lines141514161417141814191420142160 unmodified lines1482148314841485148614871488100 unmodified lines1589159015911592159315941595158 unmodified lines1754175517561757175817592196 unmodified lines395639573958395939603961159 unmodified lines412141224123412441254126412741284129413041314132413341344135413654 unmodified lines419141924193419441954196419741984199420042014202601 unmodified lines4804480548064807480848095 unmodified lines481548164817481848194820315 unmodified lines51365137513851395140514163 unmodified lines52055206520752085209521010 unmodified lines52215222522352245225522664 unmodified lines52915292529352945295529658 unmodified lines535553565357535853595360149 unmodified lines5510551155125513551455158 unmodified lines55245525552655275528552980 unmodified lines5610561156125613561456153 unmodified lines5619562056215622562356245625562656276 unmodified lines5634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565913 unmodified lines56735674567556765677567856795680568156825683367 unmodified linesreturn f"data: {json.dumps(payload)}\n\n"def _build_multimodal_content(text: str, image_urls: list[str]) -> list[dict]:"""OpenAI-compatible multimodal content array: text block + image_url blocks.602 unmodified lines"لا يكفي الشكل", "ما الدليل الذي يستبعد", "التعميم", "بصورتها المطلقة","which rule applies", "why is the generalization",]_TRANSFORMATION_MARKERS = ["أعد صياغة", "لو استبدلنا", "إذا استبدلنا", "لو غُيّر", "لو غيرنا","بحيث تصبح", "أعد كتابة", "ماذا يحدث لو", "rewrite", "if we replaced",]_MINIMAL_PAIR_MARKERS = ["في الموضعين", "في الحالتين", "في الجملتين", "الفرق بين الجملتين",22 unmodified lines]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 larger242 unmodified linescontinueif 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"146 unmodified lines# 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)60 unmodified lines# 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 -= 8100 unmodified lineshard = [q for q in questions if str(q.get("difficulty", "")).lower() == "hard"]if not hard:return Noneshallow = sum(1 for q in hard if _hard_family(_question_review_text(q)) is None)return round(100.0 * shallow / len(hard), 1)158 unmodified lines# maximum, and `EXAM_PASSAGE_GROUP_SIZE` can only lower it, never raise it._PASSAGE_GROUP_HARD_MAX = 5# 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 the2196 unmodified lines# 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)159 unmodified lines"كما هما. هذا سؤال متوسط بصياغة أطول، وليس سؤالًا صعبًا.\n""- easy: تطبيق قاعدة أو معلومة واحدة من النص تطبيقًا مباشرًا وصحيحًا.\n""- medium: خطوتان من الاستدلال، أو مقارنة بين حالتين، أو تطبيق يحتاج ربط معلومتين.\n""- hard: يجب أن يُبنى على واحد من الأنماط التالية حصرًا:\n"" • تشخيص خطأ: طالب حلّل أو أعرب أو فسّر بشكل خاطئ — أين الخطأ في تحليله ولماذا؟\n"" • تعارض قاعدتين: قاعدتان تبدوان منطبقتين — أيهما تنطبق هنا، وما الدليل الذي ""يستبعد الأخرى؟\n"" • تحويل: غيّر عنصرًا في الجملة أو الموقف، ثم فسّر ما الذي تغيّر في الحكم وما الذي ""لم يتغيّر ولماذا.\n"" • زوج متقارب: موضعان شديدا التشابه اختلف الحكم فيهما — ما سبب الاختلاف؟\n"" • أدلة متعددة: الإجابة تتطلب الجمع بين موضعين مختلفين من النص، ولا تكفي فيها ""معلومة واحدة.\n"" • نقل: طبّق القاعدة نفسها على مثال جديد لم يرد في النص.\n""- كل سؤال hard يجب ألا يكون قابلًا للحل بالذكاء العام أو المعرفة العامة أو بمطابقة ""الكلمات المشتركة بين السؤال والخيارات — من لم يدرس هذا الدرس تحديدًا لا يستطيع ""الإجابة.\n"54 unmodified lines))return (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 burying# it as "rule 12" got it dropped from a large fraction of questions601 unmodified lines# written from (`source_chunk_ids`).chunk_topic_map: dict[str, tuple[Optional[str], Optional[int]]] = {}# ── Per-section coroutine (batches within a section stay sequential for dedup) ──async def _generate_one_section(idx: int,5 unmodified lineschunk_page_start: int,) -> dict:"""Generate all questions for one section; returns {"title": ..., "questions": [...]}."""# Wall-clock breakdown for this section, in ms. Exists because# "exam generation got slower" was previously unanswerable without# guessing: retrieval, the LLM calls, and the reroll pass are all315 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.63 unmodified linesidx + 1, total_sections, stype,batch_idx + 1, len(batches), added,)except Exception as e:logger.error("Section %s batch %d failed: %s", stype, batch_idx + 1, e)10 unmodified lineswhile missing > 0 and retry_round < 3:retry_round += 1retry_count = min(missing, max(4, section_max_batch // 2))retry_figure_urls: list[str] = []retry_image_urls: list[str] = []64 unmodified lines# Same ratio, smaller count — the retry is filling in# whatever the first pass came up short on.difficulty_target=_difficulty_counts_for_section(retry_count, difficulty_target),source_block_count=len(retry_block_chunk_ids) if retry_has_context else 0,)58 unmodified lines)section_pool_size = len(source_pool) or Noneif stype != "matching" and len(all_questions) >= 4:review = _review_section_quality(all_questions, stype, retrieval_confidence=retrieval_confidence,source_pool_size=section_pool_size,149 unmodified linesidx + 1, total_sections, stype, len(review["flagged"]),len(all_questions), review["reasons"], len(reroll_indices),)await _run_reroll(reroll_indices, review["reasons"])# ── Red team ──────────────────────────────────────────────8 unmodified linesand 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,80 unmodified lineslive_passage_ids = {q.get("passage_id") for q in all_questions if q.get("passage_id")}return {"title": title,"questions": all_questions,3 unmodified lines**({"warning": section_warning} if section_warning else {}),}# Emit initial progress for all sections, then run all sections in parallelfor idx, (stype, count, title, marks, note) in enumerate(section_defs):yield f"data: {json.dumps({'progress': f'جاري إنشاء {title} ({count} أسئلة)...', 'section': idx + 1, 'total_sections': total_sections})}\n\n"# Compute chunk page start offsets so each section covers different contentsection_chunk_starts: list[int] = []6 unmodified lines# and avoid partial failures that leave the final exam under-filled.run_sequential = total_requested_questions >= 120yield ": keepalive\n\n"if run_sequential:section_results: list[dict] = []for idx, (stype, count, title, marks, note) in enumerate(section_defs):result = await _generate_one_section(idx,stype,count,title,marks,note,section_chunk_starts[idx],)section_results.append(result)else:section_results = await asyncio.gather(*[_generate_one_section(idx, stype, count, title, marks, note, section_chunk_starts[idx])for idx, (stype, count, title, marks, note) in enumerate(section_defs)])all_sections: list[dict] = list(section_results)# A section that failed its precondition (no passage for `reading`, no# figures for figure_based/diagram) comes back empty with a reason.# Tell the teacher which section was skipped and why, then drop it —13 unmodified lines# sections — the frontend/backend never see the raw per-section# metrics, only this rollup plus the per-question fields they already# got (difficulty, learning_objective).async with _get_fresh_session() as _scope_session:generation_insights = await _build_generation_insights(all_sections, chunk_topic_map, resolved_materials,materials=materials, session=_scope_session,)# One greppable line per exam with the full latency breakdown. Sections# run concurrently by default, so the exam's floor is the slowest# section's serial chain — `slowest_section_ms`, not the sum — which is367 unmodified lines368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428602 unmodified lines10311032103310341035103610371038103910401041104210431044104510461047104822 unmodified lines1071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101242 unmodified lines1344134513461347134813491350146 unmodified lines149714981499150015011502150360 unmodified lines1564156515661567156815691570100 unmodified lines1671167216731674167516761677167816791680158 unmodified lines18391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218932196 unmodified lines409040914092409340944095409640974098159 unmodified lines425842594260426142624263426454 unmodified lines4319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358601 unmodified lines4960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449955 unmodified lines5001500250035004500550065007315 unmodified lines53235324532553265327532853295330533163 unmodified lines53955396539753985399540054015402540354045405540610 unmodified lines541754185419542054215422542354245425542664 unmodified lines54915492549354945495549654975498549958 unmodified lines5558555955605561556255635564556555665567149 unmodified lines57175718571957205721572257235724572557268 unmodified lines573557365737573857395740574157425743574480 unmodified lines58255826582758285829583058315832583358343 unmodified lines5838583958405841584258435844584558465847584858496 unmodified lines585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592513 unmodified lines59395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973367 unmodified linesreturn f"data: {json.dumps(payload)}\n\n"# Phase labels for the live exam-generation progress timeline, per language.# Each section walks: generating → completing (only if short) → reviewing →# revising (only if the review flagged something) → verifying → done. The# exam-level phases (assembling/finalizing) run once, after every section.## `step_done` — not `done` — carries completion here on purpose: both the# NestJS proxy and the browser normalizer match a bare `done: true` as the# TERMINAL stream event before they ever look at `progress`, so a progress# event carrying `done` would end the stream mid-generation._EXAM_PHASE_LABELS: dict[str, dict[str, str]] = {"AR": {"queued": "في الانتظار","generating": "جاري كتابة الأسئلة","completing": "استكمال الأسئلة الناقصة","reviewing": "مراجعة جودة الأسئلة","revising": "إعادة صياغة الأسئلة الضعيفة","verifying": "التحقق من صحة الإجابات","ready": "اكتمل","assembling": "تجميع الامتحان ونموذج الإجابة","finalizing": "تحليل جودة الامتحان",},"EN": {"queued": "Queued","generating": "Writing questions","completing": "Filling in missing questions","reviewing": "Reviewing question quality","revising": "Rewriting weak questions","verifying": "Verifying answers","ready": "Done","assembling": "Assembling the exam and answer key","finalizing": "Analyzing exam quality",},"FR": {"queued": "En attente","generating": "Rédaction des questions","completing": "Complément des questions manquantes","reviewing": "Contrôle de la qualité","revising": "Réécriture des questions faibles","verifying": "Vérification des réponses","ready": "Terminé","assembling": "Assemblage de l'examen et du corrigé","finalizing": "Analyse de la qualité",},}def _exam_phase_label(phase: str, language: str) -> str:labels = _EXAM_PHASE_LABELS.get(language, _EXAM_PHASE_LABELS["AR"])return labels.get(phase, phase)def _progress_sse_line(payload: dict) -> str:return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"def _build_multimodal_content(text: str, image_urls: list[str]) -> list[dict]:"""OpenAI-compatible multimodal content array: text block + image_url blocks.602 unmodified lines"لا يكفي الشكل", "ما الدليل الذي يستبعد", "التعميم", "بصورتها المطلقة","which rule applies", "why is the generalization",]# Matched against surface text, so the inflections a generator actually# produces have to be listed. Measured misses on a real exam: the model wrote# "وأعدنا صياغة الجملة" and "إذا قمنا بتحويل الجملة" — both unambiguous# transformation questions that scored as plain recall because the list only# had the bare imperative "أعد صياغة". Stems ("صياغ", "تحويل") rather than# whole conjugations, so first-person plural, past and verbal-noun forms all# land._TRANSFORMATION_MARKERS = ["صياغة", "لو استبدلنا", "إذا استبدلنا", "إذا حذفنا", "لو حذفنا","إذا أضفنا", "لو أضفنا", "لو غُيّر", "لو غيرنا", "إذا غيرنا", "إذا غيّرنا","تحويل", "حوّلنا", "حولنا", "بحيث تصبح", "أعد كتابة", "ماذا يحدث لو","rewrite", "if we replaced", "if we removed",]_MINIMAL_PAIR_MARKERS = ["في الموضعين", "في الحالتين", "في الجملتين", "الفرق بين الجملتين",22 unmodified lines]# Section types whose task IS a reasoning family by construction, regardless of# how the individual stem is worded. A `correction` question presents a wrong# statement for the student to find and fix — that is error diagnosis whether or# not the stem says "أين الخطأ", because the instruction lives in the section# heading ("صوّب الخطأ في العبارات التالية") rather than in each question.# Without this, an entire section of exactly the cognitive operation we're# trying to elicit scored as plain recall._TYPE_IMPLIED_FAMILY = {"correction": "error_diagnosis","true_false_correction": "error_diagnosis",}def _hard_family(question_text: str, question_type: str | None = None) -> Optional[str]:"""Which reasoning family a question's task structure belongs to, if any.`question_type` lets a section type imply its family (see`_TYPE_IMPLIED_FAMILY`); the stem is still checked first, so a correctionquestion that also sets up a rule conflict reports the richer family."""t = (question_text or "").strip().lower()for family, markers in _HARD_FAMILY_MARKERS:if any(m in t for m in markers):return familyreturn _TYPE_IMPLIED_FAMILY.get(question_type or "")# How much of the smaller question's concept set has to sit inside the larger242 unmodified linescontinueif str(q.get("difficulty", "")).lower() != "hard":continueif _hard_family(_question_review_text(q), q.get("type")) is None:already.add(i)flagged.append(i)reasons[i] = "shallow_hard"146 unmodified lines# 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, question.get("type")):score += 30else:bucket = _question_stem_bucket(text)60 unmodified lines# is difficulty performed rather than difficulty present.if (len(text) > _VERBOSE_STEM_CHARSand not _hard_family(text, question.get("type"))and len(question.get("source_chunk_ids") or []) <= 1):score -= 8100 unmodified lineshard = [q for q in questions if str(q.get("difficulty", "")).lower() == "hard"]if not hard:return Noneshallow = sum(1 for q in hardif _hard_family(_question_review_text(q), q.get("type")) is None)return round(100.0 * shallow / len(hard), 1)158 unmodified lines# maximum, and `EXAM_PASSAGE_GROUP_SIZE` can only lower it, never raise it._PASSAGE_GROUP_HARD_MAX = 5# Construction recipes for hard questions, one per reasoning family.## These replace a bulleted menu of families that the model was asked to "choose# one of". Measured outcome of the menu, on a 142-question exam whose 50%-hard# target was applied correctly in every section: 67 of 70 hard-labelled# questions had no hard task structure at all (shallow_hard 93%, authentic hard# 2.1%). Describing what hard means does not change what the model generates —# it produces the same medium question and labels it hard.## So a slot no longer receives a description of a family, it receives a build# order: construct this specific artifact. "Write a wrong analysis a student# would plausibly produce, then ask where it fails" is a task with a checkable# output; "make it hard" is not. Each recipe names the thing to construct# first, and only then what to ask about it._HARD_FAMILY_RECIPES: list[tuple[str, str]] = [("error_diagnosis","اكتب أولًا تحليلًا أو إعرابًا أو تفسيرًا خاطئًا لموضع من النص، على أن يكون خطأً ""يقع فيه طالب فعلًا لأنه طبّق قاعدة صحيحة في غير موضعها (لا خطأً ساذجًا). ثم اطلب ""من الطالب تحديد موضع الخطأ وتصويبه مع ذكر سبب عدم انطباق القاعدة هنا."),("rule_conflict","اختر موضعًا من النص تبدو فيه قاعدتان منطبقتين معًا. اذكر القاعدتين بوضوح، ثم اطلب ""تحديد أيهما تنطبق فعلًا، وما الدليل الموجود في النص الذي يستبعد الأخرى."),("transformation","خذ جملة أو موقفًا من النص، وغيّر فيه عنصرًا واحدًا محددًا (أداة، أو إضافة، أو زمنًا، ""أو شرطًا). ثم اطلب بيان ما الذي تغيّر في الحكم وما الذي بقي كما هو، مع تعليل سبب ""ثبات ما ثبت — لا يكفي ذكر النتيجة دون سببها."),("minimal_pair","اختر موضعين من النص متشاب��ين جدًا في الصورة ومختلفين في الحكم. اعرضهما معًا، ثم ""اطلب تفسير سبب اختلاف الحكم، وتحديد العنصر الوحيد المسؤول عن الاختلاف."),("multi_evidence","ابنِ سؤالًا لا يمكن الإجابة عنه إلا بالجمع بين موضعين مختلفين من النص، بحيث يؤدي ""الاكتفاء بأحدهما إلى إجابة ناقصة أو خاطئة. اجعل الموضعين بعيدين عن بعضهما في النص."),("transfer","استخلص القاعدة أو الفكرة من النص، ثم اطلب تطبيقها على مثال جديد من إنشاء الطالب ""لم يرد في النص إطلاقًا، مع تعليل سبب انطباقها على مثاله."),]# 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 the2196 unmodified lines# group. None keeps the prompt byte-identical to the ungrouped path.passage: dict | None = None,passage_families: list[tuple[str, str]] | None = None,# Rotates which hard-question recipe a batch starts from, so a# multi-section exam doesn't open every section with error diagnosis.family_offset: int = 0,) -> str:"""Build a focused system prompt for generating a single exam section."""language_directive = _exam_language_directive(language)159 unmodified lines"كما هما. هذا سؤال متوسط بصياغة أطول، وليس سؤالًا صعبًا.\n""- easy: تطبيق قاعدة أو معلومة واحدة من النص تطبيقًا مباشرًا وصحيحًا.\n""- medium: خطوتان من الاستدلال، أو مقارنة بين حالتين، أو تطبيق يحتاج ربط معلومتين.\n""- hard: لا يُكتب بالاختيار الحر — كل سؤال صعب يُبنى وفق وصفة محددة تُعطى لك أدناه.\n""- كل سؤال hard يجب ألا يكون قابلًا للحل بالذكاء العام أو المعرفة العامة أو بمطابقة ""الكلمات المشتركة بين السؤال والخيارات — من لم يدرس هذا الدرس تحديدًا لا يستطيع ""الإجابة.\n"54 unmodified lines))# Per-slot build orders for the hard questions in this batch. Only# emitted when a difficulty target says how many hard questions are# wanted — without a target there are no slots to assign, and the# contract's general definition is all there is to go on.## `family_offset` rotates the starting recipe per batch/section so a# multi-section exam doesn't open every section with error diagnosis.hard_spec = ""hard_wanted = (difficulty_target or {}).get("hard", 0)if hard_wanted > 0 and not passage:recipes = [_HARD_FAMILY_RECIPES[(family_offset + i) % len(_HARD_FAMILY_RECIPES)]for i in range(hard_wanted)]hard_spec = ("\n=== وصفات بناء الأسئلة الصعبة (إلزامية) ===\n"f"الأسئلة الصعبة في هذه الدفعة عددها {hard_wanted}. لكل واحد منها وصفة ""محددة، ابنِ السؤال وفقها حرفيًا ولا تستبدل وصفة بأخرى:\n"+ "\n".join(f" {i + 1}) [{family}] {recipe}"for i, (family, recipe) in enumerate(recipes))+ "\n- كل وصفة تطلب منك أن *تصنع* شيئًا (تحليلًا خاطئًا، موضعين متقابلين، ""جملة محوَّلة) قبل أن تسأل عنه. السؤال الذي لا يحتوي على هذا المصنوع ليس ""سؤالًا صعبًا مهما بدت صياغته.\n")return (general_rules+ difficulty_contract+ section_spec+ passage_spec+ batch_spec+ hard_spec# Deliberately outside the numbered rule list and stated last: this# is the one field the model has no prior instinct for, and burying# it as "rule 12" got it dropped from a large fraction of questions601 unmodified lines# written from (`source_chunk_ids`).chunk_topic_map: dict[str, tuple[Optional[str], Optional[int]]] = {}# ── Live progress channel ─────────────────────────────────────────# Sections are plain coroutines run under gather(), so they cannot# `yield` SSE lines themselves. They push progress payloads here and# the driver loop below drains the queue while the sections run, which# is what makes the timeline advance in real time instead of printing# every section's line up front and then going silent for minutes.progress_queue: asyncio.Queue[dict] = asyncio.Queue()def _emit_progress(idx: int,title: str,phase: str,*,done: bool = False,detail: str | None = None,) -> None:payload = {# `progress` stays the human-readable line older consumers# (and the exam-level fallback headline) already render."progress": f"{title} — {_exam_phase_label(phase, exam_language)}","section": idx + 1,"total_sections": total_sections,"title": title,"phase": phase,"step_done": done,}if detail:payload["detail"] = detailprogress_queue.put_nowait(payload)# ── Per-section coroutine (batches within a section stay sequential for dedup) ──async def _generate_one_section(idx: int,5 unmodified lineschunk_page_start: int,) -> dict:"""Generate all questions for one section; returns {"title": ..., "questions": [...]}."""_emit_progress(idx, title, "generating", detail=f"0 / {count}")# Wall-clock breakdown for this section, in ms. Exists because# "exam generation got slower" was previously unanswerable without# guessing: retrieval, the LLM calls, and the reroll pass are all315 unmodified lineshas_figures=bool(batch_figure_urls),language=exam_language,difficulty_target=_difficulty_counts_for_section(batch_count, difficulty_target),# Distinct per section AND per batch, so section 3's second# batch doesn't rebuild section 1's first batch's recipes.family_offset=idx + batch_idx,# 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.63 unmodified linesidx + 1, total_sections, stype,batch_idx + 1, len(batches), added,)# Live count after every batch — the only signal a teacher# gets that a long section is actually moving._emit_progress(idx, title, "generating",detail=f"{len(all_questions)} / {count}",)except Exception as e:logger.error("Section %s batch %d failed: %s", stype, batch_idx + 1, e)10 unmodified lineswhile missing > 0 and retry_round < 3:retry_round += 1retry_count = min(missing, max(4, section_max_batch // 2))_emit_progress(idx, title, "completing",detail=f"{len(all_questions)} / {count}",)retry_figure_urls: list[str] = []retry_image_urls: list[str] = []64 unmodified lines# Same ratio, smaller count — the retry is filling in# whatever the first pass came up short on.difficulty_target=_difficulty_counts_for_section(retry_count, difficulty_target),# Offset past the main batches so a top-up doesn't repeat# the recipes the section already used.family_offset=idx + len(batches) + retry_round,source_block_count=len(retry_block_chunk_ids) if retry_has_context else 0,)58 unmodified lines)section_pool_size = len(source_pool) or Noneif stype != "matching" and len(all_questions) >= 4:_emit_progress(idx, title, "reviewing",detail=f"{len(all_questions)} / {count}",)review = _review_section_quality(all_questions, stype, retrieval_confidence=retrieval_confidence,source_pool_size=section_pool_size,149 unmodified linesidx + 1, total_sections, stype, len(review["flagged"]),len(all_questions), review["reasons"], len(reroll_indices),)_emit_progress(idx, title, "revising",detail=f"{len(reroll_indices)} / {len(all_questions)}",)await _run_reroll(reroll_indices, review["reasons"])# ── Red team ──────────────────────────────────────────────8 unmodified linesand not q.get("passage_id") # same exclusion as above][:settings.EXAM_RED_TEAM_MAX_QUESTIONS]if attackable:_emit_progress(idx, title, "verifying",detail=f"{len(attackable)} / {len(all_questions)}",)_t_rt = time.perf_counter()rt_failures = await self._red_team_section(all_questions, attackable,80 unmodified lineslive_passage_ids = {q.get("passage_id") for q in all_questions if q.get("passage_id")}_emit_progress(idx, title, "ready", done=True,detail=f"{len(all_questions)} / {count}",)return {"title": title,"questions": all_questions,3 unmodified lines**({"warning": section_warning} if section_warning else {}),}# Seed the timeline with one queued row per section, so the teacher sees# the shape of the whole exam immediately. Each row then advances# through its own phases as its section runs — these are placeholders,# not completions.for idx, (stype, count, title, marks, note) in enumerate(section_defs):_emit_progress(idx, title, "queued", detail=f"0 / {count}")# Compute chunk page start offsets so each section covers different contentsection_chunk_starts: list[int] = []6 unmodified lines# and avoid partial failures that leave the final exam under-filled.run_sequential = total_requested_questions >= 120yield ": keepalive\n\n"async def _run_all_sections() -> list[dict]:if run_sequential:results: list[dict] = []for idx, (stype, count, title, marks, note) in enumerate(section_defs):results.append(await _generate_one_section(idx, stype, count, title, marks, note,section_chunk_starts[idx],))return resultsreturn list(await asyncio.gather(*[_generate_one_section(idx, stype, count, title, marks, note, section_chunk_starts[idx])for idx, (stype, count, title, marks, note) in enumerate(section_defs)]))# Drain the progress queue while generation runs. Nothing polls: a# section pushing an event wakes this immediately, so the timeline# updates the moment a batch lands. The 10 s timeout is only the# keepalive tick for a phase that emits nothing for a long stretch.## The queue read is raced against the generation task itself rather# than gated on `sections_task.done()`: a bare `await queue.get()`# after the last event has nothing left to wake it, and would sit# there for the full keepalive tick before the finished exam could be# sent.sections_task = asyncio.create_task(_run_all_sections())try:while True:get_task = asyncio.ensure_future(progress_queue.get())finished, _pending = await asyncio.wait({get_task, sections_task},return_when=asyncio.FIRST_COMPLETED,timeout=10,)if get_task in finished:yield _progress_sse_line(get_task.result())continueget_task.cancel()if sections_task in finished:breakyield ": keepalive\n\n"# Anything pushed between the last drain and the task finishing —# notably every section's `ready` event — must still be sent, or# the timeline ends with rows stuck mid-phase.while not progress_queue.empty():yield _progress_sse_line(progress_queue.get_nowait())except BaseException:# Client disconnect / cancellation: don't leave the generation# coroutine running against a stream nobody is reading.sections_task.cancel()raise# Re-raises whatever a section raised, exactly as `gather` used to.section_results = await sections_taskall_sections: list[dict] = list(section_results)yield _progress_sse_line({"progress": _exam_phase_label("assembling", exam_language),"section": total_sections + 1,"total_sections": total_sections + 2,"title": _exam_phase_label("assembling", exam_language),"phase": "assembling","step_done": False,})# A section that failed its precondition (no passage for `reading`, no# figures for figure_based/diagram) comes back empty with a reason.# Tell the teacher which section was skipped and why, then drop it —13 unmodified lines# sections — the frontend/backend never see the raw per-section# metrics, only this rollup plus the per-question fields they already# got (difficulty, learning_objective).yield _progress_sse_line({"progress": _exam_phase_label("assembling", exam_language),"section": total_sections + 1,"total_sections": total_sections + 2,"title": _exam_phase_label("assembling", exam_language),"phase": "assembling","step_done": True,})yield _progress_sse_line({"progress": _exam_phase_label("finalizing", exam_language),"section": total_sections + 2,"total_sections": total_sections + 2,"title": _exam_phase_label("finalizing", exam_language),"phase": "finalizing","step_done": False,})async with _get_fresh_session() as _scope_session:generation_insights = await _build_generation_insights(all_sections, chunk_topic_map, resolved_materials,materials=materials, session=_scope_session,)yield _progress_sse_line({"progress": _exam_phase_label("finalizing", exam_language),"section": total_sections + 2,"total_sections": total_sections + 2,"title": _exam_phase_label("finalizing", exam_language),"phase": "finalizing","step_done": True,})# One greppable line per exam with the full latency breakdown. Sections# run concurrently by default, so the exam's floor is the slowest# section's serial chain — `slowest_section_ms`, not the sum — which is
app/models/stream_events.py+15-1
app/services/gateway.py+327-37