# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. # Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). # This is not open-source software: see the license for permitted uses. """Answer words -> PDF word boxes, by character-level alignment of the answer with the page's text layer. PDF text layers split words (kerning), merge them, and store columns and sidebars in another order than the answer. The answer and the PDF text are folded to lowercase alphanumerics and aligned in order; then each long unmatched run of the answer is aligned against the PDF text not used yet, in any order, but only where that text is unique on the page (a header repeated in several tables would otherwise be matched to the wrong copy).""" import difflib import unicodedata def _fold(ch): ch = unicodedata.normalize("NFKC", ch).lower() return "".join(c for c in ch if c.isalnum()) def pdf_chars(words): """Flatten PDF words into (char, box) with each word's box split evenly across its folded chars.""" out = [] for w in words: t = "".join(_fold(c) for c in w["text"]) if not t: continue x0, y0, x1, y1 = w["box"]; n = len(t); dx = (x1 - x0) / n for k, c in enumerate(t): out.append((c, [x0 + k * dx, y0, x0 + (k + 1) * dx, y1])) return out def unit_boxes(answer, units, words, min_share=0.6, min_block=3): pc = pdf_chars(words) if not pc: return {} ps = "".join(c for c, _ in pc) achars, owner = [], [] for u, (s, e) in enumerate(units): for ch in answer[s:e]: f = _fold(ch) for c in f: achars.append(c); owner.append(u) a = "".join(achars) sm = difflib.SequenceMatcher(None, a, ps, autojunk=False) hit = {} for m in sm.get_matching_blocks(): if m.size < min_block: continue for k in range(m.size): hit.setdefault(owner[m.a + k], []).append(pc[m.b + k][1]) n_by_unit = {} for u in owner: n_by_unit[u] = n_by_unit.get(u, 0) + 1 out = {} for u, bs in hit.items(): if len(bs) < min_share * n_by_unit[u]: continue # keep the chars on the line of the median char (a word never spans lines) ys = sorted((b[1] + b[3]) / 2 for b in bs); ym = ys[len(ys) // 2] h = sorted(b[3] - b[1] for b in bs)[len(bs) // 2] bs = [b for b in bs if abs((b[1] + b[3]) / 2 - ym) <= 0.6 * h] out[u] = [min(b[0] for b in bs), min(b[1] for b in bs), max(b[2] for b in bs), max(b[3] for b in bs)] return out def unit_boxes_multi(answer, units, words, min_share=0.6, min_block=4, seg_min=8, passes=3, unique=True): """unit_boxes plus out-of-order passes: each long run of unmatched answer chars is aligned against the PDF chars not used yet (used ones masked), so columns / sidebars the PDF stores in another order still get boxes.""" pc = pdf_chars(words) if not pc: return {} pchars = [c for c, _ in pc] achars, owner = [], [] for u, (s, e) in enumerate(units): for ch in answer[s:e]: for c in _fold(ch): achars.append(c); owner.append(u) amatch = [None] * len(achars); pused = [False] * len(pchars) full = "".join(pchars) def align(a_lo, a_hi, out_of_order=False): a = "".join(achars[a_lo:a_hi]) p = "".join(c if not pused[k] else "\x00" for k, c in enumerate(pchars)) sm = difflib.SequenceMatcher(None, a, p, autojunk=False) for m in sm.get_matching_blocks(): if m.size < (max(min_block, 8) if out_of_order and unique else min_block): continue if out_of_order and unique and full.count(a[m.a:m.a + m.size]) > 1: continue # repeated text (same header in several tables): the out-of-order pass cannot tell which for k in range(m.size): if amatch[a_lo + m.a + k] is None and not pused[m.b + k]: amatch[a_lo + m.a + k] = m.b + k; pused[m.b + k] = True align(0, len(achars)) for _ in range(passes): segs, k = [], 0 while k < len(achars): if amatch[k] is None: j = k while j < len(achars) and amatch[j] is None: j += 1 if j - k >= seg_min: segs.append((k, j)) k = j else: k += 1 if not segs: break for lo, hi in sorted(segs, key=lambda x: x[0] - x[1]): align(lo, hi, out_of_order=True) hit = {} for i, b in enumerate(amatch): if b is not None: hit.setdefault(owner[i], []).append(pc[b][1]) n_by_unit = {} for u in owner: n_by_unit[u] = n_by_unit.get(u, 0) + 1 out = {} for u, bs in hit.items(): if len(bs) < min_share * n_by_unit[u]: continue ys = sorted((b[1] + b[3]) / 2 for b in bs); ym = ys[len(ys) // 2] h = sorted(b[3] - b[1] for b in bs)[len(bs) // 2] bs = [b for b in bs if abs((b[1] + b[3]) / 2 - ym) <= 0.6 * h] out[u] = [min(b[0] for b in bs), min(b[1] for b in bs), max(b[2] for b in bs), max(b[3] for b in bs)] return out