Image-Text-to-Text
Transformers
Joblib
Safetensors
English
qwen3_5
ocr
pdf
markdown
document-parsing
tables
charts
parsebench
autoround
w4a16
gptq
llm-compressor
compressed-tensors
quantized
vllm
conversational
Run this model with HF Jobs
Run OpenTensorLab/OCRia-1-W4A16-LLM-Compressor on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/OpenTensorLab/OCRia-1-W4A16-LLM-Compressor. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/OpenTensorLab/OCRia-1-W4A16-LLM-Compressor on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/OpenTensorLab/OCRia-1-W4A16-LLM-Compressor. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Instructions to use OpenTensorLab/OCRia-1-W4A16-LLM-Compressor with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use OpenTensorLab/OCRia-1-W4A16-LLM-Compressor with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="OpenTensorLab/OCRia-1-W4A16-LLM-Compressor") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("OpenTensorLab/OCRia-1-W4A16-LLM-Compressor") model = AutoModelForMultimodalLM.from_pretrained("OpenTensorLab/OCRia-1-W4A16-LLM-Compressor", device_map="auto") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use OpenTensorLab/OCRia-1-W4A16-LLM-Compressor with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "OpenTensorLab/OCRia-1-W4A16-LLM-Compressor" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "OpenTensorLab/OCRia-1-W4A16-LLM-Compressor", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker
docker model run hf.co/OpenTensorLab/OCRia-1-W4A16-LLM-Compressor
- SGLang
How to use OpenTensorLab/OCRia-1-W4A16-LLM-Compressor with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "OpenTensorLab/OCRia-1-W4A16-LLM-Compressor" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "OpenTensorLab/OCRia-1-W4A16-LLM-Compressor", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "OpenTensorLab/OCRia-1-W4A16-LLM-Compressor" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "OpenTensorLab/OCRia-1-W4A16-LLM-Compressor", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }' - Docker Model Runner
How to use OpenTensorLab/OCRia-1-W4A16-LLM-Compressor with Docker Model Runner:
docker model run hf.co/OpenTensorLab/OCRia-1-W4A16-LLM-Compressor
File size: 22,803 Bytes
d8db4d8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 | # 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.
"""Rectangular block estimates from attention density and transcript geometry."""
from dataclasses import dataclass
import statistics
import numpy as np
from .native import get_native
from .io import SparseWordMaps
from scipy import ndimage
from scipy.signal import find_peaks
from .blocks import Block, resolve_page_numbers
from .boxes import envelope
from .words import norm
from .rust import get_rust
@dataclass(frozen=True)
class RectangleConfig:
word_threshold: float = 0.3
text_quantile: float = 0.01
image_quantile: float = 0.05
text_y_scale: float = 1.0
x_padding: float = 0.0
y_offset: float = 0.0
image_padding: float = 0.0
image_whitespace: float = 0.0
fit_lines: bool = False
centroid: bool = True
anchor_fraction: float = 0.5
font_height: float = 1.7
connected_words: bool = False
y_inset: float = 0.0
keep_prose: bool = False
keep_tables: bool = False
line_density: bool = False
line_fill: float = 0.7
density_floor: float = 0.1
compact_image: bool = False
adaptive_anchor: bool = False
guard_expansion: float = 0.0
heading_x_scale: float = 1.0
heading_y_inset: float = 0.0
heading_y_shift: float = 0.0
furniture_x_scale: float = 1.0
furniture_y_inset: float = 0.0
furniture_y_shift: float = 0.0
text_x_scale: float = 1.0
text_y_inset: float = 0.0
component_centroid: bool = False
component_center: bool = False
centroid_radius: float = 1.0
glyph_widths: bool = False
fit_blend_x: float = 1.0
fit_blend_y: float = 1.0
image_power: float = 1.0
image_component_share: float = 0.0
image_hot_threshold: float = 0.3
image_text_suppression: float = 0.0
def mass_box(
density: np.ndarray, quantile: float, compact: bool = False
) -> list[float]:
"""Axis-wise attention quantiles in cell-edge coordinates, including edge cells."""
bounds = []
for marginal in (density.sum(axis=0), density.sum(axis=1)):
cdf = np.cumsum(marginal)
total = float(cdf[-1])
lo = int(np.searchsorted(cdf, quantile * total, side="right"))
hi = int(np.searchsorted(cdf, (1 - quantile) * total, side="left")) + 1
if compact:
prefix = np.concatenate(([0.0], cdf))
target = (1 - 2 * quantile) * total
candidates = [
(
start,
int(np.searchsorted(prefix, prefix[start] + target, side="left")),
)
for start in range(len(marginal))
if prefix[start] + target <= total
]
lo, hi = min(candidates, key=lambda pair: pair[1] - pair[0])
bounds.append((lo, min(len(marginal), hi)))
return [
float(bounds[0][0]),
float(bounds[1][0]),
float(bounds[0][1]),
float(bounds[1][1]),
]
def mass_boxes(density: np.ndarray, quantiles: list[float]) -> list[list[float]]:
"""Share reductions across attention quantiles when the native backend is enabled."""
native = get_native()
if native is not None:
return native.mass_boxes(density, quantiles)
return [mass_box(density, q) for q in quantiles]
def fitted_lines(
points: list[tuple[float, float, float]],
cw: float,
ch: float,
config: RectangleConfig,
) -> list[float] | None:
"""Fit word positions to cumulative character counts within transcript-order lines.
A peak may land partway through a word. The anchor fraction models that
offset; robust slopes and intercepts recover the line's first and last edge.
Coordinates and inferred character advances are in rendered-page pixels.
"""
groups: list[list[tuple[float, float, float]]] = []
for point in points:
if (
not groups
or abs(point[1] - statistics.median(p[1] for p in groups[-1])) > 0.8 * ch
or point[0] < groups[-1][-1][0] - 1.5 * cw
):
groups.append([])
groups[-1].append(point)
slopes = []
for group in groups:
for a, b in zip(group, group[1:]):
chars = (
(1 - config.anchor_fraction) * a[2] + 1 + config.anchor_fraction * b[2]
)
advance = (b[0] - a[0]) / chars
if 0.1 * cw <= advance <= 1.5 * cw:
slopes.append(advance)
if not slopes:
return None
default_advance = statistics.median(slopes)
lines = []
for group in groups:
local = []
for a, b in zip(group, group[1:]):
chars = (
(1 - config.anchor_fraction) * a[2] + 1 + config.anchor_fraction * b[2]
)
advance = (b[0] - a[0]) / chars
if 0.1 * cw <= advance <= 1.5 * cw:
local.append(advance)
advance = statistics.median(local) if len(local) >= 2 else default_advance
offsets, length = [], 0
for x, _, chars in group:
offsets.append(x - advance * (length + config.anchor_fraction * chars))
length += chars + 1
left = statistics.median(offsets)
if (
config.adaptive_anchor
and len(group) >= 5
and len({p[2] for p in group}) >= 3
):
chars = np.array([p[2] for p in group], dtype=float)
preceding = np.concatenate(([0.0], np.cumsum(chars[:-1] + 1)))
xs = np.array([p[0] for p in group])
design = np.column_stack((np.ones(len(group)), preceding, chars))
weights = np.ones(len(group))
for _ in range(3):
fit = np.linalg.lstsq(
design * weights[:, None], xs * weights, rcond=None
)[0]
residual = np.abs(xs - design @ fit)
scale = max(0.35 * cw, 1.5 * float(np.median(residual)))
weights = np.sqrt(np.minimum(1.0, scale / np.maximum(residual, 1e-9)))
if 0.1 * cw <= fit[1] <= 1.5 * cw and 0 <= fit[2] / fit[1] <= 1:
# Separately fitting cumulative characters and word length lets
# the observed peaks choose their own within-word anchor.
left, advance = float(fit[0]), float(fit[1])
cy = statistics.median(p[1] for p in group) + config.y_offset * ch
h = max(0.5 * ch, min(3 * ch, config.font_height * advance))
lines.append([left, cy - h / 2, left + advance * (length - 1), cy + h / 2])
return envelope(lines)
def rectangle_boxes(
size: tuple[int, int],
answer: str,
blocks: list[Block],
units: list[tuple[int, int]],
per_block: list[list[int]],
maps: np.ndarray | SparseWordMaps,
grid: tuple[int, int],
has: np.ndarray,
config: RectangleConfig,
) -> dict:
"""Fit one rectangle per emitted block using only attention and text.
Normalize each word's retained attention before pooling so a few confident
words cannot dominate the block. Pictures retain their own spatial density.
No source pixels, PDF text layer, detector, or ground-truth boxes are read.
"""
width, height = size
gh, gw = grid
cw, ch = width / gw, height / gh
# Reuse one peak scan for occupancy, word support, and the coarse guard.
if isinstance(maps, SparseWordMaps):
peaks, maxima = maps.peaks, maps.maxima
else:
peaks = (
maps.reshape(len(maps), -1).argmax(axis=1)
if len(maps)
else np.array([], dtype=np.int64)
)
maxima = maps.reshape(len(maps), gh * gw)[np.arange(len(maps)), peaks]
text_occupancy = np.zeros(grid, dtype=float)
if config.image_text_suppression:
for block, indices in zip(blocks, per_block):
if block.type in ("image", "table"):
continue
for u in indices:
if has[u] and maxima[u] > 0:
text_occupancy.flat[int(peaks[u])] = 1
text_occupancy = ndimage.maximum_filter(text_occupancy, size=3)
# The coarse guard uses the same 0.3-threshold connected word support.
# Cache cell bounds locally so that pass need not relabel each word map.
support_boxes: dict[int, tuple[int, int, int, int]] = {}
native = get_native()
reuse_support = config.connected_words and config.word_threshold == 0.3
rust = get_rust()
fused_density = (
rust is not None
and reuse_support
and (
isinstance(maps, SparseWordMaps)
or (maps.dtype == np.float32 and maps.flags.c_contiguous)
)
and not config.component_centroid
and not config.component_center
)
boxes: list[list[float] | None] = []
for block, indices in zip(blocks, per_block):
batch = None
if (
fused_density
and isinstance(maps, SparseWordMaps)
and block.type != "image"
and config.centroid_radius == 1
):
indices = [u for u in indices if has[u] and maxima[u] > 0]
density, batch_bounds, batch_centers = rust.add_components(
[maps.indices[u] for u in indices],
[maps.values[u] for u in indices],
peaks[indices],
grid,
)
batch = {
u: (tuple(int(v) for v in b), c)
for u, b, c in zip(indices, batch_bounds, batch_centers)
}
else:
density = np.zeros(grid, dtype=np.float64)
points = []
for u in indices:
if not has[u] or maxima[u] <= 0:
continue
m = None if batch is not None else maps[u]
if block.type == "image":
density += m / m.sum()
continue
if fused_density:
if batch is not None:
y, x = divmod(int(peaks[u]), gw)
bounds, center = batch[u]
else:
y, x, bounds, center = rust.add_component(m, density, int(peaks[u]))
support_boxes[u] = bounds
else:
y, x = divmod(int(peaks[u]), gw)
mask = m >= config.word_threshold * maxima[u]
if config.connected_words:
if native is not None and mask[y, x]:
mask, bounds = native.peak_component_bounds(mask, y, x)
if reuse_support:
support_boxes[u] = bounds
else:
labels, _ = ndimage.label(mask, structure=np.ones((3, 3)))
mask = labels == labels[y, x]
if reuse_support and u not in support_boxes:
yy, xx = np.nonzero(mask)
support_boxes[u] = (
int(xx.min()),
int(yy.min()),
int(xx.max()) + 1,
int(yy.max()) + 1,
)
selected = np.where(mask, m, 0)
total = selected.sum()
if u in support_boxes:
# Preserve the full-map reduction order, but normalize and add
# only the nonzero component's bounding rectangle.
bx0, by0, bx1, by1 = support_boxes[u]
density[by0:by1, bx0:bx1] += selected[by0:by1, bx0:bx1] / total
else:
density += selected / total
px, py = x + 0.5, y + 0.5
if config.centroid and fused_density and config.centroid_radius == 1:
px, py = center
elif config.centroid:
radius = int(config.centroid_radius)
y0, y1, x0, x1 = (
max(0, y - radius),
min(gh, y + radius + 1),
max(0, x - radius),
min(gw, x + radius + 1),
)
local = m[y0:y1, x0:x1]
px = float(np.dot(local.sum(0), np.arange(x0, x1) + 0.5) / local.sum())
py = float(np.dot(local.sum(1), np.arange(y0, y1) + 0.5) / local.sum())
if config.component_centroid:
px = float(
np.dot(selected.sum(0), np.arange(gw) + 0.5) / selected.sum()
)
py = float(
np.dot(selected.sum(1), np.arange(gh) + 0.5) / selected.sum()
)
if config.component_center:
yy, xx = np.nonzero(selected)
px, py = (
(float(xx.min() + xx.max()) + 1) / 2,
(float(yy.min() + yy.max()) + 1) / 2,
)
start, end = units[u]
word = norm(answer[start:end])
chars = (
sum(0.6 if c in "iljtf1" else 1.4 if c in "mw" else 1.0 for c in word)
if config.glyph_widths
else len(word)
)
points.append((px * cw, py * ch, max(1.0, float(chars))))
if not density.any():
boxes.append(None)
continue
q = config.image_quantile if block.type == "image" else config.text_quantile
if block.type == "image":
peak = np.unravel_index(int(density.argmax()), grid)
labels, _ = ndimage.label(
density >= config.image_hot_threshold * density.max(),
structure=np.ones((3, 3)),
)
core = labels == labels[peak]
if config.image_text_suppression:
# Preserve the image's strongest connected region; downweight
# distant attention that lands on separately emitted text.
density = density / (
1 + config.image_text_suppression * text_occupancy * ~core
)
if config.image_power != 1:
density = (density / density.max()) ** config.image_power
share = float(density[core].sum() / density.sum())
if config.image_component_share and share >= config.image_component_share:
density = np.where(core, density, 0)
q = 0.0
cell_box = mass_box(
density, q, compact=config.compact_image and block.type == "image"
)
box = [cell_box[0] * cw, cell_box[1] * ch, cell_box[2] * cw, cell_box[3] * ch]
if block.type != "image":
if config.fit_lines and block.type != "table":
box = fitted_lines(points, cw, ch, config) or box
else:
cy = (box[1] + box[3]) / 2 + config.y_offset * ch
half_height = (box[3] - box[1]) * config.text_y_scale / 2
box[1], box[3] = cy - half_height, cy + half_height
if config.line_density and block.type != "table":
profile = density.sum(axis=1)
peaks, _ = find_peaks(
np.pad(profile, (1, 1)), height=config.density_floor * profile.max()
)
rows = peaks - 1
rows = rows[(rows >= cell_box[1]) & (rows < cell_box[3])]
if len(rows):
pitch = float(np.median(np.diff(rows))) if len(rows) > 1 else 2.0
glyph_height = max(0.5, min(3.0, config.line_fill * pitch)) * ch
box[1] = (rows[0] + 0.5 + config.y_offset) * ch - glyph_height / 2
box[3] = (rows[-1] + 0.5 + config.y_offset) * ch + glyph_height / 2
box[0] -= config.x_padding * cw
box[2] += config.x_padding * cw
inset = min(config.y_inset * ch, 0.45 * (box[3] - box[1]))
box[1] += inset
box[3] -= inset
else:
box = [
box[0] - config.image_padding * cw,
box[1] - config.image_padding * ch,
box[2] + config.image_padding * cw,
box[3] + config.image_padding * ch,
]
boxes.append(box)
if config.image_whitespace:
# Only text entirely outside the seed rectangle can bound its expansion;
# chart labels inside the image must not clip the picture.
text_boxes = [
box
for b, box in zip(blocks, boxes)
if box is not None and b.type in ("text", "heading", "list")
]
for block, box in zip(blocks, boxes):
if block.type != "image" or box is None:
continue
x0, y0, x1, y1 = box
left, top, right, bottom = 0.0, 0.0, float(width), float(height)
for text in text_boxes:
if min(x1, text[2]) > max(x0, text[0]):
if text[3] <= y0:
top = max(top, text[3])
elif text[1] >= y1:
bottom = min(bottom, text[1])
if min(y1, text[3]) > max(y0, text[1]):
if text[2] <= x0:
left = max(left, text[2])
elif text[0] >= x1:
right = min(right, text[0])
f = config.image_whitespace
box[:] = [
x0 + f * (left - x0),
y0 + f * (top - y0),
x1 + f * (right - x1),
y1 + f * (bottom - y1),
]
for i, box in enumerate(boxes):
if box is None:
continue
box[:] = [
float(np.clip(v, 0, width if axis % 2 == 0 else height))
for axis, v in enumerate(box)
]
if box[2] <= box[0] or box[3] <= box[1]:
boxes[i] = None
pieces = [Block(b.type, b.start, b.end) for b in blocks]
resolve_page_numbers(pieces, boxes, height)
elements = [
{
"type": b.type,
"start": b.start,
"end": b.end,
"box": None if box is None else [round(v, 1) for v in box],
}
for b, box in zip(pieces, boxes)
]
if config.keep_prose or config.keep_tables or config.guard_expansion:
from .coarse import attention_boxes
prose = (
{"text", "list", "table", "code", "formula"}
if config.keep_prose
else ({"table"} if config.keep_tables else set())
)
guarded = (
{"text", "list", "heading", "header", "footer", "code", "formula"}
if config.guard_expansion
else set()
)
selected = [
(b, indices)
for b, indices in zip(blocks, per_block)
if b.type in prose | guarded
]
coarse = attention_boxes(
size,
[b for b, _ in selected],
units,
[indices for _, indices in selected],
maps,
grid,
has,
support=True,
answer=answer,
support_boxes=support_boxes,
peak_indices=peaks,
)
kept = []
for element in elements:
if element["type"] in prose:
continue
alternatives = [
e
for e in coarse["elements"]
if e["box"] is not None
and e["type"] == element["type"]
and e["start"] >= element["start"]
and e["end"] <= element["end"]
]
if element["type"] in guarded and alternatives:
support_box = envelope([e["box"] for e in alternatives])
box = element["box"]
replace = box is None or len(alternatives) > 1
if box is not None:
sw, sh = (
support_box[2] - support_box[0],
support_box[3] - support_box[1],
)
overlap = max(
0.0, min(box[2], support_box[2]) - max(box[0], support_box[0])
) * max(
0.0, min(box[3], support_box[3]) - max(box[1], support_box[1])
)
replace |= (
box[2] - box[0] > config.guard_expansion * sw
or box[3] - box[1] > config.guard_expansion * sh
or overlap < 0.5 * sw * sh
)
# Preserve separately supported columns and reject extrapolation
# far beyond the words that the attention-only baseline retained.
if replace:
kept.extend(alternatives)
continue
element["box"] = [
round(f * v + (1 - f) * support_box[axis], 1)
for axis, v in enumerate(box)
for f in [
config.fit_blend_x if axis % 2 == 0 else config.fit_blend_y
]
]
kept.append(element)
elements = kept + [e for e in coarse["elements"] if e["type"] in prose]
elements.sort(key=lambda e: e["start"])
for element in elements:
box = element["box"]
if box is None:
continue
if element["type"] == "heading":
x_scale, inset, shift = (
config.heading_x_scale,
config.heading_y_inset,
config.heading_y_shift,
)
elif element["type"] in ("header", "footer"):
x_scale, inset, shift = (
config.furniture_x_scale,
config.furniture_y_inset,
config.furniture_y_shift,
)
elif element["type"] in ("text", "list"):
x_scale, inset, shift = config.text_x_scale, config.text_y_inset, 0.0
else:
continue
# Correct outer-edge uncertainty in cell units. Fixed edge trimming
# preserves the interior line spacing of multi-line paragraphs.
cx = (box[0] + box[2]) / 2
half_width = (box[2] - box[0]) * x_scale / 2
trim = min(inset * ch, 0.4 * (box[3] - box[1]))
adjusted = [
cx - half_width,
box[1] + trim + shift * ch,
cx + half_width,
box[3] - trim + shift * ch,
]
adjusted = [
round(float(np.clip(v, 0, width if axis % 2 == 0 else height)), 1)
for axis, v in enumerate(adjusted)
]
if adjusted[2] > adjusted[0] and adjusted[3] > adjusted[1]:
element["box"] = adjusted
return {"width": width, "height": height, "grid": list(grid), "elements": elements}
|