Spaces:
Runtime error
Runtime error
Deploy 214d886: Web page: re-plot the extracted data next to the uploaded chart
Browse files- plotscribe/export.py +49 -0
- plotscribe/extract_line.py +32 -0
- plotscribe/web.py +208 -20
- scripts/deploy_space.sh +25 -0
- tests/test_web.py +4 -0
plotscribe/export.py
CHANGED
|
@@ -267,3 +267,52 @@ def _json_default(o: Any) -> Any:
|
|
| 267 |
if isinstance(o, np.ndarray):
|
| 268 |
return o.tolist()
|
| 269 |
return str(o)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
if isinstance(o, np.ndarray):
|
| 268 |
return o.tolist()
|
| 269 |
return str(o)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def plot_payload(res: "PipelineResult") -> dict[str, Any]:
|
| 273 |
+
"""The extracted data shaped for re-plotting (used by the web page).
|
| 274 |
+
|
| 275 |
+
``series[i].points`` are ``[x, y]`` pairs; for a categorical x axis ``x`` is the
|
| 276 |
+
category index. Stacked bars carry segment heights (the page stacks them).
|
| 277 |
+
Colours are the series colours detected in the source chart.
|
| 278 |
+
"""
|
| 279 |
+
table = res.table
|
| 280 |
+
series: list[Series] = res.extra.get("series", [])
|
| 281 |
+
x_cal, y_cal = res.x_cal, res.y_cal
|
| 282 |
+
payload: dict[str, Any] = {
|
| 283 |
+
"chart_type": res.chart_type,
|
| 284 |
+
"x": {"kind": "none"}, "y": {"log": bool(y_cal is not None and y_cal.kind == "log"),
|
| 285 |
+
"pixels": False},
|
| 286 |
+
"series": [],
|
| 287 |
+
}
|
| 288 |
+
if table is None or table.shape[1] < 2 or len(table) == 0:
|
| 289 |
+
return payload
|
| 290 |
+
# Axis ranges of the original plot area, so the re-plot frames data the same way.
|
| 291 |
+
ax = res.axes
|
| 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:
|
| 298 |
+
cats = [str(c) for c in table[first]]
|
| 299 |
+
payload["x"] = {"kind": "categorical", "categories": cats}
|
| 300 |
+
xs = list(range(len(cats)))
|
| 301 |
+
else:
|
| 302 |
+
payload["x"] = {"kind": "pixels" if "[px]" in str(first) else "numeric",
|
| 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:]):
|
| 309 |
+
rgb = series[k].rgb if k < len(series) else (90, 90, 90)
|
| 310 |
+
pts = [[x, float(v)] for x, v in zip(xs, table[col]) if v == v]
|
| 311 |
+
methods = res.extra.get("diagnostics_extra", {}).get("point_method", {})
|
| 312 |
+
payload["series"].append({
|
| 313 |
+
"dots_only": k < len(series) and methods.get(series[k].name) == "dots",
|
| 314 |
+
"name": str(col).replace(" (segment)", "").replace(" [px]", ""),
|
| 315 |
+
"color": "#%02x%02x%02x" % tuple(int(c) for c in rgb),
|
| 316 |
+
"points": pts,
|
| 317 |
+
})
|
| 318 |
+
return payload
|
plotscribe/extract_line.py
CHANGED
|
@@ -87,6 +87,35 @@ def centreline(mask: np.ndarray, alpha: np.ndarray) -> Centreline | None:
|
|
| 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
|
|
@@ -194,6 +223,9 @@ def extract_line(mask: np.ndarray, alpha: np.ndarray, category_px: list[float] |
|
|
| 194 |
cl = centreline(mask, alpha)
|
| 195 |
if cl is None:
|
| 196 |
return np.zeros((0, 2)), "none", None
|
|
|
|
|
|
|
|
|
|
| 197 |
markers = find_markers(mask, alpha, cl.thickness)
|
| 198 |
span = cl.x[-1] - cl.x[0]
|
| 199 |
if len(markers) >= 2 and np.ptp(markers[:, 0]) >= 0.5 * span:
|
|
|
|
| 87 |
return Centreline(x=xs, y=ys, observed=observed, thickness=max(thick, 1.0))
|
| 88 |
|
| 89 |
|
| 90 |
+
def separate_dots(mask: np.ndarray, alpha: np.ndarray) -> np.ndarray | None:
|
| 91 |
+
"""Centres of a 'line' that is only separate, similar blobs (a dot plot, no connecting line).
|
| 92 |
+
|
| 93 |
+
Dotted *lines* are many small pieces close together; dot plots are few blobs far
|
| 94 |
+
apart relative to their size.
|
| 95 |
+
"""
|
| 96 |
+
n, lab, stats, cents = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8)
|
| 97 |
+
if n - 1 < 2 or n - 1 > 200:
|
| 98 |
+
return None
|
| 99 |
+
st = stats[1:]
|
| 100 |
+
areas = st[:, cv2.CC_STAT_AREA].astype(float)
|
| 101 |
+
if np.std(areas) > 0.5 * np.mean(areas):
|
| 102 |
+
return None
|
| 103 |
+
size = float(np.median(np.maximum(st[:, 2], st[:, 3])))
|
| 104 |
+
order = np.argsort(cents[1:, 0])
|
| 105 |
+
gaps = np.diff(cents[1:, 0][order])
|
| 106 |
+
if size < 4 or np.median(gaps) < 3 * size:
|
| 107 |
+
return None
|
| 108 |
+
pts = []
|
| 109 |
+
for i in range(1, n):
|
| 110 |
+
x, y, w, h = st[i - 1, :4]
|
| 111 |
+
sub = lab[y:y + h, x:x + w] == i
|
| 112 |
+
wts = alpha[y:y + h, x:x + w] * sub + 1e-9 * sub
|
| 113 |
+
yy, xx = np.mgrid[y:y + h, x:x + w]
|
| 114 |
+
t = wts.sum()
|
| 115 |
+
pts.append(((xx * wts).sum() / t + 0.5, (yy * wts).sum() / t + 0.5))
|
| 116 |
+
return np.asarray(sorted(pts))
|
| 117 |
+
|
| 118 |
+
|
| 119 |
def find_markers(mask: np.ndarray, alpha: np.ndarray, thickness: float) -> np.ndarray:
|
| 120 |
"""Marker centres (x, y) via morphological opening wider than the stroke."""
|
| 121 |
k = int(np.ceil(2.2 * thickness)) | 1
|
|
|
|
| 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.thickness)
|
| 230 |
span = cl.x[-1] - cl.x[0]
|
| 231 |
if len(markers) >= 2 and np.ptp(markers[:, 0]) >= 0.5 * span:
|
plotscribe/web.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Minimal web front end: upload a chart image, get
|
| 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).
|
|
@@ -22,37 +22,224 @@ 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 |
-
|
|
|
|
|
|
|
| 30 |
.warn{color:#a15c00} .bad{color:#b00020} .ok{color:#1b7f3b}
|
| 31 |
-
|
| 32 |
-
button{padding:.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
</style></head><body>
|
| 34 |
<h1>plotscribe</h1>
|
| 35 |
-
<p>Upload a line, bar or scatter chart (PNG/JPG).
|
| 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
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
</script></body></html>"""
|
| 57 |
|
| 58 |
|
|
@@ -89,8 +276,9 @@ async def extract(file: UploadFile = File(...), chart_type: str = Form("")) -> J
|
|
| 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 |
})
|
|
|
|
| 1 |
+
"""Minimal web front end: upload a chart image, get the re-plotted data, CSV, diagnostics and 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).
|
|
|
|
| 22 |
|
| 23 |
app = FastAPI(title="plotscribe")
|
| 24 |
|
| 25 |
+
_PAGE = r"""<!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 |
+
:root{--ink:#0b0b0b;--ink2:#52514e;--muted:#898781;--grid:#e1e0d9;--axis:#c3c2b7;--surface:#fcfcfb;--page:#f9f9f7}
|
| 30 |
+
body{font-family:system-ui,-apple-system,sans-serif;max-width:1180px;margin:0 auto;padding:1.5rem 16px;color:var(--ink);background:var(--page)}
|
| 31 |
+
h1{margin:.2rem 0} .sub{color:var(--ink2);margin-top:0}
|
| 32 |
.warn{color:#a15c00} .bad{color:#b00020} .ok{color:#1b7f3b}
|
| 33 |
+
form{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin:1rem 0}
|
| 34 |
+
button{padding:.45rem 1.1rem;cursor:pointer}
|
| 35 |
+
.pair{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,460px),1fr));gap:16px;margin:1rem 0}
|
| 36 |
+
.card{background:var(--surface);border:1px solid rgba(11,11,11,.1);border-radius:8px;padding:12px;min-width:0}
|
| 37 |
+
.card h2{font-size:.95rem;font-weight:600;margin:0 0 .5rem}
|
| 38 |
+
.card img{display:block;max-width:100%;margin:0 auto}
|
| 39 |
+
.legend{display:flex;flex-wrap:wrap;gap:.25rem 1rem;font-size:.8rem;color:var(--ink2);margin:0 0 .25rem}
|
| 40 |
+
.legend span{display:inline-flex;align-items:center;gap:.35rem}
|
| 41 |
+
.legend i{display:inline-block;width:12px;height:12px;border-radius:3px}
|
| 42 |
+
.chart{position:relative} .chart svg{display:block;width:100%;height:auto;overflow:visible}
|
| 43 |
+
.chart text{font-size:11px;fill:var(--muted)}
|
| 44 |
+
.tip{position:absolute;pointer-events:none;background:#fff;border:1px solid rgba(11,11,11,.15);border-radius:6px;
|
| 45 |
+
padding:.35rem .5rem;font-size:.8rem;color:var(--ink);box-shadow:0 2px 8px rgba(0,0,0,.08);white-space:nowrap}
|
| 46 |
+
.note{font-size:.8rem;color:var(--muted);margin:.4rem 0 0}
|
| 47 |
+
.scroll{overflow-x:auto} pre{background:#f3f2ee;padding:.75rem;margin:0;font-size:.8rem}
|
| 48 |
+
details{margin:.75rem 0}
|
| 49 |
</style></head><body>
|
| 50 |
<h1>plotscribe</h1>
|
| 51 |
+
<p class="sub">Upload a line, bar or scatter chart (PNG/JPG). The data is extracted with classical computer vision and re-plotted next to your image so you can compare.</p>
|
| 52 |
<form id="f">
|
| 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>
|
| 59 |
<script>
|
| 60 |
+
const NS = "http://www.w3.org/2000/svg";
|
| 61 |
+
const $ = (tag, attrs = {}, parent) => {
|
| 62 |
+
const el = document.createElementNS(NS, tag);
|
| 63 |
+
for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);
|
| 64 |
+
if (parent) parent.appendChild(el);
|
| 65 |
+
return el;
|
| 66 |
+
};
|
| 67 |
+
const esc = s => String(s).replace(/[&<>]/g, c => ({"&": "&", "<": "<", ">": ">"}[c]));
|
| 68 |
+
const fmt = v => {
|
| 69 |
+
if (!isFinite(v)) return "";
|
| 70 |
+
const a = Math.abs(v);
|
| 71 |
+
if (a !== 0 && (a >= 1e6 || a < 1e-3)) return v.toExponential(2).replace("e+", "e");
|
| 72 |
+
return Number(v.toPrecision(5)).toLocaleString("en-US", {maximumFractionDigits: 6, useGrouping: a >= 1e4});
|
| 73 |
+
};
|
| 74 |
+
|
| 75 |
+
function niceTicks(lo, hi, n = 5) {
|
| 76 |
+
if (lo === hi) { lo -= 1; hi += 1; }
|
| 77 |
+
const raw = (hi - lo) / n, mag = Math.pow(10, Math.floor(Math.log10(raw)));
|
| 78 |
+
const step = [1, 2, 2.5, 5, 10].map(m => m * mag).find(s => s >= raw);
|
| 79 |
+
const t = [];
|
| 80 |
+
for (let v = Math.ceil(lo / step) * step; v <= hi + step * 1e-9; v += step) t.push(+v.toPrecision(12));
|
| 81 |
+
return t;
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
function drawChart(host, plot) {
|
| 85 |
+
host.innerHTML = "";
|
| 86 |
+
const series = plot.series.filter(s => s.points.length);
|
| 87 |
+
if (!series.length) { host.innerHTML = '<p class="note">No data to plot.</p>'; return; }
|
| 88 |
+
const type = plot.chart_type, cat = plot.x.kind === "categorical";
|
| 89 |
+
const bars = type === "bar" || type === "stacked_bar" || type === "grouped_bar";
|
| 90 |
+
const stacked = type === "stacked_bar";
|
| 91 |
+
const ylog = plot.y.log, xlog = !!plot.x.log;
|
| 92 |
+
|
| 93 |
+
if (series.length > 1) {
|
| 94 |
+
const lg = document.createElement("div"); lg.className = "legend";
|
| 95 |
+
for (const s of series) lg.insertAdjacentHTML("beforeend",
|
| 96 |
+
`<span><i style="background:${s.color}"></i>${esc(s.name)}</span>`);
|
| 97 |
+
host.appendChild(lg);
|
| 98 |
+
}
|
| 99 |
+
const wrap = document.createElement("div"); wrap.className = "chart"; host.appendChild(wrap);
|
| 100 |
+
const W = 640, H = 400, M = {l: 64, r: 16, t: 12, b: cat ? 70 : 36};
|
| 101 |
+
const svg = $("svg", {viewBox: `0 0 ${W} ${H}`, role: "img", "aria-label": "Re-plotted extracted data"}, wrap);
|
| 102 |
+
const pw = W - M.l - M.r, ph = H - M.t - M.b;
|
| 103 |
+
|
| 104 |
+
// y domain (bars include 0; stacked uses cumulative sums)
|
| 105 |
+
let ys = series.flatMap(s => s.points.map(p => p[1]));
|
| 106 |
+
if (stacked) {
|
| 107 |
+
const pos = {}, neg = {};
|
| 108 |
+
for (const s of series) for (const [x, y] of s.points) {
|
| 109 |
+
if (y >= 0) pos[x] = (pos[x] || 0) + y; else neg[x] = (neg[x] || 0) + y;
|
| 110 |
+
}
|
| 111 |
+
ys = [...Object.values(pos), ...Object.values(neg), 0];
|
| 112 |
+
} else if (bars && !ylog) ys.push(0);
|
| 113 |
+
const tf = v => ylog ? Math.log10(v) : v;
|
| 114 |
+
let ylo = Math.min(...ys.filter(v => !ylog || v > 0).map(tf)), yhi = Math.max(...ys.filter(v => !ylog || v > 0).map(tf));
|
| 115 |
+
if (plot.y.range && !stacked) {
|
| 116 |
+
// Frame the data like the original plot area (but never cut extracted points off).
|
| 117 |
+
ylo = Math.min(ylo, tf(plot.y.range[0])); yhi = Math.max(yhi, tf(plot.y.range[1]));
|
| 118 |
+
} else {
|
| 119 |
+
const ypad = (yhi - ylo || 1) * 0.06;
|
| 120 |
+
if (!(bars && !ylog && ylo === 0)) ylo -= ypad;
|
| 121 |
+
yhi += ypad;
|
| 122 |
+
}
|
| 123 |
+
const Y = v => M.t + ph - (tf(v) - ylo) / (yhi - ylo) * ph;
|
| 124 |
+
|
| 125 |
+
// x scale
|
| 126 |
+
let X, xTicks, band = 0;
|
| 127 |
+
if (cat) {
|
| 128 |
+
const n = plot.x.categories.length; band = pw / n;
|
| 129 |
+
X = i => M.l + band * (i + 0.5);
|
| 130 |
+
xTicks = plot.x.categories.map((c, i) => [i, c]);
|
| 131 |
+
} else {
|
| 132 |
+
const xt = v => xlog ? Math.log10(v) : v;
|
| 133 |
+
const xv = series.flatMap(s => s.points.map(p => xt(p[0])));
|
| 134 |
+
let xlo = Math.min(...xv), xhi = Math.max(...xv);
|
| 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 |
+
xTicks = xlog ? [] : niceTicks(xlo, xhi, 6).map(v => [v, fmt(v)]);
|
| 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);
|
| 148 |
+
$("line", {x1: M.l, x2: M.l + pw, y1: y, y2: y, stroke: "var(--grid)", "stroke-width": 1}, svg);
|
| 149 |
+
$("text", {x: M.l - 8, y: y + 4, "text-anchor": "end"}, svg).textContent = ylog ? "1e" + Math.round(Math.log10(t)) : fmt(t);
|
| 150 |
+
}
|
| 151 |
+
const base = ylog ? M.t + ph : Y(0);
|
| 152 |
+
$("line", {x1: M.l, x2: M.l + pw, y1: Math.min(Math.max(base, M.t), M.t + ph), y2: Math.min(Math.max(base, M.t), M.t + ph),
|
| 153 |
+
stroke: "var(--axis)", "stroke-width": 1}, svg);
|
| 154 |
+
const step = cat ? Math.max(1, Math.ceil(xTicks.length / 24)) : 1;
|
| 155 |
+
xTicks.forEach(([v, label], k) => {
|
| 156 |
+
if (k % step) return;
|
| 157 |
+
const x = X(v);
|
| 158 |
+
if (x < M.l - 1 || x > M.l + pw + 1) return;
|
| 159 |
+
const t = $("text", {x, y: M.t + ph + 16, "text-anchor": cat ? "end" : "middle",
|
| 160 |
+
transform: cat ? `rotate(-35 ${x} ${M.t + ph + 12})` : ""}, svg);
|
| 161 |
+
t.textContent = cat && label.length > 16 ? label.slice(0, 15) + "…" : label;
|
| 162 |
+
});
|
| 163 |
+
|
| 164 |
+
// marks
|
| 165 |
+
const hits = [];
|
| 166 |
+
if (bars) {
|
| 167 |
+
const nS = series.length, inner = band * 0.8, sub = stacked ? inner : inner / nS;
|
| 168 |
+
const pos = {}, neg = {};
|
| 169 |
+
series.forEach((s, si) => {
|
| 170 |
+
for (const [i, v] of s.points) {
|
| 171 |
+
let y0 = 0, y1 = v;
|
| 172 |
+
if (stacked) {
|
| 173 |
+
if (v >= 0) { y0 = pos[i] || 0; y1 = y0 + v; pos[i] = y1; } else { y0 = neg[i] || 0; y1 = y0 + v; neg[i] = y1; }
|
| 174 |
+
}
|
| 175 |
+
const x0 = M.l + band * i + (band - inner) / 2 + (stacked ? 0 : sub * si);
|
| 176 |
+
const top = ylog ? Y(v) : Math.min(Y(y0), Y(y1)), bot = ylog ? M.t + ph : Math.max(Y(y0), Y(y1));
|
| 177 |
+
$("rect", {x: x0 + 1, y: top, width: Math.max(sub - 2, 1), height: Math.max(bot - top, 0.5),
|
| 178 |
+
fill: s.color, rx: 2}, svg);
|
| 179 |
+
hits.push({x: x0 + sub / 2, y: top, s, label: plot.x.categories[i], v});
|
| 180 |
+
}
|
| 181 |
+
});
|
| 182 |
+
} else {
|
| 183 |
+
series.forEach(s => {
|
| 184 |
+
const pts = s.points.slice().sort((a, b) => a[0] - b[0]);
|
| 185 |
+
if (type === "line" && !s.dots_only) $("polyline", {points: pts.map(p => `${X(p[0])},${Y(p[1])}`).join(" "), fill: "none",
|
| 186 |
+
stroke: s.color, "stroke-width": 2, "stroke-linejoin": "round"}, svg);
|
| 187 |
+
for (const [x, y] of pts) {
|
| 188 |
+
$("circle", {cx: X(x), cy: Y(y), r: type === "line" && !s.dots_only ? 3 : 5, fill: s.color,
|
| 189 |
+
stroke: "var(--surface)", "stroke-width": 1.5}, svg);
|
| 190 |
+
hits.push({x: X(x), y: Y(y), s, label: cat ? plot.x.categories[x] : fmt(x), v: y});
|
| 191 |
+
}
|
| 192 |
+
});
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
// hover tooltip: nearest mark within 28px
|
| 196 |
+
const tip = document.createElement("div"); tip.className = "tip"; tip.hidden = true; wrap.appendChild(tip);
|
| 197 |
+
const ring = $("circle", {r: 6, fill: "none", stroke: "var(--ink)", "stroke-width": 1.5, visibility: "hidden"}, svg);
|
| 198 |
+
svg.addEventListener("mousemove", e => {
|
| 199 |
+
const r = svg.getBoundingClientRect(), k = W / r.width;
|
| 200 |
+
const mx = (e.clientX - r.left) * k, my = (e.clientY - r.top) * k;
|
| 201 |
+
let best = null, bd = 28 * k;
|
| 202 |
+
for (const h of hits) { const d = Math.hypot(h.x - mx, h.y - my); if (d < bd) { bd = d; best = h; } }
|
| 203 |
+
if (!best) { tip.hidden = true; ring.setAttribute("visibility", "hidden"); return; }
|
| 204 |
+
ring.setAttribute("cx", best.x); ring.setAttribute("cy", best.y); ring.setAttribute("visibility", "visible");
|
| 205 |
+
tip.innerHTML = `<b>${esc(best.s.name)}</b><br>${esc(best.label)}: ${esc(fmt(best.v))}`;
|
| 206 |
+
tip.hidden = false;
|
| 207 |
+
const left = best.x / k, top = best.y / k;
|
| 208 |
+
tip.style.left = Math.min(left + 12, r.width - tip.offsetWidth - 4) + "px";
|
| 209 |
+
tip.style.top = Math.max(top - tip.offsetHeight - 8, 0) + "px";
|
| 210 |
+
});
|
| 211 |
+
svg.addEventListener("mouseleave", () => { tip.hidden = true; ring.setAttribute("visibility", "hidden"); });
|
| 212 |
+
|
| 213 |
+
const notes = [];
|
| 214 |
+
if (plot.y.pixels) notes.push("y axis could not be calibrated: values are pixel rows (image coordinates).");
|
| 215 |
+
if (plot.x.kind === "pixels") notes.push("x axis could not be calibrated: values are pixel columns.");
|
| 216 |
+
if (stacked) notes.push("Stacked: segments drawn on top of each other from the extracted segment values.");
|
| 217 |
+
for (const n of notes) host.insertAdjacentHTML("beforeend", `<p class="note">${esc(n)}</p>`);
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
const f = document.getElementById("f"), out = document.getElementById("out");
|
| 221 |
+
f.onsubmit = async e => {
|
| 222 |
+
e.preventDefault();
|
| 223 |
+
const file = document.getElementById("file").files[0];
|
| 224 |
+
out.innerHTML = "<p>Working… (a few seconds)</p>";
|
| 225 |
+
let r, d;
|
| 226 |
+
try { r = await fetch("api/extract", {method: "POST", body: new FormData(f)}); d = await r.json(); }
|
| 227 |
+
catch (err) { out.innerHTML = '<p class="bad">Request failed.</p>'; return; }
|
| 228 |
+
if (!r.ok) { out.innerHTML = `<p class="bad">${esc(d.detail || "error")}</p>`; return; }
|
| 229 |
+
const cls = {ok: "ok", low_confidence: "warn"}[d.status] || "bad";
|
| 230 |
+
const csvUrl = URL.createObjectURL(new Blob([d.csv], {type: "text/csv"}));
|
| 231 |
+
out.innerHTML =
|
| 232 |
+
`<p class="${cls}">status: <b>${esc(d.status)}</b> · type: ${esc(d.chart_type)} · confidence: ${d.confidence.toFixed(2)}</p>` +
|
| 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);
|
| 241 |
+
drawChart(document.getElementById("replot"), d.plot);
|
| 242 |
+
};
|
| 243 |
</script></body></html>"""
|
| 244 |
|
| 245 |
|
|
|
|
| 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))
|
| 279 |
+
plot = json.loads(json.dumps(export.plot_payload(res), default=export._json_default))
|
| 280 |
return JSONResponse({
|
| 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 |
})
|
scripts/deploy_space.sh
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Deploy the current commit to the Hugging Face Space (git remote "space").
|
| 3 |
+
#
|
| 4 |
+
# Hugging Face rejects binary files committed directly to git, so this pushes a
|
| 5 |
+
# deploy commit with the same code minus docs/ (images), on top of the Space's
|
| 6 |
+
# current history. GitHub history is left untouched.
|
| 7 |
+
set -euo pipefail
|
| 8 |
+
cd "$(git rev-parse --show-toplevel)"
|
| 9 |
+
|
| 10 |
+
if [ -n "$(git status --porcelain)" ]; then
|
| 11 |
+
echo "Commit your changes first." >&2
|
| 12 |
+
exit 1
|
| 13 |
+
fi
|
| 14 |
+
|
| 15 |
+
git fetch -q space
|
| 16 |
+
idx="$(mktemp)"
|
| 17 |
+
GIT_INDEX_FILE="$idx" git read-tree HEAD
|
| 18 |
+
GIT_INDEX_FILE="$idx" git rm -q --cached -r --ignore-unmatch docs
|
| 19 |
+
tree="$(GIT_INDEX_FILE="$idx" git write-tree)"
|
| 20 |
+
rm -f "$idx"
|
| 21 |
+
|
| 22 |
+
msg="Deploy $(git rev-parse --short HEAD): $(git log -1 --format=%s)"
|
| 23 |
+
commit="$(git commit-tree "$tree" -p space/main -m "$msg")"
|
| 24 |
+
git push space "${commit}:refs/heads/main"
|
| 25 |
+
echo "Deployed $(git rev-parse --short HEAD) to the Space as ${commit:0:7}."
|
tests/test_web.py
CHANGED
|
@@ -15,6 +15,10 @@ def test_upload_roundtrip(tmp_path):
|
|
| 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():
|
|
|
|
| 15 |
assert r.status_code == 200
|
| 16 |
d = r.json()
|
| 17 |
assert d["status"] == "ok" and d["csv"].startswith("category")
|
| 18 |
+
plot = d["plot"]
|
| 19 |
+
assert plot["x"]["kind"] == "categorical" and plot["series"]
|
| 20 |
+
assert all(len(p) == 2 for s in plot["series"] for p in s["points"])
|
| 21 |
+
assert "range" in plot["y"]
|
| 22 |
|
| 23 |
|
| 24 |
def test_rejects_non_image():
|