Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions scripts/benchmark_xycut_projections.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import argparse
import ast
import gc
import json
import statistics
import subprocess
import time
from pathlib import Path

import numpy as np
from numba import njit

from unstructured.documents.coordinates import PixelSpace
from unstructured.documents.elements import CoordinatesMetadata, ElementMetadata, Text
from unstructured.partition.utils import xycut
from unstructured.partition.utils.sorting import sort_page_elements

parser = argparse.ArgumentParser(
description="Compare compiled XY-cut projections and public page sorting."
)
parser.add_argument(
"--baseline-ref", required=True, help="Git revision to compare with the working tree"
)
args = parser.parse_args()
repository = Path(__file__).resolve().parents[1]
proposed = xycut.projection_by_bboxes
source = subprocess.check_output(
[
"git",
"-C",
str(repository),
"show",
f"{args.baseline_ref}:unstructured/partition/utils/xycut.py",
],
text=True,
)
function = next(
node
for node in ast.parse(source).body
if isinstance(node, ast.FunctionDef) and node.name == "projection_by_bboxes"
)
function.decorator_list = []
namespace = {"np": np}
exec(
compile(ast.Module(body=[function], type_ignores=[]), "<baseline-projection>", "exec"),
namespace,
)
baseline = njit(namespace["projection_by_bboxes"])


def paired(label, call, check):
outputs = []
times = {"base": [], "fixed": []}
for index in range(9):
for name, function in (
[("base", baseline), ("fixed", proposed)]
if index % 2 == 0
else [("fixed", proposed), ("base", baseline)]
):
xycut.projection_by_bboxes = function
gc.collect()
started = time.perf_counter()
output = call(function)
elapsed = (time.perf_counter() - started) * 1000
if index > 1:
times[name].append(elapsed)
outputs.append(check(output))
assert all(value == outputs[0] for value in outputs)
print(
json.dumps(
{
"case": label,
"median_ms": {name: statistics.median(values) for name, values in times.items()},
"samples": times,
}
),
flush=True,
)


datasets = {}
for count, width in [(20, 2000), (500, 2000), (5000, 4000)]:
datasets[f"overlap-{count}-{width}"] = np.array(
[[index % 30, index % 50, width - index % 30, 100 + index % 50] for index in range(count)]
)
datasets["two-columns-600"] = np.array(
[[(i % 2) * 1000, (i // 2) * 30, (i % 2) * 1000 + 800, (i // 2) * 30 + 20] for i in range(600)]
)
datasets["sparse-20"] = np.array(
[[i * 1000, i * 1000, i * 1000 + 20, i * 1000 + 20] for i in range(20)]
)
for label, boxes in datasets.items():
paired(f"projection-{label}", lambda f: f(boxes, 0), lambda out: out.tolist())
elements = [
Text(
str(index),
metadata=ElementMetadata(
coordinates=CoordinatesMetadata(
((x0, y0), (x0, y1), (x1, y1), (x1, y0)), PixelSpace(20000, 20000)
)
),
)
for index, (x0, y0, x1, y1) in enumerate(boxes)
]
for direction in ("x", "y"):
paired(
f"sort-page-{label}-{direction}",
lambda _: sort_page_elements(elements, xy_cut_primary_direction=direction),
lambda out: [e.text for e in out],
)
xycut.projection_by_bboxes = proposed
76 changes: 76 additions & 0 deletions test_unstructured/partition/utils/test_xycut_projection_work.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import builtins

import numpy as np
import pytest

from unstructured.documents.coordinates import PixelSpace
from unstructured.documents.elements import CoordinatesMetadata, ElementMetadata, Text
from unstructured.partition.utils import xycut
from unstructured.partition.utils.sorting import sort_page_elements


def pixel_projection(boxes, axis):
result = np.zeros(np.max(boxes[:, axis::2]), dtype=np.int64)
for box in boxes:
for position in range(box[axis], box[axis + 2]):
result[position] += 1
return result


@pytest.mark.parametrize("axis", [0, 1])
@pytest.mark.parametrize("dtype", [np.int32, np.int64])
def test_projection_matches_pixel_counts_for_seeded_and_degenerate_boxes(axis, dtype):
random = np.random.default_rng(48219)
cases = [
[[0, 0, 0, 0]],
[[4, 4, 4, 4]],
[[0, 0, 10, 10], [10, 10, 20, 20]],
[[5, 6, 3, 2], [0, 0, 10, 10]],
[[-3, -2, 3, 2], [0, 0, 10, 10]],
]
cases.extend(random.integers(0, 120, size=(30, 4)) for _ in range(100))
for values in cases:
boxes = np.asarray(values, dtype=dtype)
before = boxes.copy()
np.testing.assert_array_equal(
xycut.projection_by_bboxes(boxes, axis), pixel_projection(boxes, axis)
)
np.testing.assert_array_equal(boxes, before)


@pytest.mark.parametrize("axis", [0, 1])
def test_dense_projection_work_is_bounded_by_boxes_and_axis_length(monkeypatch, axis):
boxes = np.tile(np.array([0, 0, 2000, 2000]), (100, 1))
iterations = 0

def counted_range(*args):
nonlocal iterations
values = builtins.range(*args)
iterations += len(values)
return values

monkeypatch.setattr(xycut, "range", counted_range, raising=False)
# The Python body measures deterministic work; benchmarks exercise the compiled path.
result = xycut.projection_by_bboxes.py_func(boxes, axis)
np.testing.assert_array_equal(result, np.full(2000, 100))
assert iterations <= 3 * (len(boxes) + len(result))


@pytest.mark.parametrize("direction", ["x", "y"])
def test_public_page_sort_keeps_column_order_and_original_elements(direction):
boxes = [(0, 0, 90, 20), (100, 0, 190, 20), (0, 40, 90, 60), (100, 40, 190, 60)]
elements = []
for index in [3, 1, 2, 0]:
x0, y0, x1, y1 = boxes[index]
metadata = ElementMetadata(
coordinates=CoordinatesMetadata(
((x0, y0), (x0, y1), (x1, y1), (x1, y0)), PixelSpace(200, 100)
)
)
elements.append(Text(str(index), metadata=metadata))
result = sort_page_elements(elements, xy_cut_primary_direction=direction)
assert [element.text for element in result] == (
["0", "2", "1", "3"] if direction == "x" else ["0", "1", "2", "3"]
)
assert {id(element) for element in result} == {id(element) for element in elements}
assert [element.text for element in elements] == ["3", "1", "2", "0"]
31 changes: 29 additions & 2 deletions unstructured/partition/utils/xycut.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,38 @@ def projection_by_bboxes(boxes: np.ndarray, axis: int) -> np.ndarray:
assert axis in [0, 1]
length = np.max(boxes[:, axis::2])
res = np.zeros(length, dtype=np.int64)
if boxes.shape[0] == 1:
for j in range(boxes[0, axis], boxes[0, axis + 2]):
res[j] += 1
return res
covered_pixels = 0
has_negative = False
for i in range(boxes.shape[0]):
start = boxes[i, axis]
end = boxes[i, axis + 2]
for j in range(start, end):
res[j] += 1
has_negative = has_negative or start < 0 or end < 0
covered_pixels += max(0, end - start)

# Sparse projections cost less to fill directly. Retain the original negative-index
# behavior for direct callers; page sorting supplies nonnegative coordinates.
if has_negative or covered_pixels <= length:
for i in range(boxes.shape[0]):
for j in range(boxes[i, axis], boxes[i, axis + 2]):
res[j] += 1
return res

# Mark interval boundaries, then accumulate once instead of visiting every pixel
# covered by every overlapping box. The final endpoint is outside the output.
for i in range(boxes.shape[0]):
start = boxes[i, axis]
end = boxes[i, axis + 2]
if start >= end:
continue
res[start] += 1
if end < length:
res[end] -= 1
for j in range(1, length):
res[j] += res[j - 1]
return res


Expand Down
Loading