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)
123456345678910111213141516171819202122232425262728293031323334353637383940414243444546474894950115152535455565758596061621863646566676 unmodified lines747576317778798018 unmodified lines9910010110210310410510610710810911011118 unmodified lines13013113213313413513613713813914014114214314414514614714814915015120 unmodified lines1721731741061071081091101111121131141151161171181191201211221751761771781791801811821831841851863 unmodified lines19019119213619313819419519619714319819920020114514614714814920215115215315415515615715815920320420520620720816116216316416516616716816917017117217317417517617720917918018118218318418518618718818919019119219319419521021121219719819920020120221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730820420520620720820921021121221330921531031131231331431531631731831932032132232321821932422122222322422522622722822923032532632732832933033133233333433523323423523623723823924024124224324424524633633733833934034134234334434534634734834935035124824925025125225325425525625725825926026126226326426526626726835235335435535635735827027127235936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039136 unmodified lines4284294303154314323173184334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824833234844854864874883284893303313323333343354904914924934944953374963393403413423433444974984993465005015029 unmodified lines5125135143623635155165175185193683693703715205215223743753763773785235245255265275285297 unmodified lines5375385393945405415422 unmodified lines5455465474035485495504074085515525534104114125545555564154164174184194204214224234244254264274284295575585595605615625635645655665675685695705715725735745755765775785795805815825834325845854344355864374385875885895905915925935945954404414424434444454464474484494504514524534545965975985996006016024584594604616036046056064654664674684694704714724734744754764774784794806076086096106116126134824834844854864874884894904914924934944954964974984995005015025036146156166176185056196206216228 unmodified lines6316326335205216345236356366375276386395305316405336416425365376436446456465416476486491 unmodified line6516526535496545516556566576585566596606616626635625635645655665675685695705715725735745755765775785795805815826646655845855865875885895905915925936666676686696706716726736746756766776786796806816826836846856866875955966885985996006016026036046056066076086096106116126136146156166176186196206216226236896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457466256266276286296306316327477487497507517527537547557567577587597607617627637646347656366377667677687696396406417707717727737747757767777787797807817827837847856446456466476487867877887897907916517927937947957967976536546556566576586596606616626636646657987998008018026686698036716728048058066746756766776786796806816826838078088098108118128138148158166856866876886896906916926936946956968178188198208218228238246997007018258268278288298308318328338341 unmodified line8368378387098398408418422 unmodified lines845846847718848849850851852853725854855727856729857858859860861862735736737738739740741742743863864865745746747748749750751752753754866867868869870871872873874875876877878879880757758759760761762763764765766767768769881882883884885771772773774775776777778779780781782783784785786787788789790791792793886"""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 present 2. Font-based — large/bold spans with Arabic heading keywords 3. Regex/pattern-based — works on OCR text (primary for current 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:
PDF ├── 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 already found — it never discovers headings on its own) │ ▼ accept everything above threshold → DetectedHeading list
Candidate 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 = detect_headings(pdf_bytes, pages) headings, metrics = await detect_headings_async(pdf_bytes, pages) page_map = build_page_heading_map(headings, total_pages) # page_map[page_num] → active section title for that page # 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 dataclassfrom dataclasses import dataclass, fieldfrom enum import Enumfrom statistics import median
from json_repair import repair_json6 unmodified lines page_num: int # 1-indexed page where heading first appears title: str # Full heading text level: 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 confidence: float = 1.0 # Final combined evidence score, 0..1
# Maximum heading depth we keep. Anything deeper is treated as a paragraph18 unmodified lines r"تقديم|تمهيد(?!ي)|إهداء|توطئ[هة]|مقدم[هة]\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 lines r"العاشر[هة]|العاشر" # 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"المحتويات|الفهرس|فهرس")
# 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 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 [هة]. """ # Alef variants text = re.sub(r"[أإآٱ]", "ا", text) # Alef maqsura → ya text = text.replace("ى", "ي") return text
# ─── Public API ──────────────────────────────────────────────────────────def _collapse_ta(text: str) -> str: """Collapse ة → ه for deduplication keys.""" return text.replace("ة", "ه")
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 fitz
doc = fitz.open(stream=pdf_bytes, filetype="pdf") total_pages = len(doc)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)
# Tier 1: PDF bookmarks/outline headings = _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 headings elif headings: logger.info( "Tier 1 result too sparse (%d headings for %d pages) — falling through", len(headings), total_pages, )
# Tier 2: Font-based detection headings = _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 headings elif headings: logger.info( "Tier 2 result too sparse (%d headings for %d pages) — falling through", len(headings), total_pages, )def _ocr_quality_score(text: str) -> float: """Cheap proxy for how trustworthy a page's extracted text is.
# Tier 3: Regex on page text if pages is None: pages = [] for i, page in enumerate(doc): pages.append((i + 1, page.get_text())) doc.close() 0.0 = garbage (replacement chars present), 1.0 = clean Arabic. Used to discount candidates found on low-quality pages rather than trusting extracted text uniformly. """ if not text: return 0.0 if _REPLACEMENT_CHAR_RE.search(text): return 0.0 letters = [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 the heading detectors even look at. Keeps false positives from exercise/ index/cover pages out of the candidate pool up front, rather than filtering 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.COVER if _TOC_RE.search(first_lines): return PageType.CONTENTS if _NON_LESSON_PAGE_RE.search(first_lines): return PageType.INDEX if _UNIT_RE.search(norm[:400]): return PageType.UNIT_START if _CHAPTER_RE.search(norm[:400]): return PageType.LESSON_START if len(_EXERCISE_PAGE_KW_RE.findall(norm)) >= 3: return PageType.EXERCISE return 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
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 headings@dataclassclass HeadingCandidate: page_num: int text: str level: int evidence: dict[Evidence, float] = field(default_factory=dict) reasons: list[str] = field(default_factory=list) is_ocr_page: bool = False llm_verdict: str | None = None # "accept" | "reject" | None
@property def confidence(self) -> float: return max(0.0, min(1.0, sum(self.evidence.values())))
def _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 only kicks in above `_SHORT_DOC_PAGE_THRESHOLD` pages. """ if total_pages <= _SHORT_DOC_PAGE_THRESHOLD: return True expected_min = max( _MIN_HEADINGS_FOR_LONG_DOCS, total_pages // _MIN_HEADING_DENSITY_PAGES, ) return len(headings) >= expected_min# ─── 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 import client=None, # httpx.AsyncClient | None ocr_pages: set[int] | None = None,) -> tuple[list[DetectedHeading], dict]: """Detect unit/lesson headings via the candidate-pool + confidence engine.
def _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 that ship 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). Args: pdf_bytes: Raw PDF bytes (needed for TOC and font/position detection). pages: Pre-extracted (page_num, cleaned_text) pairs — the same OCR'd, sanitized text the chunker uses. Required for the regex/fuzzy source and for LLM verification snippets. llm_service: LLMService instance; pass None to skip LLM verification of 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 slightly more (OCR is noisier than native PDF text).
Returns: (headings, metrics) — metrics is a JSON-able summary worth logging or storing per document (see module docstring for shape). """ filtered: list[DetectedHeading] = [] seen_norm: set[str] = set()
for h in headings: if h.level and h.level > _MAX_LESSON_LEVEL: continue raw_title = (h.title or "").strip() if not raw_title or len(raw_title) < 4 or raw_title.isdigit(): continue if _REPLACEMENT_CHAR_RE.search(raw_title): continue norm = _normalize_for_match(raw_title) if _PARAGRAPH_HEADING_RE.match(norm): continue if _NON_LESSON_PAGE_RE.search(norm): continue dedup_key = _normalize_heading(raw_title) if dedup_key in seen_norm: continue seen_norm.add(dedup_key) filtered.append(h) 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)
# Stable sort by page number so the chunker sees them in reading order. filtered.sort(key=lambda h: (h.page_num, h.level)) return filtered pages_dict: dict[int, str] = dict(pages) if pages else {} llm_verified = 0 if 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, metrics
def build_page_heading_map(36 unmodified lines return result
# ─── Tier 1: PDF TOC / bookmarks ────────────────────────────────────────# ─── Candidate pool construction (runs in a thread — sync/CPU-bound) ────
def _detect_from_toc(doc) -> list[DetectedHeading]: """Extract headings from PDF bookmarks/outline."""def _build_candidate_pool( pdf_bytes: bytes, pages: list[tuple[int, str]] | None, ocr_pages: set[int] | None,) -> tuple[list[HeadingCandidate], int]: import fitz
doc = 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_pages quality = _ocr_quality_score(pages_dict.get(c.page_num, "")) penalty = 0.0 if quality < 0.5: penalty -= (0.5 - quality) if c.is_ocr_page: penalty -= 0.1 if penalty: c.evidence[Evidence.OCR_PENALTY] = penalty c.reasons.append(f"low text quality on page (score {quality:.2f})")
return candidates, total_pages
def _candidates_from_toc(doc) -> list[HeadingCandidate]: """Source 1: PDF bookmarks/outline — strongest signal when present.""" toc = doc.get_toc() if not toc: return []
headings: list[DetectedHeading] = [] candidates: list[HeadingCandidate] = [] 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 system heading_level = 1 if level <= 1 else 2 headings.append(DetectedHeading( page_num=page_num, title=title, level=heading_level, confidence=1.0, )) cand = 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 candidates
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 sizedef _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 lines all_sizes.append(span.get("size", 0))
if len(all_sizes) < 20: # Not enough font data (probably garbled PDF) return [] return [] # not enough font data (probably a garbled/scanned PDF)
body_size = median(all_sizes) heading_threshold = body_size * 1.3
# Second pass: find heading candidates headings: list[DetectedHeading] = [] seen_titles: set[str] = set()
candidates: list[HeadingCandidate] = [] for i, page in enumerate(doc): page_num = i + 1 page_text = page.get_text().strip()
# Skip TOC pages first_lines = "\n".join(page_text.split("\n")[:5]) if _TOC_RE.search(first_lines): if page_num not in eligible_pages: continue
page_rect = page.rect try: blocks = page.get_text("dict", flags=0)["blocks"] except Exception:7 unmodified lines if not line_text or len(line_text) > 80 or len(line_text) < 3: continue
# Check if any span in this line is large or bold is_heading_font = False for span in line.get("spans", []): size = span.get("size", 0)2 unmodified lines if size >= heading_threshold or (is_bold and size >= body_size): is_heading_font = True break
if not is_heading_font: continue
# Must contain Arabic heading keywords (check normalized) if not _ANY_HEADING_KW.search(_normalize_for_match(line_text)): norm_text = _normalize_for_match(line_text) if not _ANY_HEADING_KW.search(norm_text): continue
# Skip assessment/review pages if _ASSESSMENT_RE.search(_normalize_for_match(line_text)): if _ASSESSMENT_RE.search(norm_text): continue
# Deduplicate (running headers repeat on every page) norm = _normalize_heading(line_text) if norm in seen_titles: continue seen_titles.add(norm)
level = 1 if _UNIT_RE.search(_normalize_for_match(line_text)) else 2 headings.append(DetectedHeading( page_num=page_num, title=line_text, level=level, confidence=0.8, ))
return headings has_ordinal_match = bool(_UNIT_RE.search(norm_text) or _CHAPTER_RE.search(norm_text)) level = 1 if _UNIT_RE.search(norm_text) else 2
cand = 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 = bbox center = (x0 + x1) / 2 if 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)
# ─── Tier 3: Regex/pattern-based ──────────────────────────────────────── return candidates
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 first occurrence of each distinct ordinal/number to set boundaries.def _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 on text that already passed through the extraction/OCR/sanitization pipeline (unlike the font source, which reads raw PDF text directly). """ # Identify TOC pages to exclude from boundary detection toc_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: candidates: list[HeadingCandidate] = []
for page_num, orig_text in pages_dict.items(): if page_num not in eligible_pages: continue
norm_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): continue orig_lines = orig_text.split("\n")
for m in _UNIT_RE.finditer(norm_text): # Find which line this match is on, get original 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) 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 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) raw_matches.append((page_num, m.group(1), m.group(2), 2, m.group(1), full_line))
if not raw_matches: return [] 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)
# 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 deduplication key = (_collapse_ta(kw_norm), _collapse_ta(ord_norm)) if key not in seen: seen[key] = (page_num, level, full_line)
# Build headings with title extraction headings: 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 extraction title = _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, )) 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 headings return candidates
def _extract_title_from_line(8 unmodified lines Format 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 + ordinal return f"{keyword} {ordinal}"
# If line contains colon + descriptive text, keep it all # e.g., "الوحدة الثالثة: الصناعة والتكنولوجيا" → keep the whole thing if ":" in title or ":" in title: # Already has colon separator, return as is return title
# If the title is just keyword + ordinal with no description, # try to find a subtitle on the next line # No description on the keyword line — check the next line for a subtitle orig_text = pages_dict.get(page_num, "") orig_lines = [ln.strip() for ln in orig_text.split("\n") if ln.strip()]
# Find this line's index base_match_idx = None for i, ln in enumerate(orig_lines): if full_line.strip() in ln or ln in full_line.strip():1 unmodified line break
if base_match_idx is not None and base_match_idx + 1 < len(orig_lines): # Check next line for descriptive subtitle next_line = orig_lines[base_match_idx + 1].strip() # Subtitle validation: short, no special structure, no leading keywords if (len(next_line) < 100 and not any(kw in next_line for kw in ['الدرس', 'الوحدة', 'تمرين', 'سؤال']) and not next_line.startswith("-") and not next_line.startswith("•")): # Valid subtitle - append to title return f"{title}: {next_line}"
return title
def _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 content bullet 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]# ─── Sanitize / merge / score ────────────────────────────────────────────
# 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 = None for i, norm_line in enumerate(norm_lines): if pattern.search(norm_line): match_idx = i breakdef _sanitize_candidates(candidates: list[HeadingCandidate]) -> list[HeadingCandidate]: """Hard rejects — applied before merging/scoring so garbage never contributes 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(): continue if _REPLACEMENT_CHAR_RE.search(title): continue norm = _normalize_for_match(title) if _PARAGRAPH_HEADING_RE.match(norm): continue if _NON_LESSON_PAGE_RE.search(norm): continue if c.level > _MAX_LESSON_LEVEL: continue c.text = title out.append(c) return out
if 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 punctuation subtitle = "" 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) <= 6 and len(prev) <= 40 and not is_bullet and not has_heading and not has_tocdef _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] = c continue existing = 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 differ if Evidence.TOC in c.evidence and Evidence.TOC not in existing.evidence: existing.text = c.text return 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: pass for pattern, value in _ORDINAL_WORD_VALUES: if pattern.search(norm): return value return None
def _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…) gets a confidence boost — this is often enough by itself to push a borderline-OCR'd heading over the acceptance threshold. A candidate that repeats or regresses the sequence is flagged as suspicious (likely an OCR misread) without being rejected outright, since it's still just one 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, ) if is_clean: # Strip trailing punctuation from subtitle subtitle = re.sub(r"[\s:.\-–—]+$", "", prev).strip()
if subtitle: return f"{base}: {subtitle}" return base
seen_max = 0 for c in level_candidates: ordinal = _parse_ordinal(c.text) if ordinal is None: continue if ordinal == seen_max + 1: c.evidence[Evidence.ORDINAL_SEQUENCE] = _WEIGHTS[Evidence.ORDINAL_SEQUENCE] c.reasons.append(f"ordinal {ordinal} continues the sequence") seen_max = ordinal elif 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 = ordinal return suspicious
# ─── Helpers ─────────────────────────────────────────────────────────────
def _collapse_ta(text: str) -> str: """Collapse ة → ه for deduplication keys.def _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))
Ensures "الرابعة" and "الرابعه" are treated as the same unit/ordinal. """ return text.replace("ة", "ه") result: list[DetectedHeading] = [] seen: set[str] = set() for c in accepted: dedup_key = _normalize_heading(c.text) if dedup_key in seen: continue seen.add(dedup_key) result.append(DetectedHeading( page_num=c.page_num, title=c.text, level=c.level, confidence=round(c.confidence, 2), )) return result
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)# ─── Batched LLM verification (judge, not discoverer) ───────────────────
_VERIFY_SYSTEM = """\أنت تراجع مرشحين لعناوين وحدات/دروس اكتُشفوا آليًا في كتاب مدرسي عربي.لكل مرشح تُعطى رقم الصفحة والنص المرشح ومقتطف من نص الصفحة.
# ─── LLM-aided heading refinement ────────────────────────────────────────مهمتك لكل مرشح:1. حدد هل هو عنوان وحدة/درس حقيقي في الكتاب (وليس نشاطًا أو تمرينًا أو جملة عرضية مثل مقدمة أو أهداف الوحدة).2. إن كان النص يحتوي على خطأ OCR بسيط ويمكنك تصحيحه من المقتطف، صحح النص.3. لا تخترع عنوانًا غير موجود فعليًا في المقتطف.
_REFINE_SYSTEM = """\أنت تحلل كتابًا مدرسيًا عربيًا. ستُعطى مقاطع نصية من صفحات بداية وحدات أو دروس.مهمتك: استخرج عنوان الدرس أو الوحدة الكامل لكل صفحة كما هو مكتوب في الكتاب.
قواعد إلزامية:1. أعد فقط عناوين الدروس أو الوحدات (مثل "الوحدة الأولى: ...", "الدرس الثالث: ...").2. لا تعد عناوين فرعية أو فقرات داخل الدرس (تمرين / نشاط / مثال / تطبيق / للقراءة / اختبر نفسك / خلاصة / ملاحظة / تمهيد / مقدمة).3. لا تخترع عنوانًا غير موجود؛ إن لم تتوفر عنوان درس صريح فأعد سلسلة فارغة "".4. حافظ على ترتيب وصياغة الكتاب نفسها (لا تختصر ولا تعيد الصياغة).5. أجب حصريًا بـ JSON صحيح على الشكل: [{"page": <رقم_الصفحة>, "title": "<عنوان_الدرس_الكامل_أو_فارغ>"}] لا تضف أي نص خارج JSON.\أجب حصريًا بمصفوفة JSON على الشكل:[{"candidate": <رقم_المرشح_كما_أُعطي>, "verdict": "accept"|"reject", "title": "<النص المصحح أو فارغ>"}]لا تضف أي نص خارج JSON.\"""
_BATCH_SIZE = 5 # heading-candidate pages per LLM call
async def _refine_headings_with_llm( headings: list[DetectedHeading],async def _verify_candidates_with_llm( candidates: list[HeadingCandidate], pages_dict: dict[int, str], llm_service, # LLMService — duck-typed to avoid circular import client, # httpx.AsyncClient) -> list[DetectedHeading]: """Refine regex-detected heading titles using the LLM.
Batches candidate pages (5 per call) and sends page snippets to the LLM which returns the clean, exact section title from the book itself.
On any failure (timeout, invalid JSON, unexpected schema) the original regex-detected title is kept unchanged. llm_service, client,) -> int: """Verify BORDERLINE candidates only — those the evidence engine couldn't confidently accept or reject on its own. High-confidence candidates (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. """ result = list(headings) # mutable copy page_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 titles candidate_pages = [ h.page_num for h in headings if h.confidence < 0.7 and len(h.title) < 80 ] if not candidate_pages: return result # All headings already high-confidence — skip LLM
for batch_start in range(0, len(candidate_pages), _BATCH_SIZE): batch = candidate_pages[batch_start: batch_start + _BATCH_SIZE] borderline = [c for c in candidates if _LLM_REVIEW_LOW <= c.confidence < _ACCEPT_THRESHOLD] if not borderline: return 0
for batch_start in range(0, len(borderline), _BATCH_SIZE): batch = borderline[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}") 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 line if hasattr(llm_service, "_smart_model"): # CloudLLMService extra["model_tier"] = "cheap" raw = await llm_service.generate( _REFINE_SYSTEM, _VERIFY_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 list if isinstance(parsed, dict): for v in parsed.values(): if isinstance(v, list): parsed = v break else: logger.warning("LLM heading refinement: response is a dict with no list value") logger.warning("LLM heading verification: response is a dict with no list value") continue
if not isinstance(parsed, list): logger.warning("LLM heading refinement: response is not a list") logger.warning("LLM heading verification: response is not a list") continue
for item in parsed: if not isinstance(item, dict): continue page_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)): idx = item.get("candidate") if not isinstance(idx, int) or not (0 <= idx < len(batch)): continue idx = page_to_idx.get(page_num) if idx is None: continue result[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) verdict = (item.get("verdict") or "").strip().lower() cand = batch[idx] cand.llm_verdict = verdict
if 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_title cand.evidence[Evidence.LLM] = _WEIGHTS[Evidence.LLM] cand.reasons.append("LLM verified") elif verdict == "reject": cand.evidence[Evidence.LLM] = -1.0 # hard drop below threshold cand.reasons.append("LLM rejected")
except Exception as e: logger.warning("LLM heading refinement failed for batch %s: %s", batch, e) # Keep original regex titles for this batch
return result
async def detect_headings_async( pdf_bytes: bytes, pages: list[tuple[int, str]] | None, llm_service=None, # LLMService | None client=None, # httpx.AsyncClient | None) -> list[DetectedHeading]: """Async variant of detect_headings() with optional LLM title refinement. 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.
Runs Tier 1/2/3 detection in a thread pool (non-blocking), then if llm_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 headings
pages_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 refined return len(borderline)12345717 unmodified lines723724725725726727728729730731732733729734735736737738739740741742743744739740745746747748743749750745751752753747754755749756757758759760317 unmodified lines10781079108010811082108310841085108610771087108810891090109110921093109410951096import asyncioimport jsonimport loggingimport reimport unicodedata717 unmodified lines await _emit({"type": "step", "step": "normalize", "pct": 30, "msg": f'تنظيف النص: {total_chars:,} حرف من {len(clean_pages)} صفحة'})
# 2.5. Detect section headings (with optional LLM title refinement) # 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_map ocr_pages = {page_num for page_num, _, used_ocr in raw_pages if used_ocr} headings = await detect_headings_async( 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', title, len(headings), len(page_headings), '"%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", h.page_num, h.title) 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)} قسم'}) "msg": f'اكتُشف {len(headings)} قسم', "heading_metrics": heading_metrics}) else: logger.info('"%s": no section headings detected', title) logger.info('"%s": no section headings detected (metrics: %s)', title, heading_metrics) await _emit({"type": "step", "step": "headings", "pct": 40, "msg": "لم تُكتشف عناوين أقسام — المحتوى متواصل"}) "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 lines UPDATE rag_documents SET 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, "model": self._embed_model}, { "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 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