Spaces:
Runtime error
Runtime error
Deploy baad0c2: Smooth crossing curves: de-jittered vertices, marker gap fill, occluded starts, optional resampling; compact web output
Browse files- EVAL_LOG.md +31 -0
- README.md +17 -3
- plotscribe/cli.py +3 -1
- plotscribe/export.py +2 -0
- plotscribe/extract_line.py +118 -16
- plotscribe/legend.py +28 -0
- plotscribe/pipeline.py +136 -6
- plotscribe/web.py +25 -5
EVAL_LOG.md
CHANGED
|
@@ -194,3 +194,34 @@ clean unchanged (0.11% median error, 0 silent failures); perturbed silent failur
|
|
| 194 |
Remaining: held-out silent failures (4.2%) are mostly lines whose data leaves the
|
| 195 |
plotted range at one end only (indistinguishable from a maximum on the frame), and
|
| 196 |
bars 1-3 px tall that cannot be measured.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
Remaining: held-out silent failures (4.2%) are mostly lines whose data leaves the
|
| 195 |
plotted range at one end only (indistinguishable from a maximum on the frame), and
|
| 196 |
bars 1-3 px tall that cannot be measured.
|
| 197 |
+
|
| 198 |
+
## Stage 9 — smooth crossing curves (real MATLAB figure), web re-plot
|
| 199 |
+
|
| 200 |
+
Trigger: `data/vcsel_response_test.png` (7 smooth curves sharing an origin and
|
| 201 |
+
crossing). Before: dozens of clustered points per curve, y labels misread, curve
|
| 202 |
+
starts hidden under other curves missing.
|
| 203 |
+
|
| 204 |
+
Failures found and fixed:
|
| 205 |
+
1. Line thickness was inflated by markers/crossings (14.7 px on some charts), which
|
| 206 |
+
drove over-smoothing and vertex thinning. Fix: slope-corrected 30th-percentile
|
| 207 |
+
run thickness.
|
| 208 |
+
2. RDP on a jittery centreline gave clusters of vertices. Fix: Savitzky–Golay
|
| 209 |
+
de-jitter, tolerance from a MAD noise estimate, Visvalingam thinning to a minimum
|
| 210 |
+
vertex spacing (~1% of the width).
|
| 211 |
+
3. Markers hidden under another series' marker left gaps. Fix: add the line's
|
| 212 |
+
corners inside gaps >= 1.6x the marker spacing; reject marker "blobs" smaller than
|
| 213 |
+
the line could produce.
|
| 214 |
+
4. Curves whose start is hidden under another curve: continued along the occluding
|
| 215 |
+
trace (within 2x thickness) and reported in the warnings.
|
| 216 |
+
5. Y-label crops included the axis line -> misreads. Fix: crops clipped at the axis.
|
| 217 |
+
6. Legend "ImA" -> "1mA" repair when the other entries share a digit pattern.
|
| 218 |
+
7. The labels-touching-the-frame check used a fixed gap; now relative to label
|
| 219 |
+
height (it had been catching otherwise-silent perturbed failures).
|
| 220 |
+
8. Optional `--resample N` (web: "even x spacing") reports lines on a shared round x grid.
|
| 221 |
+
|
| 222 |
+
| regression check | before | after |
|
| 223 |
+
|---|---|---|
|
| 224 |
+
| clean 200: median error / silent | 0.11% / 0% | 0.11% / 0% |
|
| 225 |
+
| clean lines 100 (oracle): median / p90 chart median | 0.19% / 0.39% | 0.13% / 0.25% |
|
| 226 |
+
| perturbed 200: silent / status ok / recall | 6.5% / 55% / 79% | 6.5% / 57.5% / 80% |
|
| 227 |
+
| PlotQA test RNSS / held-out RNSS | 99.5 / 97.3 | 99.5 / 97.1 |
|
README.md
CHANGED
|
@@ -37,9 +37,13 @@ Runtime dependencies: `numpy`, `opencv-python-headless`, `scipy`, `pandas`,
|
|
| 37 |
## Usage
|
| 38 |
|
| 39 |
```bash
|
| 40 |
-
plotscribe input.png -o out/ [--type line|bar|stacked_bar|scatter] [--debug] [--ocr tesseract|paddle]
|
| 41 |
```
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
This writes:
|
| 44 |
|
| 45 |
- `out/input.csv`: the data (layout below)
|
|
@@ -73,12 +77,22 @@ Values hidden under the legend are left empty and reported in the warnings rathe
|
|
| 73 |
|
| 74 |
- First column `category` (categorical x axis) or `x` (numeric x axis).
|
| 75 |
- Then one column per series, named after the legend label (`series_1..n` if there is no legend), in legend order.
|
| 76 |
-
- Line/bar: one row per x position or category. Line charts give points at markers
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
- Scatter: one row per point; only the owning series' column is filled.
|
| 78 |
- Stacked bars: headers end in ` (segment)`; values are segment heights, not cumulative tops.
|
| 79 |
|
| 80 |
## Web page
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
```bash
|
| 83 |
uvicorn plotscribe.web:app --port 8000 # http://localhost:8000
|
| 84 |
# or
|
|
@@ -159,7 +173,7 @@ whose data lies outside the plotted y range (cut off by the frame).
|
|
| 159 |
|
| 160 |
The CI target (median error < 1% on clean charts) is met for every chart type.
|
| 161 |
On clean charts the worst single bar value is 0.9% off (150 bar charts); for lines
|
| 162 |
-
|
| 163 |
|
| 164 |
## Known limitations
|
| 165 |
|
|
|
|
| 37 |
## Usage
|
| 38 |
|
| 39 |
```bash
|
| 40 |
+
plotscribe input.png -o out/ [--type line|bar|stacked_bar|scatter] [--debug] [--ocr tesseract|paddle] [--resample N]
|
| 41 |
```
|
| 42 |
|
| 43 |
+
`--resample 40` reports line charts at ~40 evenly spaced, round x values shared by
|
| 44 |
+
all lines (one CSV row per x). Use it for smooth curves; without it a line is
|
| 45 |
+
reported at its markers, categories or corners.
|
| 46 |
+
|
| 47 |
This writes:
|
| 48 |
|
| 49 |
- `out/input.csv`: the data (layout below)
|
|
|
|
| 77 |
|
| 78 |
- First column `category` (categorical x axis) or `x` (numeric x axis).
|
| 79 |
- Then one column per series, named after the legend label (`series_1..n` if there is no legend), in legend order.
|
| 80 |
+
- Line/bar: one row per x position or category. Line charts give points at markers
|
| 81 |
+
if present (a marker hidden under another series' marker is recovered from the line's
|
| 82 |
+
corner), else at category positions, else at the line's corners (found on the
|
| 83 |
+
de-jittered trace, at least ~1% of the width apart), or on an even grid with
|
| 84 |
+
`--resample`. A line whose start/end is hidden under another line (e.g. curves
|
| 85 |
+
sharing an origin) is continued along that line and the warnings say so.
|
| 86 |
- Scatter: one row per point; only the owning series' column is filled.
|
| 87 |
- Stacked bars: headers end in ` (segment)`; values are segment heights, not cumulative tops.
|
| 88 |
|
| 89 |
## Web page
|
| 90 |
|
| 91 |
+
The page shows your chart and the chart re-plotted from the extracted numbers side by
|
| 92 |
+
side (same axis range and tick values, detected colours, hover for values), a CSV
|
| 93 |
+
download, the warnings, the detection overlay and diagnostics. Tick "even x spacing
|
| 94 |
+
for lines" for smooth curves.
|
| 95 |
+
|
| 96 |
```bash
|
| 97 |
uvicorn plotscribe.web:app --port 8000 # http://localhost:8000
|
| 98 |
# or
|
|
|
|
| 173 |
|
| 174 |
The CI target (median error < 1% on clean charts) is met for every chart type.
|
| 175 |
On clean charts the worst single bar value is 0.9% off (150 bar charts); for lines
|
| 176 |
+
median error is 0.13% (100 clean line charts).
|
| 177 |
|
| 178 |
## Known limitations
|
| 179 |
|
plotscribe/cli.py
CHANGED
|
@@ -20,11 +20,13 @@ def main(
|
|
| 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}")
|
|
|
|
| 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 |
+
resample: Optional[int] = typer.Option(
|
| 24 |
+
None, "--resample", help="Line charts: report N evenly spaced round x values shared by all lines."),
|
| 25 |
) -> None:
|
| 26 |
"""Extract data from IMAGE into OUT/<name>.csv and OUT/<name>.diagnostics.json."""
|
| 27 |
if chart_type is not None and chart_type not in ("line", "bar", "stacked_bar", "grouped_bar", "scatter"):
|
| 28 |
raise typer.BadParameter("--type must be line, bar, stacked_bar or scatter")
|
| 29 |
+
res = pipeline.run(image, ocr_backend=ocr, chart_type=chart_type, resample=resample)
|
| 30 |
paths = export.write_all(res, out, image.stem, debug=debug)
|
| 31 |
status = res.extra.get("status", "ok")
|
| 32 |
typer.echo(f"type={res.chart_type} ({res.chart_type_conf:.2f}) confidence={res.confidence:.2f} status={status}")
|
plotscribe/export.py
CHANGED
|
@@ -292,6 +292,7 @@ def plot_payload(res: "PipelineResult") -> dict[str, Any]:
|
|
| 292 |
if ax is not None and y_cal is not None and y_cal.kind != "categorical" and y_cal.n_inliers >= 2:
|
| 293 |
lo, hi = sorted(float(v) for v in y_cal.to_value(np.array([ax.plot_box.y1, ax.plot_box.y0])))
|
| 294 |
payload["y"]["range"] = [lo, hi]
|
|
|
|
| 295 |
first = table.columns[0]
|
| 296 |
categorical = first == "category"
|
| 297 |
if categorical:
|
|
@@ -303,6 +304,7 @@ def plot_payload(res: "PipelineResult") -> dict[str, Any]:
|
|
| 303 |
"log": bool(x_cal is not None and x_cal.kind == "log")}
|
| 304 |
if ax is not None and x_cal is not None and x_cal.kind != "categorical" and x_cal.n_inliers >= 2:
|
| 305 |
payload["x"]["range"] = sorted(float(v) for v in x_cal.to_value(np.array([ax.plot_box.x0, ax.plot_box.x1])))
|
|
|
|
| 306 |
xs = [float(v) for v in table[first]]
|
| 307 |
payload["y"]["pixels"] = any("[px]" in str(c) for c in table.columns[1:])
|
| 308 |
for k, col in enumerate(table.columns[1:]):
|
|
|
|
| 292 |
if ax is not None and y_cal is not None and y_cal.kind != "categorical" and y_cal.n_inliers >= 2:
|
| 293 |
lo, hi = sorted(float(v) for v in y_cal.to_value(np.array([ax.plot_box.y1, ax.plot_box.y0])))
|
| 294 |
payload["y"]["range"] = [lo, hi]
|
| 295 |
+
payload["y"]["ticks"] = sorted(float(v) for v in y_cal.tick_values)
|
| 296 |
first = table.columns[0]
|
| 297 |
categorical = first == "category"
|
| 298 |
if categorical:
|
|
|
|
| 304 |
"log": bool(x_cal is not None and x_cal.kind == "log")}
|
| 305 |
if ax is not None and x_cal is not None and x_cal.kind != "categorical" and x_cal.n_inliers >= 2:
|
| 306 |
payload["x"]["range"] = sorted(float(v) for v in x_cal.to_value(np.array([ax.plot_box.x0, ax.plot_box.x1])))
|
| 307 |
+
payload["x"]["ticks"] = sorted(float(v) for v in x_cal.tick_values)
|
| 308 |
xs = [float(v) for v in table[first]]
|
| 309 |
payload["y"]["pixels"] = any("[px]" in str(c) for c in table.columns[1:])
|
| 310 |
for k, col in enumerate(table.columns[1:]):
|
plotscribe/extract_line.py
CHANGED
|
@@ -16,6 +16,7 @@ from dataclasses import dataclass
|
|
| 16 |
|
| 17 |
import cv2
|
| 18 |
import numpy as np
|
|
|
|
| 19 |
|
| 20 |
|
| 21 |
@dataclass
|
|
@@ -23,7 +24,8 @@ 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]]:
|
|
@@ -74,17 +76,26 @@ def centreline(mask: np.ndarray, alpha: np.ndarray) -> Centreline | None:
|
|
| 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
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
| 81 |
a, b = runs_per_col[k][0]
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
| 85 |
else:
|
| 86 |
-
thick = float(np.median(lengths)) if lengths else 2.0
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
|
| 90 |
def separate_dots(mask: np.ndarray, alpha: np.ndarray) -> np.ndarray | None:
|
|
@@ -128,6 +139,10 @@ def find_markers(mask: np.ndarray, alpha: np.ndarray, thickness: float) -> np.nd
|
|
| 128 |
return np.zeros((0, 2))
|
| 129 |
areas = stats[1:, cv2.CC_STAT_AREA].astype(float)
|
| 130 |
med = float(np.median(areas))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
pts = []
|
| 132 |
for i in range(1, n):
|
| 133 |
a = stats[i, cv2.CC_STAT_AREA]
|
|
@@ -164,6 +179,32 @@ def rdp(x: np.ndarray, y: np.ndarray, eps: float) -> np.ndarray:
|
|
| 164 |
return np.flatnonzero(keep)
|
| 165 |
|
| 166 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
def _fit(x: np.ndarray, y: np.ndarray) -> tuple[float, float] | None:
|
| 168 |
if len(x) < 3 or np.ptp(x) == 0:
|
| 169 |
return None
|
|
@@ -217,28 +258,89 @@ def snap_to_ticks(vertices: np.ndarray, cl: Centreline, ticks: list[float]) -> n
|
|
| 217 |
return np.stack([tt, np.interp(tt, cl.x, cl.y)], 1)
|
| 218 |
|
| 219 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
def extract_line(mask: np.ndarray, alpha: np.ndarray, category_px: list[float] | None = None,
|
| 221 |
-
tick_px: list[float] | None = None
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
cl = centreline(mask, alpha)
|
| 224 |
if cl is None:
|
| 225 |
return np.zeros((0, 2)), "none", None
|
| 226 |
dots = separate_dots(mask, alpha)
|
| 227 |
if dots is not None:
|
| 228 |
return dots, "dots", cl
|
| 229 |
-
markers = find_markers(mask, alpha, cl.
|
| 230 |
span = cl.x[-1] - cl.x[0]
|
| 231 |
if len(markers) >= 2 and np.ptp(markers[:, 0]) >= 0.5 * span:
|
| 232 |
-
return markers, "markers", cl
|
| 233 |
if category_px:
|
| 234 |
cp = np.asarray([c for c in category_px if cl.x[0] - cl.thickness <= c <= cl.x[-1] + cl.thickness])
|
| 235 |
if len(cp):
|
| 236 |
return np.stack([cp, np.interp(cp, cl.x, cl.y)], 1), "categories", cl
|
| 237 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
if cl.observed.mean() < 0.7:
|
| 239 |
# Dotted/dashed: the centreline between pieces is interpolated and jagged.
|
| 240 |
eps *= 2.5
|
| 241 |
-
idx = rdp(cl.x,
|
|
|
|
| 242 |
verts = refine_vertices(cl, idx)
|
| 243 |
if tick_px:
|
| 244 |
snapped = snap_to_ticks(verts, cl, tick_px)
|
|
|
|
| 16 |
|
| 17 |
import cv2
|
| 18 |
import numpy as np
|
| 19 |
+
from scipy.signal import savgol_filter
|
| 20 |
|
| 21 |
|
| 22 |
@dataclass
|
|
|
|
| 24 |
x: np.ndarray # integer columns covered (first..last observed)
|
| 25 |
y: np.ndarray # sub-pixel row per column
|
| 26 |
observed: np.ndarray # bool, False where interpolated
|
| 27 |
+
thickness: float # stroke width from anti-aliasing coverage (sub-pixel)
|
| 28 |
+
run_thickness: float = 0.0 # stroke width in whole mask pixels (for morphology)
|
| 29 |
|
| 30 |
|
| 31 |
def _runs(col: np.ndarray) -> list[tuple[int, int]]:
|
|
|
|
| 76 |
return None
|
| 77 |
xs = np.arange(x0, x1, dtype=float) + 0.5
|
| 78 |
ys = np.interp(xs, xs[observed], ys[observed])
|
| 79 |
+
# Stroke thickness from every single-run column, corrected for slope (a sloped
|
| 80 |
+
# stroke's vertical run is t * sqrt(1 + slope^2)). A low percentile keeps markers
|
| 81 |
+
# and crossings - which only ever thicken a column - from inflating it.
|
| 82 |
+
slope = np.gradient(ys)
|
| 83 |
+
cov, runs_px = [], []
|
| 84 |
+
for k in range(n):
|
| 85 |
+
if observed[k] and len(runs_per_col[k]) == 1:
|
| 86 |
a, b = runs_per_col[k][0]
|
| 87 |
+
f = float(np.sqrt(1.0 + slope[k] ** 2))
|
| 88 |
+
cov.append(float(alpha[a:b, x0 + k].sum()) / f)
|
| 89 |
+
runs_px.append((b - a) / f)
|
| 90 |
+
if len(cov) >= 5:
|
| 91 |
+
thick, run_thick = float(np.percentile(cov, 30)), float(np.percentile(runs_px, 30))
|
| 92 |
else:
|
| 93 |
+
thick = run_thick = float(np.median(lengths)) if lengths else 2.0
|
| 94 |
+
# Whole-pixel runs can be inflated by markers sitting on flat stretches; never
|
| 95 |
+
# let them exceed the coverage width by more than the anti-aliased rim.
|
| 96 |
+
run_thick = min(max(run_thick, thick), thick + 1.5)
|
| 97 |
+
return Centreline(x=xs, y=ys, observed=observed, thickness=max(thick, 1.0),
|
| 98 |
+
run_thickness=max(run_thick, 1.0))
|
| 99 |
|
| 100 |
|
| 101 |
def separate_dots(mask: np.ndarray, alpha: np.ndarray) -> np.ndarray | None:
|
|
|
|
| 139 |
return np.zeros((0, 2))
|
| 140 |
areas = stats[1:, cv2.CC_STAT_AREA].astype(float)
|
| 141 |
med = float(np.median(areas))
|
| 142 |
+
# Corners of a thick line survive the opening as blobs barely larger than the
|
| 143 |
+
# kernel; real markers are clearly larger.
|
| 144 |
+
if med < 1.6 * np.pi * k * k / 4:
|
| 145 |
+
return np.zeros((0, 2))
|
| 146 |
pts = []
|
| 147 |
for i in range(1, n):
|
| 148 |
a = stats[i, cv2.CC_STAT_AREA]
|
|
|
|
| 179 |
return np.flatnonzero(keep)
|
| 180 |
|
| 181 |
|
| 182 |
+
def thin_vertices(x: np.ndarray, y: np.ndarray, idx: np.ndarray, min_gap: float) -> np.ndarray:
|
| 183 |
+
"""Remove vertices closer than ``min_gap`` columns, least significant first.
|
| 184 |
+
|
| 185 |
+
Significance is the triangle area a vertex spans with its neighbours
|
| 186 |
+
(Visvalingam), so a real corner survives while its noisy neighbours go.
|
| 187 |
+
"""
|
| 188 |
+
keep = list(idx)
|
| 189 |
+
while len(keep) > 2:
|
| 190 |
+
gaps = np.diff(x[keep])
|
| 191 |
+
if gaps.min() >= min_gap:
|
| 192 |
+
break
|
| 193 |
+
# Candidate interior vertices adjacent to a too-short gap.
|
| 194 |
+
cands = set()
|
| 195 |
+
for g in np.flatnonzero(gaps < min_gap):
|
| 196 |
+
cands.update(k for k in (g, g + 1) if 0 < k < len(keep) - 1)
|
| 197 |
+
if not cands:
|
| 198 |
+
break
|
| 199 |
+
|
| 200 |
+
def area(k: int) -> float:
|
| 201 |
+
a, b, c = keep[k - 1], keep[k], keep[k + 1]
|
| 202 |
+
return abs((x[b] - x[a]) * (y[c] - y[a]) - (x[c] - x[a]) * (y[b] - y[a]))
|
| 203 |
+
|
| 204 |
+
del keep[min(cands, key=area)]
|
| 205 |
+
return np.asarray(keep)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
def _fit(x: np.ndarray, y: np.ndarray) -> tuple[float, float] | None:
|
| 209 |
if len(x) < 3 or np.ptp(x) == 0:
|
| 210 |
return None
|
|
|
|
| 258 |
return np.stack([tt, np.interp(tt, cl.x, cl.y)], 1)
|
| 259 |
|
| 260 |
|
| 261 |
+
def smoothed(cl: Centreline) -> np.ndarray:
|
| 262 |
+
"""Centreline with column-to-column jitter removed (Savitzky-Golay, cubic: keeps peaks)."""
|
| 263 |
+
n = len(cl.y)
|
| 264 |
+
win = int(max(7, round(4 * cl.thickness))) | 1
|
| 265 |
+
if n <= win:
|
| 266 |
+
return cl.y.copy()
|
| 267 |
+
return savgol_filter(cl.y, win, 3)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def sample_curve(cl: Centreline, grid_px: np.ndarray) -> np.ndarray:
|
| 271 |
+
"""De-jittered curve sampled at the grid columns inside its extent."""
|
| 272 |
+
ys = smoothed(cl)
|
| 273 |
+
g = grid_px[(grid_px >= cl.x[0] - 0.5) & (grid_px <= cl.x[-1] + 0.5)]
|
| 274 |
+
return np.stack([g, np.interp(g, cl.x, ys)], 1) if len(g) else np.zeros((0, 2))
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def fill_marker_gaps(markers: np.ndarray, cl: Centreline) -> np.ndarray:
|
| 278 |
+
"""Add line corners where a marker is missing (hidden under another series' marker).
|
| 279 |
+
|
| 280 |
+
A gap between consecutive markers much wider than their usual spacing still has
|
| 281 |
+
the line drawn across it; its corners there are the hidden data points.
|
| 282 |
+
"""
|
| 283 |
+
if len(markers) < 3:
|
| 284 |
+
return markers
|
| 285 |
+
gaps = np.diff(markers[:, 0])
|
| 286 |
+
typical = float(np.median(gaps))
|
| 287 |
+
extra = []
|
| 288 |
+
for (xa, _), (xb, _), g in zip(markers[:-1], markers[1:], gaps):
|
| 289 |
+
if g < 1.6 * typical:
|
| 290 |
+
continue
|
| 291 |
+
sel = (cl.x > xa) & (cl.x < xb)
|
| 292 |
+
if sel.sum() < 3:
|
| 293 |
+
continue
|
| 294 |
+
idx = np.flatnonzero(sel)
|
| 295 |
+
seg = rdp(cl.x[idx], cl.y[idx], float(np.clip(0.5 * cl.thickness, 0.6, 2.0)))
|
| 296 |
+
inner = idx[seg[1:-1]]
|
| 297 |
+
for k in inner:
|
| 298 |
+
# Only corners clear of the neighbouring markers.
|
| 299 |
+
if cl.x[k] - xa > 0.4 * typical and xb - cl.x[k] > 0.4 * typical:
|
| 300 |
+
extra.append((cl.x[k], cl.y[k]))
|
| 301 |
+
if not extra:
|
| 302 |
+
return markers
|
| 303 |
+
return np.asarray(sorted([tuple(m) for m in markers] + extra))
|
| 304 |
+
|
| 305 |
+
|
| 306 |
def extract_line(mask: np.ndarray, alpha: np.ndarray, category_px: list[float] | None = None,
|
| 307 |
+
tick_px: list[float] | None = None, grid_px: np.ndarray | None = None
|
| 308 |
+
) -> tuple[np.ndarray, str, Centreline | None]:
|
| 309 |
+
"""Data points (x, y) in pixels and the method used.
|
| 310 |
+
|
| 311 |
+
Order: separate dots, markers, category positions, a regular x grid if requested
|
| 312 |
+
(``grid_px``), values at ticks, else polyline corners.
|
| 313 |
+
"""
|
| 314 |
cl = centreline(mask, alpha)
|
| 315 |
if cl is None:
|
| 316 |
return np.zeros((0, 2)), "none", None
|
| 317 |
dots = separate_dots(mask, alpha)
|
| 318 |
if dots is not None:
|
| 319 |
return dots, "dots", cl
|
| 320 |
+
markers = find_markers(mask, alpha, cl.run_thickness)
|
| 321 |
span = cl.x[-1] - cl.x[0]
|
| 322 |
if len(markers) >= 2 and np.ptp(markers[:, 0]) >= 0.5 * span:
|
| 323 |
+
return fill_marker_gaps(markers, cl), "markers", cl
|
| 324 |
if category_px:
|
| 325 |
cp = np.asarray([c for c in category_px if cl.x[0] - cl.thickness <= c <= cl.x[-1] + cl.thickness])
|
| 326 |
if len(cp):
|
| 327 |
return np.stack([cp, np.interp(cp, cl.x, cl.y)], 1), "categories", cl
|
| 328 |
+
if grid_px is not None and len(grid_px) >= 2:
|
| 329 |
+
pts = sample_curve(cl, grid_px)
|
| 330 |
+
if len(pts) >= 2:
|
| 331 |
+
return pts, "sampled", cl
|
| 332 |
+
# Corners are found on the de-jittered centreline, with a tolerance above the
|
| 333 |
+
# measured jitter, so noise does not create clusters of spurious vertices.
|
| 334 |
+
ys = smoothed(cl)
|
| 335 |
+
r = cl.y - ys
|
| 336 |
+
# Robust jitter estimate: genuine sharp corners are few, large residuals.
|
| 337 |
+
noise = float(1.4826 * np.median(np.abs(r - np.median(r))))
|
| 338 |
+
eps = float(np.clip(max(0.5 * cl.thickness, 2.5 * noise), 0.6, 4.0))
|
| 339 |
if cl.observed.mean() < 0.7:
|
| 340 |
# Dotted/dashed: the centreline between pieces is interpolated and jagged.
|
| 341 |
eps *= 2.5
|
| 342 |
+
idx = rdp(cl.x, ys, eps)
|
| 343 |
+
idx = thin_vertices(cl.x, ys, idx, max(3.0 * cl.thickness, 0.012 * (cl.x[-1] - cl.x[0])))
|
| 344 |
verts = refine_vertices(cl, idx)
|
| 345 |
if tick_px:
|
| 346 |
snapped = snap_to_ticks(verts, cl, tick_px)
|
plotscribe/legend.py
CHANGED
|
@@ -151,6 +151,7 @@ def detect_legend(rgb: np.ndarray, lab: np.ndarray, ink: np.ndarray, bg: np.ndar
|
|
| 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:]:
|
|
@@ -214,3 +215,30 @@ def legend_colour_distance(leg: Legend, lab: np.ndarray) -> np.ndarray:
|
|
| 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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
repair_label_pattern(entries)
|
| 155 |
leg.entries = entries
|
| 156 |
union = entries[0].swatch.union(entries[0].text_box)
|
| 157 |
for e in entries[1:]:
|
|
|
|
| 215 |
sw = np.stack([e.lab for e in leg.entries])
|
| 216 |
return np.linalg.norm(sw[:, None, :] - np.asarray(lab)[None, :, :], axis=2)
|
| 217 |
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
_DIGIT_LOOKALIKE = str.maketrans({"I": "1", "l": "1", "|": "1", "i": "1", "O": "0", "o": "0", "S": "5",
|
| 221 |
+
"Z": "2", "B": "8", "g": "9"})
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def repair_label_pattern(entries: list[LegendEntry]) -> None:
|
| 225 |
+
"""Fix OCR letter/digit confusions using the other labels' pattern.
|
| 226 |
+
|
| 227 |
+
If most labels are "<number><unit>" (1mA, 2mA, ...), a label like "ImA" whose
|
| 228 |
+
leading characters read as digits under the usual confusions is corrected.
|
| 229 |
+
"""
|
| 230 |
+
import re
|
| 231 |
+
|
| 232 |
+
pat = re.compile(r"^([0-9][0-9.,]*)(.*)$")
|
| 233 |
+
m = [pat.match(e.label) for e in entries]
|
| 234 |
+
units = [x.group(2) for x in m if x]
|
| 235 |
+
if len(units) < 2 or len(units) < 0.6 * len(entries):
|
| 236 |
+
return
|
| 237 |
+
common = max(set(units), key=units.count)
|
| 238 |
+
for e, mm in zip(entries, m):
|
| 239 |
+
if mm or not e.label.endswith(common) or not common:
|
| 240 |
+
continue
|
| 241 |
+
head = e.label[: len(e.label) - len(common)]
|
| 242 |
+
fixed = head.translate(_DIGIT_LOOKALIKE)
|
| 243 |
+
if head and fixed.replace(".", "").isdigit():
|
| 244 |
+
e.label = fixed + common
|
plotscribe/pipeline.py
CHANGED
|
@@ -58,10 +58,21 @@ class PipelineResult:
|
|
| 58 |
_ROTATE = {90: cv2.ROTATE_90_CLOCKWISE, -90: cv2.ROTATE_90_COUNTERCLOCKWISE}
|
| 59 |
|
| 60 |
|
|
|
|
|
|
|
|
|
|
| 61 |
def _crop(rgb: np.ndarray, b: BBox, char_h: float, rot: int = 0) -> np.ndarray:
|
| 62 |
-
"""OCR-ready crop of ``b``; ``rot`` (90 / -90) turns vertical text upright first.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
h, w = rgb.shape[:2]
|
| 64 |
r = b.expand(max(2.0, 0.25 * char_h)).clip(w, h)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
rs, cs = r.slices()
|
| 66 |
crop = rgb[rs, cs]
|
| 67 |
if rot:
|
|
@@ -336,13 +347,19 @@ def merge_labels_per_tick(rgb: np.ndarray, labels: list[TextBox], ticks: list[fl
|
|
| 336 |
return out
|
| 337 |
|
| 338 |
|
| 339 |
-
def run(path: str | Path, ocr_backend: str = "tesseract", chart_type: str | None = None
|
| 340 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
ocr = get_backend(ocr_backend)
|
| 342 |
rgb = load_rgb(path)
|
| 343 |
pre = preprocess(rgb)
|
| 344 |
res = PipelineResult(source=str(path), pre=pre)
|
| 345 |
res.extra["ocr_backend"] = ocr_backend
|
|
|
|
| 346 |
res.stage_conf["preprocess"] = pre.confidence
|
| 347 |
res.warn("preprocess", pre.warnings)
|
| 348 |
|
|
@@ -353,13 +370,21 @@ def run(path: str | Path, ocr_backend: str = "tesseract", chart_type: str | None
|
|
| 353 |
|
| 354 |
yb, ych = axes_mod.y_label_boxes(ink, ax)
|
| 355 |
xb, xch, x_rotated = axes_mod.x_label_boxes(ink, ax, ych)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
xrot = choose_rotation(pre.rgb, xb, xch, ocr) if x_rotated and xb else 0
|
| 357 |
res.extra["x_label_rotation"] = xrot
|
| 358 |
if xrot:
|
| 359 |
res.warn("axes", f"x tick labels are rotated {abs(xrot)} degrees")
|
|
|
|
| 360 |
res.x_labels = merge_labels_per_tick(pre.rgb, read_labels(pre.rgb, ink, xb, xch, ocr, xrot), ax.x_ticks,
|
| 361 |
"x", xch, ocr, xrot)
|
|
|
|
| 362 |
res.y_labels = merge_labels_per_tick(pre.rgb, read_labels(pre.rgb, ink, yb, ych, ocr), ax.y_ticks, "y", ych, ocr)
|
|
|
|
| 363 |
for name, labels, ch in (("x", res.x_labels, xch), ("y", res.y_labels, ych)):
|
| 364 |
if not is_numeric_axis([lb.value for lb in labels]):
|
| 365 |
continue
|
|
@@ -372,10 +397,17 @@ def run(path: str | Path, ocr_backend: str = "tesseract", chart_type: str | None
|
|
| 372 |
res.x_cal = calibrate_axis("x", res.x_labels, ax.x_ticks)
|
| 373 |
res.y_cal = calibrate_axis("y", res.y_labels, ax.y_ticks)
|
| 374 |
b = ax.plot_box
|
| 375 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
res.y_cal.confidence *= 0.4
|
| 377 |
res.y_cal.warnings.append("y: tick labels touch the plot area; they may be clipped (plot area uncertain)")
|
| 378 |
-
if any(lb.bbox.y0
|
|
|
|
| 379 |
res.x_cal.confidence *= 0.4
|
| 380 |
res.x_cal.warnings.append("x: tick labels touch the plot area; they may be clipped (plot area uncertain)")
|
| 381 |
for name, cal in (("x", res.x_cal), ("y", res.y_cal)):
|
|
@@ -512,12 +544,19 @@ def extract(res: PipelineResult, series: list[Series]) -> None:
|
|
| 512 |
live.append(s)
|
| 513 |
if ctype == "line":
|
| 514 |
methods = {}
|
|
|
|
| 515 |
num_ticks = res.axes.x_ticks if (res.x_cal is not None and res.x_cal.kind != "categorical") else None
|
|
|
|
|
|
|
| 516 |
for s in live:
|
| 517 |
-
pts, method,
|
|
|
|
|
|
|
| 518 |
s.points_px = pts
|
| 519 |
methods[s.name] = method
|
| 520 |
res.extra.setdefault("diagnostics_extra", {})["point_method"] = methods
|
|
|
|
|
|
|
| 521 |
elif ctype in ("bar", "grouped_bar", "stacked_bar"):
|
| 522 |
extract_bars(res, series, alpha, labels)
|
| 523 |
elif ctype == "scatter":
|
|
@@ -573,6 +612,97 @@ def recategorize_from_bars(res: PipelineResult, bars: list[bar_mod.Bar]) -> None
|
|
| 573 |
x.confidence *= 0.8
|
| 574 |
|
| 575 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 576 |
def zero_line_px(res: PipelineResult) -> float:
|
| 577 |
"""Pixel row of y = 0 if it lies on a linear y axis, else the plot bottom."""
|
| 578 |
ax = res.axes
|
|
|
|
| 58 |
_ROTATE = {90: cv2.ROTATE_90_CLOCKWISE, -90: cv2.ROTATE_90_COUNTERCLOCKWISE}
|
| 59 |
|
| 60 |
|
| 61 |
+
_CLIP: dict[str, BBox | None] = {"box": None}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
def _crop(rgb: np.ndarray, b: BBox, char_h: float, rot: int = 0) -> np.ndarray:
|
| 65 |
+
"""OCR-ready crop of ``b``; ``rot`` (90 / -90) turns vertical text upright first.
|
| 66 |
+
|
| 67 |
+
The padding never reaches past the axis lines (``_CLIP``): an axis line beside a
|
| 68 |
+
label would otherwise be read as an extra "1".
|
| 69 |
+
"""
|
| 70 |
h, w = rgb.shape[:2]
|
| 71 |
r = b.expand(max(2.0, 0.25 * char_h)).clip(w, h)
|
| 72 |
+
c = _CLIP["box"]
|
| 73 |
+
if c is not None:
|
| 74 |
+
r = BBox(max(r.x0, min(c.x0, b.x0)), max(r.y0, min(c.y0, b.y0)),
|
| 75 |
+
min(r.x1, max(c.x1, b.x1)), min(r.y1, max(c.y1, b.y1)))
|
| 76 |
rs, cs = r.slices()
|
| 77 |
crop = rgb[rs, cs]
|
| 78 |
if rot:
|
|
|
|
| 347 |
return out
|
| 348 |
|
| 349 |
|
| 350 |
+
def run(path: str | Path, ocr_backend: str = "tesseract", chart_type: str | None = None,
|
| 351 |
+
resample: int | None = None) -> PipelineResult:
|
| 352 |
+
"""Run the full pipeline on an image file.
|
| 353 |
+
|
| 354 |
+
``resample``: report line charts at ~this many evenly spaced, round x values
|
| 355 |
+
(shared by all series) instead of at their corners. Best for smooth curves.
|
| 356 |
+
"""
|
| 357 |
ocr = get_backend(ocr_backend)
|
| 358 |
rgb = load_rgb(path)
|
| 359 |
pre = preprocess(rgb)
|
| 360 |
res = PipelineResult(source=str(path), pre=pre)
|
| 361 |
res.extra["ocr_backend"] = ocr_backend
|
| 362 |
+
res.extra["resample"] = resample
|
| 363 |
res.stage_conf["preprocess"] = pre.confidence
|
| 364 |
res.warn("preprocess", pre.warnings)
|
| 365 |
|
|
|
|
| 370 |
|
| 371 |
yb, ych = axes_mod.y_label_boxes(ink, ax)
|
| 372 |
xb, xch, x_rotated = axes_mod.x_label_boxes(ink, ax, ych)
|
| 373 |
+
# Label crops stay outside the axis lines.
|
| 374 |
+
half = ax.line_thickness / 2 + 1
|
| 375 |
+
h_img, w_img = pre.rgb.shape[:2]
|
| 376 |
+
y_clip = BBox(0.0, 0.0, ax.plot_box.x0 - half, float(h_img))
|
| 377 |
+
x_clip = BBox(0.0, ax.plot_box.y1 + half, float(w_img), float(h_img))
|
| 378 |
xrot = choose_rotation(pre.rgb, xb, xch, ocr) if x_rotated and xb else 0
|
| 379 |
res.extra["x_label_rotation"] = xrot
|
| 380 |
if xrot:
|
| 381 |
res.warn("axes", f"x tick labels are rotated {abs(xrot)} degrees")
|
| 382 |
+
_CLIP["box"] = x_clip
|
| 383 |
res.x_labels = merge_labels_per_tick(pre.rgb, read_labels(pre.rgb, ink, xb, xch, ocr, xrot), ax.x_ticks,
|
| 384 |
"x", xch, ocr, xrot)
|
| 385 |
+
_CLIP["box"] = y_clip
|
| 386 |
res.y_labels = merge_labels_per_tick(pre.rgb, read_labels(pre.rgb, ink, yb, ych, ocr), ax.y_ticks, "y", ych, ocr)
|
| 387 |
+
_CLIP["box"] = None
|
| 388 |
for name, labels, ch in (("x", res.x_labels, xch), ("y", res.y_labels, ych)):
|
| 389 |
if not is_numeric_axis([lb.value for lb in labels]):
|
| 390 |
continue
|
|
|
|
| 397 |
res.x_cal = calibrate_axis("x", res.x_labels, ax.x_ticks)
|
| 398 |
res.y_cal = calibrate_axis("y", res.y_labels, ax.y_ticks)
|
| 399 |
b = ax.plot_box
|
| 400 |
+
# A label (almost) touching the plot edge means the plot area is probably wrong
|
| 401 |
+
# and the label may be merged with or cut by it. Normal label padding is at
|
| 402 |
+
# least ~0.1 glyph heights.
|
| 403 |
+
def too_close(gap: float, lb: TextBox) -> bool:
|
| 404 |
+
return gap < max(2.0, 0.1 * lb.bbox.h)
|
| 405 |
+
|
| 406 |
+
if any(too_close(b.x0 - lb.bbox.x1, lb) for lb in res.y_labels) and res.y_cal is not None:
|
| 407 |
res.y_cal.confidence *= 0.4
|
| 408 |
res.y_cal.warnings.append("y: tick labels touch the plot area; they may be clipped (plot area uncertain)")
|
| 409 |
+
if any(too_close(lb.bbox.y0 - b.y1, lb) for lb in res.x_labels if not res.extra.get("x_label_rotation")) \
|
| 410 |
+
and res.x_cal is not None:
|
| 411 |
res.x_cal.confidence *= 0.4
|
| 412 |
res.x_cal.warnings.append("x: tick labels touch the plot area; they may be clipped (plot area uncertain)")
|
| 413 |
for name, cal in (("x", res.x_cal), ("y", res.y_cal)):
|
|
|
|
| 544 |
live.append(s)
|
| 545 |
if ctype == "line":
|
| 546 |
methods = {}
|
| 547 |
+
cls = {}
|
| 548 |
num_ticks = res.axes.x_ticks if (res.x_cal is not None and res.x_cal.kind != "categorical") else None
|
| 549 |
+
n_grid = res.extra.get("resample")
|
| 550 |
+
grid = sample_grid(res, [s.mask for s in live], n_grid) if n_grid else None
|
| 551 |
for s in live:
|
| 552 |
+
pts, method, cl = extract_line(s.mask, alpha, cat_px, num_ticks, grid)
|
| 553 |
+
if cl is not None:
|
| 554 |
+
cls[s.name] = cl
|
| 555 |
s.points_px = pts
|
| 556 |
methods[s.name] = method
|
| 557 |
res.extra.setdefault("diagnostics_extra", {})["point_method"] = methods
|
| 558 |
+
if cat_px is None:
|
| 559 |
+
fill_occluded_ends(res, live, cls)
|
| 560 |
elif ctype in ("bar", "grouped_bar", "stacked_bar"):
|
| 561 |
extract_bars(res, series, alpha, labels)
|
| 562 |
elif ctype == "scatter":
|
|
|
|
| 612 |
x.confidence *= 0.8
|
| 613 |
|
| 614 |
|
| 615 |
+
SAMPLES = 40 # default number of x positions when resampling curves on an even grid
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def nice_step(raw: float) -> float:
|
| 619 |
+
mag = 10 ** np.floor(np.log10(raw))
|
| 620 |
+
return float(next(m * mag for m in (1, 2, 2.5, 5, 10) if m * mag >= raw))
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
def sample_grid(res: PipelineResult, masks: list[np.ndarray], samples: int = SAMPLES) -> np.ndarray | None:
|
| 624 |
+
"""Pixel columns of a shared, round-valued x grid (e.g. 0, 0.5, ... 20) over the
|
| 625 |
+
span covered by the lines, so all series share their rows."""
|
| 626 |
+
x = res.x_cal
|
| 627 |
+
if x is None or x.kind == "categorical" or x.n_inliers < 2 or not masks:
|
| 628 |
+
return None
|
| 629 |
+
cols = np.flatnonzero(np.any(np.stack([m.any(axis=0) for m in masks]), axis=0))
|
| 630 |
+
if cols.size < 2:
|
| 631 |
+
return None
|
| 632 |
+
lo_px, hi_px = float(cols[0]), float(cols[-1] + 1)
|
| 633 |
+
if x.kind == "log":
|
| 634 |
+
return np.linspace(lo_px, hi_px, samples + 1)
|
| 635 |
+
lo, hi = sorted(float(v) for v in x.to_value(np.array([lo_px, hi_px])))
|
| 636 |
+
step = nice_step((hi - lo) / samples)
|
| 637 |
+
vals = np.arange(np.ceil(lo / step - 1e-9) * step, hi + 1e-9 * step, step)
|
| 638 |
+
return np.sort(np.asarray(x.to_px(vals), float))
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
def fill_occluded_ends(res: PipelineResult, series: list[Series], cls: dict) -> None:
|
| 642 |
+
"""Extend lines whose visible start/end lies on another line that continues further.
|
| 643 |
+
|
| 644 |
+
Where several lines coincide (e.g. all starting at the origin) only the one drawn
|
| 645 |
+
last is visible. A line whose visible part *begins on top of* another line must
|
| 646 |
+
continue underneath it, so the hidden stretch takes that line's values. Filled
|
| 647 |
+
stretches are reported in the warnings.
|
| 648 |
+
"""
|
| 649 |
+
if len(series) < 2:
|
| 650 |
+
return
|
| 651 |
+
x_cal = res.x_cal
|
| 652 |
+
done = set()
|
| 653 |
+
for _ in range(len(series)): # repeat: a line may be hidden under an extended one
|
| 654 |
+
changed = False
|
| 655 |
+
for a in series:
|
| 656 |
+
ca = cls.get(a.name)
|
| 657 |
+
if ca is None or len(a.points_px) == 0:
|
| 658 |
+
continue
|
| 659 |
+
for side in ("start", "end"):
|
| 660 |
+
if (a.name, side) in done:
|
| 661 |
+
continue
|
| 662 |
+
xa = ca.x[0] if side == "start" else ca.x[-1]
|
| 663 |
+
ya = float(ca.y[0] if side == "start" else ca.y[-1])
|
| 664 |
+
best = None
|
| 665 |
+
for b in series:
|
| 666 |
+
cb = cls.get(b.name)
|
| 667 |
+
if b is a or cb is None or len(b.points_px) == 0:
|
| 668 |
+
continue
|
| 669 |
+
pb = np.asarray(b.points_px)
|
| 670 |
+
reach = pb[:, 0].min() if side == "start" else pb[:, 0].max()
|
| 671 |
+
if (side == "start" and reach >= xa - 2 * ca.thickness) or \
|
| 672 |
+
(side == "end" and reach <= xa + 2 * ca.thickness):
|
| 673 |
+
continue
|
| 674 |
+
# Compare against the other line's full trace where it exists (its
|
| 675 |
+
# points are sparse); where A emerges from under B only A's edge is
|
| 676 |
+
# visible, which shifts A's centre by up to a stroke width.
|
| 677 |
+
if cb.x[0] <= xa <= cb.x[-1]:
|
| 678 |
+
yb = float(np.interp(xa, cb.x, cb.y))
|
| 679 |
+
else:
|
| 680 |
+
yb = float(np.interp(xa, pb[:, 0], pb[:, 1]))
|
| 681 |
+
if abs(yb - ya) <= 2.0 * max(ca.thickness, cb.thickness):
|
| 682 |
+
if best is None or abs(yb - ya) < best[0]:
|
| 683 |
+
best = (abs(yb - ya), b, pb)
|
| 684 |
+
if best is None:
|
| 685 |
+
continue
|
| 686 |
+
_, b, pb = best
|
| 687 |
+
hidden = pb[pb[:, 0] < xa - 0.5] if side == "start" else pb[pb[:, 0] > xa + 0.5]
|
| 688 |
+
if not len(hidden):
|
| 689 |
+
continue
|
| 690 |
+
a.points_px = np.asarray(sorted([tuple(p) for p in a.points_px] + [tuple(p) for p in hidden]))
|
| 691 |
+
done.add((a.name, side))
|
| 692 |
+
changed = True
|
| 693 |
+
lo, hi = (hidden[0, 0], xa) if side == "start" else (xa, hidden[-1, 0])
|
| 694 |
+
if x_cal is not None and x_cal.kind != "categorical":
|
| 695 |
+
lo, hi = (float(v) for v in x_cal.to_value(np.array([lo, hi])))
|
| 696 |
+
span = f"x {min(lo, hi):.3g} to {max(lo, hi):.3g}"
|
| 697 |
+
else:
|
| 698 |
+
span = f"pixels {lo:.0f} to {hi:.0f}"
|
| 699 |
+
msg = f"'{a.name}' is hidden under '{b.name}' for {span}; values there are taken from '{b.name}'"
|
| 700 |
+
a.warnings.append(msg)
|
| 701 |
+
res.warn("extract", msg)
|
| 702 |
+
if not changed:
|
| 703 |
+
break
|
| 704 |
+
|
| 705 |
+
|
| 706 |
def zero_line_px(res: PipelineResult) -> float:
|
| 707 |
"""Pixel row of y = 0 if it lies on a linear y axis, else the plot bottom."""
|
| 708 |
ax = res.axes
|
plotscribe/web.py
CHANGED
|
@@ -53,6 +53,8 @@ _PAGE = r"""<!doctype html>
|
|
| 53 |
<input type="file" name="file" id="file" accept="image/png,image/jpeg" required>
|
| 54 |
<select name="chart_type"><option value="">auto-detect type</option><option>line</option>
|
| 55 |
<option>bar</option><option>stacked_bar</option><option>scatter</option></select>
|
|
|
|
|
|
|
| 56 |
<button>Extract</button>
|
| 57 |
</form>
|
| 58 |
<div id="out"></div>
|
|
@@ -81,6 +83,19 @@ function niceTicks(lo, hi, n = 5) {
|
|
| 81 |
return t;
|
| 82 |
}
|
| 83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
function drawChart(host, plot) {
|
| 85 |
host.innerHTML = "";
|
| 86 |
const series = plot.series.filter(s => s.points.length);
|
|
@@ -135,13 +150,16 @@ function drawChart(host, plot) {
|
|
| 135 |
if (plot.x.range) { xlo = Math.min(xlo, xt(plot.x.range[0])); xhi = Math.max(xhi, xt(plot.x.range[1])); }
|
| 136 |
else { const pad = (xhi - xlo || 1) * 0.04; xlo -= pad; xhi += pad; }
|
| 137 |
X = v => M.l + (xt(v) - xlo) / (xhi - xlo) * pw;
|
| 138 |
-
|
|
|
|
|
|
|
| 139 |
if (xlog) for (let e = Math.ceil(xlo); e <= Math.floor(xhi); e++) xTicks.push([10 ** e, "1e" + e]);
|
| 140 |
}
|
| 141 |
|
| 142 |
// grid + y ticks
|
| 143 |
const yTicks = [];
|
| 144 |
if (ylog) for (let e = Math.ceil(ylo); e <= Math.floor(yhi); e++) yTicks.push(10 ** e);
|
|
|
|
| 145 |
else yTicks.push(...niceTicks(ylo, yhi, 5));
|
| 146 |
for (const t of yTicks) {
|
| 147 |
const y = Y(t);
|
|
@@ -233,8 +251,7 @@ f.onsubmit = async e => {
|
|
| 233 |
(d.warnings.length ? `<ul class="warn">${d.warnings.map(w => `<li>${esc(w)}</li>`).join("")}</ul>` : "") +
|
| 234 |
`<div class="pair"><div class="card"><h2>Your chart</h2><img id="orig" alt="uploaded chart"></div>` +
|
| 235 |
`<div class="card"><h2>Re-plotted from the extracted data</h2><div id="replot"></div></div></div>` +
|
| 236 |
-
`<p><a download="data.csv" href="${csvUrl}">Download CSV</a></p>` +
|
| 237 |
-
`<div class="scroll"><pre>${esc(d.csv)}</pre></div>` +
|
| 238 |
`<details><summary>Debug overlay (what was detected)</summary><img style="max-width:100%" src="data:image/png;base64,${d.debug_png}"></details>` +
|
| 239 |
`<details><summary>Diagnostics</summary><div class="scroll"><pre>${esc(JSON.stringify(d.diagnostics, null, 2))}</pre></div></details>`;
|
| 240 |
document.getElementById("orig").src = URL.createObjectURL(file);
|
|
@@ -254,7 +271,8 @@ def healthz() -> dict[str, str]:
|
|
| 254 |
|
| 255 |
|
| 256 |
@app.post("/api/extract")
|
| 257 |
-
async def extract(file: UploadFile = File(...), chart_type: str = Form("")
|
|
|
|
| 258 |
"""Run the pipeline on an uploaded image; returns CSV text, diagnostics and overlay PNG."""
|
| 259 |
data = await file.read()
|
| 260 |
if len(data) > MAX_BYTES:
|
|
@@ -272,7 +290,8 @@ async def extract(file: UploadFile = File(...), chart_type: str = Form("")) -> J
|
|
| 272 |
raise HTTPException(400, "could not decode image")
|
| 273 |
if img.shape[0] * img.shape[1] > MAX_PIXELS:
|
| 274 |
raise HTTPException(413, "image has too many pixels")
|
| 275 |
-
res = pipeline.run(path, chart_type=chart_type or None
|
|
|
|
| 276 |
csv = res.table.to_csv(index=False) if res.table is not None else ""
|
| 277 |
ok, png = cv2.imencode(".png", cv2.cvtColor(export.debug_overlay(res), cv2.COLOR_RGB2BGR))
|
| 278 |
diag = json.loads(json.dumps(export.diagnostics(res), default=export._json_default))
|
|
@@ -281,4 +300,5 @@ async def extract(file: UploadFile = File(...), chart_type: str = Form("")) -> J
|
|
| 281 |
"status": res.extra.get("status", "ok"), "chart_type": res.chart_type,
|
| 282 |
"confidence": res.confidence, "warnings": res.warnings, "csv": csv, "diagnostics": diag,
|
| 283 |
"debug_png": base64.b64encode(png.tobytes()).decode() if ok else "", "plot": plot,
|
|
|
|
| 284 |
})
|
|
|
|
| 53 |
<input type="file" name="file" id="file" accept="image/png,image/jpeg" required>
|
| 54 |
<select name="chart_type"><option value="">auto-detect type</option><option>line</option>
|
| 55 |
<option>bar</option><option>stacked_bar</option><option>scatter</option></select>
|
| 56 |
+
<label title="Report line charts at evenly spaced round x values shared by all lines (best for smooth curves)">
|
| 57 |
+
<input type="checkbox" name="resample" value="40"> even x spacing for lines</label>
|
| 58 |
<button>Extract</button>
|
| 59 |
</form>
|
| 60 |
<div id="out"></div>
|
|
|
|
| 83 |
return t;
|
| 84 |
}
|
| 85 |
|
| 86 |
+
// Extend an evenly spaced tick list (the chart's own labels) across [lo, hi].
|
| 87 |
+
function fillTicks(ticks, lo, hi) {
|
| 88 |
+
const t = [...new Set(ticks)].sort((a, b) => a - b);
|
| 89 |
+
const gaps = t.slice(1).map((v, i) => v - t[i]);
|
| 90 |
+
const step = Math.min(...gaps);
|
| 91 |
+
// Some labels may have been rejected: every gap must be a whole number of steps.
|
| 92 |
+
if (!(step > 0) || gaps.some(g => Math.abs(g / step - Math.round(g / step)) > 0.05)) return niceTicks(lo, hi, 5);
|
| 93 |
+
const out = [];
|
| 94 |
+
for (let v = t[0] + Math.ceil((lo - t[0]) / step - 1e-9) * step; v <= hi + step * 1e-9; v += step)
|
| 95 |
+
out.push(+v.toPrecision(12));
|
| 96 |
+
return out;
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
function drawChart(host, plot) {
|
| 100 |
host.innerHTML = "";
|
| 101 |
const series = plot.series.filter(s => s.points.length);
|
|
|
|
| 150 |
if (plot.x.range) { xlo = Math.min(xlo, xt(plot.x.range[0])); xhi = Math.max(xhi, xt(plot.x.range[1])); }
|
| 151 |
else { const pad = (xhi - xlo || 1) * 0.04; xlo -= pad; xhi += pad; }
|
| 152 |
X = v => M.l + (xt(v) - xlo) / (xhi - xlo) * pw;
|
| 153 |
+
// The original chart's own tick values when known (gridlines line up), else nice ticks.
|
| 154 |
+
const own = (plot.x.ticks || []).filter(v => !xlog || v > 0);
|
| 155 |
+
xTicks = xlog ? [] : (own.length >= 3 ? fillTicks(own, xlo, xhi) : niceTicks(xlo, xhi, 6)).map(v => [v, fmt(v)]);
|
| 156 |
if (xlog) for (let e = Math.ceil(xlo); e <= Math.floor(xhi); e++) xTicks.push([10 ** e, "1e" + e]);
|
| 157 |
}
|
| 158 |
|
| 159 |
// grid + y ticks
|
| 160 |
const yTicks = [];
|
| 161 |
if (ylog) for (let e = Math.ceil(ylo); e <= Math.floor(yhi); e++) yTicks.push(10 ** e);
|
| 162 |
+
else if ((plot.y.ticks || []).length >= 3) yTicks.push(...fillTicks(plot.y.ticks, ylo, yhi));
|
| 163 |
else yTicks.push(...niceTicks(ylo, yhi, 5));
|
| 164 |
for (const t of yTicks) {
|
| 165 |
const y = Y(t);
|
|
|
|
| 251 |
(d.warnings.length ? `<ul class="warn">${d.warnings.map(w => `<li>${esc(w)}</li>`).join("")}</ul>` : "") +
|
| 252 |
`<div class="pair"><div class="card"><h2>Your chart</h2><img id="orig" alt="uploaded chart"></div>` +
|
| 253 |
`<div class="card"><h2>Re-plotted from the extracted data</h2><div id="replot"></div></div></div>` +
|
| 254 |
+
`<p><a download="data.csv" href="${csvUrl}">Download CSV</a> <span class="note">(${d.n_rows} rows × ${d.plot.series.length} series)</span></p>` +
|
|
|
|
| 255 |
`<details><summary>Debug overlay (what was detected)</summary><img style="max-width:100%" src="data:image/png;base64,${d.debug_png}"></details>` +
|
| 256 |
`<details><summary>Diagnostics</summary><div class="scroll"><pre>${esc(JSON.stringify(d.diagnostics, null, 2))}</pre></div></details>`;
|
| 257 |
document.getElementById("orig").src = URL.createObjectURL(file);
|
|
|
|
| 271 |
|
| 272 |
|
| 273 |
@app.post("/api/extract")
|
| 274 |
+
async def extract(file: UploadFile = File(...), chart_type: str = Form(""), resample: int = Form(0)
|
| 275 |
+
) -> JSONResponse:
|
| 276 |
"""Run the pipeline on an uploaded image; returns CSV text, diagnostics and overlay PNG."""
|
| 277 |
data = await file.read()
|
| 278 |
if len(data) > MAX_BYTES:
|
|
|
|
| 290 |
raise HTTPException(400, "could not decode image")
|
| 291 |
if img.shape[0] * img.shape[1] > MAX_PIXELS:
|
| 292 |
raise HTTPException(413, "image has too many pixels")
|
| 293 |
+
res = pipeline.run(path, chart_type=chart_type or None,
|
| 294 |
+
resample=min(max(resample, 5), 400) if resample else None)
|
| 295 |
csv = res.table.to_csv(index=False) if res.table is not None else ""
|
| 296 |
ok, png = cv2.imencode(".png", cv2.cvtColor(export.debug_overlay(res), cv2.COLOR_RGB2BGR))
|
| 297 |
diag = json.loads(json.dumps(export.diagnostics(res), default=export._json_default))
|
|
|
|
| 300 |
"status": res.extra.get("status", "ok"), "chart_type": res.chart_type,
|
| 301 |
"confidence": res.confidence, "warnings": res.warnings, "csv": csv, "diagnostics": diag,
|
| 302 |
"debug_png": base64.b64encode(png.tobytes()).decode() if ok else "", "plot": plot,
|
| 303 |
+
"n_rows": 0 if res.table is None else int(len(res.table)),
|
| 304 |
})
|