Spaces:
Build error
Build error
anwarKXC commited on
Commit ·
43ebe24
1
Parent(s): 4d9ad0c
feat: Enhance exam generation with computational question types and shuffle MCQ answer positions
Browse filesFiles changed (3)
17 unmodified lines1819202122237 unmodified lines31323334353693 unmodified lines13013113213313413513613713813917 unmodified linesFILL_BLANK = "fill_blank"SHORT_ANSWER = "short_answer"MATCHING = "matching"class ExamQuestion(BaseModel):7 unmodified lines# Matching-specific fieldscolumn_a: Optional[list[str]] = Field(default=None, description="Left column items for matching")column_b: Optional[list[str]] = Field(default=None, description="Right column items for matching (shuffled)")class ExamSection(BaseModel):93 unmodified linesCURRENT_SCHEMA_VERSION = 1STRUCTURED_MODES = {"exam", "assignment", "lesson_prep"}MODE_SCHEMA_MAP: dict[str, type[BaseModel]] = {"exam": ExamStructured,"assignment": AssignmentStructured,"lesson_prep": LessonPlanStructured,}17 unmodified lines18192021222324252627287 unmodified lines3637383940414243444593 unmodified lines13914014114214314414514614714814917 unmodified linesFILL_BLANK = "fill_blank"SHORT_ANSWER = "short_answer"MATCHING = "matching"# STEM-specific computational types (Math/Physics/Chemistry/Biology) —# require an actual calculation/derivation/experiment, not a definition.NUMERICAL_PROBLEM = "numerical_problem"EQUATION = "equation"EXPERIMENT = "experiment"class ExamQuestion(BaseModel):7 unmodified lines# Matching-specific fieldscolumn_a: Optional[list[str]] = Field(default=None, description="Left column items for matching")column_b: Optional[list[str]] = Field(default=None, description="Right column items for matching (shuffled)")# Step-by-step working for computational question types — kept separate# from `answer` (which stays the final result) so auto-grading (exact# match on `answer`) is unaffected.solution_steps: Optional[list[str]] = Field(default=None, description="Ordered step-by-step working")class ExamSection(BaseModel):93 unmodified linesCURRENT_SCHEMA_VERSION = 1STRUCTURED_MODES = {"exam", "assignment", "lesson_prep", "answer_questions"}MODE_SCHEMA_MAP: dict[str, type[BaseModel]] = {"exam": ExamStructured,"assignment": AssignmentStructured,"lesson_prep": LessonPlanStructured,"answer_questions": AnswerQuestionsResult,}
123456245 unmodified lines2522532542552562571103 unmodified lines13611362136313641365136660 unmodified lines14271428142914301431143213 unmodified lines14461447144814491450145114527 unmodified lines1460146114621463146414652 unmodified lines14681469147014711472147323 unmodified lines14971498149915001501150215031 unmodified line1505150615071508150915101511150 unmodified lines16621663166416651666166716681669167056 unmodified lines17271728172917301731173228 unmodified lines17611762176317641765176653 unmodified lines18201821182218231824182550 unmodified lines187618771878187918801881353 unmodified lines223522362237223822392240import hashlibimport jsonimport loggingimport reimport timeimport asyncio245 unmodified linesreturn ""def _normalize_query(text: str) -> str:"""Normalize user query text: NFKC + Arabic normalization.1103 unmodified lines'"difficulty": "easy|medium|hard", "learning_objective": "الهدف التعليمي", ''"question": "نص السؤال", ''"choices": ["خيار 1", "خيار 2", "خيار 3", "خيار 4"] أو null, ''"answer": "نص الإجابة", 'f'"marks": {marks_per_q}' + '}]}')60 unmodified lines"""settings = get_settings()# Parse user request for section types/counts.# Prefer explicit wizard blueprint rows when available.requested_blueprint = _parse_exam_blueprint_request(question_text)13 unmodified lines"short_answer": "أجب عن الأسئلة التالية","essay": "اكتب موضوعًا","matching": "وصّل من العمود (أ) ما يناسبه من العمود (ب)",}type_notes = {"mcq": 'كل سؤال له 4 اختيارات. لا تضع حرف أمام الاختيارات — اكتب نص الخيار فقط.\n"choices" مطلوبة.\n"answer" = نص الإجابة الصحيحة كما هو في choices (مطابق تماماً).\n',"true_false": '"choices" = null. "answer" = "صح" أو "خطأ" فقط.\n',7 unmodified lines'answer = التوصيل الصحيح لعناصر العمود (أ) فقط مثل "1-ج، 2-أ، ...، 10-ك"\n''كل سؤال درجته 10. نوّع مواضيع الأسئلة.\n'),}marks_map = {"mcq": 1.0,2 unmodified lines"short_answer": 2.0,"essay": 5.0,"matching": float(_MATCHING_ITEMS_PER_Q),}if requested_blueprint:23 unmodified linesf"إجمالي عناصر التوصيل المطلوبة = {total_items} عنصر (ليس {total_items} جدول).")note = base_note + ("\n".join(note_parts) + "\n" if note_parts else "")section_defs.append((stype, effective_count, title, effective_marks, note))section_order += 1else:1 unmodified lineordinal = ordinals[section_order - 1] if section_order <= len(ordinals) else str(section_order)title = f"السؤال {ordinal}: {type_labels.get(stype, stype)}"marks = marks_map.get(stype, 1.0)note = type_notes.get(stype, '"choices" = null.\n')# Backward compatibility for legacy free-text prompts:# "30 مطابقة" often means 30 matching items (3 tables of 10).effective_count = max(1, -(-count // _MATCHING_ITEMS_PER_Q)) if stype == "matching" else count150 unmodified linescontinueq["choices"] = cleaned_choices[:4]if stype in {"true_false", "fill_blank", "short_answer", "essay"}:q["choices"] = Noneif stype == "matching":col_a = q.get("column_a")col_b = q.get("column_b")56 unmodified linestotal_sections = len(section_defs)# ── Per-section coroutine (batches within a section stay sequential for dedup) ──async def _generate_one_section(idx: int,28 unmodified linessection_titles=section_titles,offset=page_offset,limit=chunks_per_batch,)batch_context = RetrievalService.build_context(batch_chunks)batch_has_context = bool(batch_context)53 unmodified linessection_titles=section_titles,offset=page_offset,limit=chunks_per_batch,)retry_context = RetrievalService.build_context(retry_chunks)retry_has_context = bool(retry_context)50 unmodified linesif len(all_questions) > count:all_questions = all_questions[:count]logger.info("Section %d/%d (%s): %d total questions",idx + 1, total_sections, stype, len(all_questions))return {"title": title, "questions": all_questions}353 unmodified linesTrue,)# Default: general Q&A mode — stays as Markdownif has_context:return (1234567245 unmodified lines2532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133141103 unmodified lines141814191420142114221423142460 unmodified lines1485148614871488148914901491149214931494149514961497149813 unmodified lines1512151315141515151615171518151915201521152215231524152515261527152815297 unmodified lines1537153815391540154115421543154415451546154715481549155015511552155315541555155615572 unmodified lines15601561156215631564156515661567156823 unmodified lines15921593159415951596159715981 unmodified line1600160116021603160416051606150 unmodified lines1757175817591760176117621763176417651766176717681769177017711772177356 unmodified lines183018311832183318341835183618371838183918401841184228 unmodified lines187118721873187418751876187753 unmodified lines193119321933193419351936193750 unmodified lines19881989199019911992199319941995353 unmodified lines234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384import hashlibimport jsonimport loggingimport randomimport reimport timeimport asyncio245 unmodified linesreturn ""def _shuffle_mcq_answer_positions(questions: list[dict]) -> None:"""Redistribute the correct answer's position across MCQ choices in place.LLMs have a well-documented bias toward placing the correct answer in thefirst slot. Left uncorrected, a generated exam ends up with option Acorrect almost every time. This assigns each question a round-robintarget index (0, 1, 2, 3, 0, 1, ...) across the section so positions endup roughly balanced instead of relying on the model's (biased) output orindependent-per-question randomness (which can still cluster by chance)."""mcq_indices = [i for i, q in enumerate(questions) if q.get("type") == "mcq"]for position, qi in enumerate(mcq_indices):q = questions[qi]choices = q.get("choices")answer = str(q.get("answer", "")).strip()if not isinstance(choices, list) or len(choices) < 2 or not answer:continuecorrect = next((c for c in choices if str(c).strip() == answer), None)if correct is None:continue # answer doesn't match any choice verbatim — leave untoucheddistractors = [c for c in choices if c is not correct]random.shuffle(distractors)target_index = position % len(choices)new_choices = distractors[:target_index] + [correct] + distractors[target_index:]q["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 text# (from the wizard's "المادة:" line or the source document's title)._STEM_SUBJECT_KEYWORDS = frozenset({"رياضيات", "حساب", "جبر", "هندسة", "تفاضل", "تكامل", # math"فيزياء", # physics"كيمياء", # chemistry"أحياء", "biology", # biology"math", "algebra", "calculus", "geometry","physics", "chemistry",})def _detect_subject_category(subject_text: str) -> str:"""Classify a subject name as 'stem' or 'other' for prompt branching.STEM subjects get computational question requirements (solve, calculate,derive) instead of the default definitional/conceptual style."""text = (subject_text or "").strip().lower()if not text:return "other"return "stem" if any(kw in text for kw in _STEM_SUBJECT_KEYWORDS) else "other"def _normalize_query(text: str) -> str:"""Normalize user query text: NFKC + Arabic normalization.1103 unmodified lines'"difficulty": "easy|medium|hard", "learning_objective": "الهدف التعليمي", ''"question": "نص السؤال", ''"choices": ["خيار 1", "خيار 2", "خيار 3", "خيار 4"] أو null, ''"solution_steps": ["الخطوة 1", "الخطوة 2"] أو null, ''"answer": "نص الإجابة", 'f'"marks": {marks_per_q}' + '}]}')60 unmodified lines"""settings = get_settings()# Subject drives whether questions should be computational (STEM) or# conceptual — resolved early so it's available to both section-note# construction below and per-batch retrieval/prompting further down.subject_category = _detect_subject_category(_extract_labeled_value(question_text, ["المادة", "subject"]))is_stem_subject = subject_category == "stem"# Parse user request for section types/counts.# Prefer explicit wizard blueprint rows when available.requested_blueprint = _parse_exam_blueprint_request(question_text)13 unmodified lines"short_answer": "أجب عن الأسئلة التالية","essay": "اكتب موضوعًا","matching": "وصّل من العمود (أ) ما يناسبه من العمود (ب)","numerical_problem": "حل المسائل الحسابية","equation": "حل أو وازن المعادلات","experiment": "أجب عن أسئلة التجارب العملية",}# STEM subjects (math/physics/chemistry/biology): every question type# should test computation/application, not recall — appended to# whichever type_notes entry is selected below.stem_emphasis = ("بما أن المادة علمية/حسابية، يجب أن يتطلب السؤال حسابًا أو تطبيقًا فعليًا ""لقانون أو معادلة من الكتاب — وليس مجرد تعريف أو حفظ. استخدم أرقامًا ومعطيات ""محددة من السياق إن وُجدت.\n") if is_stem_subject else ""type_notes = {"mcq": 'كل سؤال له 4 اختيارات. لا تضع حرف أمام الاختيارات — اكتب نص الخيار فقط.\n"choices" مطلوبة.\n"answer" = نص الإجابة الصحيحة كما هو في choices (مطابق تماماً).\n',"true_false": '"choices" = null. "answer" = "صح" أو "خطأ" فقط.\n',7 unmodified lines'answer = التوصيل الصحيح لعناصر العمود (أ) فقط مثل "1-ج، 2-أ، ...، 10-ك"\n''كل سؤال درجته 10. نوّع مواضيع الأسئلة.\n'),"numerical_problem": ('"choices" = null. اطرح مسألة حسابية فعلية بمعطيات رقمية محددة (وليس تعريفًا).\n''"solution_steps" = مصفوفة نصية بخطوات الحل بالترتيب (خطوة بخطوة حتى الناتج).\n''"answer" = الناتج النهائي فقط (رقم أو قيمة قصيرة قابلة للمطابقة المباشرة، بدون شرح).\n'),"equation": ('"choices" = null. اطلب حل أو موازنة معادلة فعلية من محتوى الكتاب (رياضية أو كيميائية).\n''"solution_steps" = مصفوفة نصية بخطوات الحل/الموازنة بالترتيب.\n''"answer" = المعادلة النهائية أو قيمة المتغير المطلوب فقط، بدون شرح.\n'),"experiment": ('"choices" = null. صف سيناريو تجربة عملية واقعية من الكتاب واسأل عن ملاحظة أو نتيجة أو استنتاج منها.\n''"solution_steps" = مصفوفة نصية بخطوات التحليل أو الاستدلال المؤدية للإجابة.\n''"answer" = الإجابة النموذجية (جملة أو جملتان).\n'),}marks_map = {"mcq": 1.0,2 unmodified lines"short_answer": 2.0,"essay": 5.0,"matching": float(_MATCHING_ITEMS_PER_Q),"numerical_problem": 3.0,"equation": 3.0,"experiment": 3.0,}if requested_blueprint:23 unmodified linesf"إجمالي عناصر التوصيل المطلوبة = {total_items} عنصر (ليس {total_items} جدول).")note = base_note + ("\n".join(note_parts) + "\n" if note_parts else "") + stem_emphasissection_defs.append((stype, effective_count, title, effective_marks, note))section_order += 1else:1 unmodified lineordinal = ordinals[section_order - 1] if section_order <= len(ordinals) else str(section_order)title = f"السؤال {ordinal}: {type_labels.get(stype, stype)}"marks = marks_map.get(stype, 1.0)note = type_notes.get(stype, '"choices" = null.\n') + stem_emphasis# Backward compatibility for legacy free-text prompts:# "30 مطابقة" often means 30 matching items (3 tables of 10).effective_count = max(1, -(-count // _MATCHING_ITEMS_PER_Q)) if stype == "matching" else count150 unmodified linescontinueq["choices"] = cleaned_choices[:4]if stype in {"true_false", "fill_blank", "short_answer", "essay","numerical_problem", "equation", "experiment"}:q["choices"] = Nonesolution_steps = q.get("solution_steps")if isinstance(solution_steps, list):cleaned_steps = [str(s).strip() for s in solution_steps if str(s).strip()]q["solution_steps"] = cleaned_steps or Noneelse:q["solution_steps"] = Noneif stype == "matching":col_a = q.get("column_a")col_b = q.get("column_b")56 unmodified linestotal_sections = len(section_defs)# Computational section types benefit from worked-example/exercise# chunks as context rather than plain explanatory prose._COMPUTATIONAL_TYPES = {"numerical_problem", "equation", "experiment"}def _prefer_content_types_for(stype: str) -> Optional[list[str]]:return ["example", "exercise"] if stype in _COMPUTATIONAL_TYPES else None# ── Per-section coroutine (batches within a section stay sequential for dedup) ──async def _generate_one_section(idx: int,28 unmodified linessection_titles=section_titles,offset=page_offset,limit=chunks_per_batch,prefer_content_types=_prefer_content_types_for(stype),)batch_context = RetrievalService.build_context(batch_chunks)batch_has_context = bool(batch_context)53 unmodified linessection_titles=section_titles,offset=page_offset,limit=chunks_per_batch,prefer_content_types=_prefer_content_types_for(stype),)retry_context = RetrievalService.build_context(retry_chunks)retry_has_context = bool(retry_context)50 unmodified linesif len(all_questions) > count:all_questions = all_questions[:count]_shuffle_mcq_answer_positions(all_questions)logger.info("Section %d/%d (%s): %d total questions",idx + 1, total_sections, stype, len(all_questions))return {"title": title, "questions": all_questions}353 unmodified linesTrue,)if mode == "answer_questions":schema_hint = ("أرجع النتيجة كـ JSON فقط بدون أي نص إضافي. الهيكل المطلوب:\n"'{"questions": [{"question": "نص السؤال كما ورد", "answer": "الإجابة الكاملة", ''"source": "rag" أو "model_knowledge", "confidence": "high" أو "low"}]}')return ("أنت معلم خبير يجيب على أسئلة امتحان أو واجب مرفوع من معلم أو طالب.\n""القواعد:\n""1. استخرج كل سؤال مستقل من النص المُدخل بالترتيب كما ورد (لا تدمج أسئلة، ولا تتخطَّ أياً منها).\n"+ ("2. أجب كل سؤال معتمداً على النص من الكتاب المدرسي المقدم قدر الإمكان، وضع "'"source": "rag".\n'"3. إذا لم يغطِّ الكتاب سؤالاً معيناً، أجب من معلوماتك العامة وضع "'"source": "model_knowledge" و"confidence": "low".\n'if has_context else"2. لا يوجد سياق كتاب كافٍ لهذا الطلب — أجب من معلوماتك العامة العلمية/التعليمية الموثوقة، "'وضع "source": "model_knowledge" في كل سؤال، مع "confidence": "low" '"إن لم تكن متأكداً تماماً من صحة الإجابة.\n")+ "4. إذا كان السؤال حسابياً أو يتطلب حل معادلة أو تحليل تجربة (رياضيات، فيزياء، كيمياء): ""اكتب خطوات الحل كاملة داخل answer بالترتيب، وانتهِ بالنتيجة النهائية بوضوح — لا تكتفِ برقم أو ""كلمة واحدة بدون شرح الخطوات.\n""5. إذا كان السؤال نظرياً أو مفاهيمياً: أجب إجابة دقيقة ومختصرة مباشرة.\n""6. حافظ على نفس ترتيب الأسئلة كما وردت في النص.\n\n"f"{schema_hint}\n""أرقام الصفحات موجودة في ترويسات المقتطفات [مقتطف N — ... — صX].",True,)# Default: general Q&A mode — stays as Markdownif has_context:return (
86 unmodified lines878889909192329 unmodified lines42242342442542642742842943043143216 unmodified lines4494504514524534544554564574584594604614627 unmodified lines47047147247347447586 unmodified linessimilarity: floattoken_count: int = 0image_refs: list = field(default_factory=list) # [{url, description, labels, page}]# Arabic stop words to exclude from keyword extraction329 unmodified linesviewer_role: Optional[str] = None,offset: int = 0,limit: int = 20,) -> list[RetrievedChunk]:"""Fetch chunks in sequential order (by chunk_index) for exam generation.Unlike search(), this does NOT use similarity — it pages through the documentin reading order so each exam batch covers different parts of the textbook."""filters = "rd.is_active = true AND rd.status = 'INDEXED'"params: dict = {"limit": limit, "offset": offset}16 unmodified linesfilters += " AND rc.section_title = ANY(:section_titles)"params["section_titles"] = section_titlesrows = await session.execute(sql_text(f"""SELECT rc.id, rc.content, rc.section_title, rc.page_number,rc.document_id, rd.title AS document_title, rc.chunk_indexFROM rag_chunks rcJOIN rag_documents rd ON rc.document_id = rd.idWHERE {filters}ORDER BY rc.document_id, rc.chunk_indexLIMIT :limit OFFSET :offset"""),params,7 unmodified linesdocument_id=str(r.document_id),document_title=r.document_title,similarity=1.0,)for r in rows.fetchall()]86 unmodified lines87888990919293329 unmodified lines42342442542642742842943043143243343443543643743843944044116 unmodified lines4584594604614624634644654664674684694704714724734744754764774787 unmodified lines48648748848949049149286 unmodified linessimilarity: floattoken_count: int = 0image_refs: list = field(default_factory=list) # [{url, description, labels, page}]content_type: Optional[str] = None # explanation|exercise|example|summary|table# Arabic stop words to exclude from keyword extraction329 unmodified linesviewer_role: Optional[str] = None,offset: int = 0,limit: int = 20,prefer_content_types: Optional[list[str]] = None,) -> list[RetrievedChunk]:"""Fetch chunks in sequential order (by chunk_index) for exam generation.Unlike search(), this does NOT use similarity — it pages through the documentin reading order so each exam batch covers different parts of the textbook.When `prefer_content_types` is given (e.g. ['example', 'exercise'] for acomputational question section), chunks matching those types are rankedfirst across the whole document — used so STEM sections get workedproblems as context instead of plain explanatory prose. Chunks are stilldeduped/paginated by chunk_index within that ranking, so this degradesgracefully to the normal reading-order page once preferred chunks run out."""filters = "rd.is_active = true AND rd.status = 'INDEXED'"params: dict = {"limit": limit, "offset": offset}16 unmodified linesfilters += " AND rc.section_title = ANY(:section_titles)"params["section_titles"] = section_titlesif prefer_content_types:order_by = "(rc.content_type = ANY(:prefer_content_types)) DESC, rc.document_id, rc.chunk_index"params["prefer_content_types"] = prefer_content_typeselse:order_by = "rc.document_id, rc.chunk_index"rows = await session.execute(sql_text(f"""SELECT rc.id, rc.content, rc.section_title, rc.page_number,rc.document_id, rd.title AS document_title, rc.chunk_index,rc.content_typeFROM rag_chunks rcJOIN rag_documents rd ON rc.document_id = rd.idWHERE {filters}ORDER BY {order_by}LIMIT :limit OFFSET :offset"""),params,7 unmodified linesdocument_id=str(r.document_id),document_title=r.document_title,similarity=1.0,content_type=r.content_type,)for r in rows.fetchall()]
app/models/structured_schemas.py+11-1
app/services/gateway.py+147-3
app/services/retrieval.py+19-2