Spaces:
Runtime error
Runtime error
Deploy 6ff88c6: PlotQA benchmark and accuracy fixes (without docs images)
Browse files- EVAL_LOG.md +50 -0
- README.md +38 -7
- plotscribe/axes.py +94 -5
- plotscribe/export.py +16 -2
- plotscribe/extract_line.py +28 -4
- plotscribe/pipeline.py +124 -14
- plotscribe/series.py +37 -1
- pyproject.toml +1 -1
- tests/bench_plotqa.py +168 -0
- tests/metrics.py +24 -0
- tests/plot_progress.py +177 -0
EVAL_LOG.md
CHANGED
|
@@ -144,3 +144,53 @@ Dropped scikit-learn (unused) and scikit-image (peaks + watershed replaced with
|
|
| 144 |
SciPy/OpenCV; scatter points on 12 clean charts: 950 vs 949 before). Added a
|
| 145 |
FastAPI upload page (`plotscribe/web.py`), Dockerfile, pytest suite (31 tests,
|
| 146 |
including the clean-chart < 1% target) and `tests/eval_real.py`.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
SciPy/OpenCV; scatter points on 12 clean charts: 950 vs 949 before). Added a
|
| 145 |
FastAPI upload page (`plotscribe/web.py`), Dockerfile, pytest suite (31 tests,
|
| 146 |
including the clean-chart < 1% target) and `tests/eval_real.py`.
|
| 147 |
+
|
| 148 |
+
## Stage 8 — public benchmark (PlotQA) and fixes
|
| 149 |
+
|
| 150 |
+
Benchmark: Hugging Face `martinsinnona/plotqa` (PlotQA images + plotted values,
|
| 151 |
+
single series; line, dot and bar charts rendered by Bokeh). Tuned on the 100-chart
|
| 152 |
+
test split, then checked on 300 unseen charts from the train split, comparing with
|
| 153 |
+
the previous commit (`18b6371`) run on the same charts. Figure: `docs/progress.png`
|
| 154 |
+
(`python -m tests.plot_progress`).
|
| 155 |
+
|
| 156 |
+
| held-out PlotQA (287 scoreable) | before | after |
|
| 157 |
+
|---|---|---|
|
| 158 |
+
| RNSS | 84.4 | 97.3 |
|
| 159 |
+
| point recall | 50% | 91% |
|
| 160 |
+
| charts within 1% median error | 54% | 93% |
|
| 161 |
+
| status ok | 4% | 93% |
|
| 162 |
+
| silent failures | 4.2% | 4.2% |
|
| 163 |
+
|
| 164 |
+
Failures found and fixed (in order of impact):
|
| 165 |
+
1. Rotated (90°) x tick labels were OCR'd upright -> garbage categories. Fix:
|
| 166 |
+
detect vertical text (glyph shape, label shape vs. the upright y-label glyph
|
| 167 |
+
size, and vertical stacking), group glyphs vertically, OCR the crop turned
|
| 168 |
+
+/-90° (direction chosen per axis by OCR score).
|
| 169 |
+
2. With tiny tick fonts the rotated y-axis *title* sat next to the tick labels and
|
| 170 |
+
its letters became dozens of fake labels -> y axis "categorical". Fix: remove
|
| 171 |
+
long vertical glyph runs before choosing the label column.
|
| 172 |
+
3. Fine dotted lines were deleted as specks. Fix: keep many small components of
|
| 173 |
+
consistent size.
|
| 174 |
+
4. Lines sampled at the tick positions produced noisy RDP vertices. Fix: coarser
|
| 175 |
+
tolerance for dotted lines; when every corner sits on an x tick, report values
|
| 176 |
+
at the ticks (x = the tick's own label value).
|
| 177 |
+
5. Evenly spaced but non-consecutive years (1990, 1991, 1996, ...) were fitted as a
|
| 178 |
+
numeric axis with half the labels rejected. Fix: increasing integer x labels that
|
| 179 |
+
are not linear in position become categories.
|
| 180 |
+
6. Bar outlines in a different colour became extra series. Fix: drop colour
|
| 181 |
+
clusters that are thin and only border another series.
|
| 182 |
+
7. Scatter on a categorical x axis wrote pixel positions into the `category` column
|
| 183 |
+
(export bug).
|
| 184 |
+
8. Data outside the axis range is clipped by the frame (frequent in PlotQA). New
|
| 185 |
+
check: a line that leaves the plot area and comes back, or several bars ending at
|
| 186 |
+
the frame, lowers the status to `low_confidence`.
|
| 187 |
+
|
| 188 |
+
Regressions found and fixed along the way: the rotation cue misfired on low-res
|
| 189 |
+
JPEGs with touching letters (wide upright words) and the categorical fallback fired
|
| 190 |
+
on log/noisy y axes; both were restricted. Synthetic results after this stage:
|
| 191 |
+
clean unchanged (0.11% median error, 0 silent failures); perturbed silent failures
|
| 192 |
+
8% -> 6.5%, series count 86% -> 88%, status ok 57.5% -> 55%.
|
| 193 |
+
|
| 194 |
+
Remaining: held-out silent failures (4.2%) are mostly lines whose data leaves the
|
| 195 |
+
plotted range at one end only (indistinguishable from a maximum on the frame), and
|
| 196 |
+
bars 1-3 px tall that cannot be measured.
|
README.md
CHANGED
|
@@ -115,16 +115,47 @@ python -m tests.eval_real # charts in
|
|
| 115 |
pytest # includes the CI accuracy target
|
| 116 |
```
|
| 117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
| 200 charts, auto type | clean (default matplotlib PNG) | perturbed (styles, fonts, 50–150 dpi, JPEG q40–95, log, dashes, markers) |
|
| 119 |
|---|---|---|
|
| 120 |
-
| chart type correct | 100% |
|
| 121 |
-
| series count correct | 99% |
|
| 122 |
| point recall | 98.7% | 79% |
|
| 123 |
| median of per-chart median error | **0.11%** | 0.26% |
|
| 124 |
-
| p90 of per-chart median error | 0.24% |
|
| 125 |
-
| status `ok` | 100% |
|
| 126 |
| abstained (`uncalibrated`/`failed`) | 0% | 21% |
|
| 127 |
-
| **silent failures** (status `ok` but median error > 2% or recall < 50%) | **0%** |
|
| 128 |
|
| 129 |
The CI target (median error < 1% on clean charts) is met for every chart type.
|
| 130 |
On clean charts the worst single bar value is 0.9% off (150 bar charts); for lines
|
|
@@ -132,11 +163,11 @@ the per-chart worst point has a median of 1.5% (at occluded crossings).
|
|
| 132 |
|
| 133 |
## Known limitations
|
| 134 |
|
| 135 |
-
- **Perturbed styles**: 21% of perturbed charts abstain and
|
| 136 |
wrong. Weak spots: fivethirtyeight (no spines, panel = figure colour),
|
| 137 |
frameless legends drawn over data, bmh/classic low-resolution JPEGs, and
|
| 138 |
heavily overlapping category labels.
|
| 139 |
-
- Not yet supported: horizontal bars, area charts,
|
| 140 |
as dates (they are treated as categories), dual y axes, pie charts, 3-D charts.
|
| 141 |
- A series needs its own colour; two series of the same colour (e.g. differing only
|
| 142 |
by dash pattern) are merged. Very light colours (ΔE < ~15 from the background)
|
|
|
|
| 115 |
pytest # includes the CI accuracy target
|
| 116 |
```
|
| 117 |
|
| 118 |
+

|
| 119 |
+
|
| 120 |
+
### Public benchmark: PlotQA
|
| 121 |
+
|
| 122 |
+
[PlotQA](https://github.com/NiteshMethani/PlotQA) charts are real-world data (World
|
| 123 |
+
Bank etc.) rendered with Bokeh: line, dot and bar charts with rotated tick labels,
|
| 124 |
+
tiny fonts and scientific-notation axes, and no printed values. The copy used is
|
| 125 |
+
the Hugging Face dataset `martinsinnona/plotqa` (single-series charts with their
|
| 126 |
+
plotted values). RNSS is the chart-to-table metric of ChartQA/DePlot (100 = all
|
| 127 |
+
numbers matched exactly).
|
| 128 |
+
|
| 129 |
+
```bash
|
| 130 |
+
python -m tests.bench_plotqa --split test # 100 charts (used for tuning)
|
| 131 |
+
python -m tests.bench_plotqa --split train --n 300 # held-out check
|
| 132 |
+
python -m tests.plot_progress # redraws docs/progress.png
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
| PlotQA | test split (92 scoreable) | held-out (287 scoreable) before → after |
|
| 136 |
+
|---|---|---|
|
| 137 |
+
| RNSS | 99.5 | 84.4 → **97.3** |
|
| 138 |
+
| point recall | 97% | 50% → **91%** |
|
| 139 |
+
| charts with median error < 1% | 100% | 54% → **93%** |
|
| 140 |
+
| status `ok` | 93% | 4% → **93%** |
|
| 141 |
+
| silent failures | 1.1% | 4.2% → 4.2% |
|
| 142 |
+
|
| 143 |
+
Charts whose ground truth is degenerate (all values equal, e.g. rounded to 0.0 in
|
| 144 |
+
the dataset) are excluded. Most remaining held-out failures are PlotQA renders
|
| 145 |
+
whose data lies outside the plotted y range (cut off by the frame).
|
| 146 |
+
|
| 147 |
+
### Synthetic charts
|
| 148 |
+
|
| 149 |
| 200 charts, auto type | clean (default matplotlib PNG) | perturbed (styles, fonts, 50–150 dpi, JPEG q40–95, log, dashes, markers) |
|
| 150 |
|---|---|---|
|
| 151 |
+
| chart type correct | 100% | 91% |
|
| 152 |
+
| series count correct | 99% | 88% |
|
| 153 |
| point recall | 98.7% | 79% |
|
| 154 |
| median of per-chart median error | **0.11%** | 0.26% |
|
| 155 |
+
| p90 of per-chart median error | 0.24% | 9.2% |
|
| 156 |
+
| status `ok` | 100% | 55% |
|
| 157 |
| abstained (`uncalibrated`/`failed`) | 0% | 21% |
|
| 158 |
+
| **silent failures** (status `ok` but median error > 2% or recall < 50%) | **0%** | 6.5% |
|
| 159 |
|
| 160 |
The CI target (median error < 1% on clean charts) is met for every chart type.
|
| 161 |
On clean charts the worst single bar value is 0.9% off (150 bar charts); for lines
|
|
|
|
| 163 |
|
| 164 |
## Known limitations
|
| 165 |
|
| 166 |
+
- **Perturbed styles**: 21% of perturbed charts abstain and 6.5% are silently
|
| 167 |
wrong. Weak spots: fivethirtyeight (no spines, panel = figure colour),
|
| 168 |
frameless legends drawn over data, bmh/classic low-resolution JPEGs, and
|
| 169 |
heavily overlapping category labels.
|
| 170 |
+
- Not yet supported: horizontal bars, area charts, labels at angles other than 0°/90°, dates parsed
|
| 171 |
as dates (they are treated as categories), dual y axes, pie charts, 3-D charts.
|
| 172 |
- A series needs its own colour; two series of the same colour (e.g. differing only
|
| 173 |
by dash pattern) are merged. Very light colours (ΔE < ~15 from the background)
|
plotscribe/axes.py
CHANGED
|
@@ -477,8 +477,69 @@ def char_height(comps: list[BBox]) -> float:
|
|
| 477 |
return float(np.median(hs)) if hs else 10.0
|
| 478 |
|
| 479 |
|
| 480 |
-
def
|
| 481 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
h, w = ink.shape
|
| 483 |
b = ax.plot_box
|
| 484 |
start = b.y1 + ax.x_tick_len + ax.line_thickness + 1
|
|
@@ -491,17 +552,44 @@ def x_label_boxes(ink: np.ndarray, ax: AxesResult) -> tuple[list[BBox], float]:
|
|
| 491 |
# Drop thin marks hanging from the axis: tick remnants.
|
| 492 |
comps = [c for c in comps if not (c.y0 <= region.y0 + 0.5 and c.w <= 2 * ax.line_thickness + 1)]
|
| 493 |
if not comps:
|
| 494 |
-
return [], 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 495 |
ch = char_height(comps)
|
| 496 |
words = group_words(comps, ch)
|
| 497 |
if not words:
|
| 498 |
-
return [], ch
|
| 499 |
top = min(wd.y0 for wd in words)
|
| 500 |
med_h = float(np.median([wd.h for wd in words]))
|
| 501 |
row = [wd for wd in words if wd.y0 <= top + 0.7 * med_h]
|
| 502 |
row_comps = [c for c in comps if any(c.intersects(wd) for wd in row)]
|
| 503 |
row = split_at_ticks(row, row_comps, ax.x_ticks)
|
| 504 |
-
return sorted(row, key=lambda bb: bb.cx), ch
|
| 505 |
|
| 506 |
|
| 507 |
def split_at_ticks(words: list[BBox], comps: list[BBox], ticks: list[float]) -> list[BBox]:
|
|
@@ -536,6 +624,7 @@ def y_label_boxes(ink: np.ndarray, ax: AxesResult) -> tuple[list[BBox], float]:
|
|
| 536 |
region = BBox(0.0, max(0.0, b.y0 - 0.05 * h), b.x0 - ax.line_thickness / 2 - 1, min(float(h), b.y1 + 0.05 * h))
|
| 537 |
comps = [c for c in glyph_components(ink, region) if c.x0 < end - 1]
|
| 538 |
comps = [c for c in comps if not (c.x1 >= region.x1 - 0.5 and c.h <= 2 * ax.line_thickness + 1)]
|
|
|
|
| 539 |
if not comps:
|
| 540 |
return [], 0.0
|
| 541 |
ch = char_height(comps)
|
|
|
|
| 477 |
return float(np.median(hs)) if hs else 10.0
|
| 478 |
|
| 479 |
|
| 480 |
+
def vertical_runs(comps: list[BBox], gap: float) -> list[list[BBox]]:
|
| 481 |
+
"""Group glyphs stacked vertically (rotated text): overlapping in x, gap <= ``gap``."""
|
| 482 |
+
n = len(comps)
|
| 483 |
+
parent = list(range(n))
|
| 484 |
+
|
| 485 |
+
def find(i: int) -> int:
|
| 486 |
+
while parent[i] != i:
|
| 487 |
+
parent[i] = parent[parent[i]]
|
| 488 |
+
i = parent[i]
|
| 489 |
+
return i
|
| 490 |
+
|
| 491 |
+
order = sorted(range(n), key=lambda i: comps[i].y0)
|
| 492 |
+
for a_i, i in enumerate(order):
|
| 493 |
+
a = comps[i]
|
| 494 |
+
for j in order[a_i + 1:]:
|
| 495 |
+
b = comps[j]
|
| 496 |
+
if b.y0 - a.y1 > gap:
|
| 497 |
+
break
|
| 498 |
+
ov = min(a.x1, b.x1) - max(a.x0, b.x0)
|
| 499 |
+
if ov >= 0.3 * min(a.w, b.w):
|
| 500 |
+
parent[find(i)] = find(j)
|
| 501 |
+
groups: dict[int, list[BBox]] = {}
|
| 502 |
+
for i in range(n):
|
| 503 |
+
groups.setdefault(find(i), []).append(comps[i])
|
| 504 |
+
return list(groups.values())
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def _union(boxes: list[BBox]) -> BBox:
|
| 508 |
+
u = boxes[0]
|
| 509 |
+
for b in boxes[1:]:
|
| 510 |
+
u = u.union(b)
|
| 511 |
+
return u
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def is_rotated_text(comps: list[BBox], ratio: float = 1.1) -> bool:
|
| 515 |
+
"""Glyphs of text turned 90 degrees are wider than tall (upright digits are ~0.6)."""
|
| 516 |
+
sized = [c for c in comps if c.h >= 3 and c.w >= 3]
|
| 517 |
+
if len(sized) < 4:
|
| 518 |
+
return False
|
| 519 |
+
return float(np.median([c.w / c.h for c in sized])) > ratio
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def remove_rotated_titles(comps: list[BBox]) -> list[BBox]:
|
| 523 |
+
"""Drop glyphs forming a long vertical run (a rotated axis title next to tick labels)."""
|
| 524 |
+
if len(comps) < 5:
|
| 525 |
+
return comps
|
| 526 |
+
size = float(np.median([max(c.w, c.h) for c in comps]))
|
| 527 |
+
drop: set[int] = set()
|
| 528 |
+
for run in vertical_runs(comps, 0.6 * size):
|
| 529 |
+
u = _union(run)
|
| 530 |
+
if len(run) >= 5 and u.h > 3 * u.w and is_rotated_text(run, 0.9):
|
| 531 |
+
drop.update(id(c) for c in run)
|
| 532 |
+
return [c for c in comps if id(c) not in drop]
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def x_label_boxes(ink: np.ndarray, ax: AxesResult, ref_ch: float = 0.0) -> tuple[list[BBox], float, bool]:
|
| 536 |
+
"""Label boxes of the first text row below the plot area (x tick labels).
|
| 537 |
+
|
| 538 |
+
Returns (boxes, glyph size, rotated); rotated labels (vertical text) are grouped
|
| 539 |
+
as vertical runs, and the glyph size is then the glyph *width*. ``ref_ch`` is the
|
| 540 |
+
upright glyph height from the y labels (same font), used to spot rotated labels
|
| 541 |
+
whose glyphs touch and form one tall component each.
|
| 542 |
+
"""
|
| 543 |
h, w = ink.shape
|
| 544 |
b = ax.plot_box
|
| 545 |
start = b.y1 + ax.x_tick_len + ax.line_thickness + 1
|
|
|
|
| 552 |
# Drop thin marks hanging from the axis: tick remnants.
|
| 553 |
comps = [c for c in comps if not (c.y0 <= region.y0 + 0.5 and c.w <= 2 * ax.line_thickness + 1)]
|
| 554 |
if not comps:
|
| 555 |
+
return [], 0.0, False
|
| 556 |
+
tall = False
|
| 557 |
+
if ref_ch > 0 and len(comps) >= 2:
|
| 558 |
+
# Label-level cue on the first row of upright-grouped words.
|
| 559 |
+
ws = group_words(comps, ref_ch)
|
| 560 |
+
ws = [wd for wd in ws if wd.h >= 0.5 * ref_ch]
|
| 561 |
+
if len(ws) >= 2:
|
| 562 |
+
top0 = min(wd.y0 for wd in ws)
|
| 563 |
+
row0 = [wd for wd in ws if wd.y0 <= top0 + ref_ch]
|
| 564 |
+
tall = len(row0) >= 2 and float(np.median([wd.h for wd in row0])) > 1.7 * ref_ch \
|
| 565 |
+
and float(np.median([wd.w for wd in row0])) < 1.4 * ref_ch
|
| 566 |
+
# Whatever the glyph cue says, rotated labels are taller than wide as a whole
|
| 567 |
+
# (upright words with touching letters are wide single components).
|
| 568 |
+
words_up = [wd for wd in group_words(comps, char_height(comps)) if wd.h >= 3]
|
| 569 |
+
gsize = float(np.median([min(c.w, c.h) for c in comps]))
|
| 570 |
+
stacks = [_union(r) for r in vertical_runs(comps, 0.8 * gsize)]
|
| 571 |
+
|
| 572 |
+
def tallness(boxes: list[BBox]) -> float:
|
| 573 |
+
return float(np.median([b.h / max(b.w, 1.0) for b in boxes])) if boxes else 0.0
|
| 574 |
+
|
| 575 |
+
upright_wide = tallness(words_up) < 1.2 and tallness(stacks) < 1.5
|
| 576 |
+
if (is_rotated_text(comps) or tall) and not upright_wide:
|
| 577 |
+
cw = float(np.median([c.w for c in comps if c.h >= 3])) if not tall else ref_ch
|
| 578 |
+
runs = [_union(r) for r in vertical_runs(comps, 0.8 * cw)]
|
| 579 |
+
top = min(r.y0 for r in runs)
|
| 580 |
+
# Labels hang from the axis: keep the runs starting near the top of the band.
|
| 581 |
+
runs = [r for r in runs if r.y0 <= top + 1.5 * cw and r.h >= 0.8 * cw]
|
| 582 |
+
return sorted(runs, key=lambda bb: bb.cx), cw, True
|
| 583 |
ch = char_height(comps)
|
| 584 |
words = group_words(comps, ch)
|
| 585 |
if not words:
|
| 586 |
+
return [], ch, False
|
| 587 |
top = min(wd.y0 for wd in words)
|
| 588 |
med_h = float(np.median([wd.h for wd in words]))
|
| 589 |
row = [wd for wd in words if wd.y0 <= top + 0.7 * med_h]
|
| 590 |
row_comps = [c for c in comps if any(c.intersects(wd) for wd in row)]
|
| 591 |
row = split_at_ticks(row, row_comps, ax.x_ticks)
|
| 592 |
+
return sorted(row, key=lambda bb: bb.cx), ch, False
|
| 593 |
|
| 594 |
|
| 595 |
def split_at_ticks(words: list[BBox], comps: list[BBox], ticks: list[float]) -> list[BBox]:
|
|
|
|
| 624 |
region = BBox(0.0, max(0.0, b.y0 - 0.05 * h), b.x0 - ax.line_thickness / 2 - 1, min(float(h), b.y1 + 0.05 * h))
|
| 625 |
comps = [c for c in glyph_components(ink, region) if c.x0 < end - 1]
|
| 626 |
comps = [c for c in comps if not (c.x1 >= region.x1 - 0.5 and c.h <= 2 * ax.line_thickness + 1)]
|
| 627 |
+
comps = remove_rotated_titles(comps)
|
| 628 |
if not comps:
|
| 629 |
return [], 0.0
|
| 630 |
ch = char_height(comps)
|
plotscribe/export.py
CHANGED
|
@@ -83,9 +83,16 @@ def build_table(series: list[Series], x_cal: Calibration | None, y_cal: Calibrat
|
|
| 83 |
if chart_type == "scatter":
|
| 84 |
rows = []
|
| 85 |
for si, x, y in pts:
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
rows.append({xname: xv, **{n: (y if k == si else np.nan) for k, n in enumerate(names)}})
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
if categorical:
|
| 91 |
assert x_cal is not None
|
|
@@ -112,6 +119,13 @@ def build_table(series: list[Series], x_cal: Calibration | None, y_cal: Calibrat
|
|
| 112 |
for (si, _, y), k in zip(pts, lab):
|
| 113 |
table[names[si]][k] = y
|
| 114 |
xv = np.asarray(x_cal.to_value(xpx), float) if x_ok else xpx
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
df = pd.DataFrame({xname: xv, **table})
|
| 116 |
return df.sort_values(xname, kind="stable").reset_index(drop=True)
|
| 117 |
|
|
|
|
| 83 |
if chart_type == "scatter":
|
| 84 |
rows = []
|
| 85 |
for si, x, y in pts:
|
| 86 |
+
if categorical:
|
| 87 |
+
assert x_cal is not None
|
| 88 |
+
xv = x_cal.categories[x_cal.nearest_category(x)[0]]
|
| 89 |
+
else:
|
| 90 |
+
xv = float(x_cal.to_value(x)) if x_ok else x
|
| 91 |
rows.append({xname: xv, **{n: (y if k == si else np.nan) for k, n in enumerate(names)}})
|
| 92 |
+
df = pd.DataFrame(rows, columns=[xname, *names])
|
| 93 |
+
if categorical:
|
| 94 |
+
return df # keep category order as plotted
|
| 95 |
+
return df.sort_values(xname, kind="stable").reset_index(drop=True)
|
| 96 |
|
| 97 |
if categorical:
|
| 98 |
assert x_cal is not None
|
|
|
|
| 119 |
for (si, _, y), k in zip(pts, lab):
|
| 120 |
table[names[si]][k] = y
|
| 121 |
xv = np.asarray(x_cal.to_value(xpx), float) if x_ok else xpx
|
| 122 |
+
if x_ok and x_cal.tick_px:
|
| 123 |
+
# A point exactly on a labelled tick takes the label's value (no fit residual).
|
| 124 |
+
tp, tv = np.asarray(x_cal.tick_px), np.asarray(x_cal.tick_values)
|
| 125 |
+
for k, p in enumerate(xpx):
|
| 126 |
+
j = int(np.argmin(np.abs(tp - p)))
|
| 127 |
+
if abs(tp[j] - p) < 0.5:
|
| 128 |
+
xv[k] = tv[j]
|
| 129 |
df = pd.DataFrame({xname: xv, **table})
|
| 130 |
return df.sort_values(xname, kind="stable").reset_index(drop=True)
|
| 131 |
|
plotscribe/extract_line.py
CHANGED
|
@@ -172,9 +172,25 @@ def refine_vertices(cl: Centreline, idx: np.ndarray) -> np.ndarray:
|
|
| 172 |
return out
|
| 173 |
|
| 174 |
|
| 175 |
-
def
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
cl = centreline(mask, alpha)
|
| 179 |
if cl is None:
|
| 180 |
return np.zeros((0, 2)), "none", None
|
|
@@ -187,5 +203,13 @@ def extract_line(mask: np.ndarray, alpha: np.ndarray, category_px: list[float] |
|
|
| 187 |
if len(cp):
|
| 188 |
return np.stack([cp, np.interp(cp, cl.x, cl.y)], 1), "categories", cl
|
| 189 |
eps = float(np.clip(0.5 * cl.thickness, 0.6, 2.0))
|
|
|
|
|
|
|
|
|
|
| 190 |
idx = rdp(cl.x, cl.y, eps)
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
return out
|
| 173 |
|
| 174 |
|
| 175 |
+
def snap_to_ticks(vertices: np.ndarray, cl: Centreline, ticks: list[float]) -> np.ndarray | None:
|
| 176 |
+
"""Values at the x ticks if the polyline's corners all sit on ticks (data sampled at ticks)."""
|
| 177 |
+
t = np.sort(np.asarray(ticks, float))
|
| 178 |
+
if len(t) < 3 or len(vertices) < 2:
|
| 179 |
+
return None
|
| 180 |
+
spacing = float(np.median(np.diff(t)))
|
| 181 |
+
inner = vertices[1:-1, 0]
|
| 182 |
+
if len(inner) and np.max(np.min(np.abs(inner[:, None] - t[None, :]), axis=1)) > 0.12 * spacing:
|
| 183 |
+
return None
|
| 184 |
+
lo, hi = cl.x[0] - 0.12 * spacing, cl.x[-1] + 0.12 * spacing
|
| 185 |
+
tt = t[(t >= lo) & (t <= hi)]
|
| 186 |
+
if len(tt) < 2 or len(tt) < len(inner):
|
| 187 |
+
return None
|
| 188 |
+
return np.stack([tt, np.interp(tt, cl.x, cl.y)], 1)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def extract_line(mask: np.ndarray, alpha: np.ndarray, category_px: list[float] | None = None,
|
| 192 |
+
tick_px: list[float] | None = None) -> tuple[np.ndarray, str, Centreline | None]:
|
| 193 |
+
"""Data points (x, y) in pixels and the method used: markers/categories/ticks/vertices."""
|
| 194 |
cl = centreline(mask, alpha)
|
| 195 |
if cl is None:
|
| 196 |
return np.zeros((0, 2)), "none", None
|
|
|
|
| 203 |
if len(cp):
|
| 204 |
return np.stack([cp, np.interp(cp, cl.x, cl.y)], 1), "categories", cl
|
| 205 |
eps = float(np.clip(0.5 * cl.thickness, 0.6, 2.0))
|
| 206 |
+
if cl.observed.mean() < 0.7:
|
| 207 |
+
# Dotted/dashed: the centreline between pieces is interpolated and jagged.
|
| 208 |
+
eps *= 2.5
|
| 209 |
idx = rdp(cl.x, cl.y, eps)
|
| 210 |
+
verts = refine_vertices(cl, idx)
|
| 211 |
+
if tick_px:
|
| 212 |
+
snapped = snap_to_ticks(verts, cl, tick_px)
|
| 213 |
+
if snapped is not None:
|
| 214 |
+
return snapped, "ticks", cl
|
| 215 |
+
return verts, "vertices", cl
|
plotscribe/pipeline.py
CHANGED
|
@@ -10,6 +10,7 @@ from dataclasses import dataclass, field
|
|
| 10 |
from pathlib import Path
|
| 11 |
from typing import Any
|
| 12 |
|
|
|
|
| 13 |
import numpy as np
|
| 14 |
import pandas as pd
|
| 15 |
|
|
@@ -54,11 +55,31 @@ class PipelineResult:
|
|
| 54 |
self.warnings.append(f"[{stage}] {m}")
|
| 55 |
|
| 56 |
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
h, w = rgb.shape[:2]
|
| 59 |
r = b.expand(max(2.0, 0.25 * char_h)).clip(w, h)
|
| 60 |
rs, cs = r.slices()
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
|
| 64 |
def leading_minus(ink: np.ndarray, box: BBox) -> float | None:
|
|
@@ -155,7 +176,7 @@ def add_power_candidates(labels: list[TextBox], powers: list[bool]) -> None:
|
|
| 155 |
|
| 156 |
|
| 157 |
def read_labels(rgb: np.ndarray, ink: np.ndarray, boxes: list[BBox], char_h: float,
|
| 158 |
-
ocr: OCRBackend) -> list[TextBox]:
|
| 159 |
"""OCR each label box.
|
| 160 |
|
| 161 |
If the axis looks numeric, every label is re-read with a numeric charset in
|
|
@@ -166,16 +187,17 @@ def read_labels(rgb: np.ndarray, ink: np.ndarray, boxes: list[BBox], char_h: flo
|
|
| 166 |
minus: list[float | None] = []
|
| 167 |
powers: list[bool] = []
|
| 168 |
for b in boxes:
|
| 169 |
-
|
|
|
|
| 170 |
pw = read_power_label(rgb, ink, sp[0], sp[1], char_h, ocr) if sp else None
|
| 171 |
if pw is not None:
|
| 172 |
out.append(TextBox(bbox=b, text=pw[0], conf=0.8, value=pw[1], candidates=[pw[1]]))
|
| 173 |
minus.append(None)
|
| 174 |
powers.append(True)
|
| 175 |
continue
|
| 176 |
-
text, conf = ocr.read_line(_crop(rgb, b, char_h))
|
| 177 |
out.append(TextBox(bbox=b, text=text, conf=conf, value=parse_number(text)))
|
| 178 |
-
minus.append(leading_minus(ink, b))
|
| 179 |
powers.append(False)
|
| 180 |
if any(powers):
|
| 181 |
add_power_candidates(out, powers)
|
|
@@ -186,7 +208,7 @@ def read_labels(rgb: np.ndarray, ink: np.ndarray, boxes: list[BBox], char_h: flo
|
|
| 186 |
if pw:
|
| 187 |
continue
|
| 188 |
body = BBox(m + 1, tb.bbox.y0, tb.bbox.x1, tb.bbox.y1) if m is not None else tb.bbox
|
| 189 |
-
crop = _crop(rgb, body, char_h)
|
| 190 |
cands = [tb.value] if tb.value is not None else []
|
| 191 |
for word in (False, True):
|
| 192 |
t, c = ocr.read_line(crop, numeric=True, word=word)
|
|
@@ -247,6 +269,15 @@ def calibrate_axis(axis: str, labels: list[TextBox], ticks: list[float]) -> Cali
|
|
| 247 |
vals = [lb.candidates or [lb.value] for lb in labels if lb.value is not None]
|
| 248 |
powers = sum("^" in lb.text for lb in labels)
|
| 249 |
cal = fit_numeric(axis, px, vals, allow_linear=powers < 2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
n_matched = sum(s[1] for s, v in zip(snapped, values) if v is not None)
|
| 251 |
if n_matched < len(px):
|
| 252 |
cal.warnings.append(f"{axis}: {len(px) - n_matched} label(s) not matched to a tick mark")
|
|
@@ -255,7 +286,7 @@ def calibrate_axis(axis: str, labels: list[TextBox], ticks: list[float]) -> Cali
|
|
| 255 |
|
| 256 |
|
| 257 |
def merge_labels_per_tick(rgb: np.ndarray, labels: list[TextBox], ticks: list[float], axis: str,
|
| 258 |
-
char_h: float, ocr: OCRBackend) -> list[TextBox]:
|
| 259 |
"""For text (categorical) labels: one label per tick, re-reading fragments together.
|
| 260 |
|
| 261 |
Long category names can touch or overlap their neighbours, which splits or merges
|
|
@@ -289,7 +320,7 @@ def merge_labels_per_tick(rgb: np.ndarray, labels: list[TextBox], ticks: list[fl
|
|
| 289 |
cell = BBox(tp - 0.5 * spacing, band.y0, tp + 0.5 * spacing, band.y1)
|
| 290 |
else:
|
| 291 |
cell = BBox(band.x0, tp - 0.5 * spacing, band.x1, tp + 0.5 * spacing)
|
| 292 |
-
text, conf = ocr.read_line(_crop(rgb, cell, char_h))
|
| 293 |
groups[i] = [TextBox(bbox=cell, text=text or f"category_{i + 1}", conf=conf, value=None)]
|
| 294 |
out = []
|
| 295 |
for i in sorted(groups):
|
|
@@ -300,7 +331,7 @@ def merge_labels_per_tick(rgb: np.ndarray, labels: list[TextBox], ticks: list[fl
|
|
| 300 |
box = g[0].bbox
|
| 301 |
for lb in g[1:]:
|
| 302 |
box = box.union(lb.bbox)
|
| 303 |
-
text, conf = ocr.read_line(_crop(rgb, box, char_h))
|
| 304 |
out.append(TextBox(bbox=box, text=text, conf=conf, value=parse_number(text)))
|
| 305 |
return out
|
| 306 |
|
|
@@ -320,9 +351,14 @@ def run(path: str | Path, ocr_backend: str = "tesseract", chart_type: str | None
|
|
| 320 |
res.stage_conf["axes"] = ax.confidence
|
| 321 |
res.warn("axes", ax.warnings)
|
| 322 |
|
| 323 |
-
xb, xch = axes_mod.x_label_boxes(ink, ax)
|
| 324 |
yb, ych = axes_mod.y_label_boxes(ink, ax)
|
| 325 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
res.y_labels = merge_labels_per_tick(pre.rgb, read_labels(pre.rgb, ink, yb, ych, ocr), ax.y_ticks, "y", ych, ocr)
|
| 327 |
for name, labels, ch in (("x", res.x_labels, xch), ("y", res.y_labels, ych)):
|
| 328 |
if not is_numeric_axis([lb.value for lb in labels]):
|
|
@@ -383,6 +419,7 @@ def run(path: str | Path, ocr_backend: str = "tesseract", chart_type: str | None
|
|
| 383 |
extract(res, series)
|
| 384 |
status_from_calibration(res)
|
| 385 |
check_data_outside_box(res, series)
|
|
|
|
| 386 |
res.table = export.build_table(series, res.x_cal, res.y_cal, res.chart_type, ax.plot_box.w)
|
| 387 |
return res
|
| 388 |
|
|
@@ -439,6 +476,18 @@ def separate_series(res: PipelineResult, ink: np.ndarray, leg: legend_mod.Legend
|
|
| 439 |
else:
|
| 440 |
seen[n] = 1
|
| 441 |
masks, alpha, labels = series_mod.series_masks(rgb, cand, ax, colours, res.pre.noise_sigma)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
res.extra["alpha"] = alpha
|
| 443 |
res.extra["labels"] = labels
|
| 444 |
out = []
|
|
@@ -463,8 +512,9 @@ def extract(res: PipelineResult, series: list[Series]) -> None:
|
|
| 463 |
live.append(s)
|
| 464 |
if ctype == "line":
|
| 465 |
methods = {}
|
|
|
|
| 466 |
for s in live:
|
| 467 |
-
pts, method, _ = extract_line(s.mask, alpha, cat_px)
|
| 468 |
s.points_px = pts
|
| 469 |
methods[s.name] = method
|
| 470 |
res.extra.setdefault("diagnostics_extra", {})["point_method"] = methods
|
|
@@ -514,7 +564,8 @@ def recategorize_from_bars(res: PipelineResult, bars: list[bar_mod.Bar]) -> None
|
|
| 514 |
ocr = get_backend(res.extra.get("ocr_backend", "tesseract"))
|
| 515 |
names = []
|
| 516 |
for i in range(len(c)):
|
| 517 |
-
text, _ = ocr.read_line(_crop(res.pre.rgb, BBox(bounds[i], band.y0, bounds[i + 1], band.y1), ch
|
|
|
|
| 518 |
names.append(text.strip() or f"category_{i + 1}")
|
| 519 |
res.warn("calibrate", f"x: {len(x.categories)} category labels did not match {len(c)} bar groups; "
|
| 520 |
"categories re-anchored on the bars")
|
|
@@ -605,6 +656,65 @@ def check_data_outside_box(res: PipelineResult, series: list[Series]) -> None:
|
|
| 605 |
res.extra["status"] = "low_confidence"
|
| 606 |
|
| 607 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 608 |
def status_from_calibration(res: PipelineResult) -> None:
|
| 609 |
"""Mark the result uncalibrated / low-confidence instead of emitting wrong numbers."""
|
| 610 |
status = "ok"
|
|
|
|
| 10 |
from pathlib import Path
|
| 11 |
from typing import Any
|
| 12 |
|
| 13 |
+
import cv2
|
| 14 |
import numpy as np
|
| 15 |
import pandas as pd
|
| 16 |
|
|
|
|
| 55 |
self.warnings.append(f"[{stage}] {m}")
|
| 56 |
|
| 57 |
|
| 58 |
+
_ROTATE = {90: cv2.ROTATE_90_CLOCKWISE, -90: cv2.ROTATE_90_COUNTERCLOCKWISE}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _crop(rgb: np.ndarray, b: BBox, char_h: float, rot: int = 0) -> np.ndarray:
|
| 62 |
+
"""OCR-ready crop of ``b``; ``rot`` (90 / -90) turns vertical text upright first."""
|
| 63 |
h, w = rgb.shape[:2]
|
| 64 |
r = b.expand(max(2.0, 0.25 * char_h)).clip(w, h)
|
| 65 |
rs, cs = r.slices()
|
| 66 |
+
crop = rgb[rs, cs]
|
| 67 |
+
if rot:
|
| 68 |
+
crop = cv2.rotate(np.ascontiguousarray(crop), _ROTATE[rot])
|
| 69 |
+
return prepare_crop(crop, char_h)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def choose_rotation(rgb: np.ndarray, boxes: list[BBox], char_h: float, ocr: OCRBackend) -> int:
|
| 73 |
+
"""Reading direction of vertical labels: the rotation whose OCR parses/scores best."""
|
| 74 |
+
best, best_score = 90, -1.0
|
| 75 |
+
for rot in (90, -90):
|
| 76 |
+
score = 0.0
|
| 77 |
+
for b in boxes[:3]:
|
| 78 |
+
text, conf = ocr.read_line(_crop(rgb, b, char_h, rot))
|
| 79 |
+
score += conf + (1.0 if parse_number(text) is not None else 0.0)
|
| 80 |
+
if score > best_score:
|
| 81 |
+
best, best_score = rot, score
|
| 82 |
+
return best
|
| 83 |
|
| 84 |
|
| 85 |
def leading_minus(ink: np.ndarray, box: BBox) -> float | None:
|
|
|
|
| 176 |
|
| 177 |
|
| 178 |
def read_labels(rgb: np.ndarray, ink: np.ndarray, boxes: list[BBox], char_h: float,
|
| 179 |
+
ocr: OCRBackend, rot: int = 0) -> list[TextBox]:
|
| 180 |
"""OCR each label box.
|
| 181 |
|
| 182 |
If the axis looks numeric, every label is re-read with a numeric charset in
|
|
|
|
| 187 |
minus: list[float | None] = []
|
| 188 |
powers: list[bool] = []
|
| 189 |
for b in boxes:
|
| 190 |
+
# Superscript and minus geometry assume upright text.
|
| 191 |
+
sp = split_superscript(ink, b) if not rot else None
|
| 192 |
pw = read_power_label(rgb, ink, sp[0], sp[1], char_h, ocr) if sp else None
|
| 193 |
if pw is not None:
|
| 194 |
out.append(TextBox(bbox=b, text=pw[0], conf=0.8, value=pw[1], candidates=[pw[1]]))
|
| 195 |
minus.append(None)
|
| 196 |
powers.append(True)
|
| 197 |
continue
|
| 198 |
+
text, conf = ocr.read_line(_crop(rgb, b, char_h, rot))
|
| 199 |
out.append(TextBox(bbox=b, text=text, conf=conf, value=parse_number(text)))
|
| 200 |
+
minus.append(leading_minus(ink, b) if not rot else None)
|
| 201 |
powers.append(False)
|
| 202 |
if any(powers):
|
| 203 |
add_power_candidates(out, powers)
|
|
|
|
| 208 |
if pw:
|
| 209 |
continue
|
| 210 |
body = BBox(m + 1, tb.bbox.y0, tb.bbox.x1, tb.bbox.y1) if m is not None else tb.bbox
|
| 211 |
+
crop = _crop(rgb, body, char_h, rot)
|
| 212 |
cands = [tb.value] if tb.value is not None else []
|
| 213 |
for word in (False, True):
|
| 214 |
t, c = ocr.read_line(crop, numeric=True, word=word)
|
|
|
|
| 269 |
vals = [lb.candidates or [lb.value] for lb in labels if lb.value is not None]
|
| 270 |
powers = sum("^" in lb.text for lb in labels)
|
| 271 |
cal = fit_numeric(axis, px, vals, allow_linear=powers < 2)
|
| 272 |
+
ordered = [v for _, v in sorted(zip(px, [lb.value for lb in labels if lb.value is not None]))]
|
| 273 |
+
increasing = all(b > a for a, b in zip(ordered, ordered[1:]))
|
| 274 |
+
if (axis == "x" and powers == 0 and len(px) >= 4 and cal.n_inliers < 0.75 * len(px) and increasing
|
| 275 |
+
and all(v is not None and float(v).is_integer() for v in values)):
|
| 276 |
+
# Evenly placed integer labels that are not linear in position (e.g. the
|
| 277 |
+
# years 1990, 1991, 1996, ...) are category names, not a numeric scale.
|
| 278 |
+
cat = fit_categorical(axis, [s[0] for s in snapped], [lb.text for lb in labels])
|
| 279 |
+
cat.warnings.append(f"{axis}: numeric labels not linear in position; treated as categories")
|
| 280 |
+
return cat
|
| 281 |
n_matched = sum(s[1] for s, v in zip(snapped, values) if v is not None)
|
| 282 |
if n_matched < len(px):
|
| 283 |
cal.warnings.append(f"{axis}: {len(px) - n_matched} label(s) not matched to a tick mark")
|
|
|
|
| 286 |
|
| 287 |
|
| 288 |
def merge_labels_per_tick(rgb: np.ndarray, labels: list[TextBox], ticks: list[float], axis: str,
|
| 289 |
+
char_h: float, ocr: OCRBackend, rot: int = 0) -> list[TextBox]:
|
| 290 |
"""For text (categorical) labels: one label per tick, re-reading fragments together.
|
| 291 |
|
| 292 |
Long category names can touch or overlap their neighbours, which splits or merges
|
|
|
|
| 320 |
cell = BBox(tp - 0.5 * spacing, band.y0, tp + 0.5 * spacing, band.y1)
|
| 321 |
else:
|
| 322 |
cell = BBox(band.x0, tp - 0.5 * spacing, band.x1, tp + 0.5 * spacing)
|
| 323 |
+
text, conf = ocr.read_line(_crop(rgb, cell, char_h, rot))
|
| 324 |
groups[i] = [TextBox(bbox=cell, text=text or f"category_{i + 1}", conf=conf, value=None)]
|
| 325 |
out = []
|
| 326 |
for i in sorted(groups):
|
|
|
|
| 331 |
box = g[0].bbox
|
| 332 |
for lb in g[1:]:
|
| 333 |
box = box.union(lb.bbox)
|
| 334 |
+
text, conf = ocr.read_line(_crop(rgb, box, char_h, rot))
|
| 335 |
out.append(TextBox(bbox=box, text=text, conf=conf, value=parse_number(text)))
|
| 336 |
return out
|
| 337 |
|
|
|
|
| 351 |
res.stage_conf["axes"] = ax.confidence
|
| 352 |
res.warn("axes", ax.warnings)
|
| 353 |
|
|
|
|
| 354 |
yb, ych = axes_mod.y_label_boxes(ink, ax)
|
| 355 |
+
xb, xch, x_rotated = axes_mod.x_label_boxes(ink, ax, ych)
|
| 356 |
+
xrot = choose_rotation(pre.rgb, xb, xch, ocr) if x_rotated and xb else 0
|
| 357 |
+
res.extra["x_label_rotation"] = xrot
|
| 358 |
+
if xrot:
|
| 359 |
+
res.warn("axes", f"x tick labels are rotated {abs(xrot)} degrees")
|
| 360 |
+
res.x_labels = merge_labels_per_tick(pre.rgb, read_labels(pre.rgb, ink, xb, xch, ocr, xrot), ax.x_ticks,
|
| 361 |
+
"x", xch, ocr, xrot)
|
| 362 |
res.y_labels = merge_labels_per_tick(pre.rgb, read_labels(pre.rgb, ink, yb, ych, ocr), ax.y_ticks, "y", ych, ocr)
|
| 363 |
for name, labels, ch in (("x", res.x_labels, xch), ("y", res.y_labels, ych)):
|
| 364 |
if not is_numeric_axis([lb.value for lb in labels]):
|
|
|
|
| 419 |
extract(res, series)
|
| 420 |
status_from_calibration(res)
|
| 421 |
check_data_outside_box(res, series)
|
| 422 |
+
check_clipping(res, series)
|
| 423 |
res.table = export.build_table(series, res.x_cal, res.y_cal, res.chart_type, ax.plot_box.w)
|
| 424 |
return res
|
| 425 |
|
|
|
|
| 476 |
else:
|
| 477 |
seen[n] = 1
|
| 478 |
masks, alpha, labels = series_mod.series_masks(rgb, cand, ax, colours, res.pre.noise_sigma)
|
| 479 |
+
outline = series_mod.outline_clusters(masks)
|
| 480 |
+
if outline:
|
| 481 |
+
keep = [i for i in range(len(masks)) if i not in outline or from_legend[i]]
|
| 482 |
+
for i in sorted(set(range(len(masks))) - set(keep)):
|
| 483 |
+
labels[labels == i] = -1
|
| 484 |
+
res.warn("series", f"colour {series_mod.describe_color(colours[i])} only outlines other marks; ignored")
|
| 485 |
+
remap = {old: new for new, old in enumerate(keep)}
|
| 486 |
+
labels = np.where(labels >= 0, np.vectorize(lambda v: remap.get(int(v), -1))(labels), -1)
|
| 487 |
+
colours = [colours[i] for i in keep]
|
| 488 |
+
names = [names[i] for i in keep]
|
| 489 |
+
from_legend = [from_legend[i] for i in keep]
|
| 490 |
+
masks = [masks[i] for i in keep]
|
| 491 |
res.extra["alpha"] = alpha
|
| 492 |
res.extra["labels"] = labels
|
| 493 |
out = []
|
|
|
|
| 512 |
live.append(s)
|
| 513 |
if ctype == "line":
|
| 514 |
methods = {}
|
| 515 |
+
num_ticks = res.axes.x_ticks if (res.x_cal is not None and res.x_cal.kind != "categorical") else None
|
| 516 |
for s in live:
|
| 517 |
+
pts, method, _ = extract_line(s.mask, alpha, cat_px, num_ticks)
|
| 518 |
s.points_px = pts
|
| 519 |
methods[s.name] = method
|
| 520 |
res.extra.setdefault("diagnostics_extra", {})["point_method"] = methods
|
|
|
|
| 564 |
ocr = get_backend(res.extra.get("ocr_backend", "tesseract"))
|
| 565 |
names = []
|
| 566 |
for i in range(len(c)):
|
| 567 |
+
text, _ = ocr.read_line(_crop(res.pre.rgb, BBox(bounds[i], band.y0, bounds[i + 1], band.y1), ch,
|
| 568 |
+
res.extra.get("x_label_rotation", 0)))
|
| 569 |
names.append(text.strip() or f"category_{i + 1}")
|
| 570 |
res.warn("calibrate", f"x: {len(x.categories)} category labels did not match {len(c)} bar groups; "
|
| 571 |
"categories re-anchored on the bars")
|
|
|
|
| 656 |
res.extra["status"] = "low_confidence"
|
| 657 |
|
| 658 |
|
| 659 |
+
def _longest_false_run(v: np.ndarray) -> int:
|
| 660 |
+
best = cur = 0
|
| 661 |
+
for x in v:
|
| 662 |
+
cur = 0 if x else cur + 1
|
| 663 |
+
best = max(best, cur)
|
| 664 |
+
return best
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
def check_clipping(res: PipelineResult, series: list[Series]) -> None:
|
| 668 |
+
"""Data running into the top/bottom of the plot area is cut off by the axis range.
|
| 669 |
+
|
| 670 |
+
Plotting tools pad the data range, so marks never touch those edges - except bars
|
| 671 |
+
standing on a baseline at the bottom. Contact means values outside the visible
|
| 672 |
+
range, which cannot be read from the image.
|
| 673 |
+
"""
|
| 674 |
+
ax = res.axes
|
| 675 |
+
assert ax is not None
|
| 676 |
+
h, w = res.pre.rgb.shape[:2]
|
| 677 |
+
interior = series_mod.plot_interior(ax, (h, w))
|
| 678 |
+
rs, cs = interior.slices()
|
| 679 |
+
band = max(2, int(round(ax.line_thickness)))
|
| 680 |
+
bars = "bar" in res.chart_type
|
| 681 |
+
zero = zero_line_px(res) if bars else None
|
| 682 |
+
bottom_is_base = bars and zero is not None and abs(zero - ax.plot_box.y1) <= 3 * ax.line_thickness + 3
|
| 683 |
+
def runs(cols: np.ndarray) -> list[tuple[int, int]]:
|
| 684 |
+
idx = np.flatnonzero(cols)
|
| 685 |
+
if idx.size == 0:
|
| 686 |
+
return []
|
| 687 |
+
groups = np.split(idx, np.flatnonzero(np.diff(idx) > 2 * band) + 1)
|
| 688 |
+
return [(int(g[0]), int(g[-1])) for g in groups]
|
| 689 |
+
|
| 690 |
+
min_gap = 3 * ax.line_thickness + 3
|
| 691 |
+
for s in series:
|
| 692 |
+
if s.mask is None or not s.mask.any() or res.chart_type == "scatter":
|
| 693 |
+
continue # a marker cut by the frame is the range limit sitting on a data point
|
| 694 |
+
present = s.mask[rs, cs].any(axis=0)
|
| 695 |
+
edges = []
|
| 696 |
+
for name, rows in (("top", slice(rs.start, rs.start + band)), ("bottom", slice(rs.stop - band, rs.stop))):
|
| 697 |
+
if name == "bottom" and bottom_is_base:
|
| 698 |
+
continue
|
| 699 |
+
r = runs(s.mask[rows, cs].any(axis=0))
|
| 700 |
+
if bars:
|
| 701 |
+
# Several bars ending exactly at the frame: values beyond the range.
|
| 702 |
+
clipped = len(r) >= 2
|
| 703 |
+
else:
|
| 704 |
+
# A line leaving the range and coming back: touches the edge twice with
|
| 705 |
+
# no line at all in between (equal maxima keep the line in between).
|
| 706 |
+
clipped = any(_longest_false_run(present[a[1] + 1:b[0]]) >= max(min_gap, 0.04 * interior.w)
|
| 707 |
+
for a, b in zip(r, r[1:]))
|
| 708 |
+
if clipped:
|
| 709 |
+
edges.append(name)
|
| 710 |
+
if edges:
|
| 711 |
+
msg = f"'{s.name}' runs into the {' and '.join(edges)} of the plot area; values beyond the axis range are cut off"
|
| 712 |
+
s.warnings.append(msg)
|
| 713 |
+
res.warn("extract", msg)
|
| 714 |
+
if res.extra.get("status") == "ok":
|
| 715 |
+
res.extra["status"] = "low_confidence"
|
| 716 |
+
|
| 717 |
+
|
| 718 |
def status_from_calibration(res: PipelineResult) -> None:
|
| 719 |
"""Mark the result uncalibrated / low-confidence instead of emitting wrong numbers."""
|
| 720 |
status = "ok"
|
plotscribe/series.py
CHANGED
|
@@ -237,9 +237,18 @@ def soft_assign(rgb: np.ndarray, cand: np.ndarray, bg: np.ndarray, colors: list[
|
|
| 237 |
|
| 238 |
|
| 239 |
def remove_specks(mask: np.ndarray, min_area: int) -> np.ndarray:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
n, lab, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8)
|
|
|
|
| 241 |
keep = np.zeros(n, bool)
|
| 242 |
-
keep[1:] =
|
|
|
|
|
|
|
|
|
|
| 243 |
return keep[lab]
|
| 244 |
|
| 245 |
|
|
@@ -263,3 +272,30 @@ def describe_color(lab: np.ndarray) -> tuple[int, int, int]:
|
|
| 263 |
rgb = cv2.cvtColor(px, cv2.COLOR_LAB2RGB)[0, 0]
|
| 264 |
return tuple(int(round(float(np.clip(v, 0, 1)) * 255)) for v in rgb) # type: ignore[return-value]
|
| 265 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
|
| 239 |
def remove_specks(mask: np.ndarray, min_area: int) -> np.ndarray:
|
| 240 |
+
"""Drop components smaller than ``min_area`` - unless there are many of one size.
|
| 241 |
+
|
| 242 |
+
Noise specks are few and irregular; a dotted line or tiny markers give many small
|
| 243 |
+
components of consistent size, which are data.
|
| 244 |
+
"""
|
| 245 |
n, lab, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8)
|
| 246 |
+
areas = stats[1:, cv2.CC_STAT_AREA]
|
| 247 |
keep = np.zeros(n, bool)
|
| 248 |
+
keep[1:] = areas >= min_area
|
| 249 |
+
small = (areas >= 3) & (areas < min_area)
|
| 250 |
+
if small.sum() >= 15 and np.std(areas[small]) < 0.5 * np.mean(areas[small]):
|
| 251 |
+
keep[1:] |= small
|
| 252 |
return keep[lab]
|
| 253 |
|
| 254 |
|
|
|
|
| 272 |
rgb = cv2.cvtColor(px, cv2.COLOR_LAB2RGB)[0, 0]
|
| 273 |
return tuple(int(round(float(np.clip(v, 0, 1)) * 255)) for v in rgb) # type: ignore[return-value]
|
| 274 |
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def outline_clusters(masks: list[np.ndarray]) -> set[int]:
|
| 278 |
+
"""Indices of colours that only outline other series (bar edges, marker rims).
|
| 279 |
+
|
| 280 |
+
An outline colour is thin and nearly all of its pixels touch another series.
|
| 281 |
+
"""
|
| 282 |
+
out: set[int] = set()
|
| 283 |
+
if len(masks) < 2:
|
| 284 |
+
return out
|
| 285 |
+
k = np.ones((5, 5), np.uint8)
|
| 286 |
+
grown = [cv2.dilate(m.astype(np.uint8), k).astype(bool) for m in masks]
|
| 287 |
+
for i, m in enumerate(masks):
|
| 288 |
+
a = int(m.sum())
|
| 289 |
+
if a == 0:
|
| 290 |
+
continue
|
| 291 |
+
others = np.zeros_like(m)
|
| 292 |
+
for j, g in enumerate(grown):
|
| 293 |
+
if j != i:
|
| 294 |
+
others |= g
|
| 295 |
+
near = int((m & others).sum())
|
| 296 |
+
# Thin: an opening with a 3x3 kernel removes most of it.
|
| 297 |
+
thin = 1.0 - cv2.morphologyEx(m.astype(np.uint8), cv2.MORPH_OPEN, np.ones((3, 3), np.uint8)).sum() / a
|
| 298 |
+
bigger = any(int(o.sum()) > 2 * a for j, o in enumerate(masks) if j != i)
|
| 299 |
+
if near >= 0.8 * a and thin >= 0.6 and bigger:
|
| 300 |
+
out.add(i)
|
| 301 |
+
return out
|
pyproject.toml
CHANGED
|
@@ -18,7 +18,7 @@ dependencies = [
|
|
| 18 |
]
|
| 19 |
|
| 20 |
[project.optional-dependencies]
|
| 21 |
-
dev = ["pytest>=8", "matplotlib>=3.8", "pillow>=10"]
|
| 22 |
paddle = ["paddleocr>=2.7"]
|
| 23 |
web = ["fastapi>=0.110", "uvicorn>=0.29", "python-multipart>=0.0.9"]
|
| 24 |
|
|
|
|
| 18 |
]
|
| 19 |
|
| 20 |
[project.optional-dependencies]
|
| 21 |
+
dev = ["pytest>=8", "matplotlib>=3.8", "pillow>=10", "pyarrow>=14"]
|
| 22 |
paddle = ["paddleocr>=2.7"]
|
| 23 |
web = ["fastapi>=0.110", "uvicorn>=0.29", "python-multipart>=0.0.9"]
|
| 24 |
|
tests/bench_plotqa.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PlotQA benchmark (real-world data, Bokeh-rendered line / dot / bar charts).
|
| 2 |
+
|
| 3 |
+
Data: Hugging Face dataset ``martinsinnona/plotqa`` (images + Vega-style specs with
|
| 4 |
+
the plotted values), downloaded to ``data/benchmarks/plotqa_raw/{test,train}.parquet``.
|
| 5 |
+
|
| 6 |
+
python -m tests.bench_plotqa --split test # prepare + evaluate
|
| 7 |
+
python -m tests.bench_plotqa --split train --n 200 --out eval_out/plotqa
|
| 8 |
+
|
| 9 |
+
Metrics: per-point error as a fraction of the y range [min(0, y_min), y_max] (the
|
| 10 |
+
true axis limits are not in the spec), recall, and RNSS (ChartQA / DePlot).
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import ast
|
| 17 |
+
import io
|
| 18 |
+
import json
|
| 19 |
+
import time
|
| 20 |
+
import traceback
|
| 21 |
+
from multiprocessing import Pool
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from typing import Any
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import pandas as pd
|
| 27 |
+
from PIL import Image
|
| 28 |
+
|
| 29 |
+
from plotscribe import export, pipeline
|
| 30 |
+
from tests.metrics import AxisInfo, rnss, score_table
|
| 31 |
+
|
| 32 |
+
RAW = Path("data/benchmarks/plotqa_raw")
|
| 33 |
+
OUT = Path("data/benchmarks/plotqa")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def prepare(split: str, n: int | None) -> list[Path]:
|
| 37 |
+
"""Write ``<id>.png``, ``<id>.csv`` (ground truth) and ``<id>.json`` (meta) per chart."""
|
| 38 |
+
dest = OUT / split
|
| 39 |
+
dest.mkdir(parents=True, exist_ok=True)
|
| 40 |
+
df = pd.read_parquet(RAW / f"{split}.parquet")
|
| 41 |
+
paths = []
|
| 42 |
+
for i, (img, text) in enumerate(zip(df.image, df.text)):
|
| 43 |
+
if n is not None and i >= n:
|
| 44 |
+
break
|
| 45 |
+
spec = ast.literal_eval(text)
|
| 46 |
+
stem = dest / f"{split}_{i:04d}"
|
| 47 |
+
png = stem.with_suffix(".png")
|
| 48 |
+
if not png.exists():
|
| 49 |
+
Image.open(io.BytesIO(img["bytes"])).convert("RGB").save(png)
|
| 50 |
+
vals = spec["data"]["values"]
|
| 51 |
+
name = spec["encoding"]["y"]["field"]
|
| 52 |
+
gt = pd.DataFrame({"x": [v["x"] for v in vals], name: [float(v["y"]) for v in vals]})
|
| 53 |
+
gt.to_csv(stem.with_suffix(".csv"), index=False)
|
| 54 |
+
stem.with_suffix(".json").write_text(json.dumps(
|
| 55 |
+
{"mark": spec["mark"], "x_type": spec["encoding"]["x"]["type"]}))
|
| 56 |
+
paths.append(png)
|
| 57 |
+
return paths
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _as_numeric(col: pd.Series) -> pd.Series | None:
|
| 61 |
+
v = pd.to_numeric(col.astype(str).str.strip(), errors="coerce")
|
| 62 |
+
return v if v.notna().mean() >= 0.8 else None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def evaluate_one(png: str) -> dict[str, Any]:
|
| 66 |
+
p = Path(png)
|
| 67 |
+
meta = json.loads(p.with_suffix(".json").read_text())
|
| 68 |
+
gt = pd.read_csv(p.with_suffix(".csv"), dtype={"x": str})
|
| 69 |
+
rec: dict[str, Any] = {"chart": p.stem, "mark": meta["mark"], "x_type": meta["x_type"], "ok": False}
|
| 70 |
+
t0 = time.time()
|
| 71 |
+
try:
|
| 72 |
+
res = pipeline.run(p)
|
| 73 |
+
except Exception as exc: # noqa: BLE001
|
| 74 |
+
rec["error"] = f"{type(exc).__name__}: {exc}"
|
| 75 |
+
rec["trace"] = traceback.format_exc(limit=3)
|
| 76 |
+
return rec
|
| 77 |
+
rec.update(ok=True, runtime_s=time.time() - t0, status=res.extra.get("status"), type=res.chart_type,
|
| 78 |
+
warnings=res.warnings)
|
| 79 |
+
y = gt.iloc[:, 1].to_numpy(float)
|
| 80 |
+
if np.ptp(y) == 0:
|
| 81 |
+
# Degenerate annotation (e.g. values rounded to 0.0 in the dataset): unscoreable.
|
| 82 |
+
rec.update(gt_invalid=True, median_err=np.nan, recall=np.nan, rnss=np.nan, abstain=False)
|
| 83 |
+
return rec
|
| 84 |
+
rec["gt_invalid"] = False
|
| 85 |
+
ya = AxisInfo(min(0.0, y.min()), y.max() if y.max() > min(0.0, y.min()) else y.max() + 1)
|
| 86 |
+
pred = res.table
|
| 87 |
+
if pred is None or any("[px]" in str(c) for c in pred.columns):
|
| 88 |
+
rec.update(median_err=np.nan, recall=0.0, rnss=0.0, abstain=True)
|
| 89 |
+
return rec
|
| 90 |
+
rec["abstain"] = False
|
| 91 |
+
gx = _as_numeric(gt.iloc[:, 0])
|
| 92 |
+
px = _as_numeric(pred.iloc[:, 0]) if len(pred) else None
|
| 93 |
+
if gx is not None and px is not None:
|
| 94 |
+
g2 = gt.assign(x=gx)
|
| 95 |
+
p2 = pred.assign(**{pred.columns[0]: px.to_numpy(float)})
|
| 96 |
+
# Collapse multiple predicted series to the best-matching one (single-series GT).
|
| 97 |
+
xa = AxisInfo(float(gx.min()) - 0.5, float(gx.max()) + 0.5)
|
| 98 |
+
mode = "numeric"
|
| 99 |
+
if meta["mark"] == "bar" or meta["mark"] == "circle":
|
| 100 |
+
mode = "scatter" if meta["mark"] == "circle" else "numeric"
|
| 101 |
+
sc = score_table(p2, g2, mode, xa, ya)
|
| 102 |
+
else:
|
| 103 |
+
sc = score_table(pred, gt.rename(columns={"x": "category"}), "categorical", None, ya)
|
| 104 |
+
s = sc.summary()
|
| 105 |
+
rec.update(median_err=s["median_err"], max_err=s["max_err"], recall=s["recall"],
|
| 106 |
+
n_pred_series=s["n_pred_series"], category_acc=s["category_acc"], rnss=rnss(pred, gt))
|
| 107 |
+
return rec
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def main() -> None:
|
| 111 |
+
ap = argparse.ArgumentParser()
|
| 112 |
+
ap.add_argument("--split", default="test", choices=["test", "train"])
|
| 113 |
+
ap.add_argument("--n", type=int, default=None)
|
| 114 |
+
ap.add_argument("--workers", type=int, default=8)
|
| 115 |
+
ap.add_argument("--out", type=Path, default=Path("eval_out/plotqa"))
|
| 116 |
+
ap.add_argument("--worst", type=int, default=12)
|
| 117 |
+
a = ap.parse_args()
|
| 118 |
+
paths = prepare(a.split, a.n)
|
| 119 |
+
with Pool(a.workers) as pool:
|
| 120 |
+
recs = pool.map(evaluate_one, [str(p) for p in paths], chunksize=1)
|
| 121 |
+
a.out.mkdir(parents=True, exist_ok=True)
|
| 122 |
+
(a.out / "results.json").write_text(json.dumps(recs, indent=1, default=str))
|
| 123 |
+
df = pd.DataFrame(recs)
|
| 124 |
+
if "gt_invalid" in df:
|
| 125 |
+
n_bad = int(df["gt_invalid"].fillna(False).astype(bool).sum())
|
| 126 |
+
if n_bad:
|
| 127 |
+
print(f"excluded {n_bad} chart(s) with degenerate ground truth")
|
| 128 |
+
df = df[~df["gt_invalid"].fillna(False).astype(bool)]
|
| 129 |
+
df["kind"] = df["mark"] + "/" + df["x_type"]
|
| 130 |
+
ok = df[df["ok"]]
|
| 131 |
+
good = ok[~ok["abstain"]]
|
| 132 |
+
|
| 133 |
+
def summary(g: pd.DataFrame) -> pd.Series:
|
| 134 |
+
e = g[g["ok"] & ~g["abstain"].astype(bool)]
|
| 135 |
+
return pd.Series({
|
| 136 |
+
"n": len(g), "crash": int((~g["ok"]).sum()),
|
| 137 |
+
"status_ok": (g["status"] == "ok").mean(),
|
| 138 |
+
"abstain": g["abstain"].astype(bool).mean(),
|
| 139 |
+
"rnss": g["rnss"].fillna(0).mean(),
|
| 140 |
+
"recall": g["recall"].fillna(0).mean(),
|
| 141 |
+
"med_err": e["median_err"].median(),
|
| 142 |
+
"p90_chart_err": e["median_err"].quantile(0.9),
|
| 143 |
+
"within_1pct": (e["median_err"] < 0.01).sum() / max(len(g), 1),
|
| 144 |
+
"silent_fail": ((e["status"] == "ok") & ((e["median_err"] > 0.02) | (e["recall"] < 0.5))).sum()
|
| 145 |
+
/ max(len(g), 1),
|
| 146 |
+
})
|
| 147 |
+
|
| 148 |
+
pd.set_option("display.width", 200, "display.precision", 4)
|
| 149 |
+
table = pd.DataFrame({k: summary(g) for k, g in df.groupby("kind")}).T
|
| 150 |
+
table.loc["ALL"] = summary(df)
|
| 151 |
+
print(table.to_string())
|
| 152 |
+
worst = df.assign(bad=df["rnss"].fillna(-1)).sort_values("bad").head(a.worst)
|
| 153 |
+
wdir = a.out / "worst"
|
| 154 |
+
wdir.mkdir(parents=True, exist_ok=True)
|
| 155 |
+
print("\nworst cases:")
|
| 156 |
+
for _, r in worst.iterrows():
|
| 157 |
+
print(f" {r['chart']} {r['kind']} status={r.get('status')} type={r.get('type')} rnss={r.get('rnss')!s:.5} "
|
| 158 |
+
f"err={r.get('median_err')!s:.6} | {'; '.join((r.get('warnings') or [])[:3]) if isinstance(r.get('warnings'), list) else r.get('error')}")
|
| 159 |
+
try:
|
| 160 |
+
res = pipeline.run(OUT / a.split / f"{r['chart']}.png")
|
| 161 |
+
export.write_debug_overlay(res, wdir / f"{r['chart']}.debug.png")
|
| 162 |
+
except Exception: # noqa: BLE001
|
| 163 |
+
pass
|
| 164 |
+
_ = good
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
if __name__ == "__main__":
|
| 168 |
+
main()
|
tests/metrics.py
CHANGED
|
@@ -225,3 +225,27 @@ def tick_recall(pred_px: list[float], gt_px: list[float], tol: float) -> float:
|
|
| 225 |
if p.size == 0:
|
| 226 |
return 0.0
|
| 227 |
return float(np.mean([np.min(np.abs(p - g)) <= tol for g in gt_px]))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
if p.size == 0:
|
| 226 |
return 0.0
|
| 227 |
return float(np.mean([np.min(np.abs(p - g)) <= tol for g in gt_px]))
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def rnss(pred: pd.DataFrame | None, gt: pd.DataFrame) -> float:
|
| 231 |
+
"""Relative Number Set Similarity (ChartQA / DePlot chart-to-table metric), in [0, 1].
|
| 232 |
+
|
| 233 |
+
Compares only the unordered sets of numeric values (series cells): pairwise cost
|
| 234 |
+
min(1, |p - t| / |t|), optimal 1-1 matching, normalised by the larger set size.
|
| 235 |
+
"""
|
| 236 |
+
def nums(df: pd.DataFrame | None) -> np.ndarray:
|
| 237 |
+
if df is None or df.shape[1] < 2:
|
| 238 |
+
return np.zeros(0)
|
| 239 |
+
v = pd.to_numeric(df.iloc[:, 1:].stack(), errors="coerce").to_numpy(float)
|
| 240 |
+
return v[np.isfinite(v)]
|
| 241 |
+
|
| 242 |
+
p, t = nums(pred), nums(gt)
|
| 243 |
+
if len(t) == 0:
|
| 244 |
+
return float(len(p) == 0)
|
| 245 |
+
if len(p) == 0:
|
| 246 |
+
return 0.0
|
| 247 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 248 |
+
cost = np.minimum(1.0, np.abs(p[None, :] - t[:, None]) / np.abs(t[:, None]))
|
| 249 |
+
cost = np.nan_to_num(cost, nan=1.0, posinf=1.0)
|
| 250 |
+
r, c = linear_sum_assignment(cost)
|
| 251 |
+
return float(1.0 - cost[r, c].sum() / max(len(p), len(t)))
|
tests/plot_progress.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Plot development progress from saved evaluation results.
|
| 2 |
+
|
| 3 |
+
python -m tests.plot_progress # writes docs/progress.png
|
| 4 |
+
|
| 5 |
+
Every metric is recomputed from ``eval_out/*/results.json`` with the same chart
|
| 6 |
+
exclusions (degenerate ground truth) for every run, so the points are comparable.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import matplotlib
|
| 15 |
+
|
| 16 |
+
matplotlib.use("Agg")
|
| 17 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 18 |
+
import numpy as np # noqa: E402
|
| 19 |
+
import pandas as pd # noqa: E402
|
| 20 |
+
|
| 21 |
+
EVAL = Path("eval_out")
|
| 22 |
+
PLOTQA = Path("data/benchmarks/plotqa")
|
| 23 |
+
|
| 24 |
+
# Iterations on the PlotQA test split (tuning set), oldest first.
|
| 25 |
+
TEST_RUNS = [
|
| 26 |
+
("plotqa_base", "baseline"),
|
| 27 |
+
("plotqa_v1", "rotated labels,\nrotated titles,\ndotted lines"),
|
| 28 |
+
("plotqa_v2", "outline colours,\nyear categories"),
|
| 29 |
+
("plotqa_v3", "scatter on\ncategories"),
|
| 30 |
+
("plotqa_final_test", "clipping check,\nguards"),
|
| 31 |
+
]
|
| 32 |
+
HELDOUT = [("plotqa_train300_baseline", "before"), ("plotqa_final_train300", "after")]
|
| 33 |
+
# Synthetic perturbed tier, silent-failure rate per milestone (EVAL_LOG.md; the
|
| 34 |
+
# last point is recomputed from eval_out/final2_perturbed when present).
|
| 35 |
+
SYNTH_SILENT = [("first\nmeasured", 28.5), ("panels,\nclipped labels", 12.0), ("log axes", 9.0),
|
| 36 |
+
("bar categories", 8.0)]
|
| 37 |
+
|
| 38 |
+
# Validated palette (dataviz skill, light mode) and chart chrome.
|
| 39 |
+
SLOTS = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"]
|
| 40 |
+
INK, INK2, MUTED, GRID, AXIS, SURFACE = "#0b0b0b", "#52514e", "#898781", "#e1e0d9", "#c3c2b7", "#fcfcfb"
|
| 41 |
+
BASELINE_GREY = "#c3c2b7"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _degenerate(split: str, chart: str) -> bool:
|
| 45 |
+
p = PLOTQA / split / f"{chart}.csv"
|
| 46 |
+
if not p.exists():
|
| 47 |
+
return False
|
| 48 |
+
y = pd.read_csv(p).iloc[:, 1].to_numpy(float)
|
| 49 |
+
return bool(np.ptp(y) == 0)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def plotqa_metrics(run: str) -> dict[str, float] | None:
|
| 53 |
+
f = EVAL / run / "results.json"
|
| 54 |
+
if not f.exists():
|
| 55 |
+
return None
|
| 56 |
+
recs = [r for r in json.loads(f.read_text())
|
| 57 |
+
if not _degenerate("test" if r["chart"].startswith("test") else "train", r["chart"])]
|
| 58 |
+
n = len(recs)
|
| 59 |
+
|
| 60 |
+
def val(r: dict, k: str) -> float:
|
| 61 |
+
v = r.get(k)
|
| 62 |
+
return float(v) if isinstance(v, (int, float)) and v == v else np.nan
|
| 63 |
+
|
| 64 |
+
rnss = np.mean([0.0 if np.isnan(val(r, "rnss")) else val(r, "rnss") for r in recs])
|
| 65 |
+
recall = np.mean([0.0 if np.isnan(val(r, "recall")) else val(r, "recall") for r in recs])
|
| 66 |
+
ok = np.mean([r.get("status") == "ok" for r in recs])
|
| 67 |
+
within = np.mean([val(r, "median_err") < 0.01 for r in recs])
|
| 68 |
+
silent = np.mean([r.get("status") == "ok" and not r.get("abstain") and
|
| 69 |
+
((val(r, "median_err") > 0.02) or (val(r, "recall") < 0.5)) for r in recs])
|
| 70 |
+
return {"n": n, "RNSS": 100 * rnss, "Point recall": 100 * recall, "Within 1% error": 100 * within,
|
| 71 |
+
"Status ok": 100 * ok, "Silent failures": 100 * silent}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def synth_silent_now() -> float | None:
|
| 75 |
+
f = EVAL / "final2_perturbed" / "results.json"
|
| 76 |
+
if not f.exists():
|
| 77 |
+
return None
|
| 78 |
+
recs = [r for r in json.loads(f.read_text()) if r.get("ok")]
|
| 79 |
+
bad = [r for r in recs if r.get("has_table") and r.get("status") == "ok"
|
| 80 |
+
and ((r.get("median_err") or 0) > 0.02 or (r.get("recall") or 0) < 0.5)]
|
| 81 |
+
return 100 * len(bad) / max(len(json.loads(f.read_text())), 1)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _style(ax: plt.Axes, title: str) -> None:
|
| 85 |
+
ax.set_facecolor(SURFACE)
|
| 86 |
+
ax.grid(True, axis="y", color=GRID, lw=0.6)
|
| 87 |
+
ax.set_axisbelow(True)
|
| 88 |
+
for side in ("top", "right"):
|
| 89 |
+
ax.spines[side].set_visible(False)
|
| 90 |
+
for side in ("left", "bottom"):
|
| 91 |
+
ax.spines[side].set_color(AXIS)
|
| 92 |
+
ax.tick_params(colors=MUTED, labelsize=8)
|
| 93 |
+
ax.set_title(title, color=INK, fontsize=10, loc="left", pad=10)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def main() -> None:
|
| 97 |
+
metrics = ["RNSS", "Point recall", "Within 1% error", "Status ok"]
|
| 98 |
+
fig, axes = plt.subplots(1, 3, figsize=(15, 5.2), dpi=150, gridspec_kw={"width_ratios": [1.5, 1, 1]})
|
| 99 |
+
fig.patch.set_facecolor(SURFACE)
|
| 100 |
+
|
| 101 |
+
# 1. PlotQA test split across iterations.
|
| 102 |
+
ax = axes[0]
|
| 103 |
+
runs = [(lab, plotqa_metrics(r)) for r, lab in TEST_RUNS]
|
| 104 |
+
runs = [(lab, m) for lab, m in runs if m]
|
| 105 |
+
xs = np.arange(len(runs))
|
| 106 |
+
ends = []
|
| 107 |
+
for name, col in zip(metrics, SLOTS):
|
| 108 |
+
ys = [m[name] for _, m in runs]
|
| 109 |
+
ax.plot(xs, ys, color=col, lw=2, marker="o", ms=5, label=name)
|
| 110 |
+
ends.append([ys[-1], ys[-1], name])
|
| 111 |
+
# De-overlap the end labels: keep at least ~5 units between them.
|
| 112 |
+
ends.sort(key=lambda e: -e[0])
|
| 113 |
+
for i in range(1, len(ends)):
|
| 114 |
+
ends[i][1] = min(ends[i][1], ends[i - 1][1] - 5)
|
| 115 |
+
for y, ly, name in ends:
|
| 116 |
+
ax.annotate(f"{name} {y:.0f}%", (xs[-1], y), xytext=(xs[-1] + 0.15, ly), textcoords="data",
|
| 117 |
+
va="center", fontsize=8, color=INK2)
|
| 118 |
+
ax.set_xticks(xs, [lab for lab, _ in runs], fontsize=7)
|
| 119 |
+
ax.set_xlim(-0.3, len(runs) - 1 + 1.4)
|
| 120 |
+
ax.set_ylim(0, 102)
|
| 121 |
+
ax.set_ylabel("% of charts / points", color=MUTED, fontsize=8)
|
| 122 |
+
n_test = runs[0][1]["n"] if runs else 0
|
| 123 |
+
_style(ax, f"PlotQA test split ({n_test} charts): progress per iteration")
|
| 124 |
+
ax.legend(frameon=False, fontsize=7, labelcolor=INK2, loc="lower right")
|
| 125 |
+
|
| 126 |
+
# 2. Held-out PlotQA: before vs after.
|
| 127 |
+
ax = axes[1]
|
| 128 |
+
held = [(lab, plotqa_metrics(r)) for r, lab in HELDOUT]
|
| 129 |
+
held = [(lab, m) for lab, m in held if m]
|
| 130 |
+
if len(held) == 2:
|
| 131 |
+
width = 0.38
|
| 132 |
+
xs = np.arange(len(metrics))
|
| 133 |
+
for j, ((lab, m), col) in enumerate(zip(held, [BASELINE_GREY, SLOTS[0]])):
|
| 134 |
+
vals = [m[k] for k in metrics]
|
| 135 |
+
bars = ax.bar(xs + (j - 0.5) * width, vals, width - 0.04, color=col, label=lab)
|
| 136 |
+
for b, v in zip(bars, vals):
|
| 137 |
+
ax.annotate(f"{v:.0f}", (b.get_x() + b.get_width() / 2, v), xytext=(0, 2),
|
| 138 |
+
textcoords="offset points", ha="center", fontsize=7, color=INK2)
|
| 139 |
+
ax.set_xticks(xs, [k.replace(" ", "\n", 1) for k in metrics], fontsize=8)
|
| 140 |
+
ax.set_ylim(0, 108)
|
| 141 |
+
ax.legend(frameon=False, fontsize=8, labelcolor=INK2, loc="upper left", ncol=2)
|
| 142 |
+
_style(ax, f"Held-out PlotQA ({held[0][1]['n']} unseen charts)")
|
| 143 |
+
|
| 144 |
+
# 3. Silent failures (status ok but wrong) - the safety metric.
|
| 145 |
+
ax = axes[2]
|
| 146 |
+
pts = list(SYNTH_SILENT)
|
| 147 |
+
now = synth_silent_now()
|
| 148 |
+
if now is not None:
|
| 149 |
+
pts.append(("now", now))
|
| 150 |
+
xs = np.arange(len(pts))
|
| 151 |
+
ys = [v for _, v in pts]
|
| 152 |
+
ax.plot(xs, ys, color=SLOTS[1], lw=2, marker="o", ms=5, label="synthetic, perturbed styles (200)")
|
| 153 |
+
for x, y in zip(xs, ys):
|
| 154 |
+
ax.annotate(f"{y:.1f}%", (x, y), xytext=(0, 6), textcoords="offset points", ha="center",
|
| 155 |
+
fontsize=7, color=INK2)
|
| 156 |
+
hb, hn = [m for _, m in held][:2] if len(held) == 2 else (None, None)
|
| 157 |
+
if hb and hn:
|
| 158 |
+
ax.plot([xs[-2], xs[-1]], [hb["Silent failures"], hn["Silent failures"]], color=SLOTS[0], lw=2,
|
| 159 |
+
marker="o", ms=5, label="held-out PlotQA (287)")
|
| 160 |
+
ax.set_xticks(xs, [lab for lab, _ in pts], fontsize=7)
|
| 161 |
+
ax.set_ylim(0, max(ys + [10]) * 1.2)
|
| 162 |
+
ax.set_ylabel("% of charts reported 'ok' but wrong", color=MUTED, fontsize=8)
|
| 163 |
+
ax.legend(frameon=False, fontsize=7, labelcolor=INK2, loc="upper right")
|
| 164 |
+
_style(ax, "Silent failures (lower is better)")
|
| 165 |
+
|
| 166 |
+
fig.suptitle("plotscribe accuracy progress", x=0.01, ha="left", color=INK, fontsize=12)
|
| 167 |
+
fig.tight_layout()
|
| 168 |
+
out = Path("docs/progress.png")
|
| 169 |
+
out.parent.mkdir(exist_ok=True)
|
| 170 |
+
fig.savefig(out, facecolor=SURFACE)
|
| 171 |
+
print(f"wrote {out}")
|
| 172 |
+
for lab, m in runs + held:
|
| 173 |
+
print(f" {lab.replace(chr(10), ' '):40s} " + " ".join(f"{k}={m[k]:.1f}" for k in metrics + ["Silent failures"]))
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
if __name__ == "__main__":
|
| 177 |
+
main()
|