# 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. """Join consecutive lines of a heading in visible-page coordinates.""" import re _HEADING_LEVEL = re.compile(r"^\s*(#{1,6})(?:\s|$)") def merge_heading_lines(items: list[dict]) -> list[dict]: """Preserve ordered Markdown while joining aligned, equally ranked headings. Call after PDF crop/rotation conversion. All distances use the visible page's units and are normalized by line height. Compare successive original lines, not accumulated group bounds, so a multiline heading can grow consistently. """ groups: list[list[dict]] = [] for item in items: if ( groups and item["type"] == "Section-header" and groups[-1][-1]["type"] == "Section-header" ): previous = groups[-1][-1] a, b = previous["bbox"], item["bbox"] height = min(a["h"], b["h"]) gap = b["y"] - a["y"] - a["h"] levels = [_HEADING_LEVEL.match(v["md"]) for v in (previous, item)] ranks = [len(m.group(1)) if m else 0 for m in levels] # Center estimates for wide lines can differ by more than a line height. # Scale tolerance by the shorter line so neighboring columns stay apart. aligned = abs(a["x"] + a["w"] / 2 - b["x"] - b["w"] / 2) <= max( height, 0.25 * min(a["w"], b["w"]) ) if ( ranks[0] == ranks[1] and height > 0 and max(a["h"], b["h"]) <= 1.5 * height and -0.3 * height <= gap <= height and aligned ): groups[-1].append(item) continue groups.append([item]) result = [] for group in groups: if len(group) == 1: result.extend(group) continue boxes = [item["bbox"] for item in group] x, y = min(b["x"] for b in boxes), min(b["y"] for b in boxes) right = max(b["x"] + b["w"] for b in boxes) bottom = max(b["y"] + b["h"] for b in boxes) box = {**boxes[0], "x": x, "y": y, "w": right - x, "h": bottom - y} md = "\n".join(item["md"] for item in group) result.append( { **group[0], "bbox": box, "layout_segments": [dict(box)], "md": md, "value": md, } ) return result def merge_numeric_callouts(items: list[dict]) -> list[dict]: """Join a numeric heading and its short aligned label in page coordinates. The label must follow below, within two label heights, and be no taller than the number. Preserve both Markdown spans and their union box as text. """ kept: list[dict] = [] for item in items: if ( kept and kept[-1]["type"] == "Section-header" and item["type"] == "Text" and len(item["md"]) <= 100 and len(item["md"].split()) <= 15 ): previous = kept[-1] value = re.sub(r"^#{1,6}\s*", "", previous["md"]) value = value.replace("*", "").replace("_", "").strip() a, b = previous["bbox"], item["bbox"] gap = b["y"] - a["y"] - a["h"] overlap = min(a["x"] + a["w"], b["x"] + b["w"]) - max(a["x"], b["x"]) if ( re.fullmatch(r"[$€£]?\d[\d,.]*(?:%|[kKmMbB])?\+?", value) and 0 <= gap <= 2 * b["h"] and b["h"] <= a["h"] and overlap >= 0.5 * min(a["w"], b["w"]) ): x, y = min(a["x"], b["x"]), min(a["y"], b["y"]) box = { **b, "x": x, "y": y, "w": max(a["x"] + a["w"], b["x"] + b["w"]) - x, "h": max(a["y"] + a["h"], b["y"] + b["h"]) - y, } md = previous["md"] + "\n" + item["md"] kept[-1] = { **item, "md": md, "value": md, "bbox": box, "layout_segments": [dict(box)], } continue kept.append(item) return kept def trim_paragraph_heading_overlap(items: list[dict]) -> None: """Trim shallow paragraph incursions into external horizontal headings. Boxes use visible-page coordinates. A heading must be at least twice as wide as tall: elongated vertical predictions are unreliable boundary evidence. Original paragraph edges anchor every comparison so trimming cannot cascade. """ headings = [ item["bbox"] for item in items if item["type"] == "Section-header" and item["bbox"]["w"] >= 2 * item["bbox"]["h"] ] for item in items: if item["type"] != "Text": continue box = item["bbox"] top, bottom = box["y"], box["y"] + box["h"] new_top, new_bottom = top, bottom for heading in headings: overlap = min(box["x"] + box["w"], heading["x"] + heading["w"]) - max( box["x"], heading["x"] ) if overlap <= 0 or overlap < 0.75 * heading["w"]: continue center = heading["y"] + heading["h"] / 2 end = heading["y"] + heading["h"] if center < top and top < end < top + 0.2 * box["h"]: new_top = max(new_top, end) if center > bottom and bottom - 0.2 * box["h"] < heading["y"] < bottom: new_bottom = min(new_bottom, heading["y"]) if new_top != top or new_bottom != bottom: trimmed = {**box, "y": new_top, "h": new_bottom - new_top} item["bbox"] = trimmed item["layout_segments"] = [trimmed] def merge_bold_heading_continuations(answer: str, items: list[dict]) -> list[dict]: """Join a heading with its adjacent bold source line in visible-page units. Source adjacency excludes paragraph breaks. Horizontal overlap and a gap of at most two continuation heights restrict joining to nearby lines. The union represents the full label while preserving its Markdown. """ kept: list[dict] = [] for item in items: if ( kept and kept[-1]["type"] == "Section-header" and item["type"] == "Text" and re.fullmatch(r"\*\*[^\n]+\*\*", item["md"].strip()) ): previous = kept[-1] a, b = previous["bbox"], item["bbox"] gap = b["y"] - a["y"] - a["h"] overlap = min(a["x"] + a["w"], b["x"] + b["w"]) - max(a["x"], b["x"]) markdown = previous["md"].strip() + "\n" + item["md"].strip() if ( markdown in answer and 0 <= gap <= 2 * b["h"] and overlap >= 0.5 * min(a["w"], b["w"]) ): x, y = min(a["x"], b["x"]), min(a["y"], b["y"]) box = { **a, "x": x, "y": y, "w": max(a["x"] + a["w"], b["x"] + b["w"]) - x, "h": max(a["y"] + a["h"], b["y"] + b["h"]) - y, } kept[-1] = { **previous, "md": markdown, "value": markdown, "bbox": box, "layout_segments": [dict(box)], } continue kept.append(item) return kept def expand_table_to_embedded_heading(items: list[dict]) -> None: """Include an embedded title's edges in the following table's page-space box. Attention can cover a chart's plot while missing its title overhang. Keep the heading's precise box and text independent, expanding only a table that contains its center and overlaps most of its width. """ for heading, table in zip(items, items[1:]): if heading["type"] != "Section-header" or table["type"] != "Table": continue a, b = heading["bbox"], table["bbox"] cx, cy = a["x"] + a["w"] / 2, a["y"] + a["h"] / 2 overlap = min(a["x"] + a["w"], b["x"] + b["w"]) - max(a["x"], b["x"]) if ( b["x"] <= cx <= b["x"] + b["w"] and b["y"] <= cy <= b["y"] + b["h"] and overlap >= 0.75 * a["w"] and b["h"] >= 3 * a["h"] ): x, y = min(a["x"], b["x"]), min(a["y"], b["y"]) box = { **b, "x": x, "y": y, "w": max(a["x"] + a["w"], b["x"] + b["w"]) - x, "h": max(a["y"] + a["h"], b["y"] + b["h"]) - y, } table["bbox"] = box table["layout_segments"] = [dict(box)]