\s*| ]*colspan=[\"']?\d+[\"']?[^>]*>"
+ r"(Source:(?:(?!?(?:td|th|tr|table)\b).)*) | \s*
\s*\s*$",
+ re.I | re.S,
+)
+
+
+def separate_table_sources(
+ answer: str,
+ elements: list[dict],
+ units: list[tuple[int, int]],
+ lookup: dict[int, int],
+ peaks: np.ndarray,
+ grid_boxes: np.ndarray,
+ word_boxes: np.ndarray,
+) -> list[dict]:
+ """Ground explicit final source rows using existing word predictions.
+
+ Spans remain offsets into the original transcript and boxes use capture
+ pixels. Table geometry is already refined and stays unchanged. A marker
+ tells serialization to restore the closing tag after removing the row.
+ """
+ rebuilt: list[dict] = []
+ for element in elements:
+ match = (
+ _SOURCE_FOOTER.search(answer, element["start"], element["end"])
+ if element["type"] == "table"
+ else None
+ )
+ if match:
+ start, end = match.span(1)
+ selected = [
+ lookup[u]
+ for u, (s, e) in enumerate(units)
+ if start <= s and e <= end and u in lookup
+ ]
+ selected = coherent_paragraph_words(selected, peaks, grid_boxes)
+ if selected:
+ boxes = word_boxes[selected]
+ bounds = np.r_[boxes[:, :2].min(0), boxes[:, 2:].max(0)]
+ rebuilt.append({**element, "end": match.start(), "close_table": True})
+ rebuilt.append(
+ {
+ "type": "text",
+ "start": start,
+ "end": end,
+ "box": np.round(bounds, 1).tolist(),
+ }
+ )
+ continue
+ rebuilt.append(element)
+ return rebuilt
+
+
+def ground_cached(
+ answer: str,
+ capture: dict,
+ models: list[Predictor] | None = None,
+ with_context: bool = False,
+ picture_model: PicturePredictor | None = None,
+ with_extended_context: bool = False,
+ region_models: list[Predictor] | None = None,
+ collect_region_features: bool = False,
+ table_model: TablePredictor | None = None,
+ with_region_context: bool = False,
+ peak_model: PeakPredictor | None = None,
+ *,
+ _rotated_spans: set[tuple[int, int]] | None = None,
+) -> dict:
+ """Reconstruct pixel-coordinate boxes from dimensions and cached attention.
+
+ Models predict center dx/dy and log width/height in attention-grid cells.
+ The caller owns model loading; this function performs no file or image I/O.
+ Without models, return the deterministic rectangle baseline. Region models
+ adjust outer edges in local word-height units. Feature collection returns
+ each region's element index, feature row, grid-cell anchor, and word height
+ for offline training-label construction.
+ """
+ if (region_models is not None or collect_region_features) and models is None:
+ raise ValueError("Region refinement requires word boundary models")
+ if region_models is not None and len(region_models) != 4:
+ raise ValueError("Expected four region edge predictors")
+ width, height = capture["width"], capture["height"]
+ gh, gw = capture["grid"]
+ cw, ch = width / gw, height / gh
+ blocks = split_column_blocks(answer, capture, split_blocks(answer))
+ blocks = split_bullet_tables(answer, blocks)
+ blocks = split_navigation_headers(answer, capture, blocks)
+ units, per_block = units_for(answer, blocks)
+ sparse = capture["sparse_maps"]
+ if len(units) != len(sparse["idx"]):
+ raise ValueError("Cached attention units do not match the transcript")
+ if get_rust() is not None:
+ maps, has = (
+ SparseWordMaps(sparse, (gh, gw)),
+ np.asarray(sparse["has"], dtype=bool),
+ )
+ else:
+ maps, has = dense_maps(sparse, (gh, gw))
+ base = rectangle_boxes(
+ (width, height),
+ answer,
+ blocks,
+ units,
+ per_block,
+ maps,
+ (gh, gw),
+ has,
+ BASE_CONFIG,
+ )
+ if picture_model is not None:
+ refine_pictures(capture, blocks, per_block, base, picture_model, answer=answer)
+ if table_model is not None:
+ refine_tables(capture, answer, blocks, per_block, units, base, table_model)
+ if models is None:
+ return base
+ if len(models) != 4:
+ raise ValueError(
+ "Expected center-x, center-y, log-width, and log-height predictors"
+ )
+ features, valid, peaks = attention_features(answer, units, sparse, (gh, gw))
+ if not len(valid):
+ if collect_region_features:
+ base["region_features"] = []
+ return base
+ if peak_model is not None:
+ context = contextual_features(answer, units, per_block, features, valid, peaks)
+ anchors = select_word_peaks(
+ context, valid, peaks, sparse, (gh, gw), blocks, per_block, peak_model
+ )
+ if anchors:
+ # Local attention features depend only on the changed word's map.
+ # Recompute those rows; contextual features below still see every peak.
+ changed = [u for u in valid if u in anchors]
+ changed_sparse = {
+ key: [values[u] for u in changed] for key, values in sparse.items()
+ }
+ changed_features, _, changed_peaks = attention_features(
+ answer,
+ [units[u] for u in changed],
+ changed_sparse,
+ (gh, gw),
+ {i: anchors[u] for i, u in enumerate(changed)},
+ )
+ lookup = {u: row for row, u in enumerate(valid)}
+ rows = [lookup[u] for u in changed]
+ features[rows] = changed_features
+ peaks[rows] = changed_peaks
+ if with_context or with_extended_context:
+ if peak_model is not None and not anchors:
+ features = context
+ else:
+ features = contextual_features(
+ answer, units, per_block, features, valid, peaks
+ )
+ if with_extended_context:
+ features = extended_features(
+ answer, units, blocks, per_block, features, valid, peaks, sparse, (gh, gw)
+ )
+ predicted = np.column_stack([predict(model, features) for model in models])
+ centers, sizes = peaks + predicted[:, :2], np.exp(predicted[:, 2:])
+ grid_boxes = np.column_stack([centers - sizes / 2, centers + sizes / 2])
+ word_boxes = grid_boxes * [
+ cw,
+ ch,
+ cw,
+ ch,
+ ]
+ lookup = {u: j for j, u in enumerate(valid)}
+ valid_starts = [units[u][0] for u in valid]
+ # Descriptions inside image references are not printed text. Keep their
+ # cached indices intact, but exclude them from text-region boundaries.
+ image_units = set()
+ for match in _INLINE_IMAGE_REFERENCE.finditer(answer):
+ first = bisect_left(valid_starts, match.start())
+ last = bisect_left(valid_starts, match.end())
+ image_units.update(u for u in valid[first:last] if units[u][1] <= match.end())
+ region_records = []
+ cell_scale = np.array([cw, ch, cw, ch])
+ refine_table_word_boxes(
+ answer, base["elements"], units, valid, grid_boxes, peaks, cell_scale
+ )
+ # Snapshot pixel-coordinate paragraph edges before any word-based updates.
+ # Three agreeing right edges provide a candidate width for the same left column.
+ column_evidence = [
+ list(e["box"])
+ for e in base["elements"]
+ if e["box"] is not None
+ and e["type"] in {"text", "list"}
+ and e["end"] - e["start"] >= 80
+ and e["box"][3] - e["box"][1] >= 2 * ch
+ ]
+ for element_index, element in enumerate(base["elements"]):
+ box = element["box"]
+ if box is None or element["type"] not in _TEXT_TYPES:
+ continue
+ # Units are in transcript order; only this element's span can contribute.
+ first = bisect_left(valid_starts, element["start"])
+ last = bisect_right(valid_starts, element["end"])
+ element_units = [
+ (u, units[u]) for u in valid[first:last] if u not in image_units
+ ]
+ column_right = box[2]
+ if element["type"] in {"text", "list"}:
+ rights = np.array(
+ [
+ b[2]
+ for b in column_evidence
+ if abs(b[0] - box[0]) <= 2 * cw and b[2] > box[2] + cw
+ ]
+ )
+ if len(rights) >= 3:
+ groups = [rights[abs(rights - r) <= cw] for r in rights]
+ support = max(groups, key=len)
+ if len(support) >= 3:
+ column_right = float(np.median(support))
+ # Require two consecutive valid words in the added band to advance along
+ # one attention row. This guards against isolated peaks in adjacent blocks.
+ # Peak distances are grid cells; the original vertical band stays fixed.
+ if column_right > box[2]:
+ outer = [
+ lookup[u]
+ for u, (start, end) in element_units
+ if u in lookup
+ and element["start"] <= start
+ and end <= element["end"]
+ and box[2] + cw < peaks[lookup[u], 0] * cw <= column_right + cw
+ and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch
+ ]
+ coherent = any(
+ b == a + 1
+ and abs(peaks[a, 1] - peaks[b, 1]) <= 1
+ and 0 <= peaks[b, 0] - peaks[a, 0] <= 3
+ for a, b in zip(outer, outer[1:])
+ )
+ if not coherent:
+ column_right = box[2]
+ selected = [
+ lookup[u]
+ for u, (start, end) in element_units
+ if u in lookup
+ and element["start"] <= start
+ and end <= element["end"]
+ and (
+ element["type"] in {"heading", "header", "footer"}
+ or (element["start"], element["end"]) in (_rotated_spans or ())
+ or box[0] - cw <= peaks[lookup[u], 0] * cw <= column_right + cw
+ )
+ and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch
+ ]
+ # Extend paragraph and list lines through nearby transcript neighbors. Cell
+ # distances keep the rule independent of render resolution; the original
+ # vertical guard keeps recovery within the existing vertical band.
+ if selected and element["type"] in {"text", "list"}:
+ candidates = {
+ lookup[u]
+ for u, (start, end) in element_units
+ if u in lookup
+ and element["start"] <= start
+ and end <= element["end"]
+ and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch
+ }
+ accepted = set(selected)
+ changed = True
+ while changed:
+ changed = False
+ for j in sorted(candidates - accepted):
+ for neighbor in (j - 1, j + 1):
+ if (
+ neighbor not in accepted
+ or abs(peaks[j, 1] - peaks[neighbor, 1]) > 1
+ ):
+ continue
+ gap = max(
+ 0,
+ grid_boxes[j, 0] - grid_boxes[neighbor, 2],
+ grid_boxes[neighbor, 0] - grid_boxes[j, 2],
+ )
+ if gap <= 1:
+ accepted.add(j)
+ changed = True
+ break
+ selected = recover_line_tails(accepted, candidates, peaks)
+ selected = recover_short_line_tails(selected, candidates, peaks, grid_boxes)
+ if selected and element["type"] in {"text", "list"} and _rotated_spans is None:
+ selected = coherent_paragraph_words(selected, peaks, grid_boxes)
+ # Short key/value blocks can have distant right-aligned values.
+ # Require overlapping word extents on distinct rows; one isolated
+ # numeric peak cannot expand the paragraph's horizontal boundary.
+ if 4 <= len(element_units) <= 16:
+ numeric = [
+ lookup[u]
+ for u, (start, end) in element_units
+ if u in lookup
+ and lookup[u] not in selected
+ and _NUMERIC_WORD.fullmatch(answer[start:end])
+ and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch
+ and peaks[lookup[u], 0] * cw > box[2] + cw
+ ]
+ supported = [
+ j
+ for j in numeric
+ if any(
+ k != j
+ and max(grid_boxes[j, 0], grid_boxes[k, 0])
+ <= min(grid_boxes[j, 2], grid_boxes[k, 2])
+ and abs(peaks[j, 1] - peaks[k, 1]) >= 2
+ for k in numeric
+ )
+ ]
+ selected = sorted(set(selected) | set(supported))
+
+ if element["type"] in {"text", "list"}:
+ selected = recover_paragraph_opening(
+ selected, element_units, lookup, peaks, grid_boxes
+ )
+ if selected and (element["start"], element["end"]) in (_rotated_spans or ()):
+ selected = coherent_rotated_words(selected, peaks)
+ if selected and element["type"] in {"text", "list", "heading"}:
+ align_word_boxes_to_neighbor_row(
+ selected, element_units, lookup, peaks, grid_boxes, word_boxes, ch
+ )
+ align_word_boxes_to_reading_order(
+ selected, element_units, lookup, peaks, grid_boxes, word_boxes, cw
+ )
+ if selected:
+ boxes = word_boxes[selected]
+ bounds = np.r_[boxes[:, :2].min(0), boxes[:, 2:].max(0)]
+ bounds = np.clip(bounds, 0, [width, height, width, height])
+ if bounds[2] > bounds[0] and bounds[3] > bounds[1]:
+ element["box"] = np.round(bounds, 1).tolist()
+ if region_models is not None or collect_region_features:
+ anchor = np.asarray(element["box"]) / cell_scale
+ row, word_height = region_features(
+ element["type"],
+ answer[element["start"] : element["end"]],
+ anchor,
+ np.asarray(box) / cell_scale,
+ grid_boxes[selected],
+ features[selected, 0],
+ (gh, gw),
+ )
+ region_records.append(
+ {
+ "element_index": element_index,
+ "text": element_text(
+ answer, element["start"], element["end"]
+ ),
+ "features": row,
+ "anchor": anchor.tolist(),
+ "height": word_height,
+ }
+ )
+ if with_region_context and region_records:
+ for record, row in zip(
+ region_records, contextual_region_features(region_records)
+ ):
+ record["features"] = row.tolist()
+ if region_models is not None and region_records:
+ rows = np.asarray([record["features"] for record in region_records])
+ glyph_rows = None
+ if any(isinstance(model, HeadingGlyphRegionBlend) for model in region_models):
+ glyph_rows = np.column_stack(
+ [
+ rows,
+ heading_glyph_features(
+ [record["text"] for record in region_records]
+ ),
+ ]
+ )
+ residuals = np.column_stack(
+ [
+ predict(
+ model,
+ glyph_rows if isinstance(model, HeadingGlyphRegionBlend) else rows,
+ )
+ for model in region_models
+ ]
+ )
+ for record, residual in zip(region_records, residuals):
+ # Limit extrapolation to two local word heights on each edge.
+ bounds = np.clip(
+ np.asarray(record["anchor"]) + residual.clip(-2, 2) * record["height"],
+ 0,
+ [gw, gh, gw, gh],
+ )
+ if bounds[2] > bounds[0] and bounds[3] > bounds[1]:
+ base["elements"][record["element_index"]]["box"] = np.round(
+ bounds * cell_scale, 1
+ ).tolist()
+ base["elements"] = separate_table_sources(
+ answer, base["elements"], units, lookup, peaks, grid_boxes, word_boxes
+ )
+ if collect_region_features:
+ base["region_features"] = region_records
+ # Region feature records describe the original pre-refinement anchors.
+ # Orientation recovery only replaces final boxes; the private span set
+ # marks the normalized pass and prevents recursively rotating it again.
+ if _rotated_spans is None:
+ spans = vertical_text_spans(answer, capture)
+ if spans:
+ rotated = ground_cached(
+ answer,
+ rotate_attention_clockwise(capture),
+ models,
+ with_context=with_context,
+ picture_model=picture_model,
+ with_extended_context=with_extended_context,
+ region_models=region_models,
+ table_model=table_model,
+ with_region_context=with_region_context,
+ peak_model=peak_model,
+ _rotated_spans=spans,
+ )
+ lookup_boxes = {
+ (element["start"], element["end"]): element["box"]
+ for element in rotated["elements"]
+ }
+ for element in base["elements"]:
+ key = (element["start"], element["end"])
+ rotated_box = lookup_boxes.get(key)
+ if key in spans and rotated_box is not None:
+ x0, y0, x1, y1 = rotated_box
+ element["box"] = [y0, height - x1, y1, height - x0]
+ if _rotated_spans is None:
+ recover_repeated_paragraphs(answer, capture, base["elements"], units)
+ return base
diff --git a/parse_rl_utils/ocria_attention_grounding/native.py b/parse_rl_utils/ocria_attention_grounding/native.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad81f4df9d57bd027c0b9d46bbb59e984a80dbec
--- /dev/null
+++ b/parse_rl_utils/ocria_attention_grounding/native.py
@@ -0,0 +1,254 @@
+# 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.
+"""Optional native kernels; build explicitly, then set OCRIA_GROUNDING_NATIVE."""
+
+import argparse
+import ctypes
+from functools import lru_cache
+import os
+from pathlib import Path
+import subprocess
+
+import numpy as np
+
+# Matches TreeNode in native_kernels.cpp: two doubles and four 32-bit integers.
+# Flags use bit 0 for missing-go-left and bit 1 for leaves.
+TREE_NODE_DTYPE = np.dtype(
+ [
+ ("value", np.float64),
+ ("threshold", np.float64),
+ ("feature", np.int32),
+ ("left", np.int32),
+ ("right", np.int32),
+ ("flags", np.int32),
+ ],
+ align=True,
+)
+
+_LIBRARY_ENV = "OCRIA_GROUNDING_NATIVE"
+
+
+class NativeKernels:
+ """Own a trusted shared library and its typed, contiguous-array interfaces."""
+
+ def __init__(self, path: str) -> None:
+ self.library = ctypes.CDLL(path)
+ double = np.ctypeslib.ndpointer(np.float64, flags="C_CONTIGUOUS")
+ integer = np.ctypeslib.ndpointer(np.int32, flags="C_CONTIGUOUS")
+ boolean = np.ctypeslib.ndpointer(np.bool_, flags="C_CONTIGUOUS")
+ self.library.neighborhood.argtypes = [
+ ctypes.c_int,
+ ctypes.c_int,
+ double,
+ double,
+ integer,
+ integer,
+ double,
+ ]
+ self.library.pool_profiles.argtypes = [
+ ctypes.c_int,
+ ctypes.c_int,
+ double,
+ integer,
+ integer,
+ integer,
+ double,
+ double,
+ ]
+ self.library.peak_component.argtypes = [
+ ctypes.c_int,
+ ctypes.c_int,
+ boolean,
+ ctypes.c_int,
+ boolean,
+ ]
+ self.library.peak_component_bounds.argtypes = [
+ *self.library.peak_component.argtypes,
+ integer,
+ ]
+ self.library.predict_compact_trees.argtypes = [
+ ctypes.c_int,
+ ctypes.c_int,
+ double,
+ ctypes.c_int,
+ integer,
+ np.ctypeslib.ndpointer(TREE_NODE_DTYPE, flags="C_CONTIGUOUS"),
+ ctypes.c_double,
+ double,
+ ]
+ self.library.component_boxes.argtypes = [
+ ctypes.c_int,
+ ctypes.c_int,
+ boolean,
+ integer,
+ ]
+ self.library.component_boxes.restype = ctypes.c_int
+ self.library.box_maxima.argtypes = [
+ ctypes.c_int,
+ double,
+ ctypes.c_int,
+ integer,
+ double,
+ ]
+ self.library.box_maxima.restype = None
+ self.library.mass_boxes.argtypes = [
+ ctypes.c_int,
+ ctypes.c_int,
+ double,
+ ctypes.c_int,
+ double,
+ double,
+ ]
+ self.library.mass_boxes.restype = None
+ for name in (
+ "neighborhood",
+ "pool_profiles",
+ "peak_component",
+ "peak_component_bounds",
+ "predict_compact_trees",
+ ):
+ getattr(self.library, name).restype = None
+
+ def neighborhood(
+ self,
+ positions: np.ndarray,
+ lengths: list[int],
+ owners: dict[int, int],
+ valid: list[int],
+ ) -> np.ndarray:
+ """Return 19 contextual features per valid word, preserving unit indices."""
+ owner_array = np.full(len(positions), -1, dtype=np.int32)
+ for u, owner in owners.items():
+ owner_array[u] = owner
+ out = np.empty((len(valid), 19))
+ self.library.neighborhood(
+ len(positions),
+ len(valid),
+ positions,
+ np.asarray(lengths, dtype=np.float64),
+ owner_array,
+ np.asarray(valid, dtype=np.int32),
+ out,
+ )
+ return out
+
+ def pool_profiles(
+ self,
+ positions: np.ndarray,
+ owners: dict[int, int],
+ valid: list[int],
+ profiles: np.ndarray,
+ ) -> np.ndarray:
+ """Return seven pooled profile bins and a neighbor count per valid word."""
+ owner_array = np.full(len(positions), -1, dtype=np.int32)
+ for u, owner in owners.items():
+ owner_array[u] = owner
+ inverse = np.full(len(positions), -1, dtype=np.int32)
+ inverse[valid] = np.arange(len(valid), dtype=np.int32)
+ out = np.empty((len(valid), 8))
+ self.library.pool_profiles(
+ len(positions),
+ len(valid),
+ positions,
+ owner_array,
+ np.asarray(valid, dtype=np.int32),
+ inverse,
+ profiles,
+ out,
+ )
+ return out
+
+ def mass_boxes(
+ self, density: np.ndarray, quantiles: list[float]
+ ) -> list[list[float]]:
+ """Compute cell-edge mass boxes while sharing the marginal reductions."""
+ density = np.ascontiguousarray(density, dtype=np.float64)
+ levels = np.asarray(quantiles, dtype=np.float64)
+ if density.ndim != 2 or 0 in density.shape or levels.ndim != 1:
+ raise ValueError(
+ "Expected a nonempty density and one-dimensional quantiles"
+ )
+ out = np.empty((len(levels), 4))
+ self.library.mass_boxes(*density.shape, density, len(levels), levels, out)
+ return out.tolist()
+
+ def box_maxima(self, density: np.ndarray, bounds: np.ndarray) -> np.ndarray:
+ """Reduce clipped nonempty cell-edge rectangles without per-box calls."""
+ density = np.ascontiguousarray(density, dtype=np.float64)
+ bounds = np.ascontiguousarray(bounds, dtype=np.int32)
+ if density.ndim != 2 or bounds.ndim != 2 or bounds.shape[1] != 4:
+ raise ValueError("Expected a two-dimensional density and N x 4 bounds")
+ limits = np.array([density.shape[1], density.shape[0]])
+ if (
+ np.any(bounds[:, :2] < 0)
+ or np.any(bounds[:, 2:] > limits)
+ or np.any(bounds[:, 2:] <= bounds[:, :2])
+ ):
+ raise ValueError("Bounds must be clipped and nonempty")
+ out = np.empty(len(bounds))
+ self.library.box_maxima(density.shape[1], density, len(bounds), bounds, out)
+ return out
+
+ def component_boxes(self, mask: np.ndarray) -> np.ndarray:
+ """Return eight-connected component edges in row-major seed order."""
+ if mask.ndim != 2:
+ raise ValueError("Component mask must be two-dimensional")
+ mask = np.ascontiguousarray(mask, dtype=np.bool_)
+ bounds = np.empty((mask.size, 4), dtype=np.int32)
+ count = self.library.component_boxes(*mask.shape, mask, bounds)
+ return bounds[:count]
+
+ def peak_component_bounds(
+ self, mask: np.ndarray, y: int, x: int
+ ) -> tuple[np.ndarray, tuple[int, int, int, int]]:
+ """Return the peak component and exclusive cell bounds in x/y order."""
+ out = np.zeros_like(mask)
+ bounds = np.empty(4, dtype=np.int32)
+ self.library.peak_component_bounds(
+ *mask.shape, mask, int(y * mask.shape[1] + x), out, bounds
+ )
+ return out, (int(bounds[0]), int(bounds[1]), int(bounds[2]), int(bounds[3]))
+
+ def peak_component(self, mask: np.ndarray, y: int, x: int) -> np.ndarray:
+ """Flood the true peak's eight-connected component in a boolean grid."""
+ out = np.zeros_like(mask)
+ self.library.peak_component(*mask.shape, mask, int(y * mask.shape[1] + x), out)
+ return out
+
+
+@lru_cache(maxsize=1)
+def get_native() -> NativeKernels | None:
+ """Read the opt-in library path once; an invalid explicit path fails visibly."""
+ path = os.environ.get(_LIBRARY_ENV)
+ return NativeKernels(path) if path else None
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--output", required=True, type=Path)
+ parser.add_argument("--compiler", default="c++")
+ args = parser.parse_args()
+ source = Path(__file__).with_name("native_kernels.cpp")
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ # Disable fused arithmetic so feature rounding matches the NumPy reference.
+ subprocess.run(
+ [
+ args.compiler,
+ "-O3",
+ "-std=c++17",
+ "-ffp-contract=off",
+ "-shared",
+ "-fPIC",
+ str(source),
+ "-o",
+ str(args.output),
+ ],
+ check=True,
+ timeout=120,
+ )
+ print(f"Set {_LIBRARY_ENV}={args.output.resolve()}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/parse_rl_utils/ocria_attention_grounding/native_kernels.cpp b/parse_rl_utils/ocria_attention_grounding/native_kernels.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..88444e5e18446255647f96094e3ad3a9b4c80957
--- /dev/null
+++ b/parse_rl_utils/ocria_attention_grounding/native_kernels.cpp
@@ -0,0 +1,176 @@
+// 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.
+// Arrays are contiguous float64, int32, or byte booleans, owned by Python.
+// Coordinates use attention-grid cells; valid indices retain transcript positions.
+// Compile without fused arithmetic to preserve reference feature rounding.
+#include