Spaces:
Build error
Build error
anwarKXC commited on
Commit ·
4e3a10b
1
Parent(s): 306b57a
Enhance IngestService and migrate_rag_db with new heading metrics and database schema updates
Browse filesFiles changed (3)
1234567891011121314151617181920216 unmodified lines2829303132333418 unmodified lines53545556575818 unmodified lines77787980818220 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261271281293 unmodified lines13313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427536 unmodified lines3123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483499 unmodified lines3593603613623633643653663673683693703713723733743753763773783793803813823837 unmodified lines3913923933943953963972 unmodified lines4004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075088 unmodified lines5175185195205215225235245255265275285295305315325335345355365375385395405415425435441 unmodified line5465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037041 unmodified line7067077087097107117122 unmodified lines715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793"""Detect section/chapter headings from Arabic textbook PDFs.Three detection tiers (tried in order, first non-empty result wins):1. PDF TOC/bookmarks — most reliable if present2. Font-based — large/bold spans with Arabic heading keywords3. Regex/pattern-based — works on OCR text (primary for current PDFs)Usage:headings = detect_headings(pdf_bytes, pages)page_map = build_page_heading_map(headings, total_pages)# page_map[page_num] → active section title for that page"""import asyncioimport jsonimport loggingimport refrom dataclasses import dataclassfrom statistics import medianfrom json_repair import repair_json6 unmodified linespage_num: int # 1-indexed page where heading first appearstitle: str # Full heading textlevel: int # 1 = unit/باب, 2 = chapter/فصل/درس, 3+ = sub-section (filtered out)confidence: float = 1.0 # Detection confidence: TOC=1.0, Font=0.8, Regex=0.6# Maximum heading depth we keep. Anything deeper is treated as a paragraph18 unmodified linesr"تقديم|تمهيد(?!ي)|إهداء|توطئ[هة]|مقدم[هة]\s+المؤلف)")# ─── Arabic heading keywords ────────────────────────────────────────────#18 unmodified linesr"العاشر[هة]|العاشر" # tenth)# Unit-level keywords — الوحد[هة] covers both ة and ه forms_UNIT_KW = r"الوحد[هة]|الباب"20 unmodified lines# TOC page indicator_TOC_RE = re.compile(r"المحتويات|الفهرس|فهرس")# U+FFFD is what PyMuPDF/OCR emit when a custom textbook font's glyph can't# be mapped to a real character. A heading containing it is corrupted text,# not a real title — never trust it (2026-08-05 biology-book incident: a# corrupted line was accepted as a heading and buried the rest of the book)._REPLACEMENT_CHAR_RE = re.compile("�")# A tier "succeeding" with only a handful of stray matches is worse than it# finding nothing — those few headings get carried forward as the active# section for every page until the next heading, silently burying whatever# real unit/lesson structure the document has. Long documents must clear a# minimum heading density before a tier's result is trusted; otherwise we# fall through to the next (stricter) tier._MIN_HEADING_DENSITY_PAGES = 25_MIN_HEADINGS_FOR_LONG_DOCS = 3_SHORT_DOC_PAGE_THRESHOLD = 15# Any heading keyword family (used in Tier 2 font-based filtering)_ANY_HEADING_KW = re.compile(rf"{_UNIT_KW}|{_CHAPTER_KW}|المقدم[هة]|التمهيد")def _normalize_for_match(text: str) -> str:"""Light normalization before regex heading detection.3 unmodified lines- ى → ي (alef maqsura vs ya)We intentionally do NOT change ه↔ة here — patterns already use [هة]."""# Alef variantstext = re.sub(r"[أإآٱ]", "ا", text)# Alef maqsura → yatext = text.replace("ى", "ي")return text# ─── Public API ──────────────────────────────────────────────────────────def detect_headings(pdf_bytes: bytes,pages: list[tuple[int, str]] | None = None,) -> list[DetectedHeading]:"""Detect section headings from a PDF using a tiered approach.Args:pdf_bytes: Raw PDF bytes (needed for TOC and font detection).pages: Optional pre-extracted (page_num, text) pairs for regex detection.If None, plain text is extracted from pdf_bytes."""import fitzdoc = fitz.open(stream=pdf_bytes, filetype="pdf")total_pages = len(doc)# Tier 1: PDF bookmarks/outlineheadings = _detect_from_toc(doc)if headings:before = len(headings)headings = _filter_lesson_headings(headings)logger.info("Tier 1 (TOC): %d → %d lesson-level headings",before, len(headings),)if headings and _has_sufficient_coverage(headings, total_pages):doc.close()return headingselif headings:logger.info("Tier 1 result too sparse (%d headings for %d pages) — falling through",len(headings), total_pages,)# Tier 2: Font-based detectionheadings = _detect_from_fonts(doc)if headings:before = len(headings)headings = _filter_lesson_headings(headings)logger.info("Tier 2 (fonts): %d → %d lesson-level headings",before, len(headings),)if headings and _has_sufficient_coverage(headings, total_pages):doc.close()return headingselif headings:logger.info("Tier 2 result too sparse (%d headings for %d pages) — falling through",len(headings), total_pages,)# Tier 3: Regex on page textif pages is None:pages = []for i, page in enumerate(doc):pages.append((i + 1, page.get_text()))doc.close()headings = _detect_from_regex(pages)if headings:before = len(headings)headings = _filter_lesson_headings(headings)logger.info("Tier 3 (regex): %d → %d lesson-level headings",before, len(headings),)else:logger.info("No headings detected across all 3 tiers (%d pages)", total_pages)return headingsdef _has_sufficient_coverage(headings: list[DetectedHeading], total_pages: int) -> bool:"""Reject a tier's result if it's too sparse to be real book structure.Short documents may genuinely have just one section, so this onlykicks in above `_SHORT_DOC_PAGE_THRESHOLD` pages."""if total_pages <= _SHORT_DOC_PAGE_THRESHOLD:return Trueexpected_min = max(_MIN_HEADINGS_FOR_LONG_DOCS,total_pages // _MIN_HEADING_DENSITY_PAGES,)return len(headings) >= expected_mindef _filter_lesson_headings(headings: list[DetectedHeading],) -> list[DetectedHeading]:"""Drop sub-paragraph / activity titles, keep unit + lesson headings only.Rules:- level > _MAX_LESSON_LEVEL → drop (these are sub-sections in PDFs thatship a deep TOC).- title matches _PARAGRAPH_HEADING_RE (تمرين/نشاط/مثال/...) → drop.- title sits on a non-lesson page (مقدمة، فهرس، مراجع) → drop.- title is suspiciously short (< 4 chars) or all-digits → drop.- exact duplicates (post-normalization) → drop the later one.Order is preserved (page_num ascending after dedup)."""filtered: list[DetectedHeading] = []seen_norm: set[str] = set()for h in headings:if h.level and h.level > _MAX_LESSON_LEVEL:continueraw_title = (h.title or "").strip()if not raw_title or len(raw_title) < 4 or raw_title.isdigit():continueif _REPLACEMENT_CHAR_RE.search(raw_title):continuenorm = _normalize_for_match(raw_title)if _PARAGRAPH_HEADING_RE.match(norm):continueif _NON_LESSON_PAGE_RE.search(norm):continuededup_key = _normalize_heading(raw_title)if dedup_key in seen_norm:continueseen_norm.add(dedup_key)filtered.append(h)# Stable sort by page number so the chunker sees them in reading order.filtered.sort(key=lambda h: (h.page_num, h.level))return filtereddef build_page_heading_map(36 unmodified linesreturn result# ─── Tier 1: PDF TOC / bookmarks ────────────────────────────────────────def _detect_from_toc(doc) -> list[DetectedHeading]:"""Extract headings from PDF bookmarks/outline."""toc = doc.get_toc()if not toc:return []headings: list[DetectedHeading] = []for level, title, page_num in toc:title = title.strip()if not title or len(title) < 3:continue# Map PDF outline level (1=top) to our level systemheading_level = 1 if level <= 1 else 2headings.append(DetectedHeading(page_num=page_num,title=title,level=heading_level,confidence=1.0,))return headings# ─── Tier 2: Font-based detection ───────────────────────────────────────def _detect_from_fonts(doc) -> list[DetectedHeading]:"""Detect headings via font size/weight analysis."""# First pass: collect all font sizes to compute median body sizeall_sizes: list[float] = []for page in doc:try:blocks = page.get_text("dict", flags=0)["blocks"]9 unmodified linesall_sizes.append(span.get("size", 0))if len(all_sizes) < 20:# Not enough font data (probably garbled PDF)return []body_size = median(all_sizes)heading_threshold = body_size * 1.3# Second pass: find heading candidatesheadings: list[DetectedHeading] = []seen_titles: set[str] = set()for i, page in enumerate(doc):page_num = i + 1page_text = page.get_text().strip()# Skip TOC pagesfirst_lines = "\n".join(page_text.split("\n")[:5])if _TOC_RE.search(first_lines):continuetry:blocks = page.get_text("dict", flags=0)["blocks"]except Exception:7 unmodified linesif not line_text or len(line_text) > 80 or len(line_text) < 3:continue# Check if any span in this line is large or boldis_heading_font = Falsefor span in line.get("spans", []):size = span.get("size", 0)2 unmodified linesif size >= heading_threshold or (is_bold and size >= body_size):is_heading_font = Truebreakif not is_heading_font:continue# Must contain Arabic heading keywords (check normalized)if not _ANY_HEADING_KW.search(_normalize_for_match(line_text)):continue# Skip assessment/review pagesif _ASSESSMENT_RE.search(_normalize_for_match(line_text)):continue# Deduplicate (running headers repeat on every page)norm = _normalize_heading(line_text)if norm in seen_titles:continueseen_titles.add(norm)level = 1 if _UNIT_RE.search(_normalize_for_match(line_text)) else 2headings.append(DetectedHeading(page_num=page_num,title=line_text,level=level,confidence=0.8,))return headings# ─── Tier 3: Regex/pattern-based ────────────────────────────────────────def _detect_from_regex(pages: list[tuple[int, str]]) -> list[DetectedHeading]:"""Detect headings using regex patterns on page text.For each heading keyword (الوحدة, الفصل, etc.), finds the firstoccurrence of each distinct ordinal/number to set boundaries."""# Identify TOC pages to exclude from boundary detectiontoc_pages: set[int] = set()for page_num, text in pages:norm = _normalize_for_match(text)first_lines = "\n".join(norm.split("\n")[:5])if _TOC_RE.search(first_lines):toc_pages.add(page_num)# Collect all heading matches with their page numbers.# We run regex on NORMALIZED text but keep the original text for title# extraction so the displayed title matches what's in the PDF.raw_matches: list[tuple[int, str, str, int, str, str]] = [] # (page, kw_norm, ord_norm, level, kw_orig, full_line)for page_num, orig_text in pages:if page_num in toc_pages:continuenorm_text = _normalize_for_match(orig_text)orig_lines = orig_text.split("\n")norm_lines = norm_text.split("\n")# Skip assessment pages (check normalized text)if _ASSESSMENT_RE.search(norm_text):continuefor m in _UNIT_RE.finditer(norm_text):# Find which line this match is on, get original textmatch_start = m.start()line_idx = norm_text[:match_start].count("\n")full_line = orig_lines[line_idx] if line_idx < len(orig_lines) else m.group(0)raw_matches.append((page_num, m.group(1), m.group(2), 1, m.group(1), full_line))for m in _CHAPTER_RE.finditer(norm_text):# Find which line this match is on, get original textmatch_start = m.start()line_idx = norm_text[:match_start].count("\n")full_line = orig_lines[line_idx] if line_idx < len(orig_lines) else m.group(0)raw_matches.append((page_num, m.group(1), m.group(2), 2, m.group(1), full_line))if not raw_matches:return []# Deduplicate: keep only the FIRST page for each (keyword_norm, ordinal_norm) pair.# Normalize the key so "الرابعة"/"الرابعه" and "الوحدة"/"الوحده" map to the same unit.seen: dict[tuple[str, str], tuple[int, int, str]] = {} # key → (first_page, level, full_line)for page_num, kw_norm, ord_norm, level, _kw_orig, full_line in raw_matches:# Normalise key: collapse [هة] → ه for consistent deduplicationkey = (_collapse_ta(kw_norm), _collapse_ta(ord_norm))if key not in seen:seen[key] = (page_num, level, full_line)# Build headings with title extractionheadings: list[DetectedHeading] = []pages_dict = dict(pages)for (kw_key, ord_key), (first_page, level, full_line) in sorted(seen.items(), key=lambda x: x[1][0]):# Use full_line if available (contains potential descriptive text), fallback to extractiontitle = _extract_title_from_line(full_line, kw_key, ord_key, first_page, pages_dict)headings.append(DetectedHeading(page_num=first_page,title=title,level=level,confidence=0.6,))return headingsdef _extract_title_from_line(8 unmodified linesFormat examples:"الوحدة الثالثة: الصناعة والتكنولوجيا في وطننا العربي""الدرس الأول: السكان في وطننا العربي"Handles cases where title is on the same line as keyword+ordinal with descriptive text."""# Clean the line (strip excessive whitespace/punctuation)title = re.sub(r"[\s:.\-–—]+$", "", full_line).strip()if not title:# Fallback to basic keyword + ordinalreturn f"{keyword} {ordinal}"# If line contains colon + descriptive text, keep it all# e.g., "الوحدة الثالثة: الصناعة والتكنولوجيا" → keep the whole thingif ":" in title or ":" in title:# Already has colon separator, return as isreturn title# If the title is just keyword + ordinal with no description,# try to find a subtitle on the next lineorig_text = pages_dict.get(page_num, "")orig_lines = [ln.strip() for ln in orig_text.split("\n") if ln.strip()]# Find this line's indexbase_match_idx = Nonefor i, ln in enumerate(orig_lines):if full_line.strip() in ln or ln in full_line.strip():1 unmodified linebreakif base_match_idx is not None and base_match_idx + 1 < len(orig_lines):# Check next line for descriptive subtitlenext_line = orig_lines[base_match_idx + 1].strip()# Subtitle validation: short, no special structure, no leading keywordsif (len(next_line) < 100 andnot any(kw in next_line for kw in ['الدرس', 'الوحدة', 'تمرين', 'سؤال']) andnot next_line.startswith("-") andnot next_line.startswith("•")):# Valid subtitle - append to titlereturn f"{title}: {next_line}"return titledef _extract_title(keyword: str,ordinal: str,page_num: int,pages_dict: dict[int, str],) -> str:"""Extract the section heading title from the page text.Strategy:1. Build the base title from the matched keyword+ordinal line(strip trailing colons/punctuation from the OCR line).2. Look for a subtitle on the line immediately BEFORE the keyword —in Arabic textbooks the topic name often appears above the lesson number.Only use it if it looks like a clean title (short, no trailing bullets).3. Do NOT include lines AFTER the keyword — they are typically contentbullet points ("استخدام الوسائل الرقمية", "المواطنة", etc.), not headings.4. Format: "الدرس الأول: الانتماء" (keyword ordinal: subtitle)"""orig_text = pages_dict.get(page_num, "")orig_lines = [ln.strip() for ln in orig_text.split("\n") if ln.strip()]norm_lines = [_normalize_for_match(ln) for ln in orig_lines]# Build a pattern from normalized keyword+ordinal (ه/ة both accepted)kw_pat = keyword.replace("ه", "[هة]").replace("ة", "[هة]")ord_pat = ordinal.replace("ه", "[هة]").replace("ة", "[هة]")pattern = re.compile(rf"{kw_pat}\s+{ord_pat}")match_idx = Nonefor i, norm_line in enumerate(norm_lines):if pattern.search(norm_line):match_idx = ibreakif match_idx is None:return f"{keyword} {ordinal}"# Base: clean the matched keyword line (strip trailing : . - and whitespace)base = re.sub(r"[\s:.\-–—]+$", "", orig_lines[match_idx]).strip()if not base:base = f"{keyword} {ordinal}"# Look for a subtitle on the line immediately BEFORE the keyword.# Characteristics of a valid subtitle:# - Short (≤ 6 words, ≤ 40 chars)# - Doesn't start with a bullet/dash or digit list marker# - Not another heading keyword line# - Not a TOC indicator# - Not pure punctuationsubtitle = ""if match_idx > 0:prev = orig_lines[match_idx - 1]prev_norm = norm_lines[match_idx - 1]words = prev.split()is_bullet = bool(re.match(r"^[-–—•\d]", prev))has_heading = bool(_UNIT_RE.search(prev_norm) or _CHAPTER_RE.search(prev_norm))has_toc = bool(_TOC_RE.search(prev_norm))is_clean = (1 <= len(words) <= 6and len(prev) <= 40and not is_bulletand not has_headingand not has_toc)if is_clean:# Strip trailing punctuation from subtitlesubtitle = re.sub(r"[\s:.\-–—]+$", "", prev).strip()if subtitle:return f"{base}: {subtitle}"return base# ─── Helpers ─────────────────────────────────────────────────────────────def _collapse_ta(text: str) -> str:"""Collapse ة → ه for deduplication keys.Ensures "الرابعة" and "الرابعه" are treated as the same unit/ordinal."""return text.replace("ة", "ه")def _normalize_heading(text: str) -> str:"""Normalize heading text for deduplication."""text = re.sub(r"\s+", " ", text).strip()text = re.sub(r"[:\-–—]", "", text)return _collapse_ta(text)# ─── LLM-aided heading refinement ────────────────────────────────────────_REFINE_SYSTEM = """\أنت تحلل كتابًا مدرسيًا عربيًا. ستُعطى مقاطع نصية من صفحات بداية وحدات أو دروس.مهمتك: استخرج عنوان الدرس أو الوحدة الكامل لكل صفحة كما هو مكتوب في الكتاب.قواعد إلزامية:1. أعد فقط عناوين الدروس أو الوحدات (مثل "الوحدة الأولى: ...", "الدرس الثالث: ...").2. لا تعد عناوين فرعية أو فقرات داخل الدرس (تمرين / نشاط / مثال / تطبيق / للقراءة /اختبر نفسك / خلاصة / ملاحظة / تمهيد / مقدمة).3. لا تخترع عنوانًا غير موجود؛ إن لم تتوفر عنوان درس صريح فأعد سلسلة فارغة "".4. حافظ على ترتيب وصياغة الكتاب نفسها (لا تختصر ولا تعيد الصياغة).5. أجب حصريًا بـ JSON صحيح على الشكل:[{"page": <رقم_الصفحة>, "title": "<عنوان_الدرس_الكامل_أو_فارغ>"}]لا تضف أي نص خارج JSON.\"""_BATCH_SIZE = 5 # heading-candidate pages per LLM callasync def _refine_headings_with_llm(headings: list[DetectedHeading],pages_dict: dict[int, str],llm_service, # LLMService — duck-typed to avoid circular importclient, # httpx.AsyncClient) -> list[DetectedHeading]:"""Refine regex-detected heading titles using the LLM.Batches candidate pages (5 per call) and sends page snippets to the LLMwhich returns the clean, exact section title from the book itself.On any failure (timeout, invalid JSON, unexpected schema) the originalregex-detected title is kept unchanged."""result = list(headings) # mutable copypage_to_idx: dict[int, int] = {h.page_num: i for i, h in enumerate(headings)}# Cost guard (Phase 5.3): only refine low-confidence, short titlescandidate_pages = [h.page_num for h in headingsif h.confidence < 0.7 and len(h.title) < 80]if not candidate_pages:return result # All headings already high-confidence — skip LLMfor batch_start in range(0, len(candidate_pages), _BATCH_SIZE):batch = candidate_pages[batch_start: batch_start + _BATCH_SIZE]parts: list[str] = []for p in batch:snippet = (pages_dict.get(p, "") or "")[:800].strip()parts.append(f"[صفحة {p}]\n{snippet}")user_msg = "\n\n".join(parts)try:1 unmodified lineif hasattr(llm_service, "_smart_model"): # CloudLLMServiceextra["model_tier"] = "cheap"raw = await llm_service.generate(_REFINE_SYSTEM,[{"role": "user", "content": user_msg}],client=client,json_format=True,2 unmodified lines)cleaned = repair_json(raw)parsed = json.loads(cleaned)# LLM may return a dict wrapping the listif isinstance(parsed, dict):for v in parsed.values():if isinstance(v, list):parsed = vbreakelse:logger.warning("LLM heading refinement: response is a dict with no list value")continueif not isinstance(parsed, list):logger.warning("LLM heading refinement: response is not a list")continuefor item in parsed:if not isinstance(item, dict):continuepage_num = item.get("page")title = (item.get("title") or "").strip()# Empty title is the LLM's signal that the page has no lesson# heading — keep the original regex-detected one if it survives# the lesson filter, otherwise it will be dropped downstream.if not isinstance(page_num, int) or not title or len(title) < 3:continue# Skip when the refined title is clearly a paragraph heading.if _PARAGRAPH_HEADING_RE.match(_normalize_for_match(title)):continueidx = page_to_idx.get(page_num)if idx is None:continueresult[idx] = DetectedHeading(page_num=page_num,title=title,level=result[idx].level,confidence=1.0, # LLM-refined → highest confidence)logger.debug(" LLM refined p%d: %r", page_num, title)except Exception as e:logger.warning("LLM heading refinement failed for batch %s: %s", batch, e)# Keep original regex titles for this batchreturn resultasync def detect_headings_async(pdf_bytes: bytes,pages: list[tuple[int, str]] | None,llm_service=None, # LLMService | Noneclient=None, # httpx.AsyncClient | None) -> list[DetectedHeading]:"""Async variant of detect_headings() with optional LLM title refinement.Runs Tier 1/2/3 detection in a thread pool (non-blocking), then ifllm_service and client are provided, refines the titles with the LLM.Args:pdf_bytes: Raw PDF bytes.pages: Pre-extracted (page_num, text) pairs from OCR. If None,plain text is extracted from pdf_bytes (no OCR).llm_service: LLMService instance; pass None to skip LLM refinement.client: httpx.AsyncClient; required when llm_service is provided."""headings = await asyncio.to_thread(detect_headings, pdf_bytes, pages)if not headings or llm_service is None or client is None:return headingspages_dict: dict[int, str] = dict(pages) if pages else {}logger.info("LLM heading refinement: %d candidates", len(headings))refined = await _refine_headings_with_llm(headings, pages_dict, llm_service, client)# Re-apply the lesson filter — the LLM occasionally returns paragraph-level# titles even though the prompt asks for lesson titles. Belt and braces.refined = _filter_lesson_headings(refined)logger.info("LLM heading refinement complete (%d kept)", len(refined))return refined123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676 unmodified lines7475767778798018 unmodified lines9910010110210310410510610710810911011118 unmodified lines13013113213313413513613713813914014114214314414514614714814915015120 unmodified lines1721731741751761771781791801811821831841851863 unmodified lines19019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039136 unmodified lines4284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015029 unmodified lines5125135145155165175185195205215225235245255265275285297 unmodified lines5375385395405415422 unmodified lines5455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216228 unmodified lines6316326336346356366376386396406416426436446456466476486491 unmodified line6516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338341 unmodified line8368378388398408418422 unmodified lines845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886"""Detect section/chapter headings from Arabic textbook PDFs.v2 architecture (2026-08-05). Previously this ran three tiers (TOC → font→ regex) where the first tier to return *anything* won outright. Thatfailed badly on a 252-page biology book: the font tier "succeeded" with2 garbled matches (one containing a literal OCR replacement character),which blocked the stricter regex tier from ever running — so 246 pagesof real unit/lesson structure was silently buried under one bogus title.Now every detector contributes CANDIDATES for the same page set insteadof racing each other:├── TOC / bookmarks (strongest signal, when present)├── Font + position (size/bold/centered/top-of-page)└── Regex / keyword+ordinal on cleaned (OCR'd, sanitized) text│▼candidate pool (deduped, garble-rejected)│▼weighted confidence scoring (structured evidence, not one number)│▼ordinal-sequence consistency pass (unit 1,2,3.. / lesson 1,2,3..)│▼batched LLM verification of BORDERLINE candidates only(the LLM verifies/repairs candidates the evidence engine alreadyfound — it never discovers headings on its own)│▼accept everything above threshold → DetectedHeading listCandidate generation is also gated by a cheap page-type classification(COVER / CONTENTS / INDEX / UNIT_START / LESSON_START / LESSON /EXERCISE) — detectors only run on pages that could plausibly open aunit/lesson, which removes most false positives from activity/exercisepages up front.Web verification and per-page vision analysis were considered anddeliberately left out: web search is unreliable across textbookeditions/printings and adds an external dependency to every ingest;vision-per-page is real cost/latency for marginal gain once TOC + font +regex + ordinal-consistency + LLM verification already agree. Revisitonly if the metrics below show this still isn't enough for some books.Usage:headings, metrics = await detect_headings_async(pdf_bytes, pages)page_map = build_page_heading_map(headings, total_pages)# page_map[page_num] → active (unit_title, lesson_title) for that page# metrics → {"pages", "headings_found", "units", "lessons", "ocr_pages",# "candidates_considered", "llm_verifications",# "average_confidence", "suspicious_pages"} — log/store this# per document so problem books are visible without opening# the PDF."""import asyncioimport jsonimport loggingimport refrom dataclasses import dataclass, fieldfrom enum import Enumfrom statistics import medianfrom json_repair import repair_json6 unmodified linespage_num: int # 1-indexed page where heading first appearstitle: str # Full heading textlevel: int # 1 = unit/باب, 2 = chapter/فصل/درس, 3+ = sub-section (filtered out)confidence: float = 1.0 # Final combined evidence score, 0..1# Maximum heading depth we keep. Anything deeper is treated as a paragraph18 unmodified linesr"تقديم|تمهيد(?!ي)|إهداء|توطئ[هة]|مقدم[هة]\s+المؤلف)")# U+FFFD is what PyMuPDF/OCR emit when a custom textbook font's glyph can't# be mapped to a real character. A heading containing it is corrupted text,# not a real title — never trust it, and it never even becomes a candidate# (2026-08-05 biology-book incident: a corrupted line was accepted as the# only heading in the book and buried everything after it)._REPLACEMENT_CHAR_RE = re.compile("�")# ─── Arabic heading keywords ────────────────────────────────────────────#18 unmodified linesr"العاشر[هة]|العاشر" # tenth)# Ordinal word → integer, for the sequence-consistency pass. Order matters:# check longer/more specific alternatives before shorter ones where regexes# could overlap (not an issue here, but keep in sync with _ORDINALS above)._ORDINAL_WORD_VALUES: list[tuple[re.Pattern, int]] = [(re.compile(r"الأول[ى��]?|الاول[ىي]?"), 1),(re.compile(r"الثاني[هة]?"), 2),(re.compile(r"الثالث[هة]?"), 3),(re.compile(r"الرابع[هة]?"), 4),(re.compile(r"الخامس[هة]?"), 5),(re.compile(r"السادس[هة]?"), 6),(re.compile(r"السابع[هة]?"), 7),(re.compile(r"الثامن[هة]?"), 8),(re.compile(r"التاسع[هة]?"), 9),(re.compile(r"العاشر[هة]?"), 10),]# Unit-level keywords — الوحد[هة] covers both ة and ه forms_UNIT_KW = r"الوحد[هة]|الباب"20 unmodified lines# TOC page indicator_TOC_RE = re.compile(r"المحتويات|الفهرس|فهرس")# Any heading keyword family (used for loose/fuzzy font-based matching —# keyword present but no ordinal captured, e.g. OCR ate the number)_ANY_HEADING_KW = re.compile(rf"{_UNIT_KW}|{_CHAPTER_KW}|المقدم[هة]|التمهيد")# Exercise/activity keyword density used for page-type classification_EXERCISE_PAGE_KW_RE = re.compile(r"تمرين|نشاط|تدريب|اختبر\s+نفسك|أسئلة")def _normalize_for_match(text: str) -> str:"""Light normalization before regex heading detection.3 unmodified lines- ى → ي (alef maqsura vs ya)We intentionally do NOT change ه↔ة here — patterns already use [هة]."""text = re.sub(r"[أإآٱ]", "ا", text)text = text.replace("ى", "ي")return textdef _collapse_ta(text: str) -> str:"""Collapse ة → ه for deduplication keys."""return text.replace("ة", "ه")def _normalize_heading(text: str) -> str:"""Normalize heading text for deduplication."""text = re.sub(r"\s+", " ", text).strip()text = re.sub(r"[:\-–—]", "", text)return _collapse_ta(text)def _ocr_quality_score(text: str) -> float:"""Cheap proxy for how trustworthy a page's extracted text is.0.0 = garbage (replacement chars present), 1.0 = clean Arabic.Used to discount candidates found on low-quality pages rather thantrusting extracted text uniformly."""if not text:return 0.0if _REPLACEMENT_CHAR_RE.search(text):return 0.0letters = [c for c in text if c.isalpha()]if not letters:return 0.5 # neutral — nothing to judge (e.g. a mostly-numeric page)arabic = sum(1 for c in letters if "" <= c <= "ۿ")return max(0.0, min(1.0, arabic / len(letters)))# ─── Page type classification ───────────────────────────────────────────class PageType(str, Enum):COVER = "cover"CONTENTS = "contents"INDEX = "index"UNIT_START = "unit_start"LESSON_START = "lesson_start"LESSON = "lesson"EXERCISE = "exercise"def classify_page_type(page_num: int, text: str) -> PageType:"""Cheap heuristic page classification, used to gate which pages theheading detectors even look at. Keeps false positives from exercise/index/cover pages out of the candidate pool up front, rather thanfiltering them out after the fact."""stripped = text.strip()norm = _normalize_for_match(stripped)first_lines = "\n".join(norm.split("\n")[:6])if page_num <= 2 and len(stripped) < 200:return PageType.COVERif _TOC_RE.search(first_lines):return PageType.CONTENTSif _NON_LESSON_PAGE_RE.search(first_lines):return PageType.INDEXif _UNIT_RE.search(norm[:400]):return PageType.UNIT_STARTif _CHAPTER_RE.search(norm[:400]):return PageType.LESSON_STARTif len(_EXERCISE_PAGE_KW_RE.findall(norm)) >= 3:return PageType.EXERCISEreturn PageType.LESSON# Pages a heading candidate is allowed to come from (font/regex detectors).# TOC candidates bypass this — bookmarks give their own page numbers# regardless of what's on that page._ELIGIBLE_PAGE_TYPES = {PageType.UNIT_START, PageType.LESSON_START, PageType.LESSON}# ─── Evidence / confidence engine ───────────────────────────────────────class Evidence(str, Enum):TOC = "toc"REGEX = "regex"FUZZY = "fuzzy"FONT_SIZE = "font_size"CENTERED = "centered"TOP_OF_PAGE = "top_of_page"ORDINAL_SEQUENCE = "ordinal_sequence"OCR_PENALTY = "ocr_penalty"LLM = "llm"# Single place to tune how much each source of evidence is worth. Additive:# a candidate's confidence is the sum of whatever evidence it collected,# capped at 1.0. Penalties (OCR_PENALTY) are negative._WEIGHTS: dict[Evidence, float] = {Evidence.TOC: 0.55,# A strict keyword+ordinal regex match on cleaned (OCR'd) text is# strong evidence on its own (it's exactly what the old regex tier# trusted outright at confidence 0.6) — pair it with one corroborating# signal (ordinal sequence, font, or LLM) to clear ACCEPT_THRESHOLD.# A lone, uncorroborated regex match still lands in the LLM-review band# rather than being auto-accepted or auto-dropped.Evidence.REGEX: 0.45,Evidence.FUZZY: 0.15,Evidence.FONT_SIZE: 0.15,Evidence.CENTERED: 0.08,Evidence.TOP_OF_PAGE: 0.07,Evidence.ORDINAL_SEQUENCE: 0.15,Evidence.LLM: 0.35,}_ACCEPT_THRESHOLD = 0.55 # confidence needed to accept a heading outright_LLM_REVIEW_LOW = 0.30 # below this, too weak even for LLM review — drop_BATCH_SIZE = 5 # candidates per LLM verification call@dataclassclass HeadingCandidate:page_num: inttext: strlevel: intevidence: dict[Evidence, float] = field(default_factory=dict)reasons: list[str] = field(default_factory=list)is_ocr_page: bool = Falsellm_verdict: str | None = None # "accept" | "reject" | None@propertydef confidence(self) -> float:return max(0.0, min(1.0, sum(self.evidence.values())))# ─── Public API ──────────────────────────────────────────────────────────async def detect_headings_async(pdf_bytes: bytes,pages: list[tuple[int, str]] | None,llm_service=None, # LLMService | None — duck-typed to avoid circular importclient=None, # httpx.AsyncClient | Noneocr_pages: set[int] | None = None,) -> tuple[list[DetectedHeading], dict]:"""Detect unit/lesson headings via the candidate-pool + confidence engine.Args:pdf_bytes: Raw PDF bytes (needed for TOC and font/position detection).pages: Pre-extracted (page_num, cleaned_text) pairs — the sameOCR'd, sanitized text the chunker uses. Required for theregex/fuzzy source and for LLM verification snippets.llm_service: LLMService instance; pass None to skip LLM verificationof borderline candidates (they're then just dropped).client: httpx.AsyncClient; required when llm_service is provided.ocr_pages: page numbers that needed OCR fallback during extraction —used to discount candidates found on those pages slightlymore (OCR is noisier than native PDF text).Returns:(headings, metrics) — metrics is a JSON-able summary worth loggingor storing per document (see module docstring for shape)."""candidates, total_pages = await asyncio.to_thread(_build_candidate_pool, pdf_bytes, pages, ocr_pages,)candidates = _sanitize_candidates(candidates)candidates = _merge_candidates(candidates)suspicious_pages = _apply_ordinal_consistency(candidates)pages_dict: dict[int, str] = dict(pages) if pages else {}llm_verified = 0if llm_service is not None and client is not None:llm_verified = await _verify_candidates_with_llm(candidates, pages_dict, llm_service, client)headings = _finalize_headings(candidates)accepted_confidences = [h.confidence for h in headings]metrics = {"pages": total_pages,"headings_found": len(headings),"units": sum(1 for h in headings if h.level == 1),"lessons": sum(1 for h in headings if h.level == 2),"ocr_pages": len(ocr_pages or ()),"candidates_considered": len(candidates),"llm_verifications": llm_verified,"average_confidence": (round(sum(accepted_confidences) / len(accepted_confidences), 2)if accepted_confidences else 0.0),"suspicious_pages": sorted(set(suspicious_pages))[:20],}logger.info("Heading detection: %d pages → %d candidates → %d accepted ""(%d units, %d lessons, avg confidence %.2f); suspicious pages=%s",total_pages, len(candidates), len(headings),metrics["units"], metrics["lessons"], metrics["average_confidence"],metrics["suspicious_pages"],)return headings, metricsdef build_page_heading_map(36 unmodified linesreturn result# ─── Candidate pool construction (runs in a thread — sync/CPU-bound) ────def _build_candidate_pool(pdf_bytes: bytes,pages: list[tuple[int, str]] | None,ocr_pages: set[int] | None,) -> tuple[list[HeadingCandidate], int]:import fitzdoc = fitz.open(stream=pdf_bytes, filetype="pdf")total_pages = len(doc)ocr_pages = ocr_pages or set()pages_dict: dict[int, str] = dict(pages) if pages else {}if not pages_dict:pages_dict = {i + 1: doc[i].get_text() for i in range(total_pages)}page_types: dict[int, PageType] = {pn: classify_page_type(pn, text) for pn, text in pages_dict.items()}eligible_pages = {pn for pn, pt in page_types.items() if pt in _ELIGIBLE_PAGE_TYPES}candidates: list[HeadingCandidate] = []candidates.extend(_candidates_from_toc(doc))candidates.extend(_candidates_from_fonts(doc, eligible_pages))candidates.extend(_candidates_from_regex(pages_dict, eligible_pages))doc.close()# OCR-quality discount: candidates on pages with garbled/low-Arabic-ratio# text (or that needed OCR fallback) get a confidence penalty rather# than an outright reject — a real heading can still shine through if# other evidence (TOC, ordinal sequence) is strong.for c in candidates:c.is_ocr_page = c.page_num in ocr_pagesquality = _ocr_quality_score(pages_dict.get(c.page_num, ""))penalty = 0.0if quality < 0.5:penalty -= (0.5 - quality)if c.is_ocr_page:penalty -= 0.1if penalty:c.evidence[Evidence.OCR_PENALTY] = penaltyc.reasons.append(f"low text quality on page (score {quality:.2f})")return candidates, total_pagesdef _candidates_from_toc(doc) -> list[HeadingCandidate]:"""Source 1: PDF bookmarks/outline — strongest signal when present."""toc = doc.get_toc()if not toc:return []candidates: list[HeadingCandidate] = []for level, title, page_num in toc:title = title.strip()if not title or len(title) < 3:continueheading_level = 1 if level <= 1 else 2cand = HeadingCandidate(page_num=page_num, text=title, level=heading_level)cand.evidence[Evidence.TOC] = _WEIGHTS[Evidence.TOC]cand.reasons.append("PDF bookmark/TOC entry")candidates.append(cand)return candidatesdef _candidates_from_fonts(doc, eligible_pages: set[int]) -> list[HeadingCandidate]:"""Source 2: font size/weight + position (centered, top-of-page)."""all_sizes: list[float] = []for page in doc:try:blocks = page.get_text("dict", flags=0)["blocks"]9 unmodified linesall_sizes.append(span.get("size", 0))if len(all_sizes) < 20:return [] # not enough font data (probably a garbled/scanned PDF)body_size = median(all_sizes)heading_threshold = body_size * 1.3candidates: list[HeadingCandidate] = []for i, page in enumerate(doc):page_num = i + 1if page_num not in eligible_pages:continuepage_rect = page.recttry:blocks = page.get_text("dict", flags=0)["blocks"]except Exception:7 unmodified linesif not line_text or len(line_text) > 80 or len(line_text) < 3:continueis_heading_font = Falsefor span in line.get("spans", []):size = span.get("size", 0)2 unmodified linesif size >= heading_threshold or (is_bold and size >= body_size):is_heading_font = Truebreakif not is_heading_font:continuenorm_text = _normalize_for_match(line_text)if not _ANY_HEADING_KW.search(norm_text):continueif _ASSESSMENT_RE.search(norm_text):continuehas_ordinal_match = bool(_UNIT_RE.search(norm_text) or _CHAPTER_RE.search(norm_text))level = 1 if _UNIT_RE.search(norm_text) else 2cand = HeadingCandidate(page_num=page_num, text=line_text, level=level)cand.evidence[Evidence.FONT_SIZE] = _WEIGHTS[Evidence.FONT_SIZE]cand.reasons.append("large/bold font")bbox = line.get("bbox")if bbox:x0, y0, x1, y1 = bboxcenter = (x0 + x1) / 2if page_rect.width and abs(center - page_rect.width / 2) < page_rect.width * 0.15:cand.evidence[Evidence.CENTERED] = _WEIGHTS[Evidence.CENTERED]cand.reasons.append("centered on page")if page_rect.height and y0 < page_rect.height * 0.35:cand.evidence[Evidence.TOP_OF_PAGE] = _WEIGHTS[Evidence.TOP_OF_PAGE]cand.reasons.append("top of page")if has_ordinal_match:cand.evidence[Evidence.REGEX] = _WEIGHTS[Evidence.REGEX]cand.reasons.append("keyword+ordinal match")else:cand.evidence[Evidence.FUZZY] = _WEIGHTS[Evidence.FUZZY]cand.reasons.append("heading keyword only (no ordinal captured)")candidates.append(cand)return candidatesdef _candidates_from_regex(pages_dict: dict[int, str],eligible_pages: set[int],) -> list[HeadingCandidate]:"""Source 3: regex keyword+ordinal matches on cleaned (OCR'd) text —the strictest and usually most reliable source since it operates ontext that already passed through the extraction/OCR/sanitizationpipeline (unlike the font source, which reads raw PDF text directly)."""candidates: list[HeadingCandidate] = []for page_num, orig_text in pages_dict.items():if page_num not in eligible_pages:continuenorm_text = _normalize_for_match(orig_text)if _ASSESSMENT_RE.search(norm_text):continueorig_lines = orig_text.split("\n")for regex, level in ((_UNIT_RE, 1), (_CHAPTER_RE, 2)):for m in regex.finditer(norm_text):match_start = m.start()line_idx = norm_text[:match_start].count("\n")full_line = orig_lines[line_idx] if line_idx < len(orig_lines) else m.group(0)title = _extract_title_from_line(full_line, m.group(1), m.group(2), page_num, pages_dict)cand = HeadingCandidate(page_num=page_num, text=title, level=level)cand.evidence[Evidence.REGEX] = _WEIGHTS[Evidence.REGEX]cand.reasons.append("regex keyword+ordinal match on cleaned text")candidates.append(cand)return candidatesdef _extract_title_from_line(8 unmodified linesFormat examples:"الوحدة الثالثة: الصناعة والتكنولوجيا في وطننا العربي""الدرس الأول: السكان في وطننا العربي""""title = re.sub(r"[\s:.\-–—]+$", "", full_line).strip()if not title:return f"{keyword} {ordinal}"if ":" in title or ":" in title:return title# No description on the keyword line — check the next line for a subtitleorig_text = pages_dict.get(page_num, "")orig_lines = [ln.strip() for ln in orig_text.split("\n") if ln.strip()]base_match_idx = Nonefor i, ln in enumerate(orig_lines):if full_line.strip() in ln or ln in full_line.strip():1 unmodified linebreakif base_match_idx is not None and base_match_idx + 1 < len(orig_lines):next_line = orig_lines[base_match_idx + 1].strip()if (len(next_line) < 100 andnot any(kw in next_line for kw in ['الدرس', 'الوحدة', 'تمرين', 'سؤال']) andnot next_line.startswith("-") andnot next_line.startswith("•")):return f"{title}: {next_line}"return title# ─── Sanitize / merge / score ────────────────────────────────────────────def _sanitize_candidates(candidates: list[HeadingCandidate]) -> list[HeadingCandidate]:"""Hard rejects — applied before merging/scoring so garbage nevercontributes evidence to a real heading it happens to share a page with."""out: list[HeadingCandidate] = []for c in candidates:title = (c.text or "").strip()if not title or len(title) < 4 or title.isdigit():continueif _REPLACEMENT_CHAR_RE.search(title):continuenorm = _normalize_for_match(title)if _PARAGRAPH_HEADING_RE.match(norm):continueif _NON_LESSON_PAGE_RE.search(norm):continueif c.level > _MAX_LESSON_LEVEL:continuec.text = titleout.append(c)return outdef _merge_candidates(candidates: list[HeadingCandidate]) -> list[HeadingCandidate]:"""Combine candidates from different sources that agree on the same(page, heading text) into one, summing their evidence."""groups: dict[tuple[int, str], HeadingCandidate] = {}for c in candidates:key = (c.page_num, _normalize_heading(c.text))if key not in groups:groups[key] = ccontinueexisting = groups[key]for src, val in c.evidence.items():existing.evidence[src] = max(existing.evidence.get(src, 0.0), val)for reason in c.reasons:if reason not in existing.reasons:existing.reasons.append(reason)# Prefer the TOC-sourced title (cleanest text) if texts differif Evidence.TOC in c.evidence and Evidence.TOC not in existing.evidence:existing.text = c.textreturn list(groups.values())def _parse_ordinal(text: str) -> int | None:"""Best-effort ordinal extraction for the sequence-consistency pass.A miss just means no consistency boost for this candidate — harmless."""norm = _normalize_for_match(text)western = norm.translate(str.maketrans("٠١٢٣٤٥٦٧٨٩", "0123456789"))m = re.search(r"\d+", western)if m:try:return int(m.group(0))except ValueError:passfor pattern, value in _ORDINAL_WORD_VALUES:if pattern.search(norm):return valuereturn Nonedef _apply_ordinal_consistency(candidates: list[HeadingCandidate]) -> list[int]:"""Cross-check unit/lesson numbering across the whole document.A candidate whose ordinal continues the running sequence (1→2→3…) getsa confidence boost — this is often enough by itself to push aborderline-OCR'd heading over the acceptance threshold. A candidatethat repeats or regresses the sequence is flagged as suspicious (likelyan OCR misread) without being rejected outright, since it's still justone signal among several.Returns the list of page numbers flagged suspicious."""suspicious: list[int] = []for level in (1, 2):level_candidates = sorted((c for c in candidates if c.level == level),key=lambda c: c.page_num,)seen_max = 0for c in level_candidates:ordinal = _parse_ordinal(c.text)if ordinal is None:continueif ordinal == seen_max + 1:c.evidence[Evidence.ORDINAL_SEQUENCE] = _WEIGHTS[Evidence.ORDINAL_SEQUENCE]c.reasons.append(f"ordinal {ordinal} continues the sequence")seen_max = ordinalelif ordinal <= seen_max:c.reasons.append(f"ordinal {ordinal} repeats/regresses (seen up to {seen_max})")suspicious.append(c.page_num)else:c.reasons.append(f"ordinal {ordinal} skips ahead (expected {seen_max + 1})")suspicious.append(c.page_num)seen_max = ordinalreturn suspiciousdef _finalize_headings(candidates: list[HeadingCandidate]) -> list[DetectedHeading]:accepted = [c for c in candidates if c.confidence >= _ACCEPT_THRESHOLD]accepted.sort(key=lambda c: (c.page_num, c.level))result: list[DetectedHeading] = []seen: set[str] = set()for c in accepted:dedup_key = _normalize_heading(c.text)if dedup_key in seen:continueseen.add(dedup_key)result.append(DetectedHeading(page_num=c.page_num,title=c.text,level=c.level,confidence=round(c.confidence, 2),))return result# ─── Batched LLM verification (judge, not discoverer) ───────────────────_VERIFY_SYSTEM = """\أنت تراجع مرشحين لعناوين وحدات/دروس اكتُشفوا آليًا في كتاب مدرسي عربي.لكل مرشح تُعطى رقم الصفحة والنص المرشح ومقتطف من نص الصفحة.مهمتك لكل مرشح:1. حدد هل هو عنوان وحدة/درس حقيقي في الكتاب (وليس نشاطًا أو تمرينًا أوجملة عرضية مثل مقدمة أو أهداف الوحدة).2. إن كان النص يحتوي على خطأ OCR بسيط ويمكنك تصحيحه من المقتطف، صحح النص.3. لا تخترع عنوانًا غير موجود فعليًا في المقتطف.أجب حصريًا بمصفوفة JSON على الشكل:[{"candidate": <رقم_المرشح_كما_أُعطي>, "verdict": "accept"|"reject", "title": "<النص المصحح أو فارغ>"}]لا تضف أي نص خارج JSON.\"""async def _verify_candidates_with_llm(candidates: list[HeadingCandidate],pages_dict: dict[int, str],llm_service,client,) -> int:"""Verify BORDERLINE candidates only — those the evidence enginecouldn't confidently accept or reject on its own. High-confidencecandidates (TOC+regex+ordinal already agreeing) skip the LLM entirely;very weak ones are dropped without spending a call on them.Returns the number of candidates actually sent for verification."""borderline = [c for c in candidates if _LLM_REVIEW_LOW <= c.confidence < _ACCEPT_THRESHOLD]if not borderline:return 0for batch_start in range(0, len(borderline), _BATCH_SIZE):batch = borderline[batch_start: batch_start + _BATCH_SIZE]parts: list[str] = []for i, c in enumerate(batch):snippet = (pages_dict.get(c.page_num, "") or "")[:500].strip()parts.append(f"[مرشح {i}] صفحة {c.page_num}\n"f"النص المرشح: {c.text!r}\n"f"مقتطف الصفحة:\n{snippet}")user_msg = "\n\n".join(parts)try:1 unmodified lineif hasattr(llm_service, "_smart_model"): # CloudLLMServiceextra["model_tier"] = "cheap"raw = await llm_service.generate(_VERIFY_SYSTEM,[{"role": "user", "content": user_msg}],client=client,json_format=True,2 unmodified lines)cleaned = repair_json(raw)parsed = json.loads(cleaned)if isinstance(parsed, dict):for v in parsed.values():if isinstance(v, list):parsed = vbreakelse:logger.warning("LLM heading verification: response is a dict with no list value")continueif not isinstance(parsed, list):logger.warning("LLM heading verification: response is not a list")continuefor item in parsed:if not isinstance(item, dict):continueidx = item.get("candidate")if not isinstance(idx, int) or not (0 <= idx < len(batch)):continueverdict = (item.get("verdict") or "").strip().lower()cand = batch[idx]cand.llm_verdict = verdictif verdict == "accept":cleaned_title = (item.get("title") or "").strip()if cleaned_title and len(cleaned_title) >= 3 and not _REPLACEMENT_CHAR_RE.search(cleaned_title):cand.text = cleaned_titlecand.evidence[Evidence.LLM] = _WEIGHTS[Evidence.LLM]cand.reasons.append("LLM verified")elif verdict == "reject":cand.evidence[Evidence.LLM] = -1.0 # hard drop below thresholdcand.reasons.append("LLM rejected")except Exception as e:logger.warning("LLM heading verification failed for batch %s: %s",[c.page_num for c in batch], e)# Leave these candidates at their evidence-only confidence —# a failed verification call should not silently reject them.return len(borderline)
1234717 unmodified lines722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752317 unmodified lines10701071107210731074107510761077107810791080import asyncioimport loggingimport reimport unicodedata717 unmodified linesawait _emit({"type": "step", "step": "normalize", "pct": 30,"msg": f'تنظيف النص: {total_chars:,} حرف من {len(clean_pages)} صفحة'})# 2.5. Detect section headings (with optional LLM title refinement)await _emit({"type": "step", "step": "headings", "pct": 35,"msg": "جاري اكتشاف عناوين الأقسام..."})from app.services.heading_detector import detect_headings_async, build_page_heading_mapheadings = await detect_headings_async(pdf_bytes,clean_pages,llm_service=self._llm,client=client,)page_headings: dict[int, tuple[str | None, str | None]] = {}if headings:page_headings = build_page_heading_map(headings, total_pages=len(raw_pages))logger.info('"%s": %d section headings → %d pages mapped',title, len(headings), len(page_headings),)for h in headings[:6]:logger.debug(" p%d: %s", h.page_num, h.title)await _emit({"type": "step", "step": "headings", "pct": 40,"msg": f'اكتُشف {len(headings)} قسم'})else:logger.info('"%s": no section headings detected', title)await _emit({"type": "step", "step": "headings", "pct": 40,"msg": "لم تُكتشف عناوين أقسام — المحتوى متواصل"})# 3. Chunk — per-section strategy (one topic per chunk)chunks = self._chunk_text_with_pages(clean_pages, page_headings=page_headings or None)317 unmodified linesUPDATE rag_documentsSET status = 'INDEXED',chunk_count = :cnt,embedding_model = :model,indexed_at = NOW()WHERE id = :id"""),{"id": document_id, "cnt": indexed, "model": self._embed_model},)await session.commit()12345717 unmodified lines723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760317 unmodified lines1078107910801081108210831084108510861087108810891090109110921093109410951096import asyncioimport jsonimport loggingimport reimport unicodedata717 unmodified linesawait _emit({"type": "step", "step": "normalize", "pct": 30,"msg": f'تنظيف النص: {total_chars:,} حرف من {len(clean_pages)} صفحة'})# 2.5. Detect unit/lesson headings — candidate pool + confidence# engine (TOC/font/regex evidence, ordinal-consistency pass,# batched LLM verification of borderline candidates). See# heading_detector.py module docstring for the full design.await _emit({"type": "step", "step": "headings", "pct": 35,"msg": "جاري اكتشاف عناوين الأقسام..."})from app.services.heading_detector import detect_headings_async, build_page_heading_mapocr_pages = {page_num for page_num, _, used_ocr in raw_pages if used_ocr}headings, heading_metrics = await detect_headings_async(pdf_bytes,clean_pages,llm_service=self._llm,client=client,ocr_pages=ocr_pages,)page_headings: dict[int, tuple[str | None, str | None]] = {}if headings:page_headings = build_page_heading_map(headings, total_pages=len(raw_pages))logger.info('"%s": %d section headings → %d pages mapped (metrics: %s)',title, len(headings), len(page_headings), heading_metrics,)for h in headings[:6]:logger.debug(" p%d: %s (confidence %.2f)", h.page_num, h.title, h.confidence)await _emit({"type": "step", "step": "headings", "pct": 40,"msg": f'اكتُشف {len(headings)} قسم',"heading_metrics": heading_metrics})else:logger.info('"%s": no section headings detected (metrics: %s)', title, heading_metrics)await _emit({"type": "step", "step": "headings", "pct": 40,"msg": "لم تُكتشف عناوين أقسام — المحتوى متواصل","heading_metrics": heading_metrics})# 3. Chunk — per-section strategy (one topic per chunk)chunks = self._chunk_text_with_pages(clean_pages, page_headings=page_headings or None)317 unmodified linesUPDATE rag_documentsSET status = 'INDEXED',chunk_count = :cnt,page_count = :page_count,embedding_model = :model,heading_metrics = CAST(:heading_metrics AS jsonb),indexed_at = NOW()WHERE id = :id"""),{"id": document_id,"cnt": indexed,"page_count": len(raw_pages),"model": self._embed_model,"heading_metrics": json.dumps(heading_metrics, ensure_ascii=False),},)await session.commit()
162 unmodified lines163164165166167168162 unmodified linesALTER TABLE rag_documents ADD COLUMN IF NOT EXISTS graph_metrics JSONB;ALTER TABLE rag_documents ADD COLUMN IF NOT EXISTS heading_metrics JSONB;ALTER TABLE rag_chunks ADD COLUMN IF NOT EXISTS unit_title TEXT;"""162 unmodified lines163164165166167168169162 unmodified linesALTER TABLE rag_documents ADD COLUMN IF NOT EXISTS graph_metrics JSONB;ALTER TABLE rag_documents ADD COLUMN IF NOT EXISTS heading_metrics JSONB;ALTER TABLE rag_chunks ADD COLUMN IF NOT EXISTS unit_title TEXT;ALTER TABLE rag_questions ADD COLUMN IF NOT EXISTS unit_title TEXT;"""
app/services/heading_detector.py+545-452
app/services/ingest.py+25-9
app_tools/migrate_rag_db.py+1