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: 19,629 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 | # 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.
"""Candidate table/chart extents from transcript structure and sparse attention."""
from bisect import bisect_left, bisect_right
import re
from typing import Protocol
from .predict import predict
import numpy as np
from .blocks import Block
from .rectangles import mass_box, mass_boxes
from .pictures import ious
TABLE_FEATURE_VERSION = "table-candidates-v1"
TABLE_FEATURE_COUNT = 41
TABLE_SELECTION_MARGIN = 0.05
class TablePredictor(Protocol):
def predict(self, features: np.ndarray) -> np.ndarray: ...
_HINTS = (
"figure",
"chart",
"graph",
"plot",
"series",
"axis",
"reference line",
"table",
)
def table_candidates(
answer: str,
blocks: list[Block],
per: list[list[int]],
units: list[tuple[int, int]],
capture: dict,
block_index: int,
original: list[float],
) -> tuple[list[list[float]], list[list[float]]]:
"""Propose grid-cell rectangles using table words, cell alignment, and neighbors.
The first candidate preserves the original box. Chart-like transcripts can
place numeric cells throughout a plot; their pooled attention and adjacent
captions provide broader extents than a connected-word component alone.
"""
gh, gw = capture["grid"]
sp = capture["sparse_maps"]
block = blocks[block_index]
us = [
u
for u in per[block_index]
if sp["has"][u] and sp["val"][u] and max(sp["val"][u]) > 0
]
if not us:
return [], []
peak_by = {}
density = np.zeros((gh, gw))
sharp = np.zeros_like(density)
for u in us:
ix = np.asarray(sp["idx"][u])
v = np.asarray(sp["val"][u])
p = ix[v.argmax()]
peak_by[u] = (p % gw + 0.5, p // gw + 0.5)
density.flat[ix] += v / v.sum()
keep = v >= 0.3 * v.max()
sharp.flat[ix[keep]] += v[keep] / v[keep].sum()
density /= density.sum()
sharp /= sharp.sum()
peaks = np.array([peak_by[u] for u in us])
boxes = [original]
kinds = [0]
def add(b: np.ndarray | list[float], kind: int) -> None:
b = np.clip(b, 0, [gw, gh, gw, gh]).tolist()
if b[2] > b[0] and b[3] > b[1] and b not in boxes:
boxes.append(b)
kinds.append(kind)
for kind, m in [(1, density), (2, sharp)]:
for box in mass_boxes(m, [0, 0.01, 0.025, 0.05, 0.1, 0.2]):
add(box, kind)
quantiles = np.array([0, 0.01, 0.025, 0.05, 0.1])
low, high = np.quantile(peaks, [quantiles, 1 - quantiles], axis=0)
for lower, upper in zip(low, high):
bb = np.r_[lower - 0.5, upper + 0.5]
for pad in [0, 0.5, 1, 2]:
add(bb + np.array([-pad, -pad, pad, pad]), 3)
# The generated heading often represents axis/legend text of a chart.
if block_index and blocks[block_index - 1].type == "heading":
heading = []
for u in per[block_index - 1]:
if sp["has"][u] and sp["val"][u] and max(sp["val"][u]) > 0:
p = sp["idx"][u][int(np.argmax(sp["val"][u]))]
heading.append([p % gw + 0.5, p // gw + 0.5])
if heading:
joint = np.vstack([peaks, heading])
add(
np.r_[
np.quantile(joint, 0.01, axis=0) - 0.5,
np.quantile(joint, 0.99, axis=0) + 0.5,
],
4,
)
anchors = []
for direction in [-1, 1]:
anchor = None
for k in range(
block_index + direction, -1 if direction < 0 else len(blocks), direction
):
if blocks[k].type in ("image", "table"):
break
pts = []
for u in per[k]:
if sp["has"][u] and sp["val"][u] and max(sp["val"][u]) > 0:
p = sp["idx"][u][int(np.argmax(sp["val"][u]))]
pts.append([p % gw + 0.5, p // gw + 0.5])
if pts:
pts = np.array(pts)
anchor = np.r_[
np.quantile(pts, 0.05, axis=0) - 0.5,
np.quantile(pts, 0.95, axis=0) + 0.5,
]
break
anchors.append(anchor)
seed = np.array(mass_box(sharp, 0.025))
prev, nxt = anchors
top = prev[3] if prev is not None and prev[3] < seed[1] else seed[1]
bottom = nxt[1] if nxt is not None and nxt[1] > seed[3] else seed[3]
for fraction in [0.25, 0.5, 0.75, 1.0]:
b = seed.copy()
b[1] += fraction * (top - b[1])
b[3] += fraction * (bottom - b[3])
add(b, 5)
available = [a for a in anchors if a is not None]
if available:
b[0] = min(b[0], min(a[0] for a in available))
b[2] = max(b[2], max(a[2] for a in available))
add(b, 6)
# Cell alignment distinguishes a printed grid from values read off a plot.
cells = []
word_starts = [units[u][0] for u in us]
for row, tr in enumerate(
re.finditer(
r"<tr\b[^>]*>(.*?)</tr>", answer[block.start : block.end], re.I | re.S
)
):
for col, cell in enumerate(
re.finditer(r"<t[dh]\b[^>]*>(.*?)</t[dh]>", tr.group(1), re.I | re.S)
):
start = block.start + tr.start(1) + cell.start(1)
end = block.start + tr.start(1) + cell.end(1)
first = bisect_left(word_starts, start)
last = bisect_right(word_starts, end)
ps = [peak_by[u] for u in us[first:last] if units[u][1] <= end]
if ps:
cells.append([row, col, *np.median(ps, axis=0)])
structure = [0.0] * 8
if cells:
c = np.array(cells)
rows = np.unique(c[:, 0])
cols = np.unique(c[:, 1])
sx = max(1.0, np.std(c[:, 2]))
sy = max(1.0, np.std(c[:, 3]))
row_scatter = np.mean([np.std(c[c[:, 0] == r, 3]) for r in rows]) / sy
col_scatter = np.mean([np.std(c[c[:, 1] == r, 2]) for r in cols]) / sx
def corr(a: np.ndarray, b: np.ndarray) -> float:
a = a - a.mean()
b = b - b.mean()
return float(
(a * b).sum() / max(1e-9, np.sqrt((a * a).sum() * (b * b).sum()))
)
structure = [
len(rows),
len(cols),
len(cells),
row_scatter,
col_scatter,
corr(c[:, 0], c[:, 3]),
corr(c[:, 1], c[:, 2]),
sx / sy,
]
nearby = (
answer[max(0, block.start - 400) : block.start].lower()
+ " "
+ answer[block.end : block.end + 250].lower()
)
hints = [float(h in nearby) for h in _HINTS]
numeric_fraction = sum(
answer[units[u][0] : units[u][1]].replace(".", "").replace("-", "").isdigit()
for u in us
) / len(us)
features = []
for b, kind in zip(boxes, kinds):
x0, y0, x1, y1 = b
inside = (
(peaks[:, 0] >= x0)
& (peaks[:, 0] <= x1)
& (peaks[:, 1] >= y0)
& (peaks[:, 1] <= y1)
)
patch = density[int(y0) : int(np.ceil(y1)), int(x0) : int(np.ceil(x1))]
area = (x1 - x0) * (y1 - y0)
mass = float(patch.sum())
f = [
kind,
x0 / gw,
y0 / gh,
x1 / gw,
y1 / gh,
(x1 - x0) / gw,
(y1 - y0) / gh,
area / (gw * gh),
mass,
float(inside.mean()),
np.log1p(len(us)),
float(numeric_fraction),
gh,
gw,
]
f += (
structure
+ hints
+ ious(np.array([b]), np.array([original])).ravel().tolist()
+ ((np.array(b) - original) / [gw, gh, gw, gh]).tolist()
)
for anchor in anchors:
f.extend(
[0.0, 0.0, 0.0]
if anchor is None
else [1.0, (y0 - anchor[3]) / gh, (y1 - anchor[1]) / gh]
)
features.append(f)
return boxes, features
def refine_tables(
capture: dict,
answer: str,
blocks: list[Block],
per_block: list[list[int]],
units: list[tuple[int, int]],
result: dict,
model: TablePredictor,
) -> None:
"""Replace a table box only when predicted quality clears the baseline margin.
Transcript spans and table types are preserved, including charts transcribed
as HTML tables. Features use cached attention and text, with no page pixels.
"""
gh, gw = capture["grid"]
scale = np.array([capture["width"] / gw, capture["height"] / gh] * 2)
elements = {
(element["start"], element["end"]): element
for element in result["elements"]
if element["type"] == "table" and element["box"] is not None
}
for block_index, block in enumerate(blocks):
if block.type != "table":
continue
element = elements.get((block.start, block.end))
if element is None:
continue
original = (np.asarray(element["box"]) / scale).tolist()
boxes, features = table_candidates(
answer, blocks, per_block, units, capture, block_index, original
)
if not boxes:
continue
quality = predict(model, np.asarray(features))
selected = int(quality.argmax())
if quality[selected] > quality[0] + TABLE_SELECTION_MARGIN:
element["box"] = (np.asarray(boxes[selected]) * scale).tolist()
_TABLE_CELL = re.compile(r"<t[dh][^>]*>(.*?)</t[dh]>", re.S | re.I)
def coherent_table_words(
selected: list[int],
cells: list[list[int]],
boxes: np.ndarray,
peaks: np.ndarray,
) -> list[int]:
"""Drop isolated word bands while preserving support in every table cell.
Coordinates and predicted word heights use attention-grid cells. Each axis
needs a band containing 90% of the words; sparse genuine rows or columns
survive when any cell depends on them.
"""
for axis in (0, 1):
if len(selected) < 12:
break
ordered = sorted(selected, key=lambda j: peaks[j, axis])
gap = max(3.0, 3 * float(np.median(boxes[selected, 3] - boxes[selected, 1])))
bands: list[list[int]] = [[]]
for j in ordered:
if bands[-1] and peaks[j, axis] - peaks[bands[-1][-1], axis] > gap:
bands.append([])
bands[-1].append(j)
main = max(bands, key=len)
members = set(main)
if len(main) >= 0.9 * len(selected) and all(
members.intersection(cell) for cell in cells
):
selected = main
return selected
def _refine_supported_table_words(
answer: str,
elements: list[dict],
units: list[tuple[int, int]],
valid: list[int],
boxes: np.ndarray,
peaks: np.ndarray,
scale: np.ndarray,
) -> None:
"""Refine whole-table extents from supported cell words, preserving one region.
Word boxes and peaks use grid cells; element boxes and the result use pixels.
Every cell with available word predictions must have support inside the old
table bounds plus one grid cell. A cell whose predictions all lie outside
that guard preserves the old table box.
"""
starts = [units[u][0] for u in valid]
for element in elements:
if element["type"] != "table" or element["box"] is None:
continue
bounds = np.asarray(element["box"]) / scale
selected: list[int] = []
cell_groups: list[list[int]] = []
complete = True
for cell in _TABLE_CELL.finditer(answer, element["start"], element["end"]):
first = bisect_left(starts, cell.start(1))
last = bisect_right(starts, cell.end(1))
rows = [j for j in range(first, last) if units[valid[j]][1] <= cell.end(1)]
if not rows:
continue
supported = [
j
for j in rows
if bounds[0] - 1 <= peaks[j, 0] <= bounds[2] + 1
and bounds[1] - 1 <= peaks[j, 1] <= bounds[3] + 1
]
if not supported:
complete = False
break
selected.extend(supported)
cell_groups.append(supported)
if complete and len(cell_groups) >= 2:
selected = coherent_table_words(selected, cell_groups, boxes, peaks)
words = boxes[selected]
element["box"] = (
np.r_[words[:, :2].min(0), words[:, 2:].max(0)] * scale
).tolist()
# Text glyphs stop short of the table's vertical cell padding.
padding = 0.25 * float(np.median(words[:, 3] - words[:, 1])) * scale[1]
element["box"][1] -= padding
element["box"][3] += padding
_TABLE_ROW = re.compile(r"<tr\b[^>]*>(.*?)</tr>", re.S | re.I)
def refine_table_word_boxes(
answer: str,
elements: list[dict],
units: list[tuple[int, int]],
valid: list[int],
boxes: np.ndarray,
peaks: np.ndarray,
scale: np.ndarray,
) -> None:
"""Recover vertically truncated tables from ordered, multi-column cell rows.
Peaks and word boxes use grid cells; element boxes use pixels. Two HTML rows
must independently agree outside the coarse bounds before those bounds expand.
The expanded guard still requires support from every available table cell.
"""
snapshots = [
(e, list(e["box"]))
for e in elements
if e["type"] == "table" and e["box"] is not None
]
_refine_supported_table_words(answer, elements, units, valid, boxes, peaks, scale)
starts = [units[u][0] for u in valid]
for element, old in snapshots:
bounds = np.array(old) / scale
votes: list[list[tuple[list[int], float]]] = [[], []]
for row in _TABLE_ROW.finditer(answer, element["start"], element["end"]):
cells: list[list[list[int]]] = [[], []]
for cell in _TABLE_CELL.finditer(answer, row.start(1), row.end(1)):
first = bisect_left(starts, cell.start(1))
last = bisect_right(starts, cell.end(1))
indices = [
j for j in range(first, last) if units[valid[j]][1] <= cell.end(1)
]
if not indices:
continue
supported = [
j for j in indices if bounds[0] - 1 <= peaks[j, 0] <= bounds[2] + 1
]
if len(supported) < 0.9 * len(indices):
continue
for direction in (0, 1):
outside = [
j
for j in supported
if (
peaks[j, 1] < bounds[1] - 1
if direction == 0
else peaks[j, 1] > bounds[3] + 1
)
]
if len(outside) >= 0.8 * len(supported):
cells[direction].append(outside)
for direction in (0, 1):
row_cells = cells[direction]
if len(row_cells) < 2:
continue
# Separate columns must agree on a row band, allowing multiline cells.
centers = np.array(
[
np.median(peaks[word_indices], axis=0)
for word_indices in row_cells
]
)
heights = [np.ptp(peaks[word_indices, 1]) for word_indices in row_cells]
if np.ptp(centers[:, 0]) < 2 or np.ptp(centers[:, 1]) > max(
2, float(np.median(heights))
):
continue
votes[direction].append(
(
[j for word_indices in row_cells for j in word_indices],
float(np.median(centers[:, 1])),
)
)
expanded = bounds.copy()
for direction in (0, 1):
ordered_rows = votes[direction]
if len(ordered_rows) < 2 or any(
b[1] <= a[1] for a, b in zip(ordered_rows, ordered_rows[1:])
):
continue
indices = [j for word_indices, _ in ordered_rows for j in word_indices]
if direction == 0:
expanded[1] = min(expanded[1], float(peaks[indices, 1].min()))
else:
expanded[3] = max(expanded[3], float(peaks[indices, 1].max()))
if np.array_equal(expanded, bounds):
continue
guard = (expanded * scale).tolist()
candidate = {**element, "box": guard.copy()}
_refine_supported_table_words(
answer, [candidate], units, valid, boxes, peaks, scale
)
# A cell without support leaves the guard untouched; preserve the prior result.
if candidate["box"] != guard:
element["box"] = candidate["box"]
expand_chart_category_axis(answer, elements, units, valid, peaks, scale)
def expand_chart_category_axis(
answer: str,
elements: list[dict],
units: list[tuple[int, int]],
valid: list[int],
peaks: np.ndarray,
scale: np.ndarray,
) -> None:
"""Extend categorical chart bounds by half the category spacing at each end.
HTML data rows can describe bars rather than physical table rows. Require
three evenly spaced horizontal labels with aligned values above them.
Peaks use grid cells; element boxes and the updated bounds use pixels.
"""
starts = [units[u][0] for u in valid]
for element in elements:
if element["type"] != "table" or element["box"] is None:
continue
rows = list(_TABLE_ROW.finditer(answer, element["start"], element["end"]))
labels = []
values = []
for row in rows[1:]:
cells = list(_TABLE_CELL.finditer(answer, row.start(1), row.end(1)))
if len(cells) != 2:
break
centers = []
for cell in cells:
first = bisect_left(starts, cell.start(1))
last = bisect_right(starts, cell.end(1))
indices = [
j for j in range(first, last) if units[valid[j]][1] <= cell.end(1)
]
if not indices:
break
centers.append(np.median(peaks[indices], axis=0))
if len(centers) != 2:
break
labels.append(centers[0])
values.append(centers[1])
if len(labels) < 3 or len(labels) != len(rows) - 1:
continue
category_points = np.asarray(labels)
value_points = np.asarray(values)
steps = np.diff(category_points[:, 0])
if (
np.ptp(category_points[:, 1]) > 1
or np.any(steps < 2)
or steps.max() > 1.5 * steps.min()
or np.any(abs(value_points[:, 0] - category_points[:, 0]) > 2)
or np.sum(value_points[:, 1] < category_points[:, 1] - 2)
< 0.75 * len(labels)
):
continue
bounds = np.asarray(element["box"]) / scale
half_step = float(np.median(steps)) / 2
bounds[0] = min(bounds[0], category_points[0, 0] - half_step)
bounds[2] = max(bounds[2], category_points[-1, 0] + half_step)
element["box"] = (bounds * scale).tolist()
|