Spaces:
Build error

trackademi / app /services /ocr_layout.py
anwarKXC
Refactor OCR layout processing for Arabic text and enhance exam generation tests
8ea168e
Raw History Blame Contribute Delete
10.1 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Heading detection from OCR layout geometry.
Google Vision's DOCUMENT_TEXT_DETECTION returns a full hierarchy — pages,
blocks, paragraphs, words, symbols — each with a bounding box. We were keeping
only `fullTextAnnotation.text`, the flattened string, and throwing the geometry
away. That discarded the one signal that identifies a heading which carries no
textual marker at all.
It matters because the keyword detectors can only find sections that announce
themselves ("الفصل الأول", "1.1 ..."). A page like
الدعامه في النبات <- larger type, own line
يلجا النبات الي وسائل كثيره لدعمه ... <- body
has no keyword and no number. In the flattened text those two lines are
indistinguishable; in the layout the first is visibly a heading. On the
2026-08-06 biology book this is the difference between 6 detectable sections
and the ~30 topics a teacher actually wants to scope an exam to.
The approach is deliberately geometric rather than linguistic:
* A line's height (its bounding box) is a proxy for font size. Compare each
line against the page's own median body height rather than an absolute
threshold, since DPI and page size vary.
* Headings are short. Body paragraphs are not.
* Headings tend to start a block and sit alone on their line.
Everything here is pure geometry over a plain dict, so it runs without network
or model access and is fully testable offline.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from statistics import median
@dataclass
class LayoutLine:
"""One visual line lifted from the OCR layout."""
text: str
height: float # bounding-box height, proxy for font size
top: float # vertical position, 0.0 = top of page
left: float # horizontal start, normalized
width: float # normalized width of the line
block_index: int # which block it came from
first_in_block: bool
# A heading must stand out by this much against the page's median line height.
_HEIGHT_RATIO = 1.18
# Headings are labels. Anything longer is a paragraph that happens to be big.
#
# Tighter than the 90 the keyword/regex sources use, because height carries far
# less information on Arabic than it looks like it should: a fully vocalized
# word ("يُكْرَهُون", "أَكَلَ") has tashkeel above and below the letters, so its
# bounding box is as tall as a heading set in genuinely larger type. Measured
# against Google Vision on the 2026-08-07 Arabic book, page 150's baseline was
# 22.0 and the threshold 26.0, while body prose reached 27–28 — the same height
# as the real heading "الوحدة الأولى". Length is the signal that still
# separates them: real unit/lesson titles run 13–45 characters, and every
# false positive on that page was a 75+ character run of prose.
_MAX_HEADING_CHARS = 55
_MIN_HEADING_CHARS = 6
# A heading rarely spans the full text width — body lines do.
_MAX_WIDTH_RATIO = 0.92
# Lines that are page furniture rather than structure.
_FURNITURE_RE = re.compile(
r"^(?:علم\s*الاحياء|الاحياء\s*للثانوي|صفحه|page)\b|^[\d٠-٩۰-۹\s.\-]+$"
)
# Figure/table captions look heading-ish (short, own line) but are not sections.
_CAPTION_RE = re.compile(r"^\s*(?:شكل|جدول|صوره|figure|fig\.?|table)\s*[\(\d٠-٩]")
_ARABIC_CHAR_RE = re.compile(r"[؀-ۿݐ-ݿ]")
def _is_rtl_group(group: list[tuple]) -> bool:
"""True when this visual line is predominantly Arabic and so reads RTL.
Decided per line rather than per document: textbook pages mix an Arabic
body with Latin technical terms, and a line that is genuinely Latin
("Chromosomal Mutations") must keep its left-to-right order.
"""
arabic = sum(1 for g in group if _ARABIC_CHAR_RE.search(g[4]))
return arabic * 2 > len(group)
def _bbox_metrics(bbox: dict) -> tuple[float, float, float, float]:
"""Return (height, top, left, width) from a Vision boundingBox."""
verts = bbox.get("normalizedVertices") or bbox.get("vertices") or []
xs = [v.get("x", 0) or 0 for v in verts]
ys = [v.get("y", 0) or 0 for v in verts]
if not xs or not ys:
return 0.0, 0.0, 0.0, 0.0
return max(ys) - min(ys), min(ys), min(xs), max(xs) - min(xs)
def lines_from_vision_page(page: dict) -> list[LayoutLine]:
"""Flatten one Vision page annotation into visual lines.
Vision groups words into paragraphs but does not expose "lines" directly,
so words are regrouped by vertical position — words whose boxes overlap
vertically belong to the same visual line.
"""
lines: list[LayoutLine] = []
for block_index, block in enumerate(page.get("blocks", []) or []):
for para in block.get("paragraphs", []) or []:
words: list[tuple[float, float, float, float, str]] = []
for word in para.get("words", []) or []:
text = "".join(
s.get("text", "") for s in (word.get("symbols") or [])
)
if not text:
continue
h, top, left, width = _bbox_metrics(word.get("boundingBox", {}))
words.append((h, top, left, width, text))
if not words:
continue
# Group words into visual lines by vertical overlap.
words.sort(key=lambda w: (round(w[1], 3), w[2]))
current: list[tuple] = []
current_top = None
tolerance = median([w[0] for w in words]) * 0.6 or 0.01
def _flush(group: list[tuple]) -> None:
if not group:
return
# Arabic is RTL, so the right-most word comes FIRST. The words
# were sorted by ascending `left` for line grouping, which is
# reading order for Latin and exactly backwards for Arabic.
#
# Joining in box order was previously assumed to be harmless.
# It is not: on the 2026-08-07 Arabic book the unit heading
# "الوحدة الأولى" came out as "الأولى الوحدة" and "النطق
# والإملاء" as "والإملاء النطق". Reversed titles match no
# keyword pattern (so _UNIT_RE can't assign level 1) and read
# as nonsense to the LLM verifier, which is why this source
# contributed 0 accepted headings on every book so far.
#
# Latin runs inside the line keep their own internal order —
# only the word sequence is reversed, which is what RTL layout
# actually means.
ordered = sorted(group, key=lambda g: -g[2]) if _is_rtl_group(group) else group
text = " ".join(g[4] for g in ordered).strip()
if not text:
return
heights = [g[0] for g in group]
lefts = [g[2] for g in group]
rights = [g[2] + g[3] for g in group]
lines.append(LayoutLine(
text=text,
height=median(heights),
top=min(g[1] for g in group),
left=min(lefts),
width=max(rights) - min(lefts),
block_index=block_index,
first_in_block=False,
))
for w in words:
if current_top is None or abs(w[1] - current_top) <= tolerance:
current.append(w)
# Track the running mean rather than pinning to the first
# word's top. Scanned pages are always slightly skewed, so
# a fixed reference drifts out of tolerance partway across
# a wide line and splits it into fragments — which then
# read as short "headings" or bury a real one in a longer
# run than it actually is.
current_top = sum(g[1] for g in current) / len(current)
else:
_flush(current)
current, current_top = [w], w[1]
_flush(current)
# Mark the first line of each block — headings usually open one.
seen_blocks: set[int] = set()
for line in lines:
if line.block_index not in seen_blocks:
line.first_in_block = True
seen_blocks.add(line.block_index)
return lines
def heading_lines(lines: list[LayoutLine]) -> list[LayoutLine]:
"""Pick the lines whose geometry says 'heading'.
Compares against the page's own median line height rather than an absolute
size, so it survives varying DPI and page dimensions.
"""
body = [ln for ln in lines if len(ln.text) > 25]
if len(body) < 3:
return [] # too little text to establish a baseline
baseline = median([ln.height for ln in body])
if baseline <= 0:
return []
page_width = max((ln.width for ln in lines), default=0.0) or 1.0
picked: list[LayoutLine] = []
for ln in lines:
text = ln.text.strip()
if not (_MIN_HEADING_CHARS <= len(text) <= _MAX_HEADING_CHARS):
continue
if _FURNITURE_RE.search(text) or _CAPTION_RE.match(text):
continue
if ln.height < baseline * _HEIGHT_RATIO:
continue
if ln.width / page_width > _MAX_WIDTH_RATIO:
continue # spans the column like body text
picked.append(ln)
picked.sort(key=lambda l: l.top)
return picked
def headings_from_vision_response(item: dict) -> list[str]:
"""Convenience: the heading texts for one Vision image response."""
pages = (item.get("fullTextAnnotation") or {}).get("pages") or []
out: list[str] = []
for page in pages:
out.extend(ln.text for ln in heading_lines(lines_from_vision_page(page)))
return out