jkos9 Claude Opus 5.5 commited on
Commit
6f423bd
·
0 Parent(s):

plotscribe: classical-CV chart image to CSV extractor

Browse files

Pipeline (axes, OCR calibration, legend, series separation, line/bar/scatter
extraction), synthetic evaluation harness, tests, FastAPI upload page and
Dockerfile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

.dockerignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ .venv
2
+ data
3
+ eval_out
4
+ out
5
+ tests
6
+ **/__pycache__
7
+ *.egg-info
8
+ .git
.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ .pytest_cache/
5
+ /data/
6
+ /out/
7
+ /eval_out/
8
+ .DS_Store
Dockerfile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Small CPU-only image: Python + OpenCV (headless) + Tesseract. No GPU, no ML models.
2
+ FROM python:3.12-slim
3
+
4
+ RUN apt-get update \
5
+ && apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-eng \
6
+ && rm -rf /var/lib/apt/lists/*
7
+
8
+ WORKDIR /app
9
+ COPY pyproject.toml README.md ./
10
+ COPY plotscribe ./plotscribe
11
+ RUN pip install --no-cache-dir ".[web]"
12
+
13
+ ENV OMP_NUM_THREADS=1
14
+ EXPOSE 8000
15
+ CMD ["uvicorn", "plotscribe.web:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2"]
EVAL_LOG.md ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # plotscribe evaluation log
2
+
3
+ Per-stage results, failure analysis and what was changed. Errors are fractions of
4
+ the axis range (log10 space for log axes). "clean" = default matplotlib PNG export;
5
+ "perturbed" = random style/font/resolution/JPEG/log/markers/dashes/legend position.
6
+ Regenerate any table with the command shown (data is generated deterministically
7
+ from the seed).
8
+
9
+ ## Stage 1 — scaffold, synthetic generator, evaluation harness
10
+
11
+ - `tests/synth.py` renders random charts with matplotlib and stores exact ground
12
+ truth: data, axis limits/scale, and the *pixel* plot box and tick positions taken
13
+ from matplotlib's transforms (verified by overlaying them on renders).
14
+ - `tests/metrics.py`: per-point error (numeric x: GT x interpolated on the
15
+ predicted polyline; categorical: matched by category; scatter: optimal 1-1 point
16
+ matching), series matched by Hungarian assignment; calibration error at the GT
17
+ tick pixels; tick recall (±1.5 px).
18
+ - `tests/evaluate.py`: parallel evaluation, summaries by chart type / tier /
19
+ perturbation, and debug overlays of the worst cases in `<out>/worst/`.
20
+
21
+ ## Stage 2 — axes, ticks, OCR, calibration
22
+
23
+ `python -m tests.evaluate --n 100 --tier clean`
24
+
25
+ | metric (100 clean charts, all types) | first run | after fixes |
26
+ |---|---|---|
27
+ | plot-box IoU (median) | 0.986 | 0.988 |
28
+ | x / y tick recall | 0.99 / 0.999 | 1.00 / 1.00 |
29
+ | y axis type correct (linear/log/categorical) | 0.75 | 1.00 |
30
+ | y calibration error median / p90 | 0.08% / 0.17% | 0.07% / 0.14% |
31
+ | y calibration failures (>1% error or none) | 26% | 0% |
32
+
33
+ Failures found and fixed:
34
+ 1. Gridlines lose the pixels where they cross a spine, so the box edge was 4 px
35
+ inside the spine and tick marks leaked into the label region (OCR read "100 -").
36
+ Fix: snap box edges onto spines; drop thin tick remnants at the region border.
37
+ 2. Bars interrupting gridlines out-voted the spines for the plot bottom (negative
38
+ bar charts used the zero line as the x axis -> tick length 24 px -> the last
39
+ digit of every y label cut off -> a *consistent but 10x wrong* calibration).
40
+ Fix: plot box from the outer extent of long lines; per-axis tick length.
41
+ 3. Tesseract misreads isolated single digits and drops the U+2212 minus sign.
42
+ Fix: geometric minus-sign detection; each numeric label is read three ways
43
+ (line/numeric line/numeric word) and RANSAC chooses among the candidate values.
44
+
45
+ Residual error (~0.1-0.2%) is dominated by matplotlib snapping tick marks to the
46
+ pixel grid (up to 0.5 px), i.e. a property of the rendering, not of the fit.
47
+
48
+ ## Stage 3 — line charts end to end
49
+
50
+ `python -m tests.evaluate --n 100 --tier clean --kinds line --oracle-type --start-seed 2000`
51
+ (`--oracle-type` passes the true chart type so this stage is scored in isolation.)
52
+
53
+ | metric (100 clean line charts) | first run (20 charts) | final |
54
+ |---|---|---|
55
+ | point recall | 0.85 | 0.997 |
56
+ | series count correct | 0.60 | 1.00 |
57
+ | median of per-chart median error | 0.16% | 0.19% |
58
+ | p90 of per-chart median error | 0.60% | 0.39% |
59
+ | per-chart max error: median / p90 | | 1.5% / 5.6% |
60
+
61
+ Failures found and fixed:
62
+ 1. Long category labels touch/overlap -> merged OCR boxes -> wrong category
63
+ positions. Fix: assign label glyphs to tick cells when ticks are regular; one
64
+ label per tick (fragments re-read together).
65
+ 2. matplotlib offset text ("+1.063e3" at the end of the axis) made all x values
66
+ relative. Fix: detect and parse offset/multiplier text, apply to labels.
67
+ 3. Anti-aliased edges formed their own colour peaks (one series became 2-3).
68
+ Blending is linear in sRGB, not Lab, so the blend test and soft assignment now
69
+ run in sRGB.
70
+ 4. Semi-transparent legends over data lines: glyphs and swatches fused with the
71
+ faded lines -> legend entries missed. Fix: text from dark achromatic pixels,
72
+ swatches from strong-contrast pixels only.
73
+
74
+ Remaining worst cases (clean): max errors of 10-20% at isolated points where
75
+ several lines cross and one series is occluded around a vertex; the polyline
76
+ interpolates across the occlusion and cuts the corner.
77
+
78
+ Perturbed lines (`--tier perturbed`, 100 charts): calibration fails on 45% —
79
+ almost entirely non-default styles (Solarize, ggplot, fivethirtyeight: no spines
80
+ or tinted panels; bmh/classic: inward ticks) and low resolution. Deferred to
81
+ stage 7 by design.
82
+
83
+ ## Stage 4 — bar charts (simple, grouped, stacked, negative)
84
+
85
+ `python -m tests.evaluate --n 150 --tier clean --kinds bar,grouped_bar,stacked_bar --oracle-type --start-seed 3000`
86
+
87
+ | 150 clean bar charts | first run | final |
88
+ |---|---|---|
89
+ | median of per-chart median error | — (bars sliced) | 0.12% |
90
+ | worst point error (all charts) | 54% | 0.86% |
91
+ | recall | | 98.8% (rest = bars hidden by the legend, left empty) |
92
+
93
+ Failures found and fixed:
94
+ 1. matplotlib draws gridlines *over* bars; removing grey pixels sliced every bar and
95
+ the grey/colour blend became a fake series. Fix: inpaint gridlines with a
96
+ per-pixel "semi-transparent grey overlay" model (P = N + a(g - N)).
97
+ 2. The gridline detector estimated "background" as the region median, which is a bar
98
+ colour in stacked charts. Fix: use the detected panel background.
99
+ 3. Bar edges integrated alpha from edge to mid-bar, picking up interior deficits
100
+ (tall bars read 1-2% low). Fix: integrate across the edge zone only.
101
+ 4. Bar tops coinciding with a gridline split off slivers. Fix: merge pieces
102
+ (symmetric adjacency test).
103
+ 5. Legend placed over tall bars (`loc="best"`) truncated them. Fix: bars ending
104
+ at the legend box are reported as occluded (empty + warning).
105
+
106
+ ## Stage 5 — scatter
107
+
108
+ `python -m tests.evaluate --n 100 --tier clean --kinds scatter --oracle-type --start-seed 4000`
109
+ Median error 0.096%, recall 98.3%, series count 97%. Fixes: tick at the plot corner
110
+ extended the spine and moved the plot bottom 8 px (digits cut → "0" read as "U");
111
+ legend markers sit ~2 glyphs from their text (wider pairing gap). Remaining misses
112
+ are markers >70% hidden by other series.
113
+
114
+ ## Stage 6 — chart type, legend pairing, series count (no oracle)
115
+
116
+ 200 clean charts: chart type 100% (stacked vs grouped included), series count 99%,
117
+ recall 98.7%, median 0.11%, 0 silent failures.
118
+
119
+ ## Stage 7 — robustness (perturbed tier, 200 charts, seed 6000)
120
+
121
+ | metric | baseline | final |
122
+ |---|---|---|
123
+ | silent failures (status ok, wrong) | 28.5% | 8% |
124
+ | y calibration failures | 38% | 29% |
125
+ | chart type accuracy | 85% | 92% |
126
+ | median of per-chart median error | 0.42% | 0.26% |
127
+
128
+ Fixes: low-contrast and tinted panels (Solarize/ggplot: neutral-colour candidates,
129
+ opening + cell growth); ticks hanging from the panel edge without axis lines; label
130
+ glyphs selected without clipping (a clipped last digit gave consistent 10x-wrong
131
+ calibrations); clipped-label and data-outside-plot checks lower the status;
132
+ `10^n` superscript labels (geometric split, single-char OCR, log-only fit, bounded
133
+ tick snapping); line vs scatter by chaining continuity; stacked detection robust to
134
+ JPEG fragments; categories re-anchored on bar groups when labels merge.
135
+
136
+ Remaining perturbed failures (from `eval_out/stage7_perturbed`): category labels
137
+ merging on bmh/whitegrid/fivethirtyeight bars without tick marks; fivethirtyeight
138
+ plot box; frameless legends on top of data; low-resolution classic-style JPEG bars
139
+ misclassified as line.
140
+
141
+ ## Consolidation for deployment
142
+
143
+ 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`.
README.md ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # plotscribe
2
+
3
+ Fully automatic conversion of a chart image (PNG/JPG) into a CSV of its data,
4
+ using classical computer vision only: OpenCV, NumPy/SciPy and Tesseract OCR. No
5
+ neural networks or LLM calls at runtime. It is CPU-only, needs no model files, and
6
+ takes about 3–4 s per chart.
7
+
8
+ Supported: line charts, vertical bar charts (simple, grouped, stacked, negative
9
+ values) and scatter plots, with linear, log (including `10^n` labels) and
10
+ categorical axes.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ # system dependency: Tesseract OCR
16
+ brew install tesseract # macOS
17
+ sudo apt install tesseract-ocr # Debian/Ubuntu
18
+
19
+ pip install -e . # library + CLI
20
+ pip install -e ".[web]" # + upload web page
21
+ pip install -e ".[dev]" # + tests / synthetic data (matplotlib)
22
+ ```
23
+
24
+ Runtime dependencies: `numpy`, `opencv-python-headless`, `scipy`, `pandas`,
25
+ `pytesseract`, `typer` (+ `fastapi`, `uvicorn`, `python-multipart` for the web page).
26
+
27
+ ## Usage
28
+
29
+ ```bash
30
+ plotscribe input.png -o out/ [--type line|bar|stacked_bar|scatter] [--debug] [--ocr tesseract|paddle]
31
+ ```
32
+
33
+ This writes:
34
+
35
+ - `out/input.csv`: the data (layout below)
36
+ - `out/input.diagnostics.json`: chart type and confidence, plot area, axis
37
+ calibration (type, slope, intercept, residuals, R²), tick labels, legend mapping,
38
+ number of series and points, per-stage confidences, and warnings
39
+ - `out/input.debug.png` (with `--debug`): plot box, ticks, OCR'd labels, series
40
+ masks, extracted points
41
+
42
+ The exit code is 2 when the status is not `ok`.
43
+
44
+ ```python
45
+ from plotscribe import pipeline, export
46
+ res = pipeline.run("chart.png")
47
+ print(res.extra["status"], res.chart_type, res.warnings)
48
+ res.table # pandas DataFrame
49
+ ```
50
+
51
+ ### Status: the tool says when not to trust it
52
+
53
+ | status | meaning |
54
+ |---|---|
55
+ | `ok` | all stages confident |
56
+ | `low_confidence` | numbers produced, but something is doubtful (few or rejected ticks, uncertain plot area, unreadable categories, data cut by the plot box). Read the warnings. |
57
+ | `uncalibrated` | an axis could not be calibrated; those values are **pixel coordinates** and the column header carries ` [px]` |
58
+ | `failed` | no data series or no chart type found |
59
+
60
+ Values hidden under the legend are left empty and reported in the warnings rather than estimated.
61
+
62
+ ### CSV layout
63
+
64
+ - First column `category` (categorical x axis) or `x` (numeric x axis).
65
+ - Then one column per series, named after the legend label (`series_1..n` if there is no legend), in legend order.
66
+ - Line/bar: one row per x position or category. Line charts give points at markers if present, else at category positions, else at the polyline vertices.
67
+ - Scatter: one row per point; only the owning series' column is filled.
68
+ - Stacked bars: headers end in ` (segment)`; values are segment heights, not cumulative tops.
69
+
70
+ ## Web page
71
+
72
+ ```bash
73
+ uvicorn plotscribe.web:app --port 8000 # http://localhost:8000
74
+ # or
75
+ docker build -t plotscribe . && docker run -p 8000:8000 plotscribe
76
+ ```
77
+
78
+ `GET /` serves a single upload page. `POST /api/extract` (multipart `file`,
79
+ optional `chart_type`) returns JSON with `status`, `warnings`, `csv`,
80
+ `diagnostics` and a base64 `debug_png`. Uploads are limited to 10 MB / 25 MP.
81
+ The Docker image is `python:3.12-slim` + `tesseract-ocr`. Each request is CPU-bound
82
+ for a few seconds, so scale with uvicorn workers.
83
+
84
+ ## How it works
85
+
86
+ 1. **preprocess**: RGB, deskew small rotations, Lanczos upscale to ≥800 px short side, bilateral denoise if noisy.
87
+ 2. **axes**: long thin achromatic lines (spines and gridlines) or a tinted background panel give the plot box; tick marks are found by run-length scans next to the axis or box edge, with gridlines as a fallback.
88
+ 3. **OCR + calibration**: label glyphs are grouped geometrically (one label per tick cell) and read one by one with several Tesseract modes. Minus signs and `10^n` superscripts are detected geometrically, and matplotlib offset text (`1e6`, `+1.06e3`) is applied. RANSAC over all candidate readings fits linear and log models and keeps the better one. Categorical axes keep ordered label strings and positions.
89
+ 4. **legend**: colour swatches (line, patch or marker) next to text lines; labels are OCR'd and the box is masked out.
90
+ 5. **series**: gridlines are inpainted (a semi-transparent grey-overlay model, so data drawn on top survives). Colours are found by mode-seeking on a Lab histogram, which picks k automatically, and anti-aliased blends are merged in sRGB. Pixels are softly assigned along background→colour blend lines.
91
+ 6. **chart type**: rectangles on a shared baseline (bar), chained pieces along x (line), unchained compact blobs (scatter).
92
+ 7. **extraction**:
93
+ - line: sub-pixel centreline, markers, or RDP vertices refined by intersecting fitted segments.
94
+ - bar: sub-pixel edges from alpha coverage, zero-line baseline, stacked/grouped detection, categories re-anchored on bar groups when labels are ambiguous.
95
+ - scatter: alpha-weighted centroids; touching markers split by distance-transform peaks; circle fit for occluded markers.
96
+
97
+ ## Evaluation
98
+
99
+ Synthetic charts with exact pixel-level ground truth (`tests/synth.py`). Errors are
100
+ fractions of the axis range. Full history and failure analysis: `EVAL_LOG.md`.
101
+
102
+ ```bash
103
+ python -m tests.evaluate --n 200 --tier clean --start-seed 5000 # or --tier perturbed
104
+ python -m tests.eval_real # charts in tests/real/
105
+ pytest # includes the CI accuracy target
106
+ ```
107
+
108
+ | 200 charts, auto type | clean (default matplotlib PNG) | perturbed (styles, fonts, 50–150 dpi, JPEG q40–95, log, dashes, markers) |
109
+ |---|---|---|
110
+ | chart type correct | 100% | 92% |
111
+ | series count correct | 99% | 80% |
112
+ | point recall | 98.7% | 79% |
113
+ | median of per-chart median error | **0.11%** | 0.26% |
114
+ | p90 of per-chart median error | 0.24% | 4.1% |
115
+ | status `ok` | 100% | 58% |
116
+ | abstained (`uncalibrated`/`failed`) | 0% | 21% |
117
+ | **silent failures** (status `ok` but median error > 2% or recall < 50%) | **0%** | 8% |
118
+
119
+ The CI target (median error < 1% on clean charts) is met for every chart type.
120
+ On clean charts the worst single bar value is 0.9% off (150 bar charts); for lines
121
+ the per-chart worst point has a median of 1.5% (at occluded crossings).
122
+
123
+ ## Known limitations
124
+
125
+ - **Perturbed styles**: 21% of perturbed charts abstain and 8% are silently
126
+ wrong. Weak spots: fivethirtyeight (no spines, panel = figure colour),
127
+ frameless legends drawn over data, bmh/classic low-resolution JPEGs, and
128
+ heavily overlapping category labels.
129
+ - Not yet supported: horizontal bars, area charts, rotated x labels, dates parsed
130
+ as dates (they are treated as categories), dual y axes, pie charts, 3-D charts.
131
+ - A series needs its own colour; two series of the same colour (e.g. differing only
132
+ by dash pattern) are merged. Very light colours (ΔE < ~15 from the background)
133
+ are missed.
134
+ - Line charts without markers are reported at polyline vertices. Where lines cross
135
+ and occlude each other a vertex can be cut (up to 10–20% error at that point).
136
+ - Scatter markers that are more than ~70% hidden by other markers are not recovered.
137
+ - Tesseract dominates runtime (about 20–60 calls per chart).
138
+ - Real-world accuracy is unmeasured until charts are added to `tests/real/`.
plotscribe/axes.py ADDED
@@ -0,0 +1,590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plot-area, axis-line, tick and tick-label localisation.
2
+
3
+ Assumptions:
4
+ - Axes are horizontal/vertical (preprocess deskews small rotations).
5
+ - Axis lines and gridlines are achromatic (grey/black/white); data may be any colour.
6
+ - Tick labels sit outside the plot area: x labels below, y labels to the left.
7
+ All thresholds are derived from the image size, line thickness or glyph height.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import cv2
13
+ import numpy as np
14
+
15
+ from .models import AxesResult, BBox, Segment
16
+
17
+ # Fractions of the image dimension; scale-free by construction.
18
+ MIN_AXIS_LINE_FRAC = 0.25
19
+ MAX_LINE_THICK_FRAC = 0.008
20
+ GRID_CHROMA_MAX = 22.0
21
+
22
+
23
+ # ----------------------------------------------------------------------------- colours
24
+
25
+ def delta_e(lab: np.ndarray, ref: np.ndarray) -> np.ndarray:
26
+ """CIE76 colour distance of every pixel to ``ref``."""
27
+ return np.linalg.norm(lab - np.asarray(ref, np.float32).reshape(1, 1, 3), axis=-1)
28
+
29
+
30
+ def dominant_lab(pixels: np.ndarray, bin_size: float = 3.0) -> np.ndarray:
31
+ """Most frequent colour (mode over a quantised Lab histogram, then local mean)."""
32
+ pix = pixels.reshape(-1, 3)
33
+ if len(pix) > 400_000:
34
+ pix = pix[:: len(pix) // 400_000 + 1]
35
+ q = np.round(pix / bin_size).astype(np.int32)
36
+ uniq, counts = np.unique(q, axis=0, return_counts=True)
37
+ mode = uniq[np.argmax(counts)].astype(np.float32) * bin_size
38
+ near = pix[np.linalg.norm(pix - mode, axis=1) < 2 * bin_size]
39
+ return near.mean(axis=0) if len(near) else mode
40
+
41
+
42
+ def chroma(lab: np.ndarray) -> np.ndarray:
43
+ return np.hypot(lab[..., 1], lab[..., 2])
44
+
45
+
46
+ def figure_background(lab: np.ndarray) -> np.ndarray:
47
+ """Background colour from a thin frame around the image border."""
48
+ h, w = lab.shape[:2]
49
+ m = max(2, int(0.02 * min(h, w)))
50
+ frame = np.concatenate([lab[:m].reshape(-1, 3), lab[-m:].reshape(-1, 3),
51
+ lab[:, :m].reshape(-1, 3), lab[:, -m:].reshape(-1, 3)])
52
+ return dominant_lab(frame)
53
+
54
+
55
+ def ink_threshold(noise_sigma: float) -> float:
56
+ """Minimum Lab distance from the background for a pixel to count as ink."""
57
+ return 10.0 + 1.5 * noise_sigma
58
+
59
+
60
+ def find_panel(lab: np.ndarray, fig_bg: np.ndarray, thr: float) -> tuple[BBox | None, np.ndarray]:
61
+ """A large rectangle filled with a non-figure-background colour (ggplot-style panels)."""
62
+ h, w = lab.shape[:2]
63
+ # Panels can be very close to the figure colour (Solarize: ~6 dE), so use a
64
+ # lower threshold than for ink; the rectangle test below guards against noise.
65
+ pthr = max(3.0, 0.4 * thr)
66
+ nonbg = delta_e(lab, fig_bg) > pthr
67
+ if nonbg.mean() < 0.15:
68
+ return None, fig_bg
69
+ pix = lab[nonbg]
70
+ # The panel is not necessarily the most frequent colour (bars can cover more),
71
+ # so test the few most frequent colours for a large filled rectangle.
72
+ for _ in range(4):
73
+ if len(pix) < 0.05 * h * w:
74
+ break
75
+ cand = dominant_lab(pix)
76
+ pix = pix[np.linalg.norm(pix - cand, axis=1) > 2 * pthr]
77
+ if np.linalg.norm(cand - fig_bg) < pthr or np.hypot(cand[1], cand[2]) > 25:
78
+ continue # panels are near-neutral; saturated rectangles are data (bars)
79
+ tol = max(pthr, 0.5 * float(np.linalg.norm(cand - fig_bg)))
80
+ pmask = (delta_e(lab, cand) < tol).astype(np.uint8)
81
+ if pmask.mean() < 0.1:
82
+ continue
83
+ box = _projection_extent(pmask)
84
+ if box is None:
85
+ continue
86
+ x, y, x1, y1 = box
87
+ bw, bh = x1 - x, y1 - y
88
+ # A panel is a big rectangle: mostly its own colour even with data drawn on
89
+ # top, and it does not touch the image border.
90
+ own = pmask[y:y1, x:x1].mean()
91
+ if bw * bh >= 0.2 * h * w and own >= 0.35 and x > 0 and y > 0 and x1 < w and y1 < h:
92
+ return BBox(float(x), float(y), float(x1), float(y1)), cand
93
+ return None, fig_bg
94
+
95
+
96
+ def _projection_extent(m: np.ndarray) -> tuple[int, int, int, int] | None:
97
+ """Bounding box of the substantial regions of ``m`` after an opening.
98
+
99
+ The opening (kernel ~1% of the image) deletes thin look-alikes such as
100
+ anti-aliased text and JPEG noise, which a closing would instead connect to
101
+ the panel; bars and gridlines drawn on the panel only cut holes into it.
102
+ """
103
+ h, w = m.shape
104
+ k = max(3, int(0.01 * min(h, w)))
105
+ opened = cv2.morphologyEx(m, cv2.MORPH_OPEN, np.ones((k, k), np.uint8))
106
+ n, _, stats, _ = cv2.connectedComponentsWithStats(opened, connectivity=4)
107
+ if n <= 1:
108
+ return None
109
+ # Gridlines cut the panel into cells: grow from the largest cell, adding cells
110
+ # separated from it by no more than a gridline (< k px). An outside legend
111
+ # with a panel-coloured background is separated by a wider gap.
112
+ boxes = [(int(x), int(y), int(x + bw), int(y + bh)) for x, y, bw, bh, _ in stats[1:]]
113
+ i = int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))
114
+ cur = list(boxes.pop(i))
115
+ tol = k + 2
116
+ grew = True
117
+ while grew:
118
+ grew = False
119
+ for b in list(boxes):
120
+ dx = max(0, b[0] - cur[2], cur[0] - b[2])
121
+ dy = max(0, b[1] - cur[3], cur[1] - b[3])
122
+ if max(dx, dy) <= tol:
123
+ cur = [min(cur[0], b[0]), min(cur[1], b[1]), max(cur[2], b[2]), max(cur[3], b[3])]
124
+ boxes.remove(b)
125
+ grew = True
126
+ return cur[0], cur[1], cur[2], cur[3]
127
+
128
+
129
+ def ink_mask(lab: np.ndarray, fig_bg: np.ndarray, panel: BBox | None, panel_bg: np.ndarray,
130
+ thr: float) -> np.ndarray:
131
+ """Pixels that differ from their local background (figure or panel)."""
132
+ ink = delta_e(lab, fig_bg) > thr
133
+ if panel is not None:
134
+ rs, cs = panel.slices()
135
+ ink[rs, cs] = delta_e(lab[rs, cs], panel_bg) > thr
136
+ return ink
137
+
138
+
139
+ # ----------------------------------------------------------------------------- lines
140
+
141
+ def find_segments(ink: np.ndarray, lab: np.ndarray, orient: str, min_len: int,
142
+ max_thick: int) -> list[Segment]:
143
+ """Thin straight lines of at least ``min_len`` pixels via morphological opening."""
144
+ m = ink.astype(np.uint8)
145
+ if orient == "h":
146
+ long_k = cv2.getStructuringElement(cv2.MORPH_RECT, (min_len, 1))
147
+ thick_k = cv2.getStructuringElement(cv2.MORPH_RECT, (1, max_thick + 1))
148
+ else:
149
+ long_k = cv2.getStructuringElement(cv2.MORPH_RECT, (1, min_len))
150
+ thick_k = cv2.getStructuringElement(cv2.MORPH_RECT, (max_thick + 1, 1))
151
+ opened = cv2.morphologyEx(m, cv2.MORPH_OPEN, long_k)
152
+ thick = cv2.morphologyEx(opened, cv2.MORPH_OPEN, thick_k)
153
+ thin = opened & (1 - thick)
154
+ n, labels, stats, _ = cv2.connectedComponentsWithStats(thin, connectivity=8)
155
+ segs: list[Segment] = []
156
+ for i in range(1, n):
157
+ x, y, bw, bh, area = stats[i]
158
+ length, thickness = (bw, bh) if orient == "h" else (bh, bw)
159
+ if length < min_len or thickness > max_thick + 1:
160
+ continue
161
+ ys, xs = np.nonzero(labels[y:y + bh, x:x + bw] == i)
162
+ col = lab[y + ys, x + xs].mean(axis=0)
163
+ # Continuous coordinates: pixel i spans [i, i + 1).
164
+ if orient == "h":
165
+ pos, start, end = y + ys.mean() + 0.5, float(x), float(x + bw)
166
+ else:
167
+ pos, start, end = x + xs.mean() + 0.5, float(y), float(y + bh)
168
+ segs.append(Segment(orient, float(pos), start, end, float(area) / length, tuple(float(c) for c in col)))
169
+ return segs
170
+
171
+
172
+ def _mode_cluster(vals: list[float], tol: float, prefer: str = "low") -> tuple[float | None, int]:
173
+ """Median of the largest group of values within ``tol``; ties broken by ``prefer``."""
174
+ if not vals:
175
+ return None, 0
176
+ v = np.sort(np.asarray(vals))
177
+ groups: list[list[float]] = [[v[0]]]
178
+ for x in v[1:]:
179
+ if x - groups[-1][-1] <= tol:
180
+ groups[-1].append(x)
181
+ else:
182
+ groups.append([x])
183
+ best = max(groups, key=lambda g: (len(g), -g[0] if prefer == "low" else g[-1]))
184
+ return float(np.median(best)), len(best)
185
+
186
+
187
+ def _snap(edge: float | None, segs: list[Segment], tol: float) -> float | None:
188
+ """Move ``edge`` onto the nearest line within ``0.6 * tol`` (spines vs gridline ends)."""
189
+ if edge is None:
190
+ return None
191
+ near = [s.pos for s in segs if abs(s.pos - edge) <= 0.6 * tol]
192
+ return min(near, key=lambda p: abs(p - edge)) if near else edge
193
+
194
+
195
+ def _pull_in(edge: float | None, segs: list[Segment], window: float) -> float | None:
196
+ """Move ``edge`` to the outermost long line within ``window`` inward (sign = direction)."""
197
+ if edge is None or not segs:
198
+ return edge
199
+ longest = max(s.length for s in segs)
200
+ lo, hi = sorted((edge, edge + window))
201
+ cand = [s.pos for s in segs if s.length >= 0.6 * longest and lo <= s.pos <= hi]
202
+ if not cand:
203
+ return edge
204
+ # Outermost = closest to the original edge.
205
+ return max(cand) if window < 0 else min(cand)
206
+
207
+
208
+ def _extent(segs: list[Segment], lo: float | None, hi: float | None, tol: float) -> tuple[float, float] | None:
209
+ """Outer start/end of the long segments whose position lies in ``[lo, hi]``.
210
+
211
+ Only segments at least 0.6x the longest one vote, so gridlines interrupted by
212
+ bars or a legend cannot pull the edge inwards.
213
+ """
214
+ cand = [s for s in segs if (lo is None or s.pos >= lo - tol) and (hi is None or s.pos <= hi + tol)]
215
+ if not cand:
216
+ return None
217
+ longest = max(s.length for s in cand)
218
+ cand = [s for s in cand if s.length >= 0.6 * longest]
219
+ return min(s.start for s in cand), max(s.end for s in cand)
220
+
221
+
222
+ def estimate_plot_box(h_segs: list[Segment], v_segs: list[Segment], width: int, height: int,
223
+ panel: BBox | None) -> tuple[BBox, float, list[str]]:
224
+ """Plot area from spines/gridlines (their outer extent) or a coloured panel."""
225
+ notes: list[str] = []
226
+ tol_x, tol_y = 0.01 * width, 0.01 * height
227
+ left = right = top = bottom = None
228
+ conf = 1.0
229
+ # Left/right: where horizontal lines start and end (most common value is robust
230
+ # to a chart-area border); then top/bottom from vertical lines inside that span;
231
+ # then refine left/right using horizontal lines inside the vertical span.
232
+ if h_segs:
233
+ left, _ = _mode_cluster([s.start for s in h_segs], tol_x, "low")
234
+ right, _ = _mode_cluster([s.end for s in h_segs], tol_x, "high")
235
+ ext_v = _extent(v_segs, left, right, 2 * tol_x)
236
+ if ext_v:
237
+ top, bottom = ext_v
238
+ if left is None:
239
+ vs = [s.pos for s in v_segs]
240
+ left, right = min(vs), max(vs)
241
+ if right - left < 0.2 * width:
242
+ right = None
243
+ ext_h = _extent(h_segs, top, bottom, 2 * tol_y)
244
+ if ext_h and h_segs:
245
+ left, right = ext_h
246
+ if top is None and len(h_segs) >= 2:
247
+ top, bottom = min(s.pos for s in h_segs), max(s.pos for s in h_segs)
248
+ notes.append("plot top/bottom from outermost horizontal lines")
249
+ conf *= 0.8
250
+ elif top is None and len(h_segs) == 1:
251
+ bottom = h_segs[0].pos
252
+ # Extents can overshoot by a tick length (a tick at the corner continues the
253
+ # spine); pull each edge onto the outermost long perpendicular line just inside.
254
+ win_x, win_y = 0.03 * width, 0.03 * height
255
+ bottom = _pull_in(bottom, h_segs, -win_y)
256
+ top = _pull_in(top, h_segs, win_y)
257
+ left = _pull_in(left, v_segs, win_x)
258
+ right = _pull_in(right, v_segs, -win_x)
259
+ # Gridlines stop short of the spines they cross; snap edges onto spines.
260
+ left = _snap(left, v_segs, tol_x)
261
+ right = _snap(right, v_segs, tol_x)
262
+ top = _snap(top, h_segs, tol_y)
263
+ bottom = _snap(bottom, h_segs, tol_y)
264
+ if panel is not None:
265
+ cand = BBox(left if left is not None else panel.x0, top if top is not None else panel.y0,
266
+ right if right is not None else panel.x1, bottom if bottom is not None else panel.y1)
267
+ if cand.iou(panel) < 0.9:
268
+ notes.append("plot area taken from background panel")
269
+ cand = panel
270
+ return cand, conf, notes
271
+ if None in (left, right, top, bottom):
272
+ notes.append("plot area partly undetermined; using image-relative defaults")
273
+ conf *= 0.4
274
+ left = left if left is not None else 0.1 * width
275
+ right = right if right is not None else 0.95 * width
276
+ top = top if top is not None else 0.05 * height
277
+ bottom = bottom if bottom is not None else 0.9 * height
278
+ return BBox(float(left), float(top), float(right), float(bottom)), conf, notes
279
+
280
+
281
+ # ----------------------------------------------------------------------------- ticks
282
+
283
+ def _runs_from(ink: np.ndarray, start: int, step: int, max_len: int) -> np.ndarray:
284
+ """Length of the ink run starting at row/col offset ``start`` moving by ``step``.
285
+
286
+ ``ink`` is oriented so that axis 0 is the direction of travel.
287
+ """
288
+ n = ink.shape[0]
289
+ run = np.zeros(ink.shape[1], np.int32)
290
+ alive = np.ones(ink.shape[1], bool)
291
+ for k in range(max_len):
292
+ i = start + step * k
293
+ if i < 0 or i >= n:
294
+ break
295
+ alive &= ink[i]
296
+ run += alive
297
+ if not alive.any():
298
+ break
299
+ return run
300
+
301
+
302
+ def _group_columns(mask: np.ndarray, weights: np.ndarray, max_width: float) -> list[tuple[float, float]]:
303
+ """Centres and mean weights of consecutive True runs no wider than ``max_width``."""
304
+ out = []
305
+ idx = np.flatnonzero(mask)
306
+ if idx.size == 0:
307
+ return out
308
+ splits = np.flatnonzero(np.diff(idx) > 1) + 1
309
+ for grp in np.split(idx, splits):
310
+ if len(grp) > max_width:
311
+ continue
312
+ w = weights[grp].astype(float)
313
+ out.append((float((grp * w).sum() / w.sum()) + 0.5, float(w.max())))
314
+ return out
315
+
316
+
317
+ def find_ticks(ink: np.ndarray, box: BBox, axis: str, line_pos: float, line_thick: float,
318
+ max_len: int) -> tuple[list[float], float, str]:
319
+ """Tick marks perpendicular to an axis line; returns (positions, tick length, direction).
320
+
321
+ Looks outward first (the usual matplotlib/Excel style), then inward.
322
+ """
323
+ if axis == "x":
324
+ oriented = ink # rows = travel direction, cols = along-axis
325
+ lo, hi = int(box.x0 - 2), int(np.ceil(box.x1 + 2))
326
+ edge_out = int(round(line_pos + line_thick / 2 + 0.5))
327
+ edge_in = int(round(line_pos - line_thick / 2 - 0.5))
328
+ out_step, in_step = 1, -1
329
+ else:
330
+ oriented = ink.T
331
+ lo, hi = int(box.y0 - 2), int(np.ceil(box.y1 + 2))
332
+ edge_out = int(round(line_pos - line_thick / 2 - 0.5))
333
+ edge_in = int(round(line_pos + line_thick / 2 + 0.5))
334
+ out_step, in_step = -1, 1
335
+ lo, hi = max(lo, 0), min(hi, oriented.shape[1])
336
+ sub = oriented[:, lo:hi]
337
+ min_len = max(2, int(round(1.5 * line_thick)))
338
+ best: tuple[list[float], float, str] = ([], 0.0, "none")
339
+ for edge, step, name in ((edge_out, out_step, "out"), (edge_in, in_step, "in")):
340
+ runs = _runs_from(sub, edge, step, max_len)
341
+ cand = runs >= min_len
342
+ groups = _group_columns(cand, runs, max_width=max(3.0, 3 * line_thick))
343
+ if len(groups) < 2:
344
+ continue
345
+ lengths = np.array([g[1] for g in groups])
346
+ major = lengths >= 0.8 * lengths.max()
347
+ pos = [lo + g[0] for g, m in zip(groups, major) if m]
348
+ if len(pos) >= 2 and len(pos) > len(best[0]):
349
+ best = (pos, float(np.median(lengths[major])), name)
350
+ if name == "out" and len(pos) >= 2:
351
+ break
352
+ return best
353
+
354
+
355
+ # ----------------------------------------------------------------------------- driver
356
+
357
+ def detect_axes(lab: np.ndarray, noise_sigma: float) -> tuple[AxesResult, np.ndarray]:
358
+ """Find plot area, axis lines, gridlines and ticks; also return the ink mask."""
359
+ h, w = lab.shape[:2]
360
+ warnings: list[str] = []
361
+ thr = ink_threshold(noise_sigma)
362
+ fig_bg = figure_background(lab)
363
+ panel, panel_bg = find_panel(lab, fig_bg, thr)
364
+ ink = ink_mask(lab, fig_bg, panel, panel_bg, thr)
365
+ max_thick = max(2, int(round(MAX_LINE_THICK_FRAC * min(h, w))))
366
+
367
+ def achromatic(segs: list[Segment]) -> list[Segment]:
368
+ return [s for s in segs if np.hypot(s.lab[1], s.lab[2]) < GRID_CHROMA_MAX]
369
+
370
+ h_all = achromatic(find_segments(ink, lab, "h", int(MIN_AXIS_LINE_FRAC * w), max_thick))
371
+ v_all = achromatic(find_segments(ink, lab, "v", int(MIN_AXIS_LINE_FRAC * h), max_thick))
372
+ box, conf, notes = estimate_plot_box(h_all, v_all, w, h, panel)
373
+ warnings.extend(notes)
374
+ tol = 0.015 * min(h, w)
375
+
376
+ # Axis lines: the darkest segment on the box edge.
377
+ def edge_line(segs: list[Segment], pos: float) -> Segment | None:
378
+ cands = [s for s in segs if abs(s.pos - pos) <= tol]
379
+ return min(cands, key=lambda s: s.lab[0]) if cands else None
380
+
381
+ xl = edge_line(h_all, box.y1)
382
+ yl = edge_line(v_all, box.x0)
383
+ thick = float(np.median([s.thickness for s in h_all + v_all])) if (h_all or v_all) else 1.0
384
+ max_tick = max(4, int(0.03 * min(h, w)))
385
+ x_ticks: list[float] = []
386
+ y_ticks: list[float] = []
387
+ x_src = y_src = "none"
388
+ x_tick_len = y_tick_len = 0.0
389
+ # Without an axis line (ggplot, Solarize, seaborn styles) ticks hang from the
390
+ # plot-area edge itself.
391
+ x_line = (xl.pos, xl.thickness) if xl is not None else (box.y1, 0.0)
392
+ y_line = (yl.pos, yl.thickness) if yl is not None else (box.x0, 0.0)
393
+ x_ticks, tl, d = find_ticks(ink, box, "x", x_line[0], x_line[1], max_tick)
394
+ if x_ticks:
395
+ x_src, x_tick_len = f"ticks_{d}", tl if d == "out" else 0.0
396
+ y_ticks, tl, d = find_ticks(ink, box, "y", y_line[0], y_line[1], max_tick)
397
+ if y_ticks:
398
+ y_src, y_tick_len = f"ticks_{d}", tl if d == "out" else 0.0
399
+ inner_h = [s for s in h_all if box.y0 + tol < s.pos < box.y1 - tol]
400
+ inner_v = [s for s in v_all if box.x0 + tol < s.pos < box.x1 - tol]
401
+ if len(x_ticks) < 2 and len(inner_v) >= 2:
402
+ x_ticks, x_src = sorted(s.pos for s in inner_v), "gridlines"
403
+ if len(y_ticks) < 2 and len(inner_h) >= 2:
404
+ y_ticks, y_src = sorted(s.pos for s in inner_h), "gridlines"
405
+ if xl is None:
406
+ warnings.append("no x-axis line found")
407
+ conf *= 0.9
408
+ if yl is None:
409
+ warnings.append("no y-axis line found")
410
+ conf *= 0.9
411
+ res = AxesResult(
412
+ plot_box=box, x_axis_y=xl.pos if xl else None, y_axis_x=yl.pos if yl else None,
413
+ x_ticks=x_ticks, y_ticks=y_ticks, h_lines=h_all, v_lines=v_all,
414
+ figure_bg=fig_bg, panel_bg=panel_bg, x_tick_len=x_tick_len, y_tick_len=y_tick_len,
415
+ line_thickness=thick,
416
+ confidence=conf, warnings=warnings, x_tick_source=x_src, y_tick_source=y_src,
417
+ )
418
+ return res, ink
419
+
420
+
421
+ # ----------------------------------------------------------------------------- text
422
+
423
+ def glyph_components(ink: np.ndarray, region: BBox) -> list[BBox]:
424
+ """Connected components of ink inside ``region`` (absolute coordinates)."""
425
+ h, w = ink.shape
426
+ r = region.clip(w, h)
427
+ rs, cs = r.slices()
428
+ sub = ink[rs, cs].astype(np.uint8)
429
+ if sub.size == 0:
430
+ return []
431
+ n, _, stats, _ = cv2.connectedComponentsWithStats(sub, connectivity=8)
432
+ out = []
433
+ for i in range(1, n):
434
+ x, y, bw, bh, area = stats[i]
435
+ if area < 3:
436
+ continue
437
+ out.append(BBox(float(x + cs.start), float(y + rs.start), float(x + cs.start + bw),
438
+ float(y + rs.start + bh)))
439
+ return out
440
+
441
+
442
+ def group_words(comps: list[BBox], char_h: float, gap_x: float | None = None,
443
+ gap_y: float | None = None) -> list[BBox]:
444
+ """Merge glyph boxes closer than ``gap_x``/``gap_y`` into word/label boxes (union-find)."""
445
+ if not comps:
446
+ return []
447
+ gx = 0.6 * char_h if gap_x is None else gap_x
448
+ gy = 0.15 * char_h if gap_y is None else gap_y
449
+ n = len(comps)
450
+ parent = list(range(n))
451
+
452
+ def find(i: int) -> int:
453
+ while parent[i] != i:
454
+ parent[i] = parent[parent[i]]
455
+ i = parent[i]
456
+ return i
457
+
458
+ arr = np.array([[b.x0, b.y0, b.x1, b.y1] for b in comps])
459
+ for i in range(n):
460
+ dx = np.maximum(arr[:, 0] - arr[i, 2], arr[i, 0] - arr[:, 2])
461
+ dy = np.maximum(arr[:, 1] - arr[i, 3], arr[i, 1] - arr[:, 3])
462
+ # Same line: vertical overlap; or stacked parts of a glyph (i, j, superscripts).
463
+ close = (dx <= gx) & (dy <= gy)
464
+ for j in np.flatnonzero(close):
465
+ if j != i:
466
+ parent[find(i)] = find(int(j))
467
+ groups: dict[int, BBox] = {}
468
+ for i, b in enumerate(comps):
469
+ r = find(i)
470
+ groups[r] = b if r not in groups else groups[r].union(b)
471
+ return list(groups.values())
472
+
473
+
474
+ def char_height(comps: list[BBox]) -> float:
475
+ """Typical glyph height (median of components that are not specks or lines)."""
476
+ hs = [b.h for b in comps if b.h >= 3 and b.w < 4 * b.h]
477
+ return float(np.median(hs)) if hs else 10.0
478
+
479
+
480
+ def x_label_boxes(ink: np.ndarray, ax: AxesResult) -> tuple[list[BBox], float]:
481
+ """Word boxes of the first text row below the plot area (x tick labels)."""
482
+ h, w = ink.shape
483
+ b = ax.plot_box
484
+ start = b.y1 + ax.x_tick_len + ax.line_thickness + 1
485
+ # Components are taken from a region reaching up to the axis and selected by
486
+ # where they *end*, so glyphs are never clipped by the region boundary (a
487
+ # clipped digit gives a consistently scaled, i.e. silently wrong, calibration).
488
+ region = BBox(max(0.0, b.x0 - 0.08 * w), b.y1 + ax.line_thickness / 2 + 1, min(float(w), b.x1 + 0.08 * w),
489
+ min(float(h), b.y1 + 0.3 * h))
490
+ comps = [c for c in glyph_components(ink, region) if c.y1 > start + 1]
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]:
508
+ """Regroup label glyphs by tick cell when ticks are regular.
509
+
510
+ Long labels can touch or overlap their neighbours; assigning every glyph to the
511
+ nearest tick (cells bounded by tick midpoints) gives one box per tick. Words
512
+ containing no tick inside are kept as they are.
513
+ """
514
+ if len(ticks) < 3:
515
+ return words
516
+ t = np.sort(np.asarray(ticks))
517
+ gaps = np.diff(t)
518
+ if np.std(gaps) > 0.1 * np.mean(gaps):
519
+ return words
520
+ multi = [wd for wd in words if np.sum((t > wd.x0) & (t < wd.x1)) >= 1 and wd.w > 0.9 * np.mean(gaps)]
521
+ if not multi:
522
+ return words
523
+ mids = (t[1:] + t[:-1]) / 2
524
+ bins: dict[int, BBox] = {}
525
+ for c in comps:
526
+ k = int(np.searchsorted(mids, c.cx))
527
+ bins[k] = c if k not in bins else bins[k].union(c)
528
+ return list(bins.values())
529
+
530
+
531
+ def y_label_boxes(ink: np.ndarray, ax: AxesResult) -> tuple[list[BBox], float]:
532
+ """Word boxes of the text column left of the plot area (y tick labels)."""
533
+ h, w = ink.shape
534
+ b = ax.plot_box
535
+ end = b.x0 - ax.y_tick_len - ax.line_thickness - 1
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)
542
+ words = group_words(comps, ch, gap_y=-0.05 * ch)
543
+ if not words:
544
+ return [], ch
545
+ right = max(wd.x1 for wd in words)
546
+ # Right-aligned labels next to the axis; a rotated axis title lies further left.
547
+ col = [wd for wd in words if wd.x1 >= right - 1.5 * ch and wd.h < 2.5 * ch]
548
+ return sorted(col, key=lambda bb: bb.cy), ch
549
+
550
+
551
+ def match_to_ticks(label_pos: list[float], ticks: list[float], max_dist: float = np.inf
552
+ ) -> list[tuple[float, bool]]:
553
+ """Snap each label centre to its nearest tick if within ~0.35 tick spacing and ``max_dist``."""
554
+ if len(ticks) < 2:
555
+ return [(p, False) for p in label_pos]
556
+ t = np.sort(np.asarray(ticks))
557
+ spacing = float(np.median(np.diff(t)))
558
+ out = []
559
+ used: dict[int, float] = {}
560
+ for p in label_pos:
561
+ i = int(np.argmin(np.abs(t - p)))
562
+ d = abs(t[i] - p)
563
+ if d <= min(0.35 * spacing, max_dist) and (i not in used or used[i] > d):
564
+ used[i] = d
565
+ out.append((float(t[i]), True))
566
+ else:
567
+ out.append((p, False))
568
+ return out
569
+
570
+
571
+ def offset_text_boxes(ink: np.ndarray, ax: AxesResult, labels: list[BBox], axis: str, ch: float) -> list[BBox]:
572
+ """Candidate boxes for an axis offset/multiplier text (matplotlib '1e6', '+1.06e3').
573
+
574
+ x: right end of the axis, just below the tick-label row; y: above the top-left
575
+ corner of the plot. Callers must parse the text to confirm.
576
+ """
577
+ h, w = ink.shape
578
+ b = ax.plot_box
579
+ if ch <= 0:
580
+ return []
581
+ if axis == "x":
582
+ y0 = max((lb.y1 for lb in labels), default=b.y1 + ax.x_tick_len + ch) - 0.3 * ch
583
+ region = BBox(b.x1 - 0.3 * b.w, y0, min(float(w), b.x1 + 0.12 * w), min(float(h), y0 + 3 * ch))
584
+ else:
585
+ region = BBox(max(0.0, b.x0 - 0.1 * w), max(0.0, b.y0 - 3 * ch), b.x0 + 0.3 * b.w, b.y0 - 1)
586
+ if region.w <= 0 or region.h <= 0:
587
+ return []
588
+ comps = [c for c in glyph_components(ink, region) if c.h <= 2 * ch]
589
+ words = group_words(comps, ch)
590
+ return [wd for wd in words if not any(wd.intersects(lb) for lb in labels) and wd.h >= 0.4 * ch]
plotscribe/calibrate.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pixel <-> data-value mapping for one axis.
2
+
3
+ Numeric axes are fitted with RANSAC over (tick pixel, label value) pairs, for both
4
+ a linear and a log10 model; the model with more inliers (then lower residual)
5
+ wins. Categorical axes keep the ordered label strings and their pixel positions.
6
+
7
+ Assumptions: tick labels sit at their tick positions; at least two distinct
8
+ numeric labels are readable for a numeric axis.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import itertools
14
+ import math
15
+ from dataclasses import dataclass, field
16
+
17
+ import numpy as np
18
+
19
+
20
+ @dataclass
21
+ class Calibration:
22
+ """Maps pixel position along an axis to a data value.
23
+
24
+ For numeric axes: ``t(value) = intercept + slope * px`` with ``t`` the identity
25
+ (linear) or log10 (log).
26
+ """
27
+
28
+ axis: str
29
+ kind: str # "linear" | "log" | "categorical"
30
+ slope: float = 0.0
31
+ intercept: float = 0.0
32
+ residuals_px: list[float] = field(default_factory=list)
33
+ r2: float = 0.0
34
+ n_labels: int = 0
35
+ n_inliers: int = 0
36
+ tick_px: list[float] = field(default_factory=list)
37
+ tick_values: list[float] = field(default_factory=list)
38
+ categories: list[str] = field(default_factory=list)
39
+ category_px: list[float] = field(default_factory=list)
40
+ confidence: float = 0.0
41
+ warnings: list[str] = field(default_factory=list)
42
+
43
+ def to_value(self, px: float | np.ndarray) -> float | np.ndarray:
44
+ """Data value at pixel ``px`` (numeric axes only)."""
45
+ t = self.intercept + self.slope * np.asarray(px, dtype=float)
46
+ if self.kind == "log":
47
+ return np.power(10.0, t)
48
+ return t
49
+
50
+ def to_px(self, value: float | np.ndarray) -> float | np.ndarray:
51
+ v = np.asarray(value, dtype=float)
52
+ t = np.log10(v) if self.kind == "log" else v
53
+ return (t - self.intercept) / self.slope
54
+
55
+ def nearest_category(self, px: float) -> tuple[int, float]:
56
+ """Index of the closest category and its distance in pixels."""
57
+ d = np.abs(np.asarray(self.category_px) - px)
58
+ i = int(np.argmin(d))
59
+ return i, float(d[i])
60
+
61
+ def rescaled(self, s: float) -> "Calibration":
62
+ """Same calibration expressed for pixels multiplied by ``1/s`` (processed -> original)."""
63
+ c = Calibration(**{**self.__dict__})
64
+ c.slope = self.slope * s
65
+ c.tick_px = [p / s for p in self.tick_px]
66
+ c.category_px = [p / s for p in self.category_px]
67
+ c.residuals_px = [r / s for r in self.residuals_px]
68
+ return c
69
+
70
+ def to_dict(self) -> dict:
71
+ d = {
72
+ "axis": self.axis, "type": self.kind, "confidence": round(self.confidence, 3),
73
+ "n_labels": self.n_labels, "n_inliers": self.n_inliers, "warnings": self.warnings,
74
+ }
75
+ if self.kind == "categorical":
76
+ d["categories"] = self.categories
77
+ d["category_px"] = [round(p, 2) for p in self.category_px]
78
+ else:
79
+ d.update({
80
+ "transform": "log10(value)" if self.kind == "log" else "value",
81
+ "slope": self.slope, "intercept": self.intercept,
82
+ "r2": round(self.r2, 6),
83
+ "residuals_px": [round(r, 3) for r in self.residuals_px],
84
+ "max_abs_residual_px": round(max((abs(r) for r in self.residuals_px), default=0.0), 3),
85
+ "ticks": [{"px": round(p, 2), "value": v} for p, v in zip(self.tick_px, self.tick_values)],
86
+ })
87
+ return d
88
+
89
+
90
+ def _fit_px_on_t(px: np.ndarray, t: np.ndarray) -> tuple[float, float]:
91
+ """Least squares ``px = c + d * t`` (pixels are the noisy variable)."""
92
+ d, c = np.polyfit(t, px, 1)
93
+ return float(c), float(d)
94
+
95
+
96
+ def _select(px: np.ndarray, cands: list[np.ndarray], c: float, d: float) -> tuple[np.ndarray, np.ndarray]:
97
+ """Per label: the candidate closest to the model, and its pixel residual."""
98
+ chosen = np.full(len(px), np.nan)
99
+ res = np.full(len(px), np.inf)
100
+ for k, ts in enumerate(cands):
101
+ if len(ts) == 0:
102
+ continue
103
+ r = np.abs(px[k] - (c + d * ts))
104
+ i = int(np.argmin(r))
105
+ chosen[k], res[k] = ts[i], r[i]
106
+ return chosen, res
107
+
108
+
109
+ def _ransac(px: np.ndarray, cands: list[np.ndarray], tol: float
110
+ ) -> tuple[np.ndarray, np.ndarray, float, float] | None:
111
+ """RANSAC over all pairs of (label, candidate value) hypotheses.
112
+
113
+ Each label may carry several candidate readings (OCR passes); a label is an
114
+ inlier if *any* of its candidates fits. Returns (inlier mask, chosen t, c, d).
115
+ """
116
+ n = len(px)
117
+ best: tuple[int, float, float, float] | None = None
118
+ for i, j in itertools.combinations(range(n), 2):
119
+ if abs(px[i] - px[j]) < 1e-6:
120
+ continue
121
+ for ti in cands[i]:
122
+ for tj in cands[j]:
123
+ if ti == tj:
124
+ continue
125
+ d = (px[j] - px[i]) / (tj - ti)
126
+ c = px[i] - d * ti
127
+ _, res = _select(px, cands, c, d)
128
+ inl = res < tol
129
+ score = (int(inl.sum()), -float(res[inl].sum()))
130
+ if best is None or score > (best[0], best[1]):
131
+ best = (score[0], score[1], c, d)
132
+ if best is None or best[0] < 2:
133
+ return None
134
+ c, d = best[2], best[3]
135
+ for _ in range(2): # refine: refit on inliers, reselect candidates
136
+ chosen, res = _select(px, cands, c, d)
137
+ inl = res < tol
138
+ if inl.sum() < 2 or len(np.unique(chosen[inl])) < 2:
139
+ break
140
+ c, d = _fit_px_on_t(px[inl], chosen[inl])
141
+ chosen, res = _select(px, cands, c, d)
142
+ inl = res < tol
143
+ return inl, chosen, c, d
144
+
145
+
146
+ def fit_numeric(axis: str, px: list[float], values: list[float] | list[list[float]],
147
+ allow_log: bool = True, allow_linear: bool = True) -> Calibration:
148
+ """Robust linear-vs-log calibration from (pixel, value or candidate values) pairs.
149
+
150
+ Pixels are along the axis (x: column, y: row). The inlier tolerance scales with
151
+ the median label spacing so it is resolution-independent.
152
+ """
153
+ cal = Calibration(axis=axis, kind="linear", n_labels=len(px))
154
+ cand_lists = [[float(v)] if not isinstance(v, (list, tuple)) else [float(x) for x in v] for v in values]
155
+ keep = [k for k, cl in enumerate(cand_lists) if np.isfinite(px[k]) and any(np.isfinite(cl))]
156
+ p = np.asarray([px[k] for k in keep], float)
157
+ cl = [np.unique(np.asarray([x for x in cand_lists[k] if np.isfinite(x)])) for k in keep]
158
+ distinct = {round(x, 12) for c in cl for x in c}
159
+ if len(p) < 2 or len(distinct) < 2:
160
+ cal.warnings.append(f"{axis}: fewer than 2 distinct numeric tick labels")
161
+ return cal
162
+ order = np.argsort(p)
163
+ p = p[order]
164
+ cl = [cl[k] for k in order]
165
+ spacing = float(np.median(np.diff(p)))
166
+ tol = max(1.5, 0.06 * spacing)
167
+
168
+ fits: list[tuple[str, np.ndarray, np.ndarray, float, float]] = []
169
+ lin = _ransac(p, cl, tol) if allow_linear else None
170
+ if lin:
171
+ fits.append(("linear", *lin))
172
+ if allow_log:
173
+ lcl = [np.log10(c[c > 0]) for c in cl]
174
+ if sum(len(c) > 0 for c in lcl) >= 2:
175
+ lg = _ransac(p, lcl, tol)
176
+ if lg:
177
+ fits.append(("log", *lg))
178
+ if not fits:
179
+ cal.warnings.append(f"{axis}: no consistent tick model")
180
+ return cal
181
+
182
+ def rms(f: tuple[str, np.ndarray, np.ndarray, float, float]) -> float:
183
+ _, inl, t, c, d = f
184
+ return float(np.sqrt(np.mean((p[inl] - (c + d * t[inl])) ** 2)))
185
+
186
+ # More inliers wins; then lower residual. Log must beat linear clearly on ties,
187
+ # because with 2-3 ticks both fit and linear is far more common.
188
+ fits.sort(key=lambda f: (-int(f[1].sum()), rms(f) * (1.0 if f[0] == "linear" else 2.0) + 1e-9))
189
+ kind, inl, t, c, d = fits[0]
190
+ if abs(d) < 1e-12:
191
+ cal.warnings.append(f"{axis}: degenerate fit")
192
+ return cal
193
+
194
+ res = p[inl] - (c + d * t[inl])
195
+ ss_tot = float(np.sum((p[inl] - p[inl].mean()) ** 2))
196
+ r2 = 1.0 - float(np.sum(res**2)) / ss_tot if ss_tot > 0 else 0.0
197
+ cal.kind = kind
198
+ cal.slope = 1.0 / d
199
+ cal.intercept = -c / d
200
+ cal.residuals_px = res.tolist()
201
+ cal.r2 = r2
202
+ cal.n_inliers = int(inl.sum())
203
+ cal.tick_px = p[inl].tolist()
204
+ cal.tick_values = (np.power(10.0, t[inl]) if kind == "log" else t[inl]).tolist()
205
+
206
+ n_out = len(p) - cal.n_inliers
207
+ conf = 1.0
208
+ if cal.n_inliers == 2:
209
+ conf *= 0.5
210
+ cal.warnings.append(f"{axis}: only 2 consistent ticks; calibration unverified")
211
+ if n_out:
212
+ conf *= max(0.3, 1.0 - n_out / len(p))
213
+ cal.warnings.append(f"{axis}: rejected {n_out} outlier tick label(s)")
214
+ max_res = float(np.max(np.abs(res))) if len(res) else 0.0
215
+ if max_res > 0.25 * spacing:
216
+ conf *= 0.5
217
+ cal.warnings.append(f"{axis}: large residual {max_res:.1f}px")
218
+ if r2 < 0.999 and cal.n_inliers > 2:
219
+ conf *= 0.7
220
+ cal.warnings.append(f"{axis}: R^2 {r2:.4f}")
221
+ if kind == "log" and len(fits) > 1 and int(fits[1][1].sum()) == cal.n_inliers and rms(fits[1]) < 2 * tol:
222
+ conf *= 0.6
223
+ cal.warnings.append(f"{axis}: log vs linear ambiguous")
224
+ cal.confidence = conf
225
+ return cal
226
+
227
+
228
+ def fit_categorical(axis: str, px: list[float], labels: list[str]) -> Calibration:
229
+ """Categorical axis: ordered labels and their pixel positions."""
230
+ order = np.argsort(px)
231
+ cal = Calibration(axis=axis, kind="categorical", n_labels=len(px), n_inliers=len(px))
232
+ cal.category_px = [float(px[i]) for i in order]
233
+ cal.categories = [labels[i] for i in order]
234
+ cal.confidence = 0.9 if len(px) >= 2 else 0.4
235
+ if len(px) < 2:
236
+ cal.warnings.append(f"{axis}: fewer than 2 category labels")
237
+ if len(px) > 2:
238
+ gaps = np.diff(cal.category_px)
239
+ if np.std(gaps) > 0.15 * np.mean(gaps):
240
+ cal.confidence *= 0.7
241
+ cal.warnings.append(f"{axis}: irregular category spacing")
242
+ return cal
243
+
244
+
245
+ def is_numeric_axis(values: list[float | None]) -> bool:
246
+ """Majority vote: an axis is numeric if most labels parse as numbers."""
247
+ if not values:
248
+ return False
249
+ n_num = sum(v is not None for v in values)
250
+ return n_num >= 2 and n_num >= math.ceil(0.6 * len(values))
plotscribe/chart_type.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chart-type classification from the separated series masks (heuristic).
2
+
3
+ Evidence per connected component of every series mask:
4
+ - bar: solid rectangles (fill ratio ~1) whose bottoms or tops share a baseline;
5
+ - scatter: many small, compact, similar-sized blobs and no long components;
6
+ - line: components spanning a large fraction of the plot width with low fill.
7
+ Scores are area fractions; confidence is the margin between the best two.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import cv2
13
+ import numpy as np
14
+
15
+ from .models import BBox
16
+
17
+
18
+ def component_stats(mask: np.ndarray) -> np.ndarray:
19
+ """Rows of (x, y, w, h, area, fill) for each component."""
20
+ n, _, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8)
21
+ if n <= 1:
22
+ return np.zeros((0, 6))
23
+ st = stats[1:].astype(float)
24
+ fill = st[:, 4] / (st[:, 2] * st[:, 3])
25
+ return np.column_stack([st, fill])
26
+
27
+
28
+ def _shared_baseline(edges: np.ndarray, tol: float) -> int:
29
+ """Size of the largest group of edge positions within ``tol`` of each other."""
30
+ if len(edges) == 0:
31
+ return 0
32
+ e = np.sort(edges)
33
+ best = 1
34
+ j = 0
35
+ for i in range(len(e)):
36
+ while e[i] - e[j] > tol:
37
+ j += 1
38
+ best = max(best, i - j + 1)
39
+ return best
40
+
41
+
42
+ def classify(masks: list[np.ndarray], region: BBox, thickness: float) -> tuple[str, float, dict[str, float]]:
43
+ """Return (type, confidence, scores) with type in line | bar | scatter."""
44
+ W, H = region.w, region.h
45
+ rect_area = line_area = blob_area = 0.0
46
+ n_blobs = 0
47
+ total = 0.0
48
+ bottoms, tops = [], []
49
+ blob_sizes = []
50
+ for m in masks:
51
+ st = component_stats(m)
52
+ for x, y, w, h, area, fill in st:
53
+ total += area
54
+ if fill > 0.85 and w > 2.5 * thickness and h > 2.5 * thickness and w < 0.5 * W:
55
+ rect_area += area
56
+ bottoms.append(y + h)
57
+ tops.append(y)
58
+ elif w >= 0.15 * W and fill < 0.5:
59
+ line_area += area
60
+ elif w < 0.08 * W and h < 0.08 * H and 0.4 < w / max(h, 1) < 2.5 and fill > 0.3:
61
+ blob_area += area
62
+ n_blobs += 1
63
+ blob_sizes.append(area)
64
+ if total == 0:
65
+ return "unknown", 0.0, {}
66
+ n_rect = len(bottoms)
67
+ aligned = max(_shared_baseline(np.asarray(bottoms), 0.01 * H), _shared_baseline(np.asarray(tops), 0.01 * H))
68
+ bar = rect_area / total * (min(1.0, 1.5 * aligned / n_rect) if n_rect >= 1 and aligned >= min(2, n_rect) else 0.0)
69
+ if n_rect >= 3:
70
+ # Identical squares are square scatter markers, not bars (bars vary in height).
71
+ hs = np.asarray(bottoms) - np.asarray(tops)
72
+ if np.std(hs) < 0.15 * np.mean(hs) and np.median(hs) < 0.08 * H:
73
+ bar *= 0.2
74
+ scatter = blob_area / total * min(1.0, n_blobs / 5)
75
+ if blob_sizes and n_blobs >= 3:
76
+ cv = float(np.std(blob_sizes) / (np.mean(blob_sizes) + 1e-9))
77
+ scatter *= 1.0 if cv < 0.8 else 0.6
78
+ # Continuity vote per series: pieces of a (dashed/dotted/marker) line chain
79
+ # end-to-end along x; scatter markers sorted by x jump around in y.
80
+ non_bar = 1.0 - rect_area / total
81
+ chained = _chained_fraction(masks, W)
82
+ line = max(line_area / total, chained * non_bar)
83
+ scatter = max(scatter * (1.0 - chained), (1.0 - chained) * non_bar * (1.0 if n_blobs >= 3 else 0.5))
84
+ if scatter > max(line, bar) and _regular_x_series(masks) >= 0.5:
85
+ # Markers at regular x steps, one per step: a line chart with markers (whose
86
+ # connecting segments are dashed/thin/hidden), not a scatter plot.
87
+ line, scatter = scatter, 0.5 * line
88
+ scores = {"line": round(line, 3), "bar": round(bar, 3), "scatter": round(scatter, 3)}
89
+ ranked = sorted(scores.items(), key=lambda kv: -kv[1])
90
+ best, second = ranked[0], ranked[1]
91
+ conf = 0.0 if best[1] == 0 else float(np.clip((best[1] - second[1]) / best[1], 0.0, 1.0))
92
+ return best[0], conf, scores
93
+
94
+
95
+ def _regular_x_series(masks: list[np.ndarray]) -> float:
96
+ """Fraction of series whose blobs sit at regularly spaced, distinct x positions."""
97
+ n_reg = n_tot = 0
98
+ for m in masks:
99
+ n, _, stats, cents = cv2.connectedComponentsWithStats(m.astype(np.uint8), connectivity=8)
100
+ if n <= 6:
101
+ continue
102
+ areas = stats[1:, cv2.CC_STAT_AREA]
103
+ keep = areas >= 0.3 * np.median(areas)
104
+ xs = np.sort(cents[1:][keep, 0])
105
+ if len(xs) < 5:
106
+ continue
107
+ n_tot += 1
108
+ d = np.diff(xs)
109
+ if d.min() > 0.3 * np.median(d) and np.std(d) < 0.35 * np.mean(d):
110
+ n_reg += 1
111
+ return n_reg / n_tot if n_tot else 0.0
112
+
113
+
114
+ def _chain_ratio(mask: np.ndarray) -> float | None:
115
+ """Median gap between x-consecutive components, relative to component size."""
116
+ n, _, stats, cents = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8)
117
+ if n <= 1:
118
+ return None
119
+ st = stats[1:]
120
+ keep = st[:, cv2.CC_STAT_AREA] >= max(3, 0.2 * np.median(st[:, cv2.CC_STAT_AREA]))
121
+ st, c = st[keep], cents[1:][keep]
122
+ if len(st) < 4:
123
+ return None
124
+ order = np.argsort(c[:, 0])
125
+ st = st[order]
126
+ x0, y0 = st[:, 0], st[:, 1]
127
+ x1, y1 = x0 + st[:, 2], y0 + st[:, 3]
128
+ dx = np.maximum(0, x0[1:] - x1[:-1])
129
+ dy = np.maximum(0, np.maximum(y0[1:] - y1[:-1], y0[:-1] - y1[1:]))
130
+ size = float(np.median(np.maximum(st[:, 2], st[:, 3])))
131
+ return float(np.median(np.hypot(dx, dy)) / max(size, 1.0))
132
+
133
+
134
+ def _chained_fraction(masks: list[np.ndarray], plot_w: float) -> float:
135
+ """Area-weighted share of series that look like one continuous line."""
136
+ tot = chained = 0.0
137
+ for m in masks:
138
+ a = float(m.sum())
139
+ if a == 0:
140
+ continue
141
+ tot += a
142
+ cols = np.flatnonzero(m.any(axis=0))
143
+ r = _chain_ratio(m)
144
+ if r is None:
145
+ # One or a few components: a line if it spans a good part of the plot.
146
+ if cols.size and (cols[-1] - cols[0]) >= 0.3 * plot_w:
147
+ chained += a
148
+ elif r < 3.0:
149
+ chained += a
150
+ return chained / tot if tot else 0.0
plotscribe/cli.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Command-line interface: ``plotscribe input.png -o out/ [--type line|bar|scatter] [--debug]``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ import typer
9
+
10
+ from . import export, pipeline
11
+
12
+ app = typer.Typer(add_completion=False, help="Convert a chart image into a CSV of its data.")
13
+
14
+
15
+ @app.command()
16
+ def main(
17
+ image: Path = typer.Argument(..., exists=True, dir_okay=False, help="Chart image (PNG/JPG)."),
18
+ out: Path = typer.Option(Path("out"), "-o", "--out", help="Output directory."),
19
+ chart_type: Optional[str] = typer.Option(
20
+ None, "--type", help="Override chart type: line | bar | stacked_bar | scatter."),
21
+ debug: bool = typer.Option(False, "--debug", help="Also write <name>.debug.png."),
22
+ ocr: str = typer.Option("tesseract", "--ocr", help="OCR backend: tesseract | paddle."),
23
+ ) -> None:
24
+ """Extract data from IMAGE into OUT/<name>.csv and OUT/<name>.diagnostics.json."""
25
+ if chart_type is not None and chart_type not in ("line", "bar", "stacked_bar", "grouped_bar", "scatter"):
26
+ raise typer.BadParameter("--type must be line, bar, stacked_bar or scatter")
27
+ res = pipeline.run(image, ocr_backend=ocr, chart_type=chart_type)
28
+ paths = export.write_all(res, out, image.stem, debug=debug)
29
+ status = res.extra.get("status", "ok")
30
+ typer.echo(f"type={res.chart_type} ({res.chart_type_conf:.2f}) confidence={res.confidence:.2f} status={status}")
31
+ for w in res.warnings:
32
+ typer.echo(f" warning: {w}")
33
+ for k, p in paths.items():
34
+ typer.echo(f" {k}: {p}")
35
+ if status != "ok":
36
+ raise typer.Exit(code=2)
37
+
38
+
39
+ if __name__ == "__main__":
40
+ app()
plotscribe/export.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Table building and output writers (CSV, diagnostics JSON, debug overlay).
2
+
3
+ CSV layout (stable):
4
+ - First column ``category`` (categorical x axis) or ``x`` (numeric x axis).
5
+ - Then one column per series, named after its legend label (``series_1..n`` without
6
+ a legend), in legend order.
7
+ - Line/bar: one row per x position or category; a series without a value there is empty.
8
+ - Scatter: one row per point; only the owning series' column is filled.
9
+ - Stacked bars: columns are suffixed `` (segment)``; values are segment heights,
10
+ not cumulative tops.
11
+ - If an axis could not be calibrated its values are pixel coordinates and the
12
+ header carries the suffix `` [px]``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from pathlib import Path
19
+ from typing import TYPE_CHECKING, Any
20
+
21
+ import cv2
22
+ import numpy as np
23
+ import pandas as pd
24
+
25
+ from .calibrate import Calibration
26
+ from .models import Series
27
+
28
+ if TYPE_CHECKING:
29
+ from .pipeline import PipelineResult
30
+
31
+ _OVERLAY_COLORS = [(230, 25, 75), (60, 180, 75), (0, 130, 200), (245, 130, 48), (145, 30, 180),
32
+ (70, 240, 240), (240, 50, 230), (128, 128, 0)]
33
+
34
+
35
+ def _y_values(cal: Calibration | None, py: np.ndarray) -> np.ndarray:
36
+ if cal is None or cal.kind == "categorical":
37
+ return py.astype(float)
38
+ return np.asarray(cal.to_value(py), float)
39
+
40
+
41
+ def _cluster_positions(xs: np.ndarray, tol: float) -> np.ndarray:
42
+ """Label positions so values closer than ``tol`` share a label (1-D single linkage)."""
43
+ order = np.argsort(xs)
44
+ labels = np.empty(len(xs), int)
45
+ cur = -1
46
+ prev = -np.inf
47
+ for i in order:
48
+ if xs[i] - prev > tol:
49
+ cur += 1
50
+ labels[i] = cur
51
+ prev = xs[i]
52
+ return labels
53
+
54
+
55
+ def build_table(series: list[Series], x_cal: Calibration | None, y_cal: Calibration | None,
56
+ chart_type: str, plot_width: float) -> pd.DataFrame:
57
+ """Convert per-series pixel points into the CSV layout described in the module doc."""
58
+ y_ok = y_cal is not None and y_cal.kind != "categorical"
59
+ y_suffix = "" if y_ok else " [px]"
60
+ stacked = chart_type == "stacked_bar"
61
+ names = [s.name + (" (segment)" if stacked else "") + y_suffix for s in series]
62
+ categorical = x_cal is not None and x_cal.kind == "categorical"
63
+ x_ok = x_cal is not None
64
+ xname = "category" if categorical else ("x" if x_ok else "x [px]")
65
+
66
+ pts: list[tuple[int, float, float]] = [] # (series index, x px, y value)
67
+ for si, s in enumerate(series):
68
+ if stacked:
69
+ for x, top, bot in s.segments_px:
70
+ v = float(_y_values(y_cal, np.array([top]))[0] - _y_values(y_cal, np.array([bot]))[0])
71
+ if not y_ok:
72
+ v = -v
73
+ pts.append((si, x, v))
74
+ else:
75
+ if len(s.points_px) == 0:
76
+ continue
77
+ ys = _y_values(y_cal, s.points_px[:, 1])
78
+ pts.extend((si, float(x), float(y)) for x, y in zip(s.points_px[:, 0], ys))
79
+
80
+ if not pts:
81
+ return pd.DataFrame(columns=[xname, *names])
82
+
83
+ if chart_type == "scatter":
84
+ rows = []
85
+ for si, x, y in pts:
86
+ xv = float(x_cal.to_value(x)) if (x_ok and not categorical) else x
87
+ rows.append({xname: xv, **{n: (y if k == si else np.nan) for k, n in enumerate(names)}})
88
+ return pd.DataFrame(rows, columns=[xname, *names]).sort_values(xname, kind="stable").reset_index(drop=True)
89
+
90
+ if categorical:
91
+ assert x_cal is not None
92
+ cats = x_cal.categories
93
+ table = {n: [np.nan] * len(cats) for n in names}
94
+ best_d = {n: [np.inf] * len(cats) for n in names}
95
+ spacing = float(np.median(np.diff(x_cal.category_px))) if len(cats) > 1 else plot_width
96
+ for si, x, y in pts:
97
+ ci, d = x_cal.nearest_category(x)
98
+ if d > 0.5 * spacing:
99
+ continue
100
+ n = names[si]
101
+ if d < best_d[n][ci]:
102
+ best_d[n][ci] = d
103
+ table[n][ci] = y
104
+ return pd.DataFrame({xname: cats, **table})
105
+
106
+ xs = np.array([p[1] for p in pts])
107
+ tol = max(1.5, 0.004 * plot_width)
108
+ lab = _cluster_positions(xs, tol)
109
+ n_rows = int(lab.max()) + 1
110
+ xpx = np.array([xs[lab == k].mean() for k in range(n_rows)])
111
+ table = {n: [np.nan] * n_rows for n in names}
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
+
118
+
119
+ def diagnostics(res: "PipelineResult") -> dict[str, Any]:
120
+ """JSON-serialisable diagnostics; pixel values are in *original* image coordinates."""
121
+ s = res.pre.scale
122
+ ax = res.axes
123
+ d: dict[str, Any] = {
124
+ "source": res.source,
125
+ "status": res.extra.get("status", "ok"),
126
+ "overall_confidence": round(res.confidence, 4),
127
+ "stage_confidence": {k: round(v, 4) for k, v in res.stage_conf.items()},
128
+ "chart_type": {"type": res.chart_type, "confidence": round(res.chart_type_conf, 3),
129
+ **res.extra.get("chart_type_scores", {})},
130
+ "image": {"original_size": list(res.pre.original_size), "processing_scale": round(s, 4),
131
+ "noise_sigma": round(res.pre.noise_sigma, 3), "deskew_deg": res.pre.deskew_deg},
132
+ "warnings": res.warnings,
133
+ }
134
+ if ax is not None:
135
+ d["plot_area"] = ax.plot_box.scaled(1 / s).to_list()
136
+ d["axes"] = {
137
+ "x_axis_line_y": None if ax.x_axis_y is None else round(ax.x_axis_y / s, 2),
138
+ "y_axis_line_x": None if ax.y_axis_x is None else round(ax.y_axis_x / s, 2),
139
+ "x_ticks_px": [round(t / s, 2) for t in ax.x_ticks], "x_tick_source": ax.x_tick_source,
140
+ "y_ticks_px": [round(t / s, 2) for t in ax.y_ticks], "y_tick_source": ax.y_tick_source,
141
+ }
142
+ d["tick_labels"] = {
143
+ "x": [{"text": t.text, "value": t.value, "conf": round(t.conf, 2), "bbox": t.bbox.scaled(1 / s).to_list()}
144
+ for t in res.x_labels],
145
+ "y": [{"text": t.text, "value": t.value, "conf": round(t.conf, 2), "bbox": t.bbox.scaled(1 / s).to_list()}
146
+ for t in res.y_labels],
147
+ }
148
+ d["calibration"] = {
149
+ "x": res.x_cal.rescaled(s).to_dict() if res.x_cal else None,
150
+ "y": res.y_cal.rescaled(s).to_dict() if res.y_cal else None,
151
+ }
152
+ series: list[Series] = res.extra.get("series", [])
153
+ d["legend"] = res.extra.get("legend_info", {"found": False})
154
+ d["series"] = [
155
+ {"name": se.name, "rgb": list(se.rgb), "from_legend": se.from_legend,
156
+ "n_points": int(len(se.segments_px) if se.segments_px else len(se.points_px)),
157
+ "confidence": round(se.confidence, 3), "warnings": se.warnings}
158
+ for se in series
159
+ ]
160
+ d["n_series"] = len(series)
161
+ d["n_points"] = int(sum(x["n_points"] for x in d["series"]))
162
+ d.update(res.extra.get("diagnostics_extra", {}))
163
+ return d
164
+
165
+
166
+ def _put_text(img: np.ndarray, text: str, org: tuple[int, int], color: tuple[int, int, int], scale: float) -> None:
167
+ cv2.putText(img, text, org, cv2.FONT_HERSHEY_SIMPLEX, scale, (255, 255, 255), 3, cv2.LINE_AA)
168
+ cv2.putText(img, text, org, cv2.FONT_HERSHEY_SIMPLEX, scale, color, 1, cv2.LINE_AA)
169
+
170
+
171
+ def debug_overlay(res: "PipelineResult") -> np.ndarray:
172
+ """RGB overlay drawn on the processed image: plot box, ticks, labels, masks and points."""
173
+ img = res.pre.rgb.copy()
174
+ h, w = img.shape[:2]
175
+ fs = max(0.35, min(h, w) / 1600)
176
+ series: list[Series] = res.extra.get("series", [])
177
+ if series:
178
+ tint = img.copy()
179
+ for i, se in enumerate(series):
180
+ if se.mask is not None:
181
+ tint[se.mask] = _OVERLAY_COLORS[i % len(_OVERLAY_COLORS)]
182
+ img = cv2.addWeighted(tint, 0.45, img, 0.55, 0)
183
+ ax = res.axes
184
+ if ax is not None:
185
+ b = ax.plot_box
186
+ cv2.rectangle(img, (int(b.x0), int(b.y0)), (int(b.x1), int(b.y1)), (255, 0, 0), 1)
187
+ tl = max(6, int(0.012 * min(h, w)))
188
+ for t in ax.x_ticks:
189
+ cv2.line(img, (int(round(t)), int(b.y1)), (int(round(t)), int(b.y1) + tl), (200, 0, 200), 2)
190
+ for t in ax.y_ticks:
191
+ cv2.line(img, (int(b.x0) - tl, int(round(t))), (int(b.x0), int(round(t))), (200, 0, 200), 2)
192
+ for lb in res.x_labels + res.y_labels:
193
+ bb = lb.bbox
194
+ ok = lb.value is not None
195
+ col = (0, 160, 0) if ok else (230, 120, 0)
196
+ cv2.rectangle(img, (int(bb.x0), int(bb.y0)), (int(bb.x1), int(bb.y1)), col, 1)
197
+ _put_text(img, lb.text if lb.value is None else f"{lb.value:g}", (int(bb.x0), int(bb.y1) + int(14 * fs * 2)),
198
+ col, fs)
199
+ leg = res.extra.get("legend_box")
200
+ if leg is not None:
201
+ cv2.rectangle(img, (int(leg.x0), int(leg.y0)), (int(leg.x1), int(leg.y1)), (0, 200, 200), 2)
202
+ r = max(3, int(0.005 * min(h, w)))
203
+ for i, se in enumerate(series):
204
+ col = _OVERLAY_COLORS[i % len(_OVERLAY_COLORS)]
205
+ pts = list(se.points_px) if not se.segments_px else [(x, t) for x, t, _ in se.segments_px]
206
+ for x, y in pts:
207
+ cv2.circle(img, (int(round(x)), int(round(y))), r + 1, (0, 0, 0), 1, cv2.LINE_AA)
208
+ cv2.circle(img, (int(round(x)), int(round(y))), r, col, 1, cv2.LINE_AA)
209
+ lines = [f"type={res.chart_type} ({res.chart_type_conf:.2f}) conf={res.confidence:.2f}"]
210
+ for cal in (res.x_cal, res.y_cal):
211
+ if cal is None:
212
+ continue
213
+ if cal.kind == "categorical":
214
+ lines.append(f"{cal.axis}: categorical n={len(cal.categories)}")
215
+ else:
216
+ mr = max((abs(v) for v in cal.residuals_px), default=0)
217
+ lines.append(f"{cal.axis}: {cal.kind} n={cal.n_inliers}/{cal.n_labels} maxres={mr:.2f}px")
218
+ for i, se in enumerate(series):
219
+ lines.append(f"[{i}] {se.name}")
220
+ y = int(22 * fs * 2)
221
+ for ln in lines:
222
+ _put_text(img, ln, (5, y), (0, 0, 0), fs * 1.1)
223
+ y += int(18 * fs * 2)
224
+ return img
225
+
226
+
227
+ def write_csv(res: "PipelineResult", path: Path) -> None:
228
+ (res.table if res.table is not None else pd.DataFrame()).to_csv(path, index=False)
229
+
230
+
231
+ def write_diagnostics(res: "PipelineResult", path: Path) -> None:
232
+ path.write_text(json.dumps(diagnostics(res), indent=2, default=_json_default))
233
+
234
+
235
+ def write_debug_overlay(res: "PipelineResult", path: Path) -> None:
236
+ cv2.imwrite(str(path), cv2.cvtColor(debug_overlay(res), cv2.COLOR_RGB2BGR))
237
+
238
+
239
+ def write_all(res: "PipelineResult", out_dir: Path, stem: str, debug: bool = True) -> dict[str, Path]:
240
+ out_dir.mkdir(parents=True, exist_ok=True)
241
+ paths = {"csv": out_dir / f"{stem}.csv", "diagnostics": out_dir / f"{stem}.diagnostics.json"}
242
+ write_csv(res, paths["csv"])
243
+ write_diagnostics(res, paths["diagnostics"])
244
+ if debug:
245
+ paths["debug"] = out_dir / f"{stem}.debug.png"
246
+ write_debug_overlay(res, paths["debug"])
247
+ return paths
248
+
249
+
250
+ def _json_default(o: Any) -> Any:
251
+ if isinstance(o, (np.floating, np.integer)):
252
+ return o.item()
253
+ if isinstance(o, np.ndarray):
254
+ return o.tolist()
255
+ return str(o)
plotscribe/extract_bar.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bar-chart extraction (vertical bars: simple, grouped, stacked; negative values).
2
+
3
+ Per series mask: split connected regions into bars at changes of the column-top /
4
+ column-bottom profile (so touching same-colour bars separate), measure sub-pixel
5
+ top/bottom edges from the anti-aliasing alpha, then decide per bar which edge is
6
+ the value edge using the calibrated zero line.
7
+
8
+ Assumptions: bars are axis-aligned filled rectangles at least ~3 px wide; a bar's
9
+ baseline is the value 0 when 0 is on the axis, otherwise the plot bottom.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+
16
+ import cv2
17
+ import numpy as np
18
+
19
+
20
+ @dataclass
21
+ class Bar:
22
+ series: int
23
+ x0: float
24
+ x1: float
25
+ top: float # continuous pixel row of the upper edge
26
+ bottom: float
27
+
28
+ @property
29
+ def cx(self) -> float:
30
+ return 0.5 * (self.x0 + self.x1)
31
+
32
+ @property
33
+ def width(self) -> float:
34
+ return self.x1 - self.x0
35
+
36
+
37
+ def _edge_from_alpha(profile: np.ndarray, start: int, inner: int) -> float:
38
+ """Sub-pixel edge: ``inner`` is a fully covered row; integrate alpha toward ``start``.
39
+
40
+ With coverage alpha in [0, 1], the covered length between the edge and the inner
41
+ reference row equals the alpha sum, independent of how the edge is anti-aliased.
42
+ """
43
+ if inner >= start:
44
+ seg = profile[start:inner]
45
+ return float(inner - seg.sum())
46
+ seg = profile[inner + 1:start + 1]
47
+ return float(inner + 1 + seg.sum())
48
+
49
+
50
+ def bars_from_mask(mask: np.ndarray, alpha: np.ndarray, series: int, min_w: float) -> list[Bar]:
51
+ """Rectangular bars in one series mask."""
52
+ n, lab, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=4)
53
+ out: list[Bar] = []
54
+ for i in range(1, n):
55
+ x, y, w, h, area = stats[i]
56
+ if w < min_w or h < 2:
57
+ continue
58
+ comp = lab[y:y + h, x:x + w] == i
59
+ has = comp.any(axis=0)
60
+ tops = np.where(has, comp.argmax(axis=0), -1)
61
+ bots = np.where(has, h - 1 - comp[::-1].argmax(axis=0), -1)
62
+ # Split where the top or bottom profile jumps (touching bars of one colour).
63
+ cut = np.flatnonzero((np.abs(np.diff(tops)) > 1) | (np.abs(np.diff(bots)) > 1) | ~has[1:] | ~has[:-1]) + 1
64
+ for seg in np.split(np.arange(w), cut):
65
+ seg = seg[has[seg]]
66
+ if len(seg) < min_w:
67
+ continue
68
+ # Interior columns only: the left/right edges are anti-aliased.
69
+ inner = seg[1:-1] if len(seg) > 4 else seg
70
+ t_est, b_est = [], []
71
+ for c in inner:
72
+ col_a = alpha[y - 2:y + h + 2, x + c].astype(float) if y >= 2 else None
73
+ t, b = int(tops[c]), int(bots[c])
74
+ if col_a is None or len(col_a) < h + 4:
75
+ t_est.append(float(y + t))
76
+ b_est.append(float(y + b + 1))
77
+ continue
78
+ # Integrate only across the edge zone (2 px each side), so alpha
79
+ # deficits deeper inside the bar cannot shift the edge.
80
+ ref_t = min(t + 2, (t + b) // 2) + 2
81
+ ref_b = max(b - 2, (t + b) // 2) + 2
82
+ t_est.append(y - 2 + _edge_from_alpha(col_a, t, ref_t))
83
+ b_est.append(y - 2 + _edge_from_alpha(col_a, b + 4, ref_b))
84
+ # Left/right edges likewise from the row profile at mid-height.
85
+ row = int(np.median([(int(tops[c]) + int(bots[c])) // 2 for c in inner]))
86
+ row_a = alpha[y + row, x:x + w].astype(float) * comp[row]
87
+ l, r = int(seg[0]), int(seg[-1])
88
+ x0 = x + _edge_from_alpha(row_a, max(l - 2, 0), min(l + 2, (l + r) // 2))
89
+ x1 = x + _edge_from_alpha(row_a, min(r + 2, w - 1), max(r - 2, (l + r) // 2))
90
+ out.append(Bar(series, float(x0), float(x1), float(np.median(t_est)), float(np.median(b_est))))
91
+ return out
92
+
93
+
94
+ def merge_split(bars: list[Bar], gap: float) -> list[Bar]:
95
+ """Re-join pieces of one bar split by a gridline it could not be bridged across."""
96
+ out: list[Bar] = []
97
+ for b in sorted(bars, key=lambda b: (b.series, b.cx, b.top)):
98
+ for o in out:
99
+ if o.series != b.series:
100
+ continue
101
+ ov = min(b.x1, o.x1) - max(b.x0, o.x0)
102
+ vgap = max(b.top - o.bottom, o.top - b.bottom)
103
+ hgap = max(b.x0 - o.x1, o.x0 - b.x1)
104
+ same_rows = abs(b.top - o.top) <= 2 and abs(b.bottom - o.bottom) <= 2
105
+ if (ov > 0.8 * min(b.width, o.width) and -1.0 <= vgap <= gap) or (same_rows and -1.0 <= hgap <= gap):
106
+ o.bottom, o.top = max(o.bottom, b.bottom), min(o.top, b.top)
107
+ o.x0, o.x1 = min(o.x0, b.x0), max(o.x1, b.x1)
108
+ break
109
+ else:
110
+ out.append(Bar(b.series, b.x0, b.x1, b.top, b.bottom))
111
+ return out
112
+
113
+
114
+ def touches(b: Bar, box_edges: tuple[float, float, float, float], tol: float) -> bool:
115
+ """Does the bar end at the boundary of an occluding box (x0, y0, x1, y1)?"""
116
+ x0, y0, x1, y1 = box_edges
117
+ if b.x1 < x0 - tol or b.x0 > x1 + tol:
118
+ return False
119
+ return abs(b.top - y1) <= tol or abs(b.bottom - y0) <= tol
120
+
121
+
122
+ def drop_fragments(bars: list[Bar], min_h: float) -> list[Bar]:
123
+ """Remove compression/anti-aliasing fragments: slivers lying inside another bar."""
124
+ out = []
125
+ for b in bars:
126
+ inside = any(o is not b and o.series != b.series and b.x0 >= o.x0 - 2 and b.x1 <= o.x1 + 2
127
+ and b.top >= o.top - 1 and b.bottom <= o.bottom + 1 for o in bars)
128
+ if inside or (b.bottom - b.top) < min_h:
129
+ continue
130
+ out.append(b)
131
+ return out
132
+
133
+
134
+ def detect_stacked(bars: list[Bar], tol: float = 4.0) -> bool:
135
+ """Stacked if most bar *area* shares its x-span with an abutting bar of another series."""
136
+ if len(bars) < 2 or len({b.series for b in bars}) < 2:
137
+ return False
138
+ abut_area = total = 0.0
139
+ for b in bars:
140
+ area = b.width * (b.bottom - b.top)
141
+ total += area
142
+ for o in bars:
143
+ if o.series == b.series:
144
+ continue
145
+ ov = min(b.x1, o.x1) - max(b.x0, o.x0)
146
+ if ov > 0.6 * min(b.width, o.width) and (abs(b.top - o.bottom) < tol or abs(b.bottom - o.top) < tol):
147
+ abut_area += area
148
+ break
149
+ return total > 0 and abut_area >= 0.5 * total
150
+
151
+
152
+ def snap_baseline(bars: list[Bar], zero_px: float, tol: float) -> None:
153
+ """Bars ending within ``tol`` of the zero line end exactly on it (spine/zero line hides it)."""
154
+ for b in bars:
155
+ if abs(b.bottom - zero_px) <= tol:
156
+ b.bottom = zero_px
157
+ if abs(b.top - zero_px) <= tol:
158
+ b.top = zero_px
159
+
160
+
161
+ def snap_stack_joints(bars: list[Bar], tol: float = 4.0) -> None:
162
+ """Adjacent stacked segments share one boundary: use the mean of both estimates."""
163
+ for b in bars:
164
+ for o in bars:
165
+ if o is b or o.series == b.series:
166
+ continue
167
+ ov = min(b.x1, o.x1) - max(b.x0, o.x0)
168
+ if ov > 0.6 * min(b.width, o.width) and abs(b.bottom - o.top) < tol:
169
+ m = 0.5 * (b.bottom + o.top)
170
+ b.bottom = o.top = m
171
+
172
+
173
+ def value_edge(b: Bar, zero_px: float) -> float:
174
+ """The edge that encodes the value: the one farther from the baseline."""
175
+ return b.top if abs(b.top - zero_px) >= abs(b.bottom - zero_px) else b.bottom
176
+
177
+
178
+ def category_clusters(bars: list[Bar]) -> list[float]:
179
+ """Centres of groups of bars that touch or overlap in x (one group per category).
180
+
181
+ Grouped bars of one category are adjacent; stacked segments share x; categories
182
+ are separated by a gap.
183
+ """
184
+ if not bars:
185
+ return []
186
+ bs = sorted(bars, key=lambda b: b.x0)
187
+ tol = 0.15 * float(np.median([b.width for b in bs]))
188
+ groups: list[list[Bar]] = [[bs[0]]]
189
+ right = bs[0].x1
190
+ for b in bs[1:]:
191
+ if b.x0 <= right + tol:
192
+ groups[-1].append(b)
193
+ right = max(right, b.x1)
194
+ else:
195
+ groups.append([b])
196
+ right = b.x1
197
+ spans = [(min(b.x0 for b in g), max(b.x1 for b in g)) for g in groups]
198
+ # A missing/tiny bar can split one category in two: merge groups whose centres
199
+ # are much closer than the typical category spacing.
200
+ while len(spans) > 2:
201
+ c = np.array([(a + b) / 2 for a, b in spans])
202
+ d = np.diff(c)
203
+ i = int(np.argmin(d))
204
+ if d[i] >= 0.6 * np.median(d):
205
+ break
206
+ spans[i] = (spans[i][0], spans[i + 1][1])
207
+ del spans[i + 1]
208
+ return [(a + b) / 2 for a, b in spans]
plotscribe/extract_line.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Line-chart extraction from one series mask.
2
+
3
+ Pipeline per series: dense sub-pixel centreline (alpha-weighted centroid per
4
+ column, with continuity tracking where a column has several runs) -> gap
5
+ interpolation -> data points from (1) markers, else (2) category positions, else
6
+ (3) polyline vertices (Ramer-Douglas-Peucker), refined by intersecting lines fitted
7
+ to the neighbouring segments.
8
+
9
+ Assumptions: each series is a function of x (one y per column); line markers, if
10
+ present, are at least ~2x wider than the stroke.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass
16
+
17
+ import cv2
18
+ import numpy as np
19
+
20
+
21
+ @dataclass
22
+ class Centreline:
23
+ x: np.ndarray # integer columns covered (first..last observed)
24
+ y: np.ndarray # sub-pixel row per column
25
+ observed: np.ndarray # bool, False where interpolated
26
+ thickness: float
27
+
28
+
29
+ def _runs(col: np.ndarray) -> list[tuple[int, int]]:
30
+ idx = np.flatnonzero(col)
31
+ if idx.size == 0:
32
+ return []
33
+ splits = np.flatnonzero(np.diff(idx) > 1) + 1
34
+ return [(int(g[0]), int(g[-1]) + 1) for g in np.split(idx, splits)]
35
+
36
+
37
+ def centreline(mask: np.ndarray, alpha: np.ndarray) -> Centreline | None:
38
+ """Sub-pixel y for every column between the first and last column with ink."""
39
+ cols = np.flatnonzero(mask.any(axis=0))
40
+ if cols.size < 2:
41
+ return None
42
+ x0, x1 = int(cols[0]), int(cols[-1]) + 1
43
+ n = x1 - x0
44
+ ys = np.full(n, np.nan)
45
+ runs_per_col: list[list[tuple[int, int]]] = []
46
+ lengths = []
47
+ for k in range(n):
48
+ rr = _runs(mask[:, x0 + k])
49
+ runs_per_col.append(rr)
50
+ if len(rr) == 1:
51
+ a, b = rr[0]
52
+ w = alpha[a:b, x0 + k].astype(float) + 1e-6
53
+ ys[k] = float((np.arange(a, b) * w).sum() / w.sum()) + 0.5
54
+ lengths.append(b - a)
55
+ single = np.isfinite(ys)
56
+ # Multi-run columns: choose the run nearest to the interpolation of single-run neighbours.
57
+ if single.sum() >= 2:
58
+ ref = np.interp(np.arange(n), np.flatnonzero(single), ys[single])
59
+ else:
60
+ ref = np.full(n, np.nan)
61
+ for k, rr in enumerate(runs_per_col):
62
+ if len(rr) <= 1:
63
+ continue
64
+ cents = []
65
+ for a, b in rr:
66
+ w = alpha[a:b, x0 + k].astype(float) + 1e-6
67
+ cents.append(float((np.arange(a, b) * w).sum() / w.sum()) + 0.5)
68
+ if np.isfinite(ref[k]):
69
+ ys[k] = min(cents, key=lambda c: abs(c - ref[k]))
70
+ else:
71
+ ys[k] = cents[int(np.argmax([b - a for a, b in rr]))]
72
+ observed = np.isfinite(ys)
73
+ if observed.sum() < 2:
74
+ return None
75
+ xs = np.arange(x0, x1, dtype=float) + 0.5
76
+ ys = np.interp(xs, xs[observed], ys[observed])
77
+ # Stroke thickness: run length where the line is locally flat.
78
+ flat = []
79
+ for k in range(1, n - 1):
80
+ if observed[k] and len(runs_per_col[k]) == 1 and abs(ys[k + 1] - ys[k - 1]) < 0.5:
81
+ a, b = runs_per_col[k][0]
82
+ flat.append(float(alpha[a:b, x0 + k].sum()))
83
+ if flat:
84
+ thick = float(np.median(flat))
85
+ else:
86
+ thick = float(np.median(lengths)) if lengths else 2.0
87
+ return Centreline(x=xs, y=ys, observed=observed, thickness=max(thick, 1.0))
88
+
89
+
90
+ def find_markers(mask: np.ndarray, alpha: np.ndarray, thickness: float) -> np.ndarray:
91
+ """Marker centres (x, y) via morphological opening wider than the stroke."""
92
+ k = int(np.ceil(2.2 * thickness)) | 1
93
+ if k < 3:
94
+ k = 3
95
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k, k))
96
+ blobs = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_OPEN, kernel)
97
+ n, lab, stats, _ = cv2.connectedComponentsWithStats(blobs, connectivity=8)
98
+ if n <= 2:
99
+ return np.zeros((0, 2))
100
+ areas = stats[1:, cv2.CC_STAT_AREA].astype(float)
101
+ med = float(np.median(areas))
102
+ pts = []
103
+ for i in range(1, n):
104
+ a = stats[i, cv2.CC_STAT_AREA]
105
+ if a < 0.4 * med or a > 2.5 * med:
106
+ continue # joins of steep lines, or overlapping markers
107
+ x, y, w, h = stats[i, :4]
108
+ sub = lab[y:y + h, x:x + w] == i
109
+ wts = alpha[y:y + h, x:x + w] * sub + 1e-9 * sub
110
+ yy, xx = np.mgrid[y:y + h, x:x + w]
111
+ s = wts.sum()
112
+ pts.append(((xx * wts).sum() / s + 0.5, (yy * wts).sum() / s + 0.5))
113
+ if len(pts) < 2:
114
+ return np.zeros((0, 2))
115
+ return np.asarray(sorted(pts))
116
+
117
+
118
+ def rdp(x: np.ndarray, y: np.ndarray, eps: float) -> np.ndarray:
119
+ """Indices of Ramer-Douglas-Peucker vertices (iterative)."""
120
+ keep = np.zeros(len(x), bool)
121
+ keep[0] = keep[-1] = True
122
+ stack = [(0, len(x) - 1)]
123
+ while stack:
124
+ i, j = stack.pop()
125
+ if j <= i + 1:
126
+ continue
127
+ dx, dy = x[j] - x[i], y[j] - y[i]
128
+ norm = np.hypot(dx, dy) or 1.0
129
+ d = np.abs(dy * (x[i + 1:j] - x[i]) - dx * (y[i + 1:j] - y[i])) / norm
130
+ k = int(np.argmax(d))
131
+ if d[k] > eps:
132
+ m = i + 1 + k
133
+ keep[m] = True
134
+ stack.extend([(i, m), (m, j)])
135
+ return np.flatnonzero(keep)
136
+
137
+
138
+ def _fit(x: np.ndarray, y: np.ndarray) -> tuple[float, float] | None:
139
+ if len(x) < 3 or np.ptp(x) == 0:
140
+ return None
141
+ b, a = np.polyfit(x, y, 1)
142
+ return float(a), float(b)
143
+
144
+
145
+ def refine_vertices(cl: Centreline, idx: np.ndarray) -> np.ndarray:
146
+ """Vertex positions as intersections of lines fitted to adjacent segments.
147
+
148
+ A column-centroid at a sharp peak is biased toward the inside of the corner by
149
+ the stroke width; intersecting the two neighbouring segment fits removes that.
150
+ """
151
+ x, y = cl.x, cl.y
152
+ m = max(2, int(np.ceil(1.5 * cl.thickness)))
153
+ out = np.stack([x[idx], y[idx]], 1)
154
+ for n in range(1, len(idx) - 1):
155
+ a, k, b = idx[n - 1], idx[n], idx[n + 1]
156
+ left = slice(a + m, k - m)
157
+ right = slice(k + m, b - m)
158
+ fl = _fit(x[left], y[left]) if k - m > a + m else None
159
+ fr = _fit(x[right], y[right]) if b - m > k + m else None
160
+ if fl is None or fr is None or abs(fl[1] - fr[1]) < 1e-3:
161
+ continue
162
+ xi = (fr[0] - fl[0]) / (fl[1] - fr[1])
163
+ if abs(xi - x[k]) <= 2 * m:
164
+ out[n] = (xi, fl[0] + fl[1] * xi)
165
+ # Endpoints: projecting caps extend the stroke by half its width.
166
+ for end, nb in ((0, 1), (len(idx) - 1, len(idx) - 2)):
167
+ if len(idx) >= 2:
168
+ d = out[nb] - out[end]
169
+ L = float(np.hypot(*d))
170
+ if L > cl.thickness:
171
+ out[end] = out[end] + d / L * (cl.thickness / 2)
172
+ return out
173
+
174
+
175
+ def extract_line(mask: np.ndarray, alpha: np.ndarray, category_px: list[float] | None = None
176
+ ) -> tuple[np.ndarray, str, Centreline | None]:
177
+ """Data points (x, y) in pixels and the method used: markers/categories/vertices."""
178
+ cl = centreline(mask, alpha)
179
+ if cl is None:
180
+ return np.zeros((0, 2)), "none", None
181
+ markers = find_markers(mask, alpha, cl.thickness)
182
+ span = cl.x[-1] - cl.x[0]
183
+ if len(markers) >= 2 and np.ptp(markers[:, 0]) >= 0.5 * span:
184
+ return markers, "markers", cl
185
+ if category_px:
186
+ cp = np.asarray([c for c in category_px if cl.x[0] - cl.thickness <= c <= cl.x[-1] + cl.thickness])
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
+ return refine_vertices(cl, idx), "vertices", cl
plotscribe/extract_scatter.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Scatter extraction: marker centres per series mask, with touching markers split.
2
+
3
+ Isolated markers give the typical marker area; components much larger than that
4
+ are split with a distance transform + watershed seeded at distance maxima. Centres
5
+ are alpha-weighted centroids; for round markers that are cut by a neighbour (same
6
+ or other series) the centre is re-estimated by a circle fit to the *free* part of
7
+ the boundary, which removes the bias towards the cut.
8
+
9
+ Assumptions: filled markers of one size per series; overlapping markers of one
10
+ series are separable when centres are at least ~0.5 marker radius apart.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import cv2
16
+ import numpy as np
17
+ from scipy import ndimage as ndi
18
+
19
+
20
+ def _centroid(ys: np.ndarray, xs: np.ndarray, w: np.ndarray) -> tuple[float, float]:
21
+ s = float(w.sum()) or 1.0
22
+ return float((xs * w).sum() / s) + 0.5, float((ys * w).sum() / s) + 0.5
23
+
24
+
25
+ def _fit_circle(px: np.ndarray, py: np.ndarray) -> tuple[float, float, float] | None:
26
+ """Algebraic (Kasa) least-squares circle fit; returns (cx, cy, r)."""
27
+ if len(px) < 6:
28
+ return None
29
+ A = np.column_stack([px, py, np.ones_like(px)])
30
+ b = -(px**2 + py**2)
31
+ sol, *_ = np.linalg.lstsq(A, b, rcond=None)
32
+ cx, cy = -sol[0] / 2, -sol[1] / 2
33
+ r2 = cx**2 + cy**2 - sol[2]
34
+ if r2 <= 0:
35
+ return None
36
+ return float(cx), float(cy), float(np.sqrt(r2))
37
+
38
+
39
+ def marker_stats(mask: np.ndarray) -> tuple[float, float]:
40
+ """(typical single-marker area, median fill ratio) from the smaller half of components."""
41
+ n, _, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8)
42
+ if n <= 1:
43
+ return 0.0, 0.0
44
+ areas = stats[1:, cv2.CC_STAT_AREA].astype(float)
45
+ fills = areas / (stats[1:, 2] * stats[1:, 3])
46
+ small = areas <= np.median(areas)
47
+ return float(np.median(areas[small])), float(np.median(fills[small]))
48
+
49
+
50
+ def extract_scatter(mask: np.ndarray, alpha: np.ndarray, others: np.ndarray) -> tuple[np.ndarray, dict]:
51
+ """Marker centres (x, y) in pixels. ``others`` marks pixels of other series."""
52
+ a_med, fill = marker_stats(mask)
53
+ info = {"marker_area_px": a_med, "fill": round(fill, 3), "split_components": 0}
54
+ if a_med <= 0:
55
+ return np.zeros((0, 2)), info
56
+ round_markers = 0.65 < fill < 0.88
57
+ radius = np.sqrt(a_med / np.pi)
58
+ n, lab, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8)
59
+ pts: list[tuple[float, float]] = []
60
+ for i in range(1, n):
61
+ x, y, w, h, area = stats[i]
62
+ if area < 0.3 * a_med:
63
+ continue # fragment of a marker hidden behind another series
64
+ sub = lab[y:y + h, x:x + w] == i
65
+ wts = alpha[y:y + h, x:x + w] * sub
66
+ k = int(round(area / a_med))
67
+ if k <= 1 or area < 1.5 * a_med:
68
+ regions = [sub]
69
+ else:
70
+ info["split_components"] += 1
71
+ dist = ndi.distance_transform_edt(np.pad(sub, 1))[1:-1, 1:-1]
72
+ peaks = _peaks(dist, max(1, int(0.5 * radius)), k + 1)
73
+ if len(peaks) <= 1:
74
+ regions = [sub]
75
+ else:
76
+ regions = _watershed(dist, sub, peaks)
77
+ for reg in regions:
78
+ ys, xs = np.nonzero(reg)
79
+ if len(ys) < 0.25 * a_med:
80
+ continue
81
+ cx, cy = _centroid(ys + y, xs + x, wts[ys, xs] + 1e-6)
82
+ cut = len(regions) > 1 or _touches(reg, x, y, others)
83
+ if round_markers and cut:
84
+ fitted = _free_boundary_circle(reg, x, y, mask, others, lab, i)
85
+ if fitted is not None and abs(fitted[2] - radius) < 0.35 * radius:
86
+ cx, cy = fitted[0], fitted[1]
87
+ pts.append((cx, cy))
88
+ out = np.asarray(sorted(pts)) if pts else np.zeros((0, 2))
89
+ return out, info
90
+
91
+
92
+ def _peaks(dist: np.ndarray, min_distance: int, n: int) -> list[tuple[int, int]]:
93
+ """Up to ``n`` local maxima of ``dist`` at least ``min_distance`` apart (greedy, highest first)."""
94
+ local = (dist == ndi.maximum_filter(dist, size=2 * min_distance + 1)) & (dist > 0)
95
+ ys, xs = np.nonzero(local)
96
+ order = np.argsort(-dist[ys, xs])
97
+ out: list[tuple[int, int]] = []
98
+ for i in order:
99
+ y, x = int(ys[i]), int(xs[i])
100
+ if all(max(abs(y - a), abs(x - b)) >= min_distance for a, b in out):
101
+ out.append((y, x))
102
+ if len(out) == n:
103
+ break
104
+ return out
105
+
106
+
107
+ def _watershed(dist: np.ndarray, sub: np.ndarray, peaks: list[tuple[int, int]]) -> list[np.ndarray]:
108
+ """Split ``sub`` into one region per peak: each pixel goes to its nearest peak.
109
+
110
+ For touching markers of equal size this equals a watershed on the distance map.
111
+ """
112
+ ys, xs = np.nonzero(sub)
113
+ pk = np.asarray(peaks, float)
114
+ owner = np.argmin((ys[:, None] - pk[None, :, 0]) ** 2 + (xs[:, None] - pk[None, :, 1]) ** 2, axis=1)
115
+ regions = []
116
+ for j in range(len(peaks)):
117
+ r = np.zeros_like(sub)
118
+ r[ys[owner == j], xs[owner == j]] = True
119
+ regions.append(r)
120
+ return regions
121
+
122
+
123
+ def _touches(reg: np.ndarray, x: int, y: int, others: np.ndarray) -> bool:
124
+ h, w = reg.shape
125
+ win = others[max(y - 1, 0):y + h + 1, max(x - 1, 0):x + w + 1]
126
+ return bool(win.any())
127
+
128
+
129
+ def _free_boundary_circle(reg: np.ndarray, x: int, y: int, mask: np.ndarray, others: np.ndarray,
130
+ lab: np.ndarray, comp: int) -> tuple[float, float, float] | None:
131
+ """Circle through boundary pixels of ``reg`` that border background (not a neighbour)."""
132
+ h, w = reg.shape
133
+ pad = np.pad(reg, 1)
134
+ er = pad & ~ndi.binary_erosion(pad)
135
+ by, bx = np.nonzero(er[1:-1, 1:-1])
136
+ gy, gx = by + y, bx + x
137
+ H, W = mask.shape
138
+ keep = []
139
+ for yy, xx in zip(gy, gx):
140
+ ok = True
141
+ for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1)):
142
+ ny, nx = yy + dy, xx + dx
143
+ if not (0 <= ny < H and 0 <= nx < W):
144
+ continue
145
+ # Neighbour must be background: not this component, not another series.
146
+ ry, rx = ny - y, nx - x
147
+ inside_reg = 0 <= ry < h and 0 <= rx < w and reg[ry, rx]
148
+ if inside_reg:
149
+ continue
150
+ if others[ny, nx] or (lab[ny, nx] == comp):
151
+ ok = False
152
+ break
153
+ keep.append(ok)
154
+ keep_arr = np.asarray(keep, bool)
155
+ if keep_arr.sum() < 8:
156
+ return None
157
+ return _fit_circle(gx[keep_arr] + 0.5, gy[keep_arr] + 0.5)
plotscribe/legend.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Legend detection: colour swatches immediately left of a text label.
2
+
3
+ Assumptions:
4
+ - Entries are laid out as [swatch][gap][label], stacked vertically (swatches
5
+ left-aligned) or in a single row (vertically centred).
6
+ - Swatches are short line segments, small filled patches, or single markers and
7
+ are no larger than a few glyph heights.
8
+ - Label text is dark/achromatic.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass, field
14
+
15
+ import cv2
16
+ import numpy as np
17
+
18
+ from .axes import group_words
19
+ from .models import BBox
20
+ from .ocr import OCRBackend, prepare_crop
21
+
22
+ COLOURED = 15.0
23
+
24
+
25
+ @dataclass
26
+ class LegendEntry:
27
+ swatch: BBox
28
+ text_box: BBox
29
+ label: str
30
+ lab: np.ndarray
31
+ kind: str # "line" | "patch" | "marker"
32
+ conf: float = 1.0
33
+
34
+
35
+ @dataclass
36
+ class Legend:
37
+ entries: list[LegendEntry] = field(default_factory=list)
38
+ box: BBox | None = None
39
+ confidence: float = 0.0
40
+ warnings: list[str] = field(default_factory=list)
41
+
42
+ def to_dict(self) -> dict:
43
+ return {
44
+ "found": bool(self.entries),
45
+ "confidence": round(self.confidence, 3),
46
+ "entries": [{"label": e.label, "swatch_kind": e.kind, "swatch_bbox": e.swatch.to_list(),
47
+ "text_bbox": e.text_box.to_list()} for e in self.entries],
48
+ }
49
+
50
+
51
+ @dataclass
52
+ class _Comp:
53
+ box: BBox
54
+ chroma: float
55
+ lab: np.ndarray
56
+ fill: float
57
+ idx: int
58
+
59
+
60
+ def _components(lab: np.ndarray, ink: np.ndarray, bg: np.ndarray, max_w: float, max_h: float) -> list[_Comp]:
61
+ n, labels, stats, _ = cv2.connectedComponentsWithStats(ink.astype(np.uint8), connectivity=8)
62
+ out = []
63
+ for i in range(1, n):
64
+ x, y, w, h, area = stats[i]
65
+ if w > max_w or h > max_h or area < 3:
66
+ continue
67
+ ys, xs = np.nonzero(labels[y:y + h, x:x + w] == i)
68
+ pix = lab[y + ys, x + xs]
69
+ de = np.linalg.norm(pix - bg, axis=1)
70
+ core = pix[de >= 0.7 * de.max()] if len(pix) else pix
71
+ col = core.mean(axis=0)
72
+ out.append(_Comp(BBox(float(x), float(y), float(x + w), float(y + h)), float(np.hypot(col[1], col[2])),
73
+ col, float(area) / float(w * h), i))
74
+ return out
75
+
76
+
77
+ def _swatch_kind(c: _Comp, ch: float) -> str:
78
+ b = c.box
79
+ if b.w >= 2.5 * b.h:
80
+ return "line"
81
+ if c.fill > 0.85 and b.w >= 0.8 * ch:
82
+ return "patch"
83
+ return "marker"
84
+
85
+
86
+ def detect_legend(rgb: np.ndarray, lab: np.ndarray, ink: np.ndarray, bg: np.ndarray, char_h: float,
87
+ ocr: OCRBackend, exclude: list[BBox]) -> Legend:
88
+ """Find legend entries anywhere in the image; ``exclude`` are known tick-label boxes."""
89
+ leg = Legend()
90
+ if char_h <= 0:
91
+ return leg
92
+ ch = char_h
93
+ # Swatches from strong-contrast pixels only: data drawn behind a semi-transparent
94
+ # legend keeps ~20% of its contrast and would otherwise fuse with the swatches.
95
+ strong = ink & (np.linalg.norm(lab - np.asarray(bg, np.float32), axis=-1) > 25.0)
96
+ comps = _components(lab, strong, bg, max_w=6 * ch, max_h=2.5 * ch)
97
+ # Text from dark achromatic pixels only: legends are often drawn semi-transparently
98
+ # over data lines, which would otherwise fuse with the glyphs.
99
+ text_ink = ink & (lab[..., 0] < 60) & (np.hypot(lab[..., 1], lab[..., 2]) < COLOURED)
100
+ text_comps = _components(lab, text_ink, bg, max_w=6 * ch, max_h=2.5 * ch)
101
+
102
+ def excluded(b: BBox) -> bool:
103
+ return any(b.intersects(e) for e in exclude)
104
+
105
+ glyphs = [c for c in text_comps if 0.25 * ch <= c.box.h <= 1.8 * ch
106
+ and c.box.w <= 2.5 * ch and not (c.box.w >= 3 * c.box.h and c.box.h <= 0.3 * ch)
107
+ and not excluded(c.box)]
108
+ swatches = [c for c in comps if (c.chroma >= COLOURED or (c.box.w >= 2.5 * c.box.h and c.box.w >= ch))
109
+ and c.box.w >= 0.3 * ch and c.box.h >= 2 and not excluded(c.box)]
110
+ lines = group_words([g.box for g in glyphs], ch, gap_x=0.8 * ch, gap_y=-0.1 * ch)
111
+ lines = [ln for ln in lines if ln.h <= 2.0 * ch and ln.h >= 0.5 * ch]
112
+
113
+ cands: list[tuple[_Comp, BBox]] = []
114
+ for ln in lines:
115
+ best = None
116
+ for s in swatches:
117
+ gap = ln.x0 - s.box.x1
118
+ # Markers sit centred in a ~2 em handle, so their gap to the text is larger.
119
+ max_gap = 3.2 * ch if _swatch_kind(s, ch) == "marker" else 2.0 * ch
120
+ if -0.2 * ch <= gap <= max_gap and abs(s.box.cy - ln.cy) <= 0.45 * ln.h and s.box.h <= 1.6 * ln.h:
121
+ if best is None or gap < best[0]:
122
+ best = (gap, s)
123
+ if best is not None:
124
+ cands.append((best[1], ln))
125
+ if not cands:
126
+ return leg
127
+
128
+ # Keep the largest mutually consistent group: same column or same row.
129
+ def group_of(ref: tuple[_Comp, BBox]) -> list[tuple[_Comp, BBox]]:
130
+ col = [c for c in cands if abs(c[0].box.x0 - ref[0].box.x0) <= 0.8 * ch]
131
+ row = [c for c in cands if abs(c[1].cy - ref[1].cy) <= 0.5 * ch]
132
+ g = col if len(col) >= len(row) else row
133
+ if g is col and len(g) > 1:
134
+ g = sorted(g, key=lambda c: c[1].cy)
135
+ gaps = np.diff([c[1].cy for c in g])
136
+ # Entries of one legend are evenly stacked.
137
+ if np.any(gaps > 3.5 * ch):
138
+ return [ref]
139
+ return g
140
+
141
+ groups = [group_of(c) for c in cands]
142
+ best_group = max(groups, key=len)
143
+ if len(best_group) == 1 and best_group[0][0].chroma < COLOURED and _swatch_kind(best_group[0][0], ch) != "line":
144
+ return leg
145
+
146
+ entries = []
147
+ h, w = rgb.shape[:2]
148
+ for sw, ln in sorted(best_group, key=lambda c: (c[1].cy, c[1].x0)):
149
+ r = ln.expand(max(2.0, 0.25 * ch)).clip(w, h)
150
+ rs, cs = r.slices()
151
+ text, conf = ocr.read_line(prepare_crop(rgb[rs, cs], ch))
152
+ entries.append(LegendEntry(swatch=sw.box, text_box=ln, label=text.strip(), lab=sw.lab,
153
+ kind=_swatch_kind(sw, ch), conf=conf))
154
+ leg.entries = entries
155
+ union = entries[0].swatch.union(entries[0].text_box)
156
+ for e in entries[1:]:
157
+ union = union.union(e.swatch).union(e.text_box)
158
+ leg.box = _grow_to_frame(ink, union.expand(0.5 * ch), ch)
159
+ leg.confidence = 0.9 if len(entries) > 1 else 0.7
160
+ # Two entries with the same colour make the pairing ambiguous.
161
+ for i, a in enumerate(entries):
162
+ for b in entries[i + 1:]:
163
+ if np.linalg.norm(a.lab - b.lab) < 10:
164
+ leg.confidence *= 0.5
165
+ leg.warnings.append(f"legend entries '{a.label}' and '{b.label}' have near-identical colours")
166
+ for e in entries:
167
+ if not e.label:
168
+ leg.warnings.append("legend label not readable")
169
+ leg.confidence *= 0.8
170
+ return leg
171
+
172
+
173
+ def _grow_to_frame(ink: np.ndarray, box: BBox, ch: float) -> BBox:
174
+ """Extend ``box`` outward (up to ~1.2 glyph heights) to include a surrounding frame."""
175
+ h, w = ink.shape
176
+ out = [box.x0, box.y0, box.x1, box.y1]
177
+ reach = int(np.ceil(1.2 * ch))
178
+ b = box.clip(w, h)
179
+ rs, cs = b.slices()
180
+ for side in range(4):
181
+ best = None
182
+ for k in range(1, reach + 1):
183
+ if side == 0:
184
+ x = int(b.x0) - k
185
+ if x < 0:
186
+ break
187
+ frac = ink[rs, x].mean()
188
+ elif side == 1:
189
+ y = int(b.y0) - k
190
+ if y < 0:
191
+ break
192
+ frac = ink[y, cs].mean()
193
+ elif side == 2:
194
+ x = int(np.ceil(b.x1)) + k - 1
195
+ if x >= w:
196
+ break
197
+ frac = ink[rs, x].mean()
198
+ else:
199
+ y = int(np.ceil(b.y1)) + k - 1
200
+ if y >= h:
201
+ break
202
+ frac = ink[y, cs].mean()
203
+ if frac > 0.6:
204
+ best = k
205
+ if best is not None:
206
+ out[side] = (out[side] - best - 1) if side < 2 else (out[side] + best + 1)
207
+ return BBox(*out)
208
+
209
+
210
+ def legend_colour_distance(leg: Legend, lab: np.ndarray) -> np.ndarray:
211
+ """Distances between legend swatch colours and an array of colours (rows)."""
212
+ if not leg.entries:
213
+ return np.zeros((0, len(lab)))
214
+ sw = np.stack([e.lab for e in leg.entries])
215
+ return np.linalg.norm(sw[:, None, :] - np.asarray(lab)[None, :, :], axis=2)
216
+
plotscribe/models.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared data types passed between pipeline stages.
2
+
3
+ Coordinates are pixels in the *processed* image (after upscaling) unless a field
4
+ says otherwise; ``pipeline`` converts to original-image pixels for output.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+
11
+ import numpy as np
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class BBox:
16
+ """Axis-aligned box, ``x1``/``y1`` exclusive-ish (continuous pixel coordinates)."""
17
+
18
+ x0: float
19
+ y0: float
20
+ x1: float
21
+ y1: float
22
+
23
+ @property
24
+ def w(self) -> float:
25
+ return self.x1 - self.x0
26
+
27
+ @property
28
+ def h(self) -> float:
29
+ return self.y1 - self.y0
30
+
31
+ @property
32
+ def cx(self) -> float:
33
+ return 0.5 * (self.x0 + self.x1)
34
+
35
+ @property
36
+ def cy(self) -> float:
37
+ return 0.5 * (self.y0 + self.y1)
38
+
39
+ @property
40
+ def area(self) -> float:
41
+ return max(self.w, 0.0) * max(self.h, 0.0)
42
+
43
+ def scaled(self, s: float) -> "BBox":
44
+ return BBox(self.x0 * s, self.y0 * s, self.x1 * s, self.y1 * s)
45
+
46
+ def expand(self, dx: float, dy: float | None = None) -> "BBox":
47
+ dy = dx if dy is None else dy
48
+ return BBox(self.x0 - dx, self.y0 - dy, self.x1 + dx, self.y1 + dy)
49
+
50
+ def clip(self, width: int, height: int) -> "BBox":
51
+ return BBox(max(0.0, self.x0), max(0.0, self.y0), min(float(width), self.x1), min(float(height), self.y1))
52
+
53
+ def union(self, other: "BBox") -> "BBox":
54
+ return BBox(min(self.x0, other.x0), min(self.y0, other.y0), max(self.x1, other.x1), max(self.y1, other.y1))
55
+
56
+ def intersects(self, other: "BBox") -> bool:
57
+ return self.x0 < other.x1 and other.x0 < self.x1 and self.y0 < other.y1 and other.y0 < self.y1
58
+
59
+ def iou(self, other: "BBox") -> float:
60
+ ix = max(0.0, min(self.x1, other.x1) - max(self.x0, other.x0))
61
+ iy = max(0.0, min(self.y1, other.y1) - max(self.y0, other.y0))
62
+ inter = ix * iy
63
+ union = self.area + other.area - inter
64
+ return inter / union if union > 0 else 0.0
65
+
66
+ def slices(self) -> tuple[slice, slice]:
67
+ """Integer (rows, cols) slices covering the box."""
68
+ return (slice(int(np.floor(self.y0)), int(np.ceil(self.y1))),
69
+ slice(int(np.floor(self.x0)), int(np.ceil(self.x1))))
70
+
71
+ def to_list(self) -> list[float]:
72
+ return [round(self.x0, 2), round(self.y0, 2), round(self.x1, 2), round(self.y1, 2)]
73
+
74
+
75
+ @dataclass
76
+ class Segment:
77
+ """A straight horizontal ('h') or vertical ('v') line found in the image."""
78
+
79
+ orient: str
80
+ pos: float # centre row (h) or column (v)
81
+ start: float
82
+ end: float
83
+ thickness: float
84
+ lab: tuple[float, float, float]
85
+
86
+ @property
87
+ def length(self) -> float:
88
+ return self.end - self.start
89
+
90
+
91
+ @dataclass
92
+ class TextBox:
93
+ """A group of glyph components believed to be one text label."""
94
+
95
+ bbox: BBox
96
+ text: str = ""
97
+ conf: float = 0.0
98
+ value: float | None = None
99
+ # Alternative numeric readings (several OCR passes); calibration picks among them.
100
+ candidates: list[float] = field(default_factory=list)
101
+
102
+
103
+ @dataclass
104
+ class TickLabel:
105
+ """An OCR'd axis label matched (or not) to a tick position."""
106
+
107
+ box: TextBox
108
+ tick_px: float # pixel position along the axis the label refers to
109
+ matched_tick: bool
110
+
111
+
112
+ @dataclass
113
+ class AxesResult:
114
+ """Plot area, axis lines and ticks."""
115
+
116
+ plot_box: BBox
117
+ x_axis_y: float | None
118
+ y_axis_x: float | None
119
+ x_ticks: list[float]
120
+ y_ticks: list[float]
121
+ h_lines: list[Segment]
122
+ v_lines: list[Segment]
123
+ figure_bg: np.ndarray
124
+ panel_bg: np.ndarray
125
+ x_tick_len: float # outward tick length (0 if ticks point inward / absent)
126
+ y_tick_len: float
127
+ line_thickness: float
128
+ confidence: float
129
+ warnings: list[str] = field(default_factory=list)
130
+ x_tick_source: str = "none"
131
+ y_tick_source: str = "none"
132
+
133
+
134
+ @dataclass
135
+ class Series:
136
+ """One extracted data series."""
137
+
138
+ name: str
139
+ lab: tuple[float, float, float]
140
+ rgb: tuple[int, int, int]
141
+ mask: np.ndarray | None = None # bool, processed-image size
142
+ points_px: np.ndarray = field(default_factory=lambda: np.zeros((0, 2))) # (x, y) pixels
143
+ # For stacked bars: (x, y_top, y_bottom) per segment; else unused.
144
+ segments_px: list[tuple[float, float, float]] = field(default_factory=list)
145
+ from_legend: bool = False
146
+ confidence: float = 1.0
147
+ warnings: list[str] = field(default_factory=list)
plotscribe/ocr.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OCR backends (swappable) and robust number parsing for tick labels.
2
+
3
+ Backends only read *single-line crops*: text localisation is done geometrically
4
+ by the caller, which is far more reliable on charts than page-level OCR.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import re
11
+ from functools import lru_cache
12
+ from typing import Protocol
13
+
14
+ import cv2
15
+ import numpy as np
16
+
17
+ TARGET_CHAR_HEIGHT = 36 # px; Tesseract is most accurate around 30-40 px glyphs
18
+
19
+
20
+ class OCRBackend(Protocol):
21
+ """Reads one line of text from an RGB crop."""
22
+
23
+ name: str
24
+
25
+ def read_line(self, crop: np.ndarray, numeric: bool = False, word: bool = False,
26
+ char: bool = False) -> tuple[str, float]:
27
+ """Return ``(text, confidence in [0, 1])``.
28
+
29
+ ``numeric`` restricts the charset to number characters; ``word`` hints that
30
+ the crop is a single short token, ``char`` that it is a single glyph.
31
+ """
32
+ ...
33
+
34
+
35
+ def prepare_crop(crop: np.ndarray, char_height: float) -> np.ndarray:
36
+ """Greyscale, dark-on-light, rescaled to the target glyph height and padded."""
37
+ gray = cv2.cvtColor(crop, cv2.COLOR_RGB2GRAY) if crop.ndim == 3 else crop
38
+ # Make the border (background) light.
39
+ border = np.concatenate([gray[0], gray[-1], gray[:, 0], gray[:, -1]])
40
+ if np.median(border) < 128:
41
+ gray = 255 - gray
42
+ # Stretch contrast so light text on tinted panels becomes black on white.
43
+ lo, hi = np.percentile(gray, 1), np.median(border if np.median(border) >= 128 else 255 - border)
44
+ if hi - lo > 10:
45
+ gray = np.clip((gray.astype(np.float32) - lo) * 255.0 / (hi - lo), 0, 255).astype(np.uint8)
46
+ f = float(np.clip(TARGET_CHAR_HEIGHT / max(char_height, 1.0), 0.5, 6.0))
47
+ if abs(f - 1.0) > 0.05:
48
+ gray = cv2.resize(gray, None, fx=f, fy=f, interpolation=cv2.INTER_CUBIC)
49
+ pad = TARGET_CHAR_HEIGHT // 2
50
+ return cv2.copyMakeBorder(gray, pad, pad, pad, pad, cv2.BORDER_CONSTANT, value=255)
51
+
52
+
53
+ class TesseractOCR:
54
+ """pytesseract backend (requires the ``tesseract`` binary)."""
55
+
56
+ name = "tesseract"
57
+
58
+ def __init__(self, lang: str = "eng") -> None:
59
+ import pytesseract # noqa: F401 (fail early if missing)
60
+
61
+ self.lang = lang
62
+
63
+ def read_line(self, crop: np.ndarray, numeric: bool = False, word: bool = False,
64
+ char: bool = False) -> tuple[str, float]:
65
+ import pytesseract
66
+
67
+ cfg = "--psm 10" if char else ("--psm 8" if word else "--psm 7")
68
+ if numeric:
69
+ cfg += " -c tessedit_char_whitelist=0123456789.,-+%$kKMB"
70
+ data = pytesseract.image_to_data(crop, lang=self.lang, config=cfg,
71
+ output_type=pytesseract.Output.DICT)
72
+ words, confs = [], []
73
+ for txt, conf in zip(data["text"], data["conf"]):
74
+ if txt.strip():
75
+ words.append(txt.strip())
76
+ confs.append(max(float(conf), 0.0) / 100.0)
77
+ if not words:
78
+ return "", 0.0
79
+ return " ".join(words), float(np.mean(confs))
80
+
81
+
82
+ class PaddleOCRBackend:
83
+ """PaddleOCR backend (optional dependency ``paddleocr``)."""
84
+
85
+ name = "paddle"
86
+
87
+ def __init__(self) -> None:
88
+ from paddleocr import PaddleOCR # type: ignore[import-not-found]
89
+
90
+ self._ocr = PaddleOCR(use_angle_cls=False, lang="en", show_log=False)
91
+
92
+ def read_line(self, crop: np.ndarray, numeric: bool = False, word: bool = False,
93
+ char: bool = False) -> tuple[str, float]:
94
+ img = crop if crop.ndim == 3 else cv2.cvtColor(crop, cv2.COLOR_GRAY2RGB)
95
+ res = self._ocr.ocr(img, det=False, cls=False)
96
+ if not res or not res[0]:
97
+ return "", 0.0
98
+ text, conf = res[0][0]
99
+ return str(text), float(conf)
100
+
101
+
102
+ @lru_cache(maxsize=4)
103
+ def get_backend(name: str = "tesseract") -> OCRBackend:
104
+ """Factory: ``tesseract`` (default) or ``paddle``."""
105
+ if name == "tesseract":
106
+ return TesseractOCR()
107
+ if name == "paddle":
108
+ return PaddleOCRBackend()
109
+ raise ValueError(f"unknown OCR backend {name!r}")
110
+
111
+
112
+ # ----------------------------------------------------------------------------- numbers
113
+
114
+ _MINUS = str.maketrans({"−": "-", "–": "-", "—": "-", "‒": "-", "~": "-"})
115
+ _CONFUSIONS = str.maketrans({"O": "0", "o": "0", "D": "0", "Q": "0", "l": "1", "I": "1", "|": "1",
116
+ "i": "1", "!": "1", "S": "5", "s": "5", "Z": "2", "z": "2", "g": "9",
117
+ "q": "9", "G": "6", "b": "6", "A": "4", "T": "7"})
118
+ _SUFFIX = {"k": 1e3, "K": 1e3, "M": 1e6, "m": 1e6, "B": 1e9, "bn": 1e9, "G": 1e9, "T": 1e12}
119
+ _CURRENCY = "$€£¥₹"
120
+ _NUM_RE = re.compile(r"^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$")
121
+ _THOUSANDS_RE = re.compile(r"^[+-]?\d{1,3}(,\d{3})+(\.\d+)?$")
122
+ _DECIMAL_COMMA_RE = re.compile(r"^[+-]?\d+,\d{1,2}$|^[+-]?\d+,\d{4,}$")
123
+ _POWER_RE = re.compile(r"^([+-]?\d+(?:\.\d+)?)?\s*[x×*]?\s*10\^\{?([+-]?\d+)\}?$")
124
+
125
+
126
+ def parse_number(text: str) -> float | None:
127
+ """Parse a tick label into a float, or ``None`` if it is not numeric.
128
+
129
+ Handles thousands separators ("1,000"), decimal commas ("1,5"), scientific
130
+ ("1e3", "10^3", "2x10^3"), percent ("5%"; returned as 5, not 0.05), currency
131
+ ("$10"), magnitude suffixes ("1.5k", "2M", "3bn"), accounting negatives
132
+ ("(5)"), unicode minus signs, and common OCR letter/digit confusions.
133
+ """
134
+ t = text.strip().translate(_MINUS).replace(" ", "").replace("'", "").replace("’", "")
135
+ if not t:
136
+ return None
137
+ neg = False
138
+ if t.startswith("(") and t.endswith(")"):
139
+ neg, t = True, t[1:-1]
140
+ t = t.strip(_CURRENCY).rstrip("%").lstrip("+")
141
+ if t.startswith("-"):
142
+ neg, t = (not neg), t[1:]
143
+ t = t.strip(_CURRENCY)
144
+ mult = 1.0
145
+ for suf in sorted(_SUFFIX, key=len, reverse=True):
146
+ if len(t) > len(suf) and t.endswith(suf) and (t[-len(suf) - 1].isdigit() or t[-len(suf) - 1] in "Oo"):
147
+ mult, t = _SUFFIX[suf], t[: -len(suf)]
148
+ break
149
+ if not t:
150
+ return None
151
+ # Letter->digit confusions only if the string is already mostly digits.
152
+ digits = sum(c.isdigit() for c in t)
153
+ if digits >= max(1, 0.5 * len(t.replace(".", "").replace(",", ""))):
154
+ core = t.translate(_CONFUSIONS)
155
+ else:
156
+ return None
157
+ m = _POWER_RE.match(core)
158
+ if m:
159
+ base = float(m.group(1)) if m.group(1) else 1.0
160
+ if not m.group(1) or "x" in core or "×" in core or "*" in core or "^" in core:
161
+ val = base * 10 ** int(m.group(2))
162
+ return _finish(val, neg, mult)
163
+ if _THOUSANDS_RE.match(core):
164
+ core = core.replace(",", "")
165
+ elif _DECIMAL_COMMA_RE.match(core):
166
+ core = core.replace(",", ".")
167
+ else:
168
+ core = core.replace(",", "")
169
+ if core.count(".") > 1:
170
+ return None
171
+ if not _NUM_RE.match(core):
172
+ return None
173
+ try:
174
+ val = float(core)
175
+ except ValueError:
176
+ return None
177
+ return _finish(val, neg, mult)
178
+
179
+
180
+ def _finish(val: float, neg: bool, mult: float) -> float | None:
181
+ val = -val * mult if neg else val * mult
182
+ return val if math.isfinite(val) else None
183
+
184
+
185
+ _SCALE_RE = re.compile(r"^(?:1e|[x×]10\^?|10\^)([+-]?\d+)$")
186
+ _OFFSET_RE = re.compile(r"^([+-]\d*\.?\d+(?:e[+-]?\d+)?)$")
187
+ _BOTH_RE = re.compile(r"^(?:1e|[x×]10\^?)([+-]?\d+)([+-]\d*\.?\d+(?:e[+-]?\d+)?)$")
188
+
189
+
190
+ def parse_offset_text(text: str) -> tuple[float, float] | None:
191
+ """Parse a matplotlib-style axis offset/multiplier label into ``(scale, offset)``.
192
+
193
+ Examples: "1e6" -> (1e6, 0); "+1.063e3" -> (1, 1063); "1e-3+2.5" -> (1e-3, 2.5);
194
+ "×10^6" -> (1e6, 0). Returns ``None`` for anything else (titles etc.).
195
+ """
196
+ t = text.strip().translate(_MINUS).replace(" ", "").replace("E", "e").lower()
197
+ if not t:
198
+ return None
199
+ m = _BOTH_RE.match(t)
200
+ if m:
201
+ return 10.0 ** int(m.group(1)), float(m.group(2))
202
+ m = _SCALE_RE.match(t)
203
+ if m:
204
+ return 10.0 ** int(m.group(1)), 0.0
205
+ m = _OFFSET_RE.match(t)
206
+ if m and "e" in t:
207
+ return 1.0, float(m.group(1))
208
+ return None
plotscribe/pipeline.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Orchestrates all stages: image -> data table + diagnostics.
2
+
3
+ Each stage returns a confidence; the pipeline multiplies them into an overall
4
+ confidence and collects warnings instead of guessing silently.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ 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
+
16
+ from . import axes as axes_mod
17
+ from . import chart_type as chart_type_mod
18
+ from . import export
19
+ from . import legend as legend_mod
20
+ from . import series as series_mod
21
+ from .calibrate import Calibration, fit_categorical, fit_numeric, is_numeric_axis
22
+ from . import extract_bar as bar_mod
23
+ from .extract_line import extract_line
24
+ from .extract_scatter import extract_scatter
25
+ from .models import AxesResult, BBox, Series, TextBox
26
+ from .ocr import OCRBackend, get_backend, parse_number, parse_offset_text, prepare_crop
27
+ from .preprocess import Preprocessed, load_rgb, preprocess, to_lab
28
+
29
+
30
+ @dataclass
31
+ class PipelineResult:
32
+ """Everything the exporters need. Pixel fields are in processed-image coordinates."""
33
+
34
+ source: str
35
+ pre: Preprocessed
36
+ axes: AxesResult | None = None
37
+ x_labels: list[TextBox] = field(default_factory=list)
38
+ y_labels: list[TextBox] = field(default_factory=list)
39
+ x_cal: Calibration | None = None
40
+ y_cal: Calibration | None = None
41
+ chart_type: str = "unknown"
42
+ chart_type_conf: float = 0.0
43
+ table: pd.DataFrame | None = None
44
+ extra: dict[str, Any] = field(default_factory=dict)
45
+ stage_conf: dict[str, float] = field(default_factory=dict)
46
+ warnings: list[str] = field(default_factory=list)
47
+
48
+ @property
49
+ def confidence(self) -> float:
50
+ return float(np.prod(list(self.stage_conf.values()))) if self.stage_conf else 0.0
51
+
52
+ def warn(self, stage: str, msgs: list[str] | str) -> None:
53
+ for m in [msgs] if isinstance(msgs, str) else msgs:
54
+ self.warnings.append(f"[{stage}] {m}")
55
+
56
+
57
+ def _crop(rgb: np.ndarray, b: BBox, char_h: float) -> np.ndarray:
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
+ return prepare_crop(rgb[rs, cs], char_h)
62
+
63
+
64
+ def leading_minus(ink: np.ndarray, box: BBox) -> float | None:
65
+ """If the label starts with a minus sign (a short mid-height dash), return where it ends.
66
+
67
+ Tesseract often drops the typographic minus (U+2212); geometry does not.
68
+ """
69
+ comps = sorted(axes_mod.glyph_components(ink, box.expand(1)), key=lambda c: c.x0)
70
+ if len(comps) < 2:
71
+ return None
72
+ m, rest = comps[0], comps[1:]
73
+ top, bot = min(c.y0 for c in rest), max(c.y1 for c in rest)
74
+ rest_h = bot - top
75
+ if m.w >= 1.5 * m.h and m.h <= 0.3 * rest_h and abs(m.cy - 0.5 * (top + bot)) <= 0.25 * rest_h \
76
+ and m.x1 <= min(c.x0 for c in rest) + 1:
77
+ return m.x1
78
+ return None
79
+
80
+
81
+ def split_superscript(ink: np.ndarray, box: BBox) -> tuple[BBox, BBox] | None:
82
+ """(body, exponent) boxes if the label ends in raised small glyphs, e.g. 10^3.
83
+
84
+ Exponent glyphs are clearly smaller than the body and sit above its middle.
85
+ """
86
+ comps = sorted(axes_mod.glyph_components(ink, box.expand(1)), key=lambda c: c.x0)
87
+ if len(comps) < 3:
88
+ return None
89
+ body_h = max(c.h for c in comps)
90
+ body_bottom = max(c.y1 for c in comps)
91
+ body = [c for c in comps if c.h >= 0.8 * body_h]
92
+ if not body:
93
+ return None
94
+ body_top = min(c.y0 for c in body)
95
+ body_right = max(c.x1 for c in body)
96
+ sup = [c for c in comps if c.x0 >= body_right - 1 and c.y1 <= body_top + 0.6 * (body_bottom - body_top)
97
+ and c.h < 0.8 * body_h]
98
+ if not sup:
99
+ return None
100
+ bb = body[0]
101
+ for c in body[1:]:
102
+ bb = bb.union(c)
103
+ sb = sup[0]
104
+ for c in sup[1:]:
105
+ sb = sb.union(c)
106
+ return bb, sb
107
+
108
+
109
+ def read_power_label(rgb: np.ndarray, ink: np.ndarray, body: BBox, sup: BBox, char_h: float,
110
+ ocr: OCRBackend) -> tuple[str, float] | None:
111
+ """Read 'base^exp' (matplotlib log ticks such as 10^{-2}); returns (text, value)."""
112
+ t_body, _ = ocr.read_line(_crop(rgb, body, char_h), numeric=True)
113
+ base = parse_number(t_body)
114
+ if base is None or base <= 0:
115
+ return None
116
+ m = leading_minus(ink, sup)
117
+ exp_box = BBox(m + 1, sup.y0, sup.x1, sup.y1) if m is not None else sup
118
+ exp = None
119
+ n_glyphs = len(axes_mod.glyph_components(ink, exp_box.expand(1)))
120
+ modes = [{"char": True}, {"word": True}] if n_glyphs == 1 else [{"word": True}, {}]
121
+ for mode in modes:
122
+ t_exp, _ = ocr.read_line(_crop(rgb, exp_box, sup.h), numeric=True, **mode)
123
+ exp = parse_number(t_exp)
124
+ if exp is not None and float(exp).is_integer():
125
+ break
126
+ exp = None
127
+ if exp is None:
128
+ return None
129
+ e = -abs(int(exp)) if m is not None else int(exp)
130
+ return f"{t_body}^{e}", float(base) ** e
131
+
132
+
133
+ def add_power_candidates(labels: list[TextBox], powers: list[bool]) -> None:
134
+ """On an axis with 10^n labels, also read unsplit labels like '103' / '10' as powers.
135
+
136
+ The exponent of a split label may itself be misread ('10' for '1'), so its
137
+ first digit is offered too. Robust calibration chooses the consistent set.
138
+ """
139
+ for tb, pw in zip(labels, powers):
140
+ digits = "".join(ch for ch in tb.text if ch.isdigit() or ch == "-")
141
+ cands = list(tb.candidates) or ([tb.value] if tb.value is not None else [])
142
+ if pw:
143
+ exp = tb.text.split("^")[-1]
144
+ if len(exp.lstrip("-")) > 1:
145
+ sign = -1 if exp.startswith("-") else 1
146
+ cands.append(10.0 ** (sign * int(exp.lstrip("-")[0])))
147
+ elif digits.startswith("10"):
148
+ rest = digits[2:]
149
+ cands.append(1.0 if not rest else 10.0 ** int(rest[:2] if rest.startswith("-") else rest[0]))
150
+ if rest and not rest.startswith("-"):
151
+ cands.append(10.0 ** int(rest))
152
+ if tb.value is None:
153
+ tb.value = cands[-1]
154
+ tb.candidates = list(dict.fromkeys(cands))
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
162
+ line and word mode; all parseable readings become candidates that the robust
163
+ calibration chooses between. A geometrically detected minus sign fixes the sign.
164
+ """
165
+ out: list[TextBox] = []
166
+ minus: list[float | None] = []
167
+ powers: list[bool] = []
168
+ for b in boxes:
169
+ sp = split_superscript(ink, b)
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)
182
+ numeric_like = sum(tb.value is not None or any(ch.isdigit() for ch in tb.text) for tb in out)
183
+ if numeric_like < max(2, 0.5 * len(out)):
184
+ return out
185
+ for tb, m, pw in zip(out, minus, powers):
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)
193
+ v = parse_number(t)
194
+ if v is not None:
195
+ cands.append(v)
196
+ if tb.value is None:
197
+ tb.text, tb.conf, tb.value = t, c, v
198
+ if m is not None:
199
+ cands = [-abs(v) for v in cands]
200
+ if tb.value is not None:
201
+ tb.value = -abs(tb.value)
202
+ if not tb.text.lstrip().startswith(("-", "\u2212")):
203
+ tb.text = "-" + tb.text
204
+ else:
205
+ # A '-' read without a visible dash is likely noise; keep both signs.
206
+ cands += [abs(v) for v in cands if v < 0]
207
+ tb.candidates = list(dict.fromkeys(cands))
208
+ return out
209
+
210
+
211
+ def read_offset(rgb: np.ndarray, ink: np.ndarray, ax: AxesResult, labels: list[TextBox], axis: str,
212
+ char_h: float, ocr: OCRBackend) -> tuple[float, float, str] | None:
213
+ """OCR an axis offset/multiplier text if present: (scale, offset, raw text)."""
214
+ for b in axes_mod.offset_text_boxes(ink, ax, [lb.bbox for lb in labels], axis, char_h):
215
+ text, _ = ocr.read_line(_crop(rgb, b, char_h))
216
+ parsed = parse_offset_text(text)
217
+ if parsed is not None:
218
+ return parsed[0], parsed[1], text
219
+ return None
220
+
221
+
222
+ def apply_offset(labels: list[TextBox], scale: float, offset: float) -> None:
223
+ for lb in labels:
224
+ if lb.value is not None:
225
+ lb.value = lb.value * scale + offset
226
+ lb.candidates = [v * scale + offset for v in lb.candidates]
227
+
228
+
229
+ def calibrate_axis(axis: str, labels: list[TextBox], ticks: list[float]) -> Calibration | None:
230
+ """Numeric or categorical calibration from OCR'd labels and detected ticks."""
231
+ if not any(lb.text.strip() for lb in labels):
232
+ return None
233
+ if is_numeric_axis([lb.value for lb in labels]):
234
+ labels = [lb for lb in labels if lb.text.strip()]
235
+ else:
236
+ # Keep unreadable category labels (their position is still a category).
237
+ for k, lb in enumerate(labels):
238
+ if not lb.text.strip():
239
+ lb.text = f"category_{k + 1}"
240
+ centres = [lb.bbox.cx if axis == "x" else lb.bbox.cy for lb in labels]
241
+ # A label belongs to a tick within about one label height of its centre.
242
+ max_d = float(np.median([lb.bbox.h for lb in labels]))
243
+ snapped = axes_mod.match_to_ticks(centres, ticks, max_d)
244
+ values = [lb.value for lb in labels]
245
+ if is_numeric_axis(values):
246
+ px = [s[0] for s, lb in zip(snapped, labels) if lb.value is not None]
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")
253
+ return cal
254
+ return fit_categorical(axis, [s[0] for s in snapped], [lb.text for lb in labels])
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
262
+ boxes; the tick marks are the reliable anchor for category positions.
263
+ """
264
+ if len(ticks) < 2 or not labels:
265
+ return labels
266
+ if is_numeric_axis([lb.value for lb in labels]):
267
+ return labels
268
+ t = np.sort(np.asarray(ticks))
269
+ spacing = float(np.median(np.diff(t)))
270
+ groups: dict[int, list[TextBox]] = {}
271
+ for lb in labels:
272
+ c = lb.bbox.cx if axis == "x" else lb.bbox.cy
273
+ i = int(np.argmin(np.abs(t - c)))
274
+ if abs(t[i] - c) <= 0.5 * spacing:
275
+ groups.setdefault(i, []).append(lb)
276
+ if len(groups) < 0.6 * len(labels):
277
+ return labels
278
+ gaps = np.diff(t)
279
+ if len(t) >= 3 and np.std(gaps) <= 0.1 * np.mean(gaps):
280
+ # Regular ticks: every tick is a category. A tick whose label merged into a
281
+ # neighbour's glyphs gets the text inside its own cell.
282
+ band = labels[0].bbox
283
+ for lb in labels[1:]:
284
+ band = band.union(lb.bbox)
285
+ for i, tp in enumerate(t):
286
+ if i in groups:
287
+ continue
288
+ if axis == "x":
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):
296
+ g = groups[i]
297
+ if len(g) == 1:
298
+ out.append(g[0])
299
+ continue
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
+
307
+
308
+ def run(path: str | Path, ocr_backend: str = "tesseract", chart_type: str | None = None) -> PipelineResult:
309
+ """Run the full pipeline on an image file."""
310
+ ocr = get_backend(ocr_backend)
311
+ rgb = load_rgb(path)
312
+ pre = preprocess(rgb)
313
+ res = PipelineResult(source=str(path), pre=pre)
314
+ res.extra["ocr_backend"] = ocr_backend
315
+ res.stage_conf["preprocess"] = pre.confidence
316
+ res.warn("preprocess", pre.warnings)
317
+
318
+ ax, ink = axes_mod.detect_axes(pre.lab, pre.noise_sigma)
319
+ res.axes = ax
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
+ res.x_labels = merge_labels_per_tick(pre.rgb, read_labels(pre.rgb, ink, xb, xch, ocr), ax.x_ticks, "x", xch, ocr)
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]):
329
+ continue
330
+ off = read_offset(pre.rgb, ink, ax, labels, name, ch, ocr)
331
+ if off is not None:
332
+ apply_offset(labels, off[0], off[1])
333
+ res.warn("calibrate", f"{name}: applied axis offset/multiplier text '{off[2]}'")
334
+ res.extra.setdefault("diagnostics_extra", {}).setdefault("axis_offset", {})[name] = {
335
+ "text": off[2], "scale": off[0], "offset": off[1]}
336
+ res.x_cal = calibrate_axis("x", res.x_labels, ax.x_ticks)
337
+ res.y_cal = calibrate_axis("y", res.y_labels, ax.y_ticks)
338
+ b = ax.plot_box
339
+ if any(lb.bbox.x1 >= b.x0 - ax.line_thickness / 2 - 2 for lb in res.y_labels) and res.y_cal is not None:
340
+ res.y_cal.confidence *= 0.4
341
+ res.y_cal.warnings.append("y: tick labels touch the plot area; they may be clipped (plot area uncertain)")
342
+ if any(lb.bbox.y0 <= b.y1 + ax.line_thickness / 2 + 2 for lb in res.x_labels) and res.x_cal is not None:
343
+ res.x_cal.confidence *= 0.4
344
+ res.x_cal.warnings.append("x: tick labels touch the plot area; they may be clipped (plot area uncertain)")
345
+ for name, cal in (("x", res.x_cal), ("y", res.y_cal)):
346
+ if cal is None:
347
+ res.warn("calibrate", f"{name}: no tick labels found")
348
+ res.stage_conf[f"calib_{name}"] = 0.0
349
+ else:
350
+ res.warn("calibrate", cal.warnings)
351
+ res.stage_conf[f"calib_{name}"] = cal.confidence
352
+
353
+ char_h = float(np.median([c for c in (xch, ych) if c > 0])) if (xch > 0 or ych > 0) else 0.0
354
+ leg = legend_mod.detect_legend(pre.rgb, pre.lab, ink, ax.panel_bg, char_h, ocr,
355
+ exclude=[lb.bbox for lb in res.x_labels + res.y_labels])
356
+ res.extra["legend_box"] = leg.box
357
+ res.extra["legend_info"] = leg.to_dict()
358
+ res.warn("legend", leg.warnings)
359
+
360
+ series = separate_series(res, ink, leg)
361
+ res.extra["series"] = series
362
+ if not series:
363
+ res.warn("series", "no data series found")
364
+ res.stage_conf["series"] = 0.0
365
+ res.extra["status"] = "failed"
366
+ return res
367
+
368
+ region = series_mod.plot_interior(ax, ink.shape)
369
+ if chart_type:
370
+ res.chart_type, res.chart_type_conf = chart_type, 1.0
371
+ else:
372
+ masks = [s.mask for s in series if s.mask is not None]
373
+ res.chart_type, res.chart_type_conf, scores = chart_type_mod.classify(masks, region, ax.line_thickness)
374
+ res.extra["chart_type_scores"] = {"scores": scores}
375
+ if res.chart_type_conf < 0.3:
376
+ res.warn("chart_type", f"ambiguous chart type {scores}")
377
+ res.stage_conf["chart_type"] = max(res.chart_type_conf, 0.3)
378
+ if res.chart_type not in ("line", "bar", "grouped_bar", "stacked_bar", "scatter"):
379
+ res.warn("chart_type", "could not determine the chart type; use --type")
380
+ res.extra["status"] = "failed"
381
+ return res
382
+
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
+
389
+
390
+ def separate_series(res: PipelineResult, ink: np.ndarray, leg: legend_mod.Legend) -> list[Series]:
391
+ """Colour clusters in the plot area, reconciled with legend swatch colours."""
392
+ ax = res.axes
393
+ assert ax is not None
394
+ region = series_mod.plot_interior(ax, ink.shape)
395
+ rgb, grid = series_mod.remove_gridlines(res.pre.rgb, region, ax.line_thickness, res.pre.noise_sigma,
396
+ ax.panel_bg)
397
+ lab = to_lab(rgb)
398
+ ink = axes_mod.ink_mask(lab, ax.figure_bg, region, ax.panel_bg, axes_mod.ink_threshold(res.pre.noise_sigma))
399
+ res.extra["clean_rgb"] = rgb
400
+ res.extra.setdefault("diagnostics_extra", {})["gridlines_removed"] = {
401
+ "rows": len(grid.rows), "cols": len(grid.cols)}
402
+ exclude = [leg.box] if leg.box is not None else []
403
+ cand, _ = series_mod.candidate_mask(lab, ink, ax, exclude)
404
+ bg = series_mod.bg_for(ax)
405
+ clusters = series_mod.find_colors(lab[cand], bg)
406
+ colours: list[np.ndarray] = []
407
+ names: list[str] = []
408
+ from_legend: list[bool] = []
409
+ used = set()
410
+ for k, e in enumerate(leg.entries):
411
+ d = [np.linalg.norm(c.lab - e.lab) for c in clusters]
412
+ j = int(np.argmin(d)) if d else -1
413
+ if j >= 0 and d[j] < 25 and j not in used:
414
+ used.add(j)
415
+ colours.append(clusters[j].lab)
416
+ else:
417
+ colours.append(np.asarray(e.lab, np.float32))
418
+ res.warn("series", f"legend entry '{e.label}' has no matching colour in the plot")
419
+ names.append(e.label or f"series_{k + 1}")
420
+ from_legend.append(True)
421
+ for j, c in enumerate(clusters):
422
+ if j in used:
423
+ continue
424
+ if leg.entries and c.weight < 0.1:
425
+ continue # stray colour (anti-aliasing, text) when the legend says otherwise
426
+ colours.append(c.lab)
427
+ names.append(f"series_{len(names) + 1}")
428
+ from_legend.append(False)
429
+ if leg.entries:
430
+ res.warn("series", f"colour cluster {series_mod.describe_color(c.lab)} not in legend")
431
+ if not leg.entries:
432
+ res.warn("legend", "no legend found; series named series_1..n")
433
+ # Unique names.
434
+ seen: dict[str, int] = {}
435
+ for i, n in enumerate(names):
436
+ if n in seen:
437
+ seen[n] += 1
438
+ names[i] = f"{n}_{seen[n]}"
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 = []
445
+ for c, n, fl, m in zip(colours, names, from_legend, masks):
446
+ out.append(Series(name=n, lab=tuple(float(v) for v in c), rgb=series_mod.describe_color(c), mask=m,
447
+ from_legend=fl))
448
+ return out
449
+
450
+
451
+ def extract(res: PipelineResult, series: list[Series]) -> None:
452
+ """Dispatch to the per-type extractor; fills ``points_px`` / ``segments_px``."""
453
+ alpha = res.extra["alpha"]
454
+ labels = res.extra["labels"]
455
+ ctype = res.chart_type
456
+ cat_px = res.x_cal.category_px if (res.x_cal is not None and res.x_cal.kind == "categorical") else None
457
+ live = []
458
+ for s in series:
459
+ if s.mask is None or not s.mask.any():
460
+ s.warnings.append("empty mask")
461
+ s.confidence = 0.0
462
+ else:
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
471
+ elif ctype in ("bar", "grouped_bar", "stacked_bar"):
472
+ extract_bars(res, series, alpha, labels)
473
+ elif ctype == "scatter":
474
+ infos = {}
475
+ for s in live:
476
+ idx = series.index(s)
477
+ others = (labels >= 0) & (labels != idx)
478
+ s.points_px, infos[s.name] = extract_scatter(s.mask, alpha, others)
479
+ res.extra.setdefault("diagnostics_extra", {})["scatter"] = infos
480
+ else:
481
+ raise NotImplementedError(f"extraction for chart type {ctype!r}")
482
+
483
+
484
+ def recategorize_from_bars(res: PipelineResult, bars: list[bar_mod.Bar]) -> None:
485
+ """Use bar groups as category anchors when the labels disagree with them.
486
+
487
+ Labels of neighbouring categories often merge (long names, no tick marks);
488
+ the bars themselves show where the categories are. Names are re-read from the
489
+ label row inside each category's cell.
490
+ """
491
+ x = res.x_cal
492
+ centres = bar_mod.category_clusters(bars)
493
+ if x is None or x.kind != "categorical" or len(centres) < 2:
494
+ return
495
+ ax = res.axes
496
+ assert ax is not None
497
+ t = np.sort(np.asarray(ax.x_ticks))
498
+ if (ax.x_tick_source.startswith("ticks") and len(t) >= 3 and len(t) == len(x.categories)
499
+ and np.std(np.diff(t)) <= 0.1 * np.mean(np.diff(t))):
500
+ return # regular tick marks, one label each: trust them
501
+ if len(centres) == len(x.categories):
502
+ d = np.abs(np.asarray(centres) - np.asarray(x.category_px))
503
+ if np.all(d < 0.25 * np.median(np.diff(centres))):
504
+ return
505
+ labels = [lb for lb in res.x_labels if lb.text.strip()]
506
+ if not labels:
507
+ return
508
+ band = labels[0].bbox
509
+ for lb in labels[1:]:
510
+ band = band.union(lb.bbox)
511
+ ch = float(np.median([lb.bbox.h for lb in labels]))
512
+ c = np.asarray(centres)
513
+ bounds = np.concatenate([[c[0] - (c[1] - c[0]) / 2], (c[1:] + c[:-1]) / 2, [c[-1] + (c[-1] - c[-2]) / 2]])
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")
521
+ x.categories, x.category_px = names, [float(v) for v in c]
522
+ x.confidence *= 0.8
523
+
524
+
525
+ def zero_line_px(res: PipelineResult) -> float:
526
+ """Pixel row of y = 0 if it lies on a linear y axis, else the plot bottom."""
527
+ ax = res.axes
528
+ assert ax is not None
529
+ y = res.y_cal
530
+ if y is not None and y.kind == "linear" and y.slope != 0:
531
+ z = float(y.to_px(0.0))
532
+ if ax.plot_box.y0 - 2 <= z <= ax.plot_box.y1 + 2:
533
+ return z
534
+ return ax.plot_box.y1
535
+
536
+
537
+ def extract_bars(res: PipelineResult, series: list[Series], alpha: np.ndarray, labels: np.ndarray) -> None:
538
+ ax = res.axes
539
+ assert ax is not None
540
+ min_w = max(3.0, 0.005 * ax.plot_box.w)
541
+ bars: list[bar_mod.Bar] = []
542
+ for i, s in enumerate(series):
543
+ if s.mask is None or not s.mask.any():
544
+ continue
545
+ soft = np.where(labels == i, alpha, 0.0)
546
+ bars += bar_mod.bars_from_mask(s.mask, soft, i, min_w)
547
+ bars = bar_mod.merge_split(bars, gap=2 * ax.line_thickness + 4)
548
+ bars = bar_mod.drop_fragments(bars, min_h=1.5 * ax.line_thickness + 1)
549
+ joint_tol = 4.0 + 2 * ax.line_thickness + res.pre.noise_sigma
550
+ zero = zero_line_px(res)
551
+ bar_mod.snap_baseline(bars, zero, ax.line_thickness + 3)
552
+ occluders = [b for b in (res.extra.get("legend_box"),) if b is not None]
553
+ occluded: set[int] = set()
554
+ for k, b in enumerate(bars):
555
+ for ob in occluders:
556
+ if bar_mod.touches(b, (ob.x0, ob.y0, ob.x1, ob.y1), ax.line_thickness + 3):
557
+ occluded.add(k)
558
+ series[b.series].warnings.append(
559
+ f"bar at x={b.cx / res.pre.scale:.0f}px runs into the legend; value occluded (left empty)")
560
+ stacked = res.chart_type == "stacked_bar" or (res.chart_type != "grouped_bar" and bar_mod.detect_stacked(bars, joint_tol))
561
+ res.chart_type = "stacked_bar" if stacked else "bar"
562
+ if stacked:
563
+ bar_mod.snap_stack_joints(bars, joint_tol)
564
+ recategorize_from_bars(res, bars)
565
+ for w in {w for s in series for w in s.warnings if "occluded" in w}:
566
+ res.warn("extract", w)
567
+ bars = [b for k, b in enumerate(bars) if k not in occluded]
568
+ for i, s in enumerate(series):
569
+ mine = sorted((b for b in bars if b.series == i), key=lambda b: b.cx)
570
+ if stacked:
571
+ s.segments_px = [(b.cx, b.top, b.bottom) for b in mine]
572
+ else:
573
+ s.points_px = np.array([(b.cx, bar_mod.value_edge(b, zero)) for b in mine]).reshape(-1, 2)
574
+ res.extra.setdefault("diagnostics_extra", {})["bars"] = {
575
+ "n_bars": len(bars), "stacked": stacked, "baseline_px": round(zero / res.pre.scale, 2)}
576
+
577
+
578
+ def check_data_outside_box(res: PipelineResult, series: list[Series]) -> None:
579
+ """Series colours just outside the plot box mean the box is too small: data is cut."""
580
+ ax = res.axes
581
+ assert ax is not None
582
+ h, w = res.pre.rgb.shape[:2]
583
+ b = ax.plot_box
584
+ m = 0.05 * min(h, w)
585
+ outer = np.zeros((h, w), bool)
586
+ rs, cs = b.expand(m).clip(w, h).slices()
587
+ outer[rs, cs] = True
588
+ rs, cs = b.expand(ax.line_thickness + 2).clip(w, h).slices()
589
+ outer[rs, cs] = False
590
+ leg = res.extra.get("legend_box")
591
+ for lb in [leg] + [t.bbox for t in res.x_labels + res.y_labels]:
592
+ if lb is not None:
593
+ r2, c2 = lb.expand(2).clip(w, h).slices()
594
+ outer[r2, c2] = False
595
+ colours = [np.asarray(s.lab, np.float32) for s in series]
596
+ if not colours or not outer.any():
597
+ return
598
+ lab = res.pre.lab[outer]
599
+ d = np.min(np.stack([np.linalg.norm(lab - c, axis=1) for c in colours]), axis=0)
600
+ n_out = int((d < 8).sum())
601
+ n_in = int(sum(int(s.mask.sum()) for s in series if s.mask is not None))
602
+ if n_in and n_out > 0.05 * n_in:
603
+ res.warn("axes", f"{n_out} series-coloured pixels just outside the plot area; it may be cut off")
604
+ if res.extra.get("status") == "ok":
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"
611
+ y = res.y_cal
612
+ if y is None or y.kind == "categorical" or y.n_inliers < 2:
613
+ status = "uncalibrated"
614
+ res.warn("calibrate", "y axis not calibrated: values are pixel rows (column suffix [px])")
615
+ elif y.confidence < 0.5:
616
+ status = "low_confidence"
617
+ if status == "ok" and res.axes is not None and res.axes.confidence < 0.5:
618
+ status = "low_confidence"
619
+ res.warn("axes", "plot area uncertain; values may be wrong")
620
+ x = res.x_cal
621
+ if x is not None and x.kind == "categorical" and x.categories:
622
+ junk = sum(sum(ch.isalnum() for ch in c) < 2 or c.startswith("category_") for c in x.categories)
623
+ if junk >= 0.5 * len(x.categories):
624
+ status = "low_confidence" if status == "ok" else status
625
+ res.warn("calibrate", "x: most category labels unreadable")
626
+ if res.chart_type in ("line", "scatter") and (res.x_cal is None or (res.x_cal.kind != "categorical"
627
+ and res.x_cal.n_inliers < 2)):
628
+ status = "uncalibrated"
629
+ res.warn("calibrate", "x axis not calibrated: x values are pixel columns")
630
+ res.extra["status"] = status
plotscribe/preprocess.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Image loading and normalisation.
2
+
3
+ Assumptions: the chart is roughly axis-aligned (skew under ~5 degrees) and the
4
+ background is lighter or darker than the axes, i.e. not a photograph.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+
12
+ import cv2
13
+ import numpy as np
14
+
15
+ MIN_SHORT_SIDE = 800
16
+
17
+
18
+ @dataclass
19
+ class Preprocessed:
20
+ """Processed RGB image plus the information needed to map back to the input."""
21
+
22
+ rgb: np.ndarray # uint8 HxWx3, processed
23
+ lab: np.ndarray # float32 HxWx3, L in [0, 100]
24
+ scale: float # processed_px = original_px * scale
25
+ original_size: tuple[int, int] # (width, height)
26
+ noise_sigma: float
27
+ deskew_deg: float
28
+ confidence: float = 1.0
29
+ warnings: list[str] = field(default_factory=list)
30
+
31
+
32
+ def load_rgb(path: str | Path) -> np.ndarray:
33
+ """Read an image as uint8 RGB; alpha is composited onto white."""
34
+ img = cv2.imread(str(path), cv2.IMREAD_UNCHANGED)
35
+ if img is None:
36
+ raise FileNotFoundError(f"cannot read image: {path}")
37
+ if img.ndim == 2:
38
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
39
+ if img.dtype != np.uint8:
40
+ img = cv2.convertScaleAbs(img, alpha=255.0 / float(img.max() or 1))
41
+ if img.shape[2] == 4:
42
+ alpha = img[:, :, 3:4].astype(np.float32) / 255.0
43
+ img = (img[:, :, :3].astype(np.float32) * alpha + 255.0 * (1 - alpha)).astype(np.uint8)
44
+ return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
45
+
46
+
47
+ def to_lab(rgb: np.ndarray) -> np.ndarray:
48
+ """uint8 RGB -> float32 CIE Lab (L 0..100, a/b roughly -127..127)."""
49
+ return cv2.cvtColor(rgb.astype(np.float32) / 255.0, cv2.COLOR_RGB2LAB)
50
+
51
+
52
+ def estimate_noise(rgb: np.ndarray) -> float:
53
+ """Robust noise sigma (grey levels) from the Laplacian of flat regions (Immerkaer)."""
54
+ gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32)
55
+ kernel = np.array([[1, -2, 1], [-2, 4, -2], [1, -2, 1]], np.float32)
56
+ resp = np.abs(cv2.filter2D(gray, -1, kernel))
57
+ # Only near-flat pixels: edges of glyphs/lines would dominate otherwise.
58
+ flat = resp[resp < np.percentile(resp, 90)]
59
+ if flat.size == 0:
60
+ return 0.0
61
+ return float(np.sqrt(np.pi / 2) * flat.mean() / 6.0)
62
+
63
+
64
+ def upscale_factor(width: int, height: int, min_short_side: int = MIN_SHORT_SIDE) -> float:
65
+ """Scale needed so the shorter side reaches ``min_short_side`` (never downscale)."""
66
+ short = min(width, height)
67
+ return max(1.0, min_short_side / float(short))
68
+
69
+
70
+ def estimate_skew(rgb: np.ndarray) -> float:
71
+ """Dominant small rotation (degrees) of long straight lines; 0 if none are found."""
72
+ gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
73
+ edges = cv2.Canny(gray, 50, 150)
74
+ h, w = gray.shape
75
+ min_len = int(0.3 * min(h, w))
76
+ lines = cv2.HoughLinesP(edges, 1, np.pi / 1800, threshold=min_len // 2,
77
+ minLineLength=min_len, maxLineGap=max(2, min_len // 50))
78
+ if lines is None:
79
+ return 0.0
80
+ angles = []
81
+ for x0, y0, x1, y1 in lines.reshape(-1, 4):
82
+ ang = np.degrees(np.arctan2(y1 - y0, x1 - x0))
83
+ # Fold to the nearest axis direction.
84
+ ang = (ang + 45) % 90 - 45
85
+ if abs(ang) < 5:
86
+ angles.append(ang)
87
+ if len(angles) < 2:
88
+ return 0.0
89
+ return float(np.median(angles))
90
+
91
+
92
+ def rotate(rgb: np.ndarray, deg: float) -> np.ndarray:
93
+ h, w = rgb.shape[:2]
94
+ m = cv2.getRotationMatrix2D((w / 2, h / 2), deg, 1.0)
95
+ border = tuple(int(v) for v in np.median(rgb.reshape(-1, 3), axis=0))
96
+ return cv2.warpAffine(rgb, m, (w, h), flags=cv2.INTER_CUBIC, borderValue=border)
97
+
98
+
99
+ def preprocess(rgb: np.ndarray) -> Preprocessed:
100
+ """Deskew, upscale small images (Lanczos) and lightly denoise noisy ones."""
101
+ h0, w0 = rgb.shape[:2]
102
+ warnings: list[str] = []
103
+ skew = estimate_skew(rgb)
104
+ # Sub-0.1 degree skew is rendering noise; rotating would only blur thin lines.
105
+ if abs(skew) >= 0.1:
106
+ rgb = rotate(rgb, skew)
107
+ warnings.append(f"deskewed by {skew:.2f} deg")
108
+ else:
109
+ skew = 0.0
110
+ scale = upscale_factor(w0, h0)
111
+ if scale > 1.0:
112
+ rgb = cv2.resize(rgb, (round(w0 * scale), round(h0 * scale)), interpolation=cv2.INTER_LANCZOS4)
113
+ # The actual factor after rounding.
114
+ scale = rgb.shape[1] / w0
115
+ sigma = estimate_noise(rgb)
116
+ if sigma > 2.0:
117
+ # Edge-preserving smoothing; strength tied to the measured noise.
118
+ d = 5
119
+ rgb = cv2.bilateralFilter(rgb, d, sigmaColor=3.0 * sigma, sigmaSpace=d)
120
+ warnings.append(f"denoised (noise sigma {sigma:.1f})")
121
+ confidence = 1.0 if min(w0, h0) >= 300 else 0.7
122
+ if min(w0, h0) < 300:
123
+ warnings.append(f"low input resolution {w0}x{h0}")
124
+ return Preprocessed(rgb=rgb, lab=to_lab(rgb), scale=scale, original_size=(w0, h0),
125
+ noise_sigma=sigma, deskew_deg=skew, confidence=confidence, warnings=warnings)
plotscribe/series.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Series separation: candidate data pixels -> colour clusters -> per-series soft masks.
2
+
3
+ Assumptions:
4
+ - Each series has one dominant colour, distinct (Lab distance >~ 12) from the
5
+ background and from the other series.
6
+ - Anti-aliased / JPEG pixels lie on the segment between the background colour and
7
+ the series colour in Lab space; that is how they are attributed (soft alpha).
8
+ - Gridlines and axis lines are achromatic and long; they are removed beforehand.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass
14
+
15
+ import cv2
16
+ import numpy as np
17
+
18
+ from .axes import chroma
19
+ from .models import AxesResult, BBox
20
+
21
+ ACHROMATIC_CHROMA = 12.0
22
+
23
+
24
+ @dataclass
25
+ class ColorCluster:
26
+ lab: np.ndarray
27
+ weight: float # fraction of candidate pixels attributed to this colour
28
+
29
+
30
+ def plot_interior(ax: AxesResult, shape: tuple[int, int]) -> BBox:
31
+ """Plot box shrunk past the spines (and inward ticks)."""
32
+ m = ax.line_thickness + 2
33
+ return ax.plot_box.expand(-m).clip(shape[1], shape[0])
34
+
35
+
36
+ @dataclass
37
+ class GridRemoval:
38
+ """Gridline rows/columns that were inpainted (processed-image pixel positions)."""
39
+
40
+ rows: list[int]
41
+ cols: list[int]
42
+
43
+
44
+ def _remove_thin_lines(rgb: np.ndarray, region: BBox, k: int, axis: int, noise: float,
45
+ bg: np.ndarray) -> list[int]:
46
+ """Inpaint achromatic thin lines along ``axis`` (0: horizontal lines, 1: vertical) in place.
47
+
48
+ A pixel is on a thin line if the pixels ``k`` away on both sides agree with each
49
+ other but not with it. Rows/columns where such pixels span > 25% of the plot and
50
+ are grey where the surroundings are background are gridlines. On those lines a
51
+ pixel is replaced by its surroundings only if it is a blend of the gridline grey
52
+ and the surroundings, so data drawn *over* a gridline is kept.
53
+ """
54
+ rs, cs = region.slices()
55
+ sub = rgb[rs, cs].astype(np.float32)
56
+ if axis == 1:
57
+ sub = sub.transpose(1, 0, 2)
58
+ n = sub.shape[0]
59
+ if n <= 2 * k + 1:
60
+ return []
61
+ up, dn, mid = sub[: n - 2 * k], sub[2 * k:], sub[k: n - k]
62
+ nb = 0.5 * (up + dn)
63
+ tol_same = 20.0 + 3 * noise
64
+ thin = (np.linalg.norm(up - dn, axis=2) < tol_same) & (np.linalg.norm(mid - nb, axis=2) > 8.0 + 2 * noise)
65
+ width = sub.shape[1]
66
+ score = thin.sum(axis=1)
67
+ lines = np.flatnonzero(score > 0.25 * width)
68
+ removed: list[int] = []
69
+ for r in lines:
70
+ on_bg = thin[r] & (np.linalg.norm(nb[r] - bg, axis=1) < tol_same)
71
+ pix = mid[r][on_bg] if on_bg.sum() >= 5 else mid[r][thin[r]]
72
+ if np.ptp(np.median(pix, axis=0)) > 30: # coloured: a flat data line, not a gridline
73
+ continue
74
+ blend = thin[r] & is_grey_overlay(mid[r], nb[r], 12.0 + 3 * noise)
75
+ mid[r][blend] = nb[r][blend]
76
+ removed.append(int(r + k))
77
+ out = sub.transpose(1, 0, 2) if axis == 1 else sub
78
+ rgb[rs, cs] = np.clip(out, 0, 255).astype(np.uint8)
79
+ offset = cs.start if axis == 1 else rs.start
80
+ return [r + offset for r in removed]
81
+
82
+
83
+ def is_grey_overlay(p: np.ndarray, n: np.ndarray, tol: float) -> np.ndarray:
84
+ """Is each pixel ``p`` = ``n`` + a * (g - n) for some grey level g and 0 < a <= 1?
85
+
86
+ That is the colour of a (semi-transparent) grey line drawn over a pixel of
87
+ colour ``n``. Solved per pixel by least squares in the unknowns (a, a*g).
88
+ """
89
+ d = p - n
90
+ sn = n.sum(axis=1)
91
+ sn2 = (n * n).sum(axis=1)
92
+ det = 3 * sn2 - sn * sn
93
+ ata_b0 = -(n * d).sum(axis=1)
94
+ ata_b1 = d.sum(axis=1)
95
+ ok_det = det > 1e-3
96
+ safe = np.where(ok_det, det, 1.0)
97
+ a = (3 * ata_b0 + sn * ata_b1) / safe
98
+ ag = (sn * ata_b0 + sn2 * ata_b1) / safe
99
+ resid = np.linalg.norm(d - (-a[:, None] * n + ag[:, None]), axis=1)
100
+ fit = ok_det & (a > 0.02) & (a <= 1.1) & (resid < tol)
101
+ # Neighbourhood itself grey: any grey pixel is a valid overlay.
102
+ grey_n = ~ok_det | (np.ptp(n, axis=1) < 8)
103
+ grey_p = np.ptp(p, axis=1) < 12 + 0.5 * tol
104
+ return fit | (grey_n & grey_p)
105
+
106
+
107
+ def remove_gridlines(rgb: np.ndarray, region: BBox, line_thickness: float, noise: float,
108
+ bg_lab: np.ndarray) -> tuple[np.ndarray, GridRemoval]:
109
+ """Copy of ``rgb`` with achromatic gridlines inpainted inside ``region``."""
110
+ out = rgb.copy()
111
+ k = int(np.ceil(line_thickness / 2)) + 3
112
+ bg = lab_to_rgb(bg_lab)
113
+ rows = _remove_thin_lines(out, region, k, 0, noise, bg)
114
+ cols = _remove_thin_lines(out, region, k, 1, noise, bg)
115
+ return out, GridRemoval(rows=rows, cols=cols)
116
+
117
+
118
+ def candidate_mask(lab: np.ndarray, ink: np.ndarray, ax: AxesResult, exclude: list[BBox]
119
+ ) -> tuple[np.ndarray, BBox]:
120
+ """Data-pixel candidates: ink inside the plot interior minus excluded boxes.
121
+
122
+ ``lab``/``ink`` should come from the gridline-free image (``remove_gridlines``).
123
+ """
124
+ h, w = ink.shape
125
+ region = plot_interior(ax, (h, w))
126
+ cand = np.zeros_like(ink)
127
+ rs, cs = region.slices()
128
+ cand[rs, cs] = ink[rs, cs]
129
+ for b in exclude:
130
+ ers, ecs = b.clip(w, h).slices()
131
+ cand[ers, ecs] = False
132
+ return cand, region
133
+
134
+
135
+ def find_colors(pixels: np.ndarray, bg: np.ndarray, min_frac: float = 0.02, max_k: int = 10,
136
+ merge_de: float = 12.0) -> list[ColorCluster]:
137
+ """Mode-seeking on a quantised Lab histogram: each peak is a series colour.
138
+
139
+ Anti-aliased blends spread thinly along bg->colour segments, so they do not form
140
+ peaks; pure series colours do. ``k`` is chosen automatically by stopping when
141
+ the next peak holds less than ``min_frac`` of the pixels.
142
+ """
143
+ if len(pixels) == 0:
144
+ return []
145
+ pix = pixels.reshape(-1, 3).astype(np.float32)
146
+ if len(pix) > 300_000:
147
+ pix = pix[:: len(pix) // 300_000 + 1]
148
+ bin_size = 4.0
149
+ q = np.round(pix / bin_size).astype(np.int32)
150
+ uniq, inv, counts = np.unique(q, axis=0, return_inverse=True, return_counts=True)
151
+ centers = uniq.astype(np.float32) * bin_size
152
+ alive = np.ones(len(uniq), bool)
153
+ total = float(len(pix))
154
+ out: list[ColorCluster] = []
155
+ while len(out) < max_k and alive.any():
156
+ i = int(np.argmax(np.where(alive, counts, -1)))
157
+ c = centers[i]
158
+ for _ in range(3): # mean shift on bins
159
+ d = np.linalg.norm(centers - c, axis=1)
160
+ near = alive & (d < 8.0)
161
+ c = (centers[near] * counts[near, None]).sum(0) / counts[near].sum()
162
+ d = np.linalg.norm(centers - c, axis=1)
163
+ member = alive & (d < merge_de)
164
+ weight = counts[member].sum() / total
165
+ alive &= d >= 1.5 * merge_de
166
+ if weight < min_frac:
167
+ break
168
+ if np.linalg.norm(c - bg) < 15.0:
169
+ continue # residual background / faint blends
170
+ out.append(ColorCluster(lab=c, weight=float(weight)))
171
+ # Merge near-duplicates and anti-aliasing blends: a cluster lying on the segment
172
+ # between the background and a purer (farther) cluster is that colour, faded.
173
+ merged: list[ColorCluster] = []
174
+ for cl in sorted(out, key=lambda c: -float(np.linalg.norm(c.lab - bg))):
175
+ for m in merged:
176
+ if np.linalg.norm(m.lab - cl.lab) < merge_de or is_blend_of(cl.lab, m.lab, bg):
177
+ m.weight += cl.weight
178
+ break
179
+ else:
180
+ merged.append(cl)
181
+ return sorted(merged, key=lambda c: -c.weight)
182
+
183
+
184
+ def lab_to_rgb(lab: np.ndarray) -> np.ndarray:
185
+ """Lab colour(s) -> float sRGB in [0, 255]."""
186
+ arr = np.asarray(lab, np.float32).reshape(-1, 1, 3)
187
+ return np.clip(cv2.cvtColor(arr, cv2.COLOR_LAB2RGB).reshape(-1, 3) * 255.0, 0, 255).reshape(np.shape(lab))
188
+
189
+
190
+ def is_blend_of(c: np.ndarray, pure: np.ndarray, bg: np.ndarray, tol: float = 10.0) -> bool:
191
+ """True if ``c`` ~ bg + a * (pure - bg) for some 0.1 < a < 0.95.
192
+
193
+ Tested in sRGB, where renderers blend anti-aliased edges linearly.
194
+ """
195
+ v = lab_to_rgb(pure) - lab_to_rgb(bg)
196
+ p = lab_to_rgb(c) - lab_to_rgb(bg)
197
+ vv = float(v @ v)
198
+ if vv < 1e-6:
199
+ return False
200
+ a = float(p @ v) / vv
201
+ perp = float(np.linalg.norm(p - a * v))
202
+ return 0.1 < a < 0.95 and perp < tol
203
+
204
+
205
+ def soft_assign(rgb: np.ndarray, cand: np.ndarray, bg: np.ndarray, colors: list[np.ndarray],
206
+ noise: float) -> tuple[np.ndarray, np.ndarray]:
207
+ """Attribute candidate pixels to colours along the bg->colour blend line (in sRGB).
208
+
209
+ Returns ``labels`` (int, -1 = none) and ``alpha`` (blend fraction in [0, 1]).
210
+ """
211
+ h, w = cand.shape
212
+ labels = np.full((h, w), -1, np.int32)
213
+ alpha = np.zeros((h, w), np.float32)
214
+ if not colors:
215
+ return labels, alpha
216
+ ys, xs = np.nonzero(cand)
217
+ bg_rgb = lab_to_rgb(bg)
218
+ px = rgb[ys, xs].astype(np.float32) - bg_rgb
219
+ best_d = np.full(len(px), np.inf)
220
+ best_i = np.full(len(px), -1)
221
+ best_a = np.zeros(len(px))
222
+ tol = 18.0 + 3.0 * noise
223
+ for i, c in enumerate(colors):
224
+ v = lab_to_rgb(c) - bg_rgb
225
+ vv = float(v @ v)
226
+ if vv < 1e-6:
227
+ continue
228
+ a = np.clip(px @ v / vv, 0.0, 1.2)
229
+ d = np.linalg.norm(px - a[:, None] * v[None, :], axis=1)
230
+ better = (d < best_d) & (a > 0.25) & (d < tol)
231
+ best_d = np.where(better, d, best_d)
232
+ best_i = np.where(better, i, best_i)
233
+ best_a = np.where(better, a, best_a)
234
+ labels[ys, xs] = best_i
235
+ alpha[ys, xs] = np.clip(best_a, 0, 1)
236
+ return labels, alpha
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:] = stats[1:, cv2.CC_STAT_AREA] >= min_area
243
+ return keep[lab]
244
+
245
+
246
+ def bg_for(ax: AxesResult) -> np.ndarray:
247
+ return np.asarray(ax.panel_bg, np.float32)
248
+
249
+
250
+ def series_masks(rgb: np.ndarray, cand: np.ndarray, ax: AxesResult, colors: list[np.ndarray],
251
+ noise: float) -> tuple[list[np.ndarray], np.ndarray, np.ndarray]:
252
+ """Boolean mask per colour (alpha > 0.35, specks removed), plus the alpha and label maps."""
253
+ labels, alpha = soft_assign(rgb, cand, bg_for(ax), colors, noise)
254
+ h, w = cand.shape
255
+ min_area = max(3, int(round((0.002 * min(h, w)) ** 2 * 4)))
256
+ masks = [remove_specks((labels == i) & (alpha > 0.35), min_area) for i in range(len(colors))]
257
+ return masks, alpha, labels
258
+
259
+
260
+ def describe_color(lab: np.ndarray) -> tuple[int, int, int]:
261
+ """Lab -> sRGB uint8 tuple."""
262
+ px = np.asarray(lab, np.float32).reshape(1, 1, 3)
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
+
plotscribe/web.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal web front end: upload a chart image, get CSV + diagnostics + debug overlay.
2
+
3
+ Run locally: uvicorn plotscribe.web:app --host 0.0.0.0 --port 8000
4
+ Requires the optional ``web`` extras (fastapi, uvicorn, python-multipart).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import json
11
+ import tempfile
12
+ from pathlib import Path
13
+
14
+ import cv2
15
+ from fastapi import FastAPI, File, Form, HTTPException, UploadFile
16
+ from fastapi.responses import HTMLResponse, JSONResponse
17
+
18
+ from . import export, pipeline
19
+
20
+ MAX_BYTES = 10 * 1024 * 1024
21
+ MAX_PIXELS = 25_000_000
22
+
23
+ app = FastAPI(title="plotscribe")
24
+
25
+ _PAGE = """<!doctype html>
26
+ <html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
27
+ <title>plotscribe</title>
28
+ <style>
29
+ body{font-family:system-ui,sans-serif;max-width:900px;margin:2rem auto;padding:0 1rem;color:#222}
30
+ .warn{color:#a15c00} .bad{color:#b00020} .ok{color:#1b7f3b}
31
+ img{max-width:100%;border:1px solid #ddd} pre{background:#f6f6f6;padding:.75rem;overflow:auto}
32
+ button{padding:.4rem 1rem}
33
+ </style></head><body>
34
+ <h1>plotscribe</h1>
35
+ <p>Upload a line, bar or scatter chart (PNG/JPG). Data is extracted with classical computer vision.</p>
36
+ <form id="f">
37
+ <input type="file" name="file" accept="image/png,image/jpeg" required>
38
+ <select name="chart_type"><option value="">auto-detect type</option><option>line</option>
39
+ <option>bar</option><option>stacked_bar</option><option>scatter</option></select>
40
+ <button>Extract</button>
41
+ </form>
42
+ <div id="out"></div>
43
+ <script>
44
+ const f=document.getElementById('f'), out=document.getElementById('out');
45
+ f.onsubmit=async e=>{e.preventDefault(); out.textContent='Working...';
46
+ const r=await fetch('api/extract',{method:'POST',body:new FormData(f)}); const d=await r.json();
47
+ if(!r.ok){out.innerHTML='<p class="bad">'+(d.detail||'error')+'</p>';return;}
48
+ const cls={ok:'ok',low_confidence:'warn'}[d.status]||'bad';
49
+ const blob=new Blob([d.csv],{type:'text/csv'}); const url=URL.createObjectURL(blob);
50
+ out.innerHTML='<p class="'+cls+'">status: <b>'+d.status+'</b> &middot; type: '+d.chart_type+
51
+ ' &middot; confidence: '+d.confidence.toFixed(2)+'</p>'+
52
+ (d.warnings.length?'<ul class="warn">'+d.warnings.map(w=>'<li>'+w.replace(/</g,'&lt;')+'</li>').join('')+'</ul>':'')+
53
+ '<p><a download="data.csv" href="'+url+'">Download CSV</a></p><pre>'+d.csv.replace(/</g,'&lt;')+'</pre>'+
54
+ '<img src="data:image/png;base64,'+d.debug_png+'"><details><summary>diagnostics</summary><pre>'+
55
+ JSON.stringify(d.diagnostics,null,2).replace(/</g,'&lt;')+'</pre></details>';};
56
+ </script></body></html>"""
57
+
58
+
59
+ @app.get("/", response_class=HTMLResponse)
60
+ def index() -> str:
61
+ return _PAGE
62
+
63
+
64
+ @app.get("/healthz")
65
+ def healthz() -> dict[str, str]:
66
+ return {"status": "ok"}
67
+
68
+
69
+ @app.post("/api/extract")
70
+ async def extract(file: UploadFile = File(...), chart_type: str = Form("")) -> JSONResponse:
71
+ """Run the pipeline on an uploaded image; returns CSV text, diagnostics and overlay PNG."""
72
+ data = await file.read()
73
+ if len(data) > MAX_BYTES:
74
+ raise HTTPException(413, "image too large (max 10 MB)")
75
+ if chart_type and chart_type not in ("line", "bar", "stacked_bar", "grouped_bar", "scatter"):
76
+ raise HTTPException(400, "invalid chart_type")
77
+ suffix = Path(file.filename or "x.png").suffix.lower()
78
+ if suffix not in (".png", ".jpg", ".jpeg"):
79
+ raise HTTPException(400, "only PNG or JPG images are supported")
80
+ with tempfile.TemporaryDirectory() as tmp:
81
+ path = Path(tmp) / f"upload{suffix}"
82
+ path.write_bytes(data)
83
+ img = cv2.imread(str(path))
84
+ if img is None:
85
+ raise HTTPException(400, "could not decode image")
86
+ if img.shape[0] * img.shape[1] > MAX_PIXELS:
87
+ raise HTTPException(413, "image has too many pixels")
88
+ res = pipeline.run(path, chart_type=chart_type or None)
89
+ csv = res.table.to_csv(index=False) if res.table is not None else ""
90
+ ok, png = cv2.imencode(".png", cv2.cvtColor(export.debug_overlay(res), cv2.COLOR_RGB2BGR))
91
+ diag = json.loads(json.dumps(export.diagnostics(res), default=export._json_default))
92
+ return JSONResponse({
93
+ "status": res.extra.get("status", "ok"), "chart_type": res.chart_type,
94
+ "confidence": res.confidence, "warnings": res.warnings, "csv": csv, "diagnostics": diag,
95
+ "debug_png": base64.b64encode(png.tobytes()).decode() if ok else "",
96
+ })
pyproject.toml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "plotscribe"
7
+ version = "0.1.0"
8
+ description = "Fully automatic chart image -> CSV extraction with classical computer vision"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ dependencies = [
12
+ "numpy>=1.26",
13
+ "opencv-python-headless>=4.8",
14
+ "scipy>=1.11",
15
+ "pandas>=2.0",
16
+ "pytesseract>=0.3.10",
17
+ "typer>=0.12",
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
+
25
+ [project.scripts]
26
+ plotscribe = "plotscribe.cli:app"
27
+
28
+ [tool.setuptools]
29
+ packages = ["plotscribe"]
30
+
31
+ [tool.pytest.ini_options]
32
+ testpaths = ["tests"]
33
+ addopts = "-q"
tests/__init__.py ADDED
File without changes
tests/eval_real.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluate plotscribe on hand-labelled real charts in tests/real/ (same metrics as synthetic)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ from plotscribe import export, pipeline
13
+ from tests.metrics import AxisInfo, score_table
14
+
15
+
16
+ def _infer(gt: pd.DataFrame, meta: dict) -> tuple[str, AxisInfo | None, AxisInfo]:
17
+ first = gt.columns[0]
18
+ vals = gt[gt.columns[1:]].to_numpy(float)
19
+ if "kind" in meta:
20
+ kind = meta["kind"]
21
+ elif first == "category":
22
+ kind = "bar"
23
+ elif (gt[gt.columns[1:]].notna().sum(axis=1) == 1).all() and gt.shape[1] > 2:
24
+ kind = "scatter"
25
+ else:
26
+ kind = "line"
27
+ mode = "scatter" if kind == "scatter" else ("categorical" if first == "category" else "numeric")
28
+ ylo, yhi = meta.get("ylim", [np.nanmin(vals), np.nanmax(vals)])
29
+ if ylo == yhi:
30
+ yhi = ylo + 1
31
+ ya = AxisInfo(min(ylo, yhi), max(ylo, yhi), log=bool(meta.get("ylog")))
32
+ xa = None
33
+ if mode != "categorical":
34
+ x = pd.to_numeric(gt[first], errors="coerce")
35
+ xlo, xhi = meta.get("xlim", [x.min(), x.max()])
36
+ xa = AxisInfo(min(xlo, xhi), max(xlo, xhi) if xhi != xlo else xlo + 1)
37
+ return mode, xa, ya
38
+
39
+
40
+ def main() -> None:
41
+ ap = argparse.ArgumentParser()
42
+ ap.add_argument("--dir", type=Path, default=Path(__file__).parent / "real")
43
+ ap.add_argument("--out", type=Path, default=None)
44
+ a = ap.parse_args()
45
+ rows = []
46
+ for img in sorted(p for p in a.dir.iterdir() if p.suffix.lower() in (".png", ".jpg", ".jpeg")):
47
+ gt_path = img.with_suffix(".csv")
48
+ if not gt_path.exists():
49
+ print(f"skip {img.name}: no ground-truth CSV")
50
+ continue
51
+ gt = pd.read_csv(gt_path)
52
+ meta_path = img.with_suffix(".json")
53
+ meta = json.loads(meta_path.read_text()) if meta_path.exists() else {}
54
+ mode, xa, ya = _infer(gt, meta)
55
+ res = pipeline.run(img)
56
+ sc = score_table(res.table, gt, mode, xa, ya)
57
+ rows.append({"chart": img.name, "status": res.extra.get("status"), "type": res.chart_type,
58
+ **{k: v for k, v in sc.summary().items() if k != "notes"}})
59
+ if a.out:
60
+ export.write_all(res, a.out, img.stem, debug=True)
61
+ if not rows:
62
+ print(f"no labelled charts in {a.dir}")
63
+ return
64
+ df = pd.DataFrame(rows)
65
+ pd.set_option("display.width", 200)
66
+ print(df.to_string(index=False))
67
+ print(f"\nmedian of per-chart median error: {df['median_err'].median():.4%} "
68
+ f"mean recall: {df['recall'].mean():.3f} series count ok: {df['series_count_ok'].mean():.2f}")
69
+
70
+
71
+ if __name__ == "__main__":
72
+ main()
tests/evaluate.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluate plotscribe on synthetic charts.
2
+
3
+ python -m tests.evaluate --n 100 --tier clean # generate + evaluate
4
+ python -m tests.evaluate --data data/synth_clean --workers 8 --worst 10
5
+
6
+ Prints summary tables by chart type and by perturbation and writes
7
+ ``<out>/results.json`` plus debug overlays of the worst cases to ``<out>/worst/``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import math
15
+ import shutil
16
+ import time
17
+ import traceback
18
+ from multiprocessing import Pool
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+
25
+ from plotscribe import pipeline
26
+ from tests import synth
27
+ from tests.metrics import AxisInfo, calibration_error, score_table, tick_recall
28
+
29
+ CATEGORICAL_KINDS = ("bar", "grouped_bar", "stacked_bar")
30
+
31
+
32
+ def axis_type(gt: dict[str, Any], axis: str) -> str:
33
+ if axis == "x":
34
+ return "categorical" if gt["categories"] else "linear"
35
+ return "log" if gt["yscale"] == "log" else "linear"
36
+
37
+
38
+ ORACLE_TYPE = False
39
+
40
+
41
+ def _oracle(kind: str) -> str:
42
+ return {"grouped_bar": "bar"}.get(kind, kind)
43
+
44
+
45
+ def evaluate_one(img_path: str) -> dict[str, Any]:
46
+ """Run the pipeline on one synthetic chart and score every stage."""
47
+ p = Path(img_path)
48
+ gt = json.loads(p.with_suffix(".json").read_text())
49
+ spec = gt["spec"]
50
+ rec: dict[str, Any] = {
51
+ "stem": p.stem, "path": img_path, "kind": spec["kind"], "tier": spec["tier"],
52
+ "n_series": spec["n_series"], "log_y": spec["log_y"], "jpeg": spec["jpeg_quality"] is not None,
53
+ "low_res": spec["dpi"] <= 72, "style": spec["style"], "markers": bool(spec["markers"]),
54
+ "dashed": spec["linestyle"] != "-", "categorical_x": spec["categorical_x"],
55
+ "legend": spec["legend_loc"] or "none", "negative": spec["negative"],
56
+ }
57
+ t0 = time.time()
58
+ try:
59
+ res = pipeline.run(img_path, chart_type=_oracle(spec["kind"]) if ORACLE_TYPE else None)
60
+ except Exception as exc: # noqa: BLE001 - evaluation must survive any failure
61
+ rec.update(ok=False, error=f"{type(exc).__name__}: {exc}", trace=traceback.format_exc(limit=4))
62
+ return rec
63
+ rec["runtime_s"] = time.time() - t0
64
+ rec["ok"] = True
65
+ s = res.pre.scale
66
+ ax = res.axes
67
+ gtb = gt["plot_bbox"]
68
+ from plotscribe.models import BBox
69
+
70
+ rec["box_iou"] = ax.plot_box.scaled(1 / s).iou(BBox(*gtb)) if ax else 0.0
71
+ tol = 1.5
72
+ rec["xtick_recall"] = tick_recall([t / s for t in ax.x_ticks], [t["px"] for t in gt["xticks"]], tol)
73
+ rec["ytick_recall"] = tick_recall([t / s for t in ax.y_ticks], [t["px"] for t in gt["yticks"]], tol)
74
+ xa = AxisInfo(*sorted(gt["xlim"]))
75
+ ya = AxisInfo(*sorted(gt["ylim"]), log=gt["yscale"] == "log")
76
+ for name, cal, axinfo in (("x", res.x_cal, xa), ("y", res.y_cal, ya)):
77
+ want = axis_type(gt, name)
78
+ got = cal.kind if cal else "none"
79
+ rec[f"{name}_axis_type_ok"] = got == want
80
+ rec[f"{name}_axis_type"] = got
81
+ rec[f"{name}_cal_conf"] = cal.confidence if cal else 0.0
82
+ if cal is not None and cal.kind != "categorical":
83
+ rec[f"{name}_cal_err"] = calibration_error(cal.rescaled(s), gt[f"{name}ticks"], axinfo)
84
+ else:
85
+ rec[f"{name}_cal_err"] = math.nan
86
+ if gt["categories"] and res.x_cal is not None and res.x_cal.kind == "categorical":
87
+ got = [c.lower() for c in res.x_cal.categories]
88
+ want = [c.lower() for c in gt["categories"]]
89
+ rec["x_cat_acc"] = float(np.mean([a == b for a, b in zip(got, want)])) if len(got) == len(want) else 0.0
90
+ rec["chart_type"] = res.chart_type
91
+ rec["chart_type_conf"] = res.chart_type_conf
92
+ rec["type_ok"] = _family(res.chart_type) == _family(spec["kind"])
93
+ rec["confidence"] = res.confidence
94
+ rec["warnings"] = res.warnings
95
+ rec["status"] = res.extra.get("status", "ok")
96
+ if res.table is not None and any("[px]" in str(c) for c in res.table.columns):
97
+ rec["has_table"] = False
98
+ rec["median_err"] = math.nan
99
+ return rec
100
+ if res.table is not None:
101
+ gt_df = synth.ground_truth_frame(gt)
102
+ kind = "scatter" if spec["kind"] == "scatter" else ("categorical" if gt["categories"] else "numeric")
103
+ sc = score_table(res.table, gt_df, kind, xa, ya)
104
+ rec.update(sc.summary())
105
+ rec["has_table"] = True
106
+ else:
107
+ rec["has_table"] = False
108
+ rec["median_err"] = math.nan
109
+ return rec
110
+
111
+
112
+ def _family(kind: str) -> str:
113
+ return "bar" if "bar" in kind else kind
114
+
115
+
116
+ def summarise(df: pd.DataFrame, by: str) -> pd.DataFrame:
117
+ """Aggregate metrics per group."""
118
+ def agg(g: pd.DataFrame) -> pd.Series:
119
+ ok = g[g["ok"]]
120
+ out = {
121
+ "n": len(g), "crash": int((~g["ok"]).sum()),
122
+ "box_iou": ok["box_iou"].median() if "box_iou" in ok else math.nan,
123
+ "xtick_rec": ok["xtick_recall"].mean(), "ytick_rec": ok["ytick_recall"].mean(),
124
+ "x_type_ok": ok["x_axis_type_ok"].mean(), "y_type_ok": ok["y_axis_type_ok"].mean(),
125
+ "y_cal_err_med": ok["y_cal_err"].median(), "y_cal_err_p90": ok["y_cal_err"].quantile(0.9),
126
+ "y_cal_fail": float((ok["y_cal_err"].isna() | (ok["y_cal_err"] > 0.01)).mean()) if len(ok) else math.nan,
127
+ }
128
+ if "x_cal_err" in ok and ok["x_cal_err"].notna().any():
129
+ out["x_cal_err_med"] = ok["x_cal_err"].median()
130
+ if "type_ok" in ok:
131
+ out["type_acc"] = ok["type_ok"].mean()
132
+ if "status" in ok:
133
+ out["status_ok"] = float((ok["status"] == "ok").mean())
134
+ out["abstain"] = float(ok["status"].isin(["uncalibrated", "failed"]).mean())
135
+ if "has_table" in ok and ok["has_table"].any():
136
+ t = ok[ok["has_table"]]
137
+ # Silent failure: reported status ok, but the numbers are wrong.
138
+ bad = (t["median_err"] > 0.02) | (t["recall"] < 0.5)
139
+ out["silent_fail"] = float((bad & (t["status"] == "ok")).sum()) / max(len(g), 1)
140
+ out["table"] = len(t) / max(len(g), 1)
141
+ out["med_err"] = t["median_err"].median()
142
+ out["p90_chart_med"] = t["median_err"].quantile(0.9)
143
+ out["recall"] = t["recall"].mean()
144
+ out["series_ok"] = t["series_count_ok"].mean()
145
+ return pd.Series(out)
146
+
147
+ out = pd.DataFrame({k: agg(g) for k, g in df.groupby(by)}).T
148
+ order = ["n", "crash", "status_ok", "abstain", "silent_fail", "box_iou", "xtick_rec", "ytick_rec",
149
+ "x_type_ok", "y_type_ok", "y_cal_err_med", "y_cal_err_p90", "y_cal_fail", "x_cal_err_med",
150
+ "type_acc", "table", "series_ok", "recall", "med_err", "p90_chart_med"]
151
+ return out[[c for c in order if c in out.columns]]
152
+
153
+
154
+ def perturbation_table(df: pd.DataFrame) -> pd.DataFrame:
155
+ rows = {}
156
+ for col in ("jpeg", "low_res", "log_y", "markers", "dashed", "negative", "categorical_x"):
157
+ for val in (True, False):
158
+ sub = df[df[col] == val]
159
+ if len(sub):
160
+ rows[f"{col}={val}"] = summarise(sub.assign(_all="all"), "_all").iloc[0]
161
+ sty = df[df["tier"] == "perturbed"]
162
+ for st in sorted(sty["style"].unique()) if len(sty) else []:
163
+ rows[f"style={st}"] = summarise(sty[sty["style"] == st].assign(_all="all"), "_all").iloc[0]
164
+ return pd.DataFrame(rows).T
165
+
166
+
167
+ def badness(r: dict[str, Any]) -> float:
168
+ """Sort key for the worst cases (crashes and missing tables first)."""
169
+ if not r.get("ok"):
170
+ return 1e9
171
+ if r.get("has_table") and r.get("median_err") == r.get("median_err"):
172
+ return float(r["median_err"]) + (1 - float(r.get("recall", 0)))
173
+ ce = r.get("y_cal_err")
174
+ return 10.0 + (ce if ce == ce and ce is not None else 5.0)
175
+
176
+
177
+ def main() -> None:
178
+ ap = argparse.ArgumentParser()
179
+ ap.add_argument("--n", type=int, default=50)
180
+ ap.add_argument("--tier", default="clean", choices=["clean", "perturbed", "mixed"])
181
+ ap.add_argument("--data", type=Path, default=None)
182
+ ap.add_argument("--out", type=Path, default=Path("eval_out"))
183
+ ap.add_argument("--workers", type=int, default=8)
184
+ ap.add_argument("--worst", type=int, default=8)
185
+ ap.add_argument("--start-seed", type=int, default=1000)
186
+ ap.add_argument("--kind", default=None, help="only evaluate this chart kind")
187
+ ap.add_argument("--kinds", default=None, help="comma-separated kinds to generate (default: all)")
188
+ ap.add_argument("--oracle-type", action="store_true", help="pass the true chart type to the pipeline")
189
+ a = ap.parse_args()
190
+ global ORACLE_TYPE
191
+ ORACLE_TYPE = a.oracle_type
192
+
193
+ kinds = tuple(a.kinds.split(",")) if a.kinds else synth.KINDS
194
+ tag = "" if kinds == synth.KINDS else "_" + "-".join(kinds)
195
+ data = a.data or Path(f"data/synth_{a.tier}_{a.n}_{a.start_seed}{tag}")
196
+ if not data.exists() or not any(data.glob("*.json")):
197
+ print(f"generating {a.n} {a.tier} charts into {data} ...")
198
+ synth.generate_set(a.n, data, a.tier, a.start_seed, kinds)
199
+ imgs = sorted(str(p) for p in data.iterdir() if p.suffix in (".png", ".jpg") and not p.name.endswith(".debug.png"))
200
+ if a.kind:
201
+ imgs = [p for p in imgs if json.loads(Path(p).with_suffix(".json").read_text())["spec"]["kind"] == a.kind]
202
+ t0 = time.time()
203
+ with Pool(a.workers, initializer=_init_worker, initargs=(a.oracle_type,)) as pool:
204
+ recs = pool.map(evaluate_one, imgs, chunksize=1)
205
+ print(f"evaluated {len(recs)} charts in {time.time() - t0:.0f}s")
206
+ a.out.mkdir(parents=True, exist_ok=True)
207
+ (a.out / "results.json").write_text(json.dumps(recs, indent=1, default=str))
208
+ df = pd.DataFrame(recs)
209
+ pd.set_option("display.width", 250, "display.max_columns", 40, "display.precision", 4)
210
+ print("\n== by chart type ==")
211
+ print(summarise(df, "kind").to_string())
212
+ print("\n== by tier ==")
213
+ print(summarise(df, "tier").to_string())
214
+ if (df["tier"] == "perturbed").any():
215
+ print("\n== by perturbation ==")
216
+ print(perturbation_table(df).to_string())
217
+ if "has_table" in df and df["has_table"].any():
218
+ t = df[df["has_table"]]
219
+ allerr = np.concatenate([[r["median_err"]] for _, r in t.iterrows()])
220
+ print(f"\nOVERALL median of per-chart median error: {np.nanmedian(allerr):.4%}")
221
+
222
+ worst = sorted(recs, key=badness, reverse=True)[: a.worst]
223
+ wdir = a.out / "worst"
224
+ shutil.rmtree(wdir, ignore_errors=True)
225
+ wdir.mkdir(parents=True)
226
+ print("\n== worst cases ==")
227
+ for r in worst:
228
+ msg = r.get("error") or (f"med_err={r.get('median_err')!s:.6} recall={r.get('recall', 0):.2f} "
229
+ f"y_cal_err={r.get('y_cal_err')!s:.6} type={r.get('chart_type')}")
230
+ print(f" {r['stem']}: {msg}")
231
+ for w in (r.get("warnings") or [])[:6]:
232
+ print(f" {w}")
233
+ _save_debug(r, wdir)
234
+
235
+
236
+ def _init_worker(oracle: bool) -> None:
237
+ global ORACLE_TYPE
238
+ ORACLE_TYPE = oracle
239
+
240
+
241
+ def _save_debug(rec: dict[str, Any], wdir: Path) -> None:
242
+ """Re-run a case and save its debug overlay next to the original image."""
243
+ src = Path(rec["path"])
244
+ shutil.copy(src, wdir / src.name)
245
+ if not rec.get("ok"):
246
+ (wdir / f"{src.stem}.error.txt").write_text(rec.get("trace", ""))
247
+ return
248
+ try:
249
+ from plotscribe import export
250
+
251
+ res = pipeline.run(str(src), chart_type=_oracle(rec["kind"]) if ORACLE_TYPE else None)
252
+ export.write_debug_overlay(res, wdir / f"{src.stem}.debug.png")
253
+ except Exception: # noqa: BLE001
254
+ (wdir / f"{src.stem}.error.txt").write_text(traceback.format_exc())
255
+
256
+
257
+ if __name__ == "__main__":
258
+ main()
tests/metrics.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Scoring of extracted tables against ground truth.
2
+
3
+ Errors are fractions of the axis range (in log10 space for log axes), so 0.01
4
+ means "1% of the axis range". Shared by the synthetic and real-image evaluators.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+ from scipy.optimize import linear_sum_assignment
16
+
17
+ MISSING = float("nan")
18
+
19
+
20
+ @dataclass
21
+ class AxisInfo:
22
+ lo: float
23
+ hi: float
24
+ log: bool = False
25
+
26
+ def norm(self, v: np.ndarray) -> np.ndarray:
27
+ v = np.asarray(v, float)
28
+ if self.log:
29
+ with np.errstate(divide="ignore", invalid="ignore"):
30
+ return (np.log10(np.where(v > 0, v, np.nan)) - math.log10(self.lo)) / (
31
+ math.log10(self.hi) - math.log10(self.lo))
32
+ return (v - self.lo) / (self.hi - self.lo)
33
+
34
+
35
+ @dataclass
36
+ class TableScore:
37
+ point_errors: list[float] = field(default_factory=list)
38
+ n_gt_points: int = 0
39
+ n_matched_points: int = 0
40
+ n_pred_points: int = 0
41
+ n_gt_series: int = 0
42
+ n_pred_series: int = 0
43
+ category_acc: float | None = None
44
+ notes: list[str] = field(default_factory=list)
45
+
46
+ @property
47
+ def recall(self) -> float:
48
+ return self.n_matched_points / self.n_gt_points if self.n_gt_points else 0.0
49
+
50
+ @property
51
+ def median(self) -> float:
52
+ return float(np.median(self.point_errors)) if self.point_errors else MISSING
53
+
54
+ @property
55
+ def p90(self) -> float:
56
+ return float(np.percentile(self.point_errors, 90)) if self.point_errors else MISSING
57
+
58
+ @property
59
+ def max(self) -> float:
60
+ return float(np.max(self.point_errors)) if self.point_errors else MISSING
61
+
62
+ def summary(self) -> dict[str, Any]:
63
+ return {
64
+ "median_err": self.median, "p90_err": self.p90, "max_err": self.max,
65
+ "recall": self.recall, "n_gt_series": self.n_gt_series, "n_pred_series": self.n_pred_series,
66
+ "series_count_ok": self.n_gt_series == self.n_pred_series,
67
+ "category_acc": self.category_acc, "notes": self.notes,
68
+ }
69
+
70
+
71
+ def _series_cols(df: pd.DataFrame) -> list[str]:
72
+ return [c for c in df.columns[1:]]
73
+
74
+
75
+ def _base_name(col: str) -> str:
76
+ return col.replace(" (segment)", "").split(" [")[0].strip().lower()
77
+
78
+
79
+ def _norm_cat(s: Any) -> str:
80
+ return "".join(ch for ch in str(s).lower() if ch.isalnum())
81
+
82
+
83
+ def _pair_errors_numeric_x(px: np.ndarray, py: np.ndarray, gx: np.ndarray, gy: np.ndarray,
84
+ xa: AxisInfo, ya: AxisInfo) -> tuple[list[float], int]:
85
+ """Interpolate the predicted polyline at the GT x positions (normalised space)."""
86
+ ok = np.isfinite(px) & np.isfinite(py)
87
+ px, py = px[ok], py[ok]
88
+ if len(px) == 0:
89
+ return [], 0
90
+ nx, ny = xa.norm(px), ya.norm(py)
91
+ fin = np.isfinite(nx) & np.isfinite(ny)
92
+ nx, ny = nx[fin], ny[fin]
93
+ if len(nx) == 0:
94
+ return [], 0
95
+ order = np.argsort(nx)
96
+ nx, ny = nx[order], ny[order]
97
+ gnx, gny = xa.norm(gx), ya.norm(gy)
98
+ tol = 0.01
99
+ errs = []
100
+ for x, y in zip(gnx, gny):
101
+ if x < nx[0] - tol or x > nx[-1] + tol:
102
+ continue
103
+ e = abs(float(np.interp(x, nx, ny)) - y)
104
+ if np.isfinite(e):
105
+ errs.append(e)
106
+ return errs, len(errs)
107
+
108
+
109
+ def _pair_errors_points(px: np.ndarray, py: np.ndarray, gx: np.ndarray, gy: np.ndarray,
110
+ xa: AxisInfo, ya: AxisInfo, gate: float = 0.05) -> tuple[list[float], int]:
111
+ """Optimal 1-1 point matching (scatter); errors are max(|dx|, |dy|) normalised."""
112
+ ok = np.isfinite(px) & np.isfinite(py)
113
+ px, py = px[ok], py[ok]
114
+ if len(px) == 0 or len(gx) == 0:
115
+ return [], 0
116
+ P = np.stack([xa.norm(px), ya.norm(py)], 1)
117
+ G = np.stack([xa.norm(gx), ya.norm(gy)], 1)
118
+ d = np.max(np.abs(G[:, None, :] - P[None, :, :]), axis=2)
119
+ d = np.nan_to_num(d, nan=10.0)
120
+ r, c = linear_sum_assignment(d)
121
+ errs = [float(d[i, j]) for i, j in zip(r, c) if d[i, j] < gate]
122
+ return errs, len(errs)
123
+
124
+
125
+ def _pair_errors_categorical(pcat: list[str], pv: np.ndarray, gcat: list[str], gv: np.ndarray,
126
+ ya: AxisInfo) -> tuple[list[float], int]:
127
+ if len(pcat) == len(gcat):
128
+ idx = list(range(len(gcat)))
129
+ else:
130
+ lookup = {_norm_cat(c): i for i, c in enumerate(pcat)}
131
+ idx = [lookup.get(_norm_cat(c), -1) for c in gcat]
132
+ errs = []
133
+ for gi, pi in enumerate(idx):
134
+ if pi < 0 or not np.isfinite(pv[pi]):
135
+ continue
136
+ e = abs(float(ya.norm(pv[pi]) - ya.norm(gv[gi])))
137
+ if np.isfinite(e):
138
+ errs.append(e)
139
+ return errs, len(errs)
140
+
141
+
142
+ def score_table(pred: pd.DataFrame | None, gt: pd.DataFrame, kind: str, xa: AxisInfo | None,
143
+ ya: AxisInfo) -> TableScore:
144
+ """Score a predicted table (plotscribe CSV layout) against the GT table.
145
+
146
+ ``kind``: ``scatter`` (point matching), ``categorical`` (rows by category) or
147
+ ``numeric`` (polyline interpolation at GT x). For stacked bars the values are
148
+ segment heights; ``ya`` should then span the segment range (handled by caller).
149
+ """
150
+ s = TableScore()
151
+ gcols = _series_cols(gt)
152
+ s.n_gt_series = len(gcols)
153
+ s.n_gt_points = int(sum(gt[c].notna().sum() for c in gcols))
154
+ if pred is None or pred.shape[1] < 2:
155
+ s.notes.append("no prediction")
156
+ return s
157
+ pcols = _series_cols(pred)
158
+ s.n_pred_series = len(pcols)
159
+ if kind != "categorical":
160
+ x_num = pd.to_numeric(pred.iloc[:, 0], errors="coerce")
161
+ if x_num.isna().mean() > 0.5:
162
+ s.notes.append("predicted x axis is not numeric")
163
+ return s
164
+ pred = pred.assign(**{pred.columns[0]: x_num})
165
+ s.n_pred_points = int(sum(pred[c].notna().sum() for c in pcols))
166
+ if kind == "categorical":
167
+ gcat = [str(v) for v in gt.iloc[:, 0]]
168
+ pcat = [str(v) for v in pred.iloc[:, 0]]
169
+ if len(pcat) == len(gcat):
170
+ s.category_acc = float(np.mean([_norm_cat(a) == _norm_cat(b) for a, b in zip(pcat, gcat)]))
171
+ else:
172
+ s.category_acc = 0.0
173
+ s.notes.append(f"category count {len(pcat)} vs {len(gcat)}")
174
+
175
+ pair: dict[tuple[int, int], list[float]] = {}
176
+ cost = np.full((len(gcols), len(pcols)), 10.0)
177
+ for i, gc in enumerate(gcols):
178
+ gmask = gt[gc].notna().to_numpy()
179
+ for j, pc in enumerate(pcols):
180
+ pmask = pred[pc].notna().to_numpy()
181
+ if kind == "scatter":
182
+ errs, _ = _pair_errors_points(
183
+ pred.iloc[:, 0].to_numpy(float)[pmask], pred[pc].to_numpy(float)[pmask],
184
+ gt.iloc[:, 0].to_numpy(float)[gmask], gt[gc].to_numpy(float)[gmask], xa, ya)
185
+ elif kind == "categorical":
186
+ errs, _ = _pair_errors_categorical(
187
+ [str(v) for v in pred.iloc[:, 0]], pred[pc].to_numpy(float),
188
+ [str(v) for v in gt.iloc[:, 0]], gt[gc].to_numpy(float), ya)
189
+ else:
190
+ errs, _ = _pair_errors_numeric_x(
191
+ pred.iloc[:, 0].to_numpy(float)[pmask], pred[pc].to_numpy(float)[pmask],
192
+ gt.iloc[:, 0].to_numpy(float)[gmask], gt[gc].to_numpy(float)[gmask], xa, ya)
193
+ pair[(i, j)] = errs
194
+ n_g = int(gmask.sum())
195
+ # Cost: mean error with missing points penalised as 0.5 (half the axis range).
196
+ miss = n_g - len(errs)
197
+ c = (sum(min(e, 0.5) for e in errs) + 0.5 * miss) / max(n_g, 1)
198
+ if _base_name(gc) == _base_name(pc):
199
+ c -= 0.05
200
+ cost[i, j] = c
201
+ r, c = linear_sum_assignment(np.nan_to_num(cost, nan=10.0, posinf=10.0))
202
+ for i, j in zip(r, c):
203
+ errs = pair[(i, j)]
204
+ s.point_errors.extend(errs)
205
+ s.n_matched_points += len(errs)
206
+ return s
207
+
208
+
209
+ def calibration_error(cal: Any, ticks: list[dict[str, Any]], axis: AxisInfo) -> float:
210
+ """Max normalised error of a numeric calibration evaluated at the GT tick pixels."""
211
+ if cal is None or cal.kind == "categorical" or not ticks:
212
+ return MISSING
213
+ px = np.array([t["px"] for t in ticks])
214
+ vals = np.array([t["value"] for t in ticks])
215
+ with np.errstate(all="ignore"):
216
+ pred = cal.to_value(px)
217
+ err = np.abs(axis.norm(pred) - axis.norm(vals))
218
+ return float(np.nanmax(err)) if np.isfinite(err).any() else 1.0
219
+
220
+
221
+ def tick_recall(pred_px: list[float], gt_px: list[float], tol: float) -> float:
222
+ if not gt_px:
223
+ return MISSING
224
+ p = np.asarray(pred_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]))
tests/real/README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Real-chart evaluation set
2
+
3
+ Drop pairs of files here:
4
+
5
+ - `name.png` (or `.jpg`) — the chart image
6
+ - `name.csv` — hand-made ground truth in the plotscribe CSV layout (first column `x`
7
+ or `category`, then one column per series; scatter: one row per point with only
8
+ the owning series' column filled; stacked bars: segment values)
9
+
10
+ Optional `name.json` with axis ranges for error normalisation, e.g.
11
+ `{"kind": "line", "ylim": [0, 100], "xlim": [0, 10], "ylog": false}`.
12
+ `kind` is one of `line`, `bar`, `stacked_bar`, `scatter`. Without it, ranges come
13
+ from the ground-truth data and the kind from the CSV layout.
14
+
15
+ Run: `python -m tests.eval_real` (add `--out eval_out/real` to keep debug overlays).
tests/synth.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Synthetic chart generator with exact ground truth.
2
+
3
+ Every chart is rendered with matplotlib from a random but seeded ``SynthSpec``.
4
+ Alongside the image we store a JSON file holding the data, the axis limits and
5
+ scale, and the *pixel* geometry of the plot area and ticks (taken from
6
+ matplotlib's own transforms), so each pipeline stage can be scored on its own.
7
+
8
+ Usage::
9
+
10
+ python -m tests.synth --n 200 --tier mixed --out data/synth
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import io
16
+ import json
17
+ import random
18
+ from dataclasses import asdict, dataclass
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ import matplotlib
23
+
24
+ matplotlib.use("Agg")
25
+ import matplotlib.pyplot as plt # noqa: E402
26
+ import numpy as np # noqa: E402
27
+ from PIL import Image # noqa: E402
28
+
29
+ KINDS = ("line", "bar", "grouped_bar", "stacked_bar", "scatter")
30
+ TIERS = ("clean", "perturbed")
31
+
32
+ _WORDS = [
33
+ "Apple", "Banana", "Cherry", "Date", "Fig", "Grape", "Kiwi", "Lemon", "Mango",
34
+ "Nectar", "Olive", "Peach", "Pear", "Plum", "Quince",
35
+ ]
36
+ _MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
37
+ _SERIES_NAMES = [
38
+ "Revenue", "Cost", "Profit", "North", "South", "East", "West", "Alpha", "Beta",
39
+ "Gamma", "Model A", "Model B", "Baseline", "Control", "Treatment",
40
+ ]
41
+ _STYLES_PERTURBED = [
42
+ "default", "default", "default", "seaborn-v0_8-whitegrid", "ggplot", "bmh",
43
+ "seaborn-v0_8-ticks", "fivethirtyeight", "Solarize_Light2", "classic",
44
+ ]
45
+
46
+
47
+ @dataclass
48
+ class SynthSpec:
49
+ """All random choices for one synthetic chart."""
50
+
51
+ seed: int
52
+ tier: str
53
+ kind: str
54
+ n_series: int
55
+ n_points: int
56
+ categorical_x: bool
57
+ log_y: bool
58
+ negative: bool
59
+ grid: bool
60
+ style: str
61
+ markers: str # "" for none, else a matplotlib marker code
62
+ linestyle: str
63
+ legend_loc: str | None
64
+ font_size: float
65
+ font_family: str
66
+ figsize: tuple[float, float]
67
+ dpi: int
68
+ jpeg_quality: int | None
69
+ palette: str # "default" or "random"
70
+
71
+
72
+ def random_spec(seed: int, tier: str = "clean", kind: str | None = None) -> SynthSpec:
73
+ """Draw a random chart specification.
74
+
75
+ The *clean* tier mimics a default matplotlib export (PNG, default style, 100 dpi,
76
+ solid lines, default fonts). The *perturbed* tier varies style, fonts,
77
+ resolution, line style, markers, legend position, log scales and JPEG quality.
78
+ """
79
+ rng = random.Random(seed)
80
+ kind = kind or rng.choice(KINDS)
81
+ if kind == "bar":
82
+ n_series = 1
83
+ elif kind in ("grouped_bar", "stacked_bar"):
84
+ n_series = rng.randint(2, 4)
85
+ else:
86
+ n_series = rng.randint(1, 5)
87
+
88
+ if kind == "scatter":
89
+ n_points = rng.randint(10, 40)
90
+ elif kind == "line":
91
+ n_points = rng.randint(5, 30)
92
+ else:
93
+ n_points = rng.randint(3, 9)
94
+
95
+ categorical_x = kind in ("bar", "grouped_bar", "stacked_bar") or (
96
+ kind == "line" and rng.random() < 0.25
97
+ )
98
+ if categorical_x:
99
+ n_points = min(n_points, 12)
100
+ clean = tier == "clean"
101
+ log_y = (not clean) and kind in ("line", "scatter") and rng.random() < 0.25
102
+ negative = (not log_y) and kind in ("line", "bar", "grouped_bar") and rng.random() < 0.25
103
+ legend_loc: str | None
104
+ if n_series == 1 and rng.random() < 0.6:
105
+ legend_loc = None
106
+ elif clean:
107
+ legend_loc = "best"
108
+ else:
109
+ legend_loc = rng.choice(["best", "upper left", "upper right", "lower right", "outside"])
110
+
111
+ if clean:
112
+ return SynthSpec(
113
+ seed=seed, tier=tier, kind=kind, n_series=n_series, n_points=n_points,
114
+ categorical_x=categorical_x, log_y=False, negative=negative,
115
+ grid=rng.random() < 0.5, style="default",
116
+ markers=rng.choice(["", "", "o"]) if kind == "line" else "",
117
+ linestyle="-", legend_loc=legend_loc, font_size=10.0,
118
+ font_family="DejaVu Sans", figsize=(6.4, 4.8), dpi=100,
119
+ jpeg_quality=None, palette="default",
120
+ )
121
+ return SynthSpec(
122
+ seed=seed, tier=tier, kind=kind, n_series=n_series, n_points=n_points,
123
+ categorical_x=categorical_x, log_y=log_y, negative=negative,
124
+ grid=rng.random() < 0.5, style=rng.choice(_STYLES_PERTURBED),
125
+ markers=rng.choice(["", "", "o", "s", "^", "D"]) if kind == "line" else rng.choice(["o", "s", "^"]),
126
+ linestyle=rng.choice(["-", "-", "-", "--", ":"]) if kind == "line" else "-",
127
+ legend_loc=legend_loc, font_size=rng.choice([7, 8, 9, 10, 11, 12, 14]),
128
+ font_family=rng.choice(["DejaVu Sans", "DejaVu Serif", "DejaVu Sans Mono"]),
129
+ figsize=(round(rng.uniform(4.0, 10.0), 2), round(rng.uniform(3.0, 7.0), 2)),
130
+ dpi=rng.choice([50, 60, 72, 80, 100, 120, 150]),
131
+ jpeg_quality=rng.choice([None, None, 95, 80, 60, 40]),
132
+ palette=rng.choice(["default", "random"]),
133
+ )
134
+
135
+
136
+ def _magnitude(rng: np.random.Generator) -> float:
137
+ return float(10 ** rng.uniform(-1, 4))
138
+
139
+
140
+ def _random_walk(rng: np.random.Generator, n: int) -> np.ndarray:
141
+ steps = rng.normal(0, 1, n)
142
+ walk = np.cumsum(steps) + rng.uniform(-1, 1) * np.arange(n) * 0.3
143
+ return walk
144
+
145
+
146
+ def make_data(spec: SynthSpec) -> dict[str, Any]:
147
+ """Generate x values, category labels and per-series y values for ``spec``."""
148
+ rng = np.random.default_rng(spec.seed)
149
+ prng = random.Random(spec.seed + 1)
150
+ names = prng.sample(_SERIES_NAMES, spec.n_series)
151
+ out: dict[str, Any] = {"names": names}
152
+
153
+ if spec.categorical_x:
154
+ if prng.random() < 0.3 and spec.n_points <= 12:
155
+ start = prng.randint(0, 12 - spec.n_points)
156
+ cats = _MONTHS[start:start + spec.n_points]
157
+ else:
158
+ cats = prng.sample(_WORDS, spec.n_points)
159
+ out["categories"] = cats
160
+ x = np.arange(spec.n_points, dtype=float)
161
+ elif spec.kind == "scatter":
162
+ x = None
163
+ else:
164
+ x0 = prng.choice([0.0, 1.0, float(prng.randint(-50, 2000))])
165
+ step = prng.choice([0.1, 0.5, 1.0, 2.0, 5.0, 10.0, 0.25])
166
+ x = x0 + step * np.arange(spec.n_points)
167
+
168
+ mag = _magnitude(rng)
169
+ series: list[dict[str, list[float]]] = []
170
+ for _ in range(spec.n_series):
171
+ if spec.kind == "scatter":
172
+ sx = rng.uniform(0, 1, spec.n_points) * mag * rng.uniform(0.5, 2) + rng.uniform(-1, 1) * mag
173
+ if spec.log_y:
174
+ sy = 10 ** (rng.uniform(0, 3.5, spec.n_points) + rng.uniform(-1, 1))
175
+ else:
176
+ sy = (0.3 * sx / mag + rng.normal(0, 0.5, spec.n_points)) * mag
177
+ series.append({"x": sx.tolist(), "y": sy.tolist()})
178
+ continue
179
+ assert x is not None
180
+ if spec.kind == "line":
181
+ walk = _random_walk(rng, spec.n_points)
182
+ if spec.log_y:
183
+ walk = (walk - walk.min()) / max(np.ptp(walk), 1e-9) * rng.uniform(1.5, 4)
184
+ y = 10 ** (walk + rng.uniform(-1, 2))
185
+ else:
186
+ y = walk / max(np.ptp(walk), 1e-9) * mag
187
+ if not spec.negative:
188
+ y = y - y.min() + mag * rng.uniform(0.05, 1.5)
189
+ else:
190
+ if spec.negative:
191
+ y = rng.uniform(-1, 1, spec.n_points) * mag
192
+ y[np.abs(y) < 0.05 * mag] = 0.1 * mag
193
+ else:
194
+ y = rng.uniform(0.1, 1, spec.n_points) * mag
195
+ series.append({"x": x.tolist(), "y": y.tolist()})
196
+ out["series"] = series
197
+ return out
198
+
199
+
200
+ def _palette(spec: SynthSpec) -> list[Any]:
201
+ if spec.palette == "default":
202
+ return [f"C{i}" for i in range(spec.n_series)]
203
+ rng = random.Random(spec.seed + 2)
204
+ hue0 = rng.random()
205
+ cols = []
206
+ for i in range(spec.n_series):
207
+ h = (hue0 + i / spec.n_series) % 1.0
208
+ s = rng.uniform(0.55, 0.95)
209
+ v = rng.uniform(0.45, 0.85)
210
+ cols.append(matplotlib.colors.hsv_to_rgb((h, s, v)))
211
+ return cols
212
+
213
+
214
+ def render(spec: SynthSpec, data: dict[str, Any]) -> tuple[np.ndarray, dict[str, Any]]:
215
+ """Render the chart; return the RGB image and its pixel-level ground truth."""
216
+ rc = {"font.size": spec.font_size, "font.family": spec.font_family}
217
+ style = spec.style if spec.style != "default" else "default"
218
+ with plt.style.context(style), plt.rc_context(rc):
219
+ fig, ax = plt.subplots(figsize=spec.figsize, dpi=spec.dpi)
220
+ colors = _palette(spec)
221
+ names = data["names"]
222
+ ser = data["series"]
223
+ n = spec.n_series
224
+ if spec.kind == "line":
225
+ for i, s in enumerate(ser):
226
+ ax.plot(s["x"], s["y"], color=colors[i], linestyle=spec.linestyle,
227
+ marker=spec.markers or None, label=names[i])
228
+ elif spec.kind == "scatter":
229
+ for i, s in enumerate(ser):
230
+ ax.scatter(s["x"], s["y"], color=colors[i], marker=spec.markers or "o",
231
+ label=names[i], s=random.Random(spec.seed + 3).choice([20, 30, 40]))
232
+ elif spec.kind == "bar":
233
+ ax.bar(ser[0]["x"], ser[0]["y"], color=colors[0], label=names[0])
234
+ elif spec.kind == "grouped_bar":
235
+ width = 0.8 / n
236
+ for i, s in enumerate(ser):
237
+ ax.bar(np.asarray(s["x"]) - 0.4 + width * (i + 0.5), s["y"], width=width,
238
+ color=colors[i], label=names[i])
239
+ elif spec.kind == "stacked_bar":
240
+ bottom = np.zeros(spec.n_points)
241
+ for i, s in enumerate(ser):
242
+ ax.bar(s["x"], s["y"], bottom=bottom, color=colors[i], label=names[i])
243
+ bottom = bottom + np.asarray(s["y"])
244
+ if spec.kind in ("bar", "grouped_bar", "stacked_bar") and spec.negative:
245
+ ax.axhline(0, color="black", linewidth=0.8)
246
+ if spec.categorical_x:
247
+ ax.set_xticks(range(spec.n_points), data["categories"])
248
+ if spec.log_y:
249
+ ax.set_yscale("log")
250
+ if spec.grid:
251
+ ax.grid(True, alpha=0.6)
252
+ rng = random.Random(spec.seed + 4)
253
+ if rng.random() < 0.5:
254
+ ax.set_xlabel(rng.choice(["Time", "Category", "x", "Month", "Input value"]))
255
+ if rng.random() < 0.5:
256
+ ax.set_ylabel(rng.choice(["Value", "Amount ($)", "y", "Count", "Score"]))
257
+ if rng.random() < 0.3:
258
+ ax.set_title(rng.choice(["Results", "Quarterly overview", "Measurements"]))
259
+ if spec.legend_loc == "outside":
260
+ ax.legend(loc="center left", bbox_to_anchor=(1.02, 0.5))
261
+ fig.subplots_adjust(right=0.72)
262
+ elif spec.legend_loc:
263
+ ax.legend(loc=spec.legend_loc)
264
+
265
+ fig.canvas.draw()
266
+ renderer = fig.canvas.get_renderer()
267
+ width_px, height_px = fig.canvas.get_width_height()
268
+ bbox = ax.get_window_extent(renderer)
269
+ gt = {
270
+ "spec": asdict(spec),
271
+ "image_size": [width_px, height_px],
272
+ "plot_bbox": [bbox.x0, height_px - bbox.y1, bbox.x1, height_px - bbox.y0],
273
+ "xlim": list(ax.get_xlim()),
274
+ "ylim": list(ax.get_ylim()),
275
+ "yscale": ax.get_yscale(),
276
+ "xticks": _ticks(ax, "x", height_px),
277
+ "yticks": _ticks(ax, "y", height_px),
278
+ "names": names,
279
+ "categories": data.get("categories"),
280
+ "series": ser,
281
+ }
282
+ buf = io.BytesIO()
283
+ fig.savefig(buf, format="png", dpi=spec.dpi)
284
+ plt.close(fig)
285
+ buf.seek(0)
286
+ img = np.array(Image.open(buf).convert("RGB"))
287
+ assert img.shape[1] == width_px and img.shape[0] == height_px, (img.shape, width_px, height_px)
288
+ return img, gt
289
+
290
+
291
+ def _ticks(ax: Any, which: str, height_px: int) -> list[dict[str, Any]]:
292
+ axis = ax.xaxis if which == "x" else ax.yaxis
293
+ lo, hi = sorted(ax.get_xlim() if which == "x" else ax.get_ylim())
294
+ ticks = []
295
+ for val, lab in zip(axis.get_majorticklocs(), axis.get_majorticklabels()):
296
+ if not (lo - 1e-9 * abs(hi - lo) <= val <= hi + 1e-9 * abs(hi - lo)):
297
+ continue
298
+ if which == "x":
299
+ px = float(ax.transData.transform((val, ax.get_ylim()[0]))[0])
300
+ else:
301
+ px = float(height_px - ax.transData.transform((ax.get_xlim()[0], val))[1])
302
+ ticks.append({"value": float(val), "label": lab.get_text(), "px": px})
303
+ return ticks
304
+
305
+
306
+ def ground_truth_frame(gt: dict[str, Any]) -> "Any":
307
+ """Ground truth in the plotscribe CSV layout (see README, 'CSV layout')."""
308
+ import pandas as pd
309
+
310
+ kind = gt["spec"]["kind"]
311
+ names = gt["names"]
312
+ if kind == "scatter":
313
+ rows = []
314
+ for name, s in zip(names, gt["series"]):
315
+ for x, y in zip(s["x"], s["y"]):
316
+ rows.append({"x": x, **{n: (y if n == name else np.nan) for n in names}})
317
+ return pd.DataFrame(rows, columns=["x", *names])
318
+ first = "category" if gt["categories"] else "x"
319
+ xcol = gt["categories"] if gt["categories"] else gt["series"][0]["x"]
320
+ cols = {first: xcol}
321
+ suffix = " (segment)" if kind == "stacked_bar" else ""
322
+ for name, s in zip(names, gt["series"]):
323
+ cols[name + suffix] = s["y"]
324
+ return pd.DataFrame(cols)
325
+
326
+
327
+ def generate(seed: int, out_dir: Path, tier: str = "clean", kind: str | None = None) -> Path:
328
+ """Render one chart into ``out_dir``; return the image path."""
329
+ spec = random_spec(seed, tier, kind)
330
+ data = make_data(spec)
331
+ img, gt = render(spec, data)
332
+ out_dir.mkdir(parents=True, exist_ok=True)
333
+ stem = f"{tier}_{spec.kind}_{seed:05d}"
334
+ if spec.jpeg_quality:
335
+ path = out_dir / f"{stem}.jpg"
336
+ Image.fromarray(img).save(path, quality=spec.jpeg_quality)
337
+ else:
338
+ path = out_dir / f"{stem}.png"
339
+ Image.fromarray(img).save(path)
340
+ (out_dir / f"{stem}.json").write_text(json.dumps(gt, indent=1))
341
+ ground_truth_frame(gt).to_csv(out_dir / f"{stem}.gt.csv", index=False)
342
+ return path
343
+
344
+
345
+ def generate_set(n: int, out_dir: Path, tier: str = "clean", start_seed: int = 0,
346
+ kinds: tuple[str, ...] = KINDS) -> list[Path]:
347
+ """Generate ``n`` charts cycling through ``kinds`` so every kind is represented."""
348
+ paths = []
349
+ for i in range(n):
350
+ seed = start_seed + i
351
+ tiers = TIERS if tier == "mixed" else (tier,)
352
+ t = tiers[i % len(tiers)]
353
+ kind = kinds[(i // len(tiers)) % len(kinds)]
354
+ paths.append(generate(seed, out_dir, t, kind))
355
+ return paths
356
+
357
+
358
+ if __name__ == "__main__":
359
+ import argparse
360
+
361
+ p = argparse.ArgumentParser()
362
+ p.add_argument("--n", type=int, default=100)
363
+ p.add_argument("--tier", default="clean", choices=[*TIERS, "mixed"])
364
+ p.add_argument("--out", type=Path, default=Path("data/synth"))
365
+ p.add_argument("--start-seed", type=int, default=0)
366
+ a = p.parse_args()
367
+ ps = generate_set(a.n, a.out, a.tier, a.start_seed)
368
+ print(f"wrote {len(ps)} charts to {a.out}")
tests/test_calibrate.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from plotscribe.calibrate import fit_categorical, fit_numeric
5
+
6
+
7
+ def test_linear_with_outlier():
8
+ px = [100, 200, 300, 400, 500]
9
+ vals = [50, 40, 30, 200, 10] # one OCR error
10
+ cal = fit_numeric("y", px, vals)
11
+ assert cal.kind == "linear"
12
+ assert cal.n_inliers == 4
13
+ assert float(cal.to_value(250)) == pytest.approx(35.0)
14
+ assert any("outlier" in w for w in cal.warnings)
15
+
16
+
17
+ def test_log_axis():
18
+ px = [400, 300, 200, 100]
19
+ cal = fit_numeric("y", px, [1, 10, 100, 1000])
20
+ assert cal.kind == "log"
21
+ assert float(cal.to_value(250)) == pytest.approx(10 ** 1.5)
22
+
23
+
24
+ def test_candidates_pick_consistent_reading():
25
+ px = [0, 100, 200, 300]
26
+ vals = [[0.0], [10.0, 1.0], [20.0, 2.0], [30.0]]
27
+ cal = fit_numeric("x", px, vals)
28
+ assert cal.n_inliers == 4
29
+ assert cal.tick_values == pytest.approx([0, 10, 20, 30])
30
+
31
+
32
+ def test_too_few_labels_is_flagged():
33
+ cal = fit_numeric("y", [10.0], [5.0])
34
+ assert cal.confidence == 0 and cal.warnings
35
+
36
+
37
+ def test_categorical_order():
38
+ cal = fit_categorical("x", [300.0, 100.0, 200.0], ["c", "a", "b"])
39
+ assert cal.categories == ["a", "b", "c"]
40
+ assert cal.nearest_category(190)[0] == 1
41
+
42
+
43
+ def test_rescale_roundtrip():
44
+ cal = fit_numeric("y", [100, 200, 300], [3, 2, 1])
45
+ r = cal.rescaled(2.0)
46
+ assert float(r.to_value(100)) == pytest.approx(float(cal.to_value(200)))
47
+ assert np.isclose(float(cal.to_px(cal.to_value(123.0))), 123.0)
tests/test_ocr_parse.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from plotscribe.ocr import parse_number, parse_offset_text
4
+
5
+
6
+ @pytest.mark.parametrize("text,value", [
7
+ ("1,000", 1000.0), ("1e3", 1000.0), ("5%", 5.0), ("$10", 10.0), ("1.5k", 1500.0),
8
+ ("−2.5", -2.5), ("(5)", -5.0), ("O.5", 0.5), ("l00", 100.0), ("S0", 50.0),
9
+ ("2M", 2e6), ("1,5", 1.5), ("10^3", 1000.0), ("-0.25", -0.25), ("3bn", 3e9),
10
+ ])
11
+ def test_parse_number(text, value):
12
+ assert parse_number(text) == pytest.approx(value)
13
+
14
+
15
+ @pytest.mark.parametrize("text", ["Jan", "Revenue", "", "--", "1.2.3"])
16
+ def test_parse_number_rejects_text(text):
17
+ assert parse_number(text) is None
18
+
19
+
20
+ def test_offset_text():
21
+ assert parse_offset_text("1e6") == (1e6, 0.0)
22
+ assert parse_offset_text("+1.063e3") == (1.0, 1063.0)
23
+ assert parse_offset_text("Results") is None
tests/test_pipeline.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """End-to-end check on clean synthetic charts (the CI accuracy target)."""
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from plotscribe import export, pipeline
7
+ from tests import synth
8
+ from tests.metrics import AxisInfo, score_table
9
+
10
+ SEEDS = range(9000, 9010) # two charts of each kind
11
+
12
+
13
+ @pytest.fixture(scope="module")
14
+ def charts(tmp_path_factory):
15
+ out = tmp_path_factory.mktemp("synth")
16
+ return synth.generate_set(len(SEEDS), out, "clean", SEEDS.start)
17
+
18
+
19
+ def _score(path):
20
+ import json
21
+
22
+ gt = json.loads(path.with_suffix(".json").read_text())
23
+ res = pipeline.run(path)
24
+ kind = "scatter" if gt["spec"]["kind"] == "scatter" else ("categorical" if gt["categories"] else "numeric")
25
+ sc = score_table(res.table, synth.ground_truth_frame(gt), kind, AxisInfo(*sorted(gt["xlim"])),
26
+ AxisInfo(*sorted(gt["ylim"]), log=gt["yscale"] == "log"))
27
+ return res, sc, gt
28
+
29
+
30
+ def test_clean_median_error_under_one_percent(charts):
31
+ medians, recalls = [], []
32
+ for p in charts:
33
+ res, sc, gt = _score(p)
34
+ assert res.extra["status"] == "ok", (p.name, res.warnings)
35
+ assert ("bar" in res.chart_type) == ("bar" in gt["spec"]["kind"]), p.name
36
+ medians.append(sc.median)
37
+ recalls.append(sc.recall)
38
+ assert np.nanmedian(medians) < 0.01
39
+ assert np.mean(recalls) > 0.9
40
+
41
+
42
+ def test_outputs_written(charts, tmp_path):
43
+ res = pipeline.run(charts[0])
44
+ paths = export.write_all(res, tmp_path, "c", debug=True)
45
+ assert all(p.exists() for p in paths.values())
46
+ assert paths["csv"].read_text().strip()
tests/test_web.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ fastapi = pytest.importorskip("fastapi")
4
+ from fastapi.testclient import TestClient # noqa: E402
5
+
6
+ from plotscribe.web import app # noqa: E402
7
+ from tests import synth # noqa: E402
8
+
9
+
10
+ def test_upload_roundtrip(tmp_path):
11
+ img = synth.generate(9100, tmp_path, "clean", "bar")
12
+ client = TestClient(app)
13
+ assert client.get("/").status_code == 200
14
+ r = client.post("/api/extract", files={"file": (img.name, img.read_bytes(), "image/png")})
15
+ assert r.status_code == 200
16
+ d = r.json()
17
+ assert d["status"] == "ok" and d["csv"].startswith("category")
18
+
19
+
20
+ def test_rejects_non_image():
21
+ r = TestClient(app).post("/api/extract", files={"file": ("x.txt", b"hello", "text/plain")})
22
+ assert r.status_code == 400