plotscribe / README.md
jkos9's picture
Deploy e846010: AI chat access: GET /api/extract?url= with plain-text result, AI instructions on the page, local file MCP tool
1d60f3a
|
Raw History Blame Contribute Delete
12.3 kB
---
title: plotscribe – Chart Image to CSV
emoji: 📈
colorFrom: blue
colorTo: green
sdk: docker
app_port: 8000
pinned: true
license: mit
short_description: Extract data from chart images (PNG/JPG) to CSV
tags:
- plot-digitizer
- chart-data-extraction
- graph-to-csv
- computer-vision
- ocr
- opencv
---
# plotscribe: extract data from chart images to CSV
**Try it online:** [huggingface.co/spaces/jkos9/plotscribe](https://huggingface.co/spaces/jkos9/plotscribe)
plotscribe is a free, automatic plot digitizer. Upload a picture of a line chart,
bar chart or scatter plot (a screenshot, a figure from a paper, a PNG or JPEG) and
get the underlying data back as a CSV file. Unlike WebPlotDigitizer and similar
tools, there is nothing to click: axes, tick labels, legends and series are found
automatically.
It uses classical computer vision only: OpenCV, NumPy/SciPy and Tesseract OCR. No
neural networks or LLM calls at runtime. It is CPU-only, needs no model files, and
takes about 3–4 s per chart.
Supported: line charts, vertical bar charts (simple, grouped, stacked, negative
values) and scatter plots, with linear, log (including `10^n` labels) and
categorical axes.
## Install
```bash
# system dependency: Tesseract OCR
brew install tesseract # macOS
sudo apt install tesseract-ocr # Debian/Ubuntu
pip install -e . # library + CLI
pip install -e ".[web]" # + upload web page
pip install -e ".[dev]" # + tests / synthetic data (matplotlib)
```
Runtime dependencies: `numpy`, `opencv-python-headless`, `scipy`, `pandas`,
`pytesseract`, `typer` (+ `fastapi`, `uvicorn`, `python-multipart` for the web page).
## Usage
```bash
plotscribe input.png -o out/ [--type line|bar|stacked_bar|scatter] [--debug] [--ocr tesseract|paddle] [--resample N]
```
`--resample 40` reports line charts at ~40 evenly spaced, round x values shared by
all lines (one CSV row per x). Use it for smooth curves; without it a line is
reported at its markers, categories or corners.
This writes:
- `out/input.csv`: the data (layout below)
- `out/input.diagnostics.json`: chart type and confidence, plot area, axis
calibration (type, slope, intercept, residuals, R²), tick labels, legend mapping,
number of series and points, per-stage confidences, and warnings
- `out/input.debug.png` (with `--debug`): plot box, ticks, OCR'd labels, series
masks, extracted points
The exit code is 2 when the status is not `ok`.
```python
from plotscribe import pipeline, export
res = pipeline.run("chart.png")
print(res.extra["status"], res.chart_type, res.warnings)
res.table # pandas DataFrame
```
### Status: the tool says when not to trust it
| status | meaning |
|---|---|
| `ok` | all stages confident |
| `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. |
| `uncalibrated` | an axis could not be calibrated; those values are **pixel coordinates** and the column header carries ` [px]` |
| `failed` | no data series or no chart type found |
Values hidden under the legend are left empty and reported in the warnings rather than estimated.
### CSV layout
- First column `category` (categorical x axis) or `x` (numeric x axis).
- Then one column per series, named after the legend label (`series_1..n` if there is no legend), in legend order.
- Line/bar: one row per x position or category. Line charts give points at markers
if present (a marker hidden under another series' marker is recovered from the line's
corner), else at category positions, else at the line's corners (found on the
de-jittered trace, at least ~1% of the width apart), or on an even grid with
`--resample`. A line whose start/end is hidden under another line (e.g. curves
sharing an origin) is continued along that line and the warnings say so.
- Scatter: one row per point; only the owning series' column is filled.
- Stacked bars: headers end in ` (segment)`; values are segment heights, not cumulative tops.
## Web page
The page shows your chart and the chart re-plotted from the extracted numbers side by
side (same axis range and tick values, detected colours, hover for values), a CSV
download, the warnings, the detection overlay and diagnostics. Tick "even x spacing
for lines" for smooth curves.
```bash
uvicorn plotscribe.web:app --port 8000 # http://localhost:8000
# or
docker build -t plotscribe . && docker run -p 8000:8000 plotscribe
```
`GET /` serves a single upload page. `POST /api/extract` (multipart `file`,
optional `chart_type`, `resample`) returns JSON with `status`, `warnings`, `csv`,
`diagnostics`, re-plot data and a base64 `debug_png`. Uploads are limited to 10 MB / 25 MP.
The Docker image is `python:3.12-slim` + `tesseract-ocr`. Each request is CPU-bound
for a few seconds, so scale with uvicorn workers. Interactive API docs are at `/docs`,
and `/llms.txt` describes the tool for AI crawlers.
```bash
curl -F file=@chart.png https://jkos9-plotscribe.hf.space/api/extract
```
## Use from AI assistants
**In any AI chat that can open web pages** (ChatGPT, Claude, Gemini, Perplexity, ...), for a
chart image that is online:
> Use https://jkos9-plotscribe.hf.space/api/extract?url=IMAGE_URL to extract the data from this
> figure: https://example.org/figure.png
The reply is plain text (status, warnings and the data as CSV); add `&format=json` for
JSON. Give the AI the `jkos9-plotscribe.hf.space` address, not the Hugging Face page:
that page only embeds the app, so a chat tool opening it sees almost nothing.
**As an MCP tool** (works with images in more places, and the AI calls it by itself
when needed). The server is `https://jkos9-plotscribe.hf.space/mcp` (streamable HTTP, no
authentication), with one tool, `extract_chart_data(image_url | image_base64,
chart_type, resample)`, which returns `status`, `chart_type`, `confidence`, `warnings`,
`n_rows` and the `csv`. `image_url` must be a public http(s) address.
- Claude (web/desktop): Settings → Connectors → Add custom connector → paste the URL.
- ChatGPT: Settings → Apps & Connectors → enable developer mode → create a connector
with the URL, no authentication.
- Claude Code: `claude mcp add --transport http plotscribe https://jkos9-plotscribe.hf.space/mcp`
- Cursor / VS Code: add it as a remote (HTTP) MCP server with the same URL.
**Images on your own computer**: run the server locally (after `pip install -e ".[web]"`),
which adds a second tool, `extract_chart_file(image_path, ...)`:
```json
{"mcpServers": {"plotscribe": {"command": "plotscribe-mcp"}}}
```
(Claude Desktop: `claude_desktop_config.json`; Cursor: `.cursor/mcp.json`; Claude Code:
`claude mcp add plotscribe -- plotscribe-mcp`.) Set `PLOTSCRIBE_PUBLIC_URL` when the web
app is served from another address, so its AI instructions point there.
## How it works
1. **preprocess**: RGB, deskew small rotations, Lanczos upscale to ≥800 px short side, bilateral denoise if noisy.
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.
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.
4. **legend**: colour swatches (line, patch or marker) next to text lines; labels are OCR'd and the box is masked out.
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.
6. **chart type**: rectangles on a shared baseline (bar), chained pieces along x (line), unchained compact blobs (scatter).
7. **extraction**:
- line: sub-pixel centreline, markers, or RDP vertices refined by intersecting fitted segments.
- bar: sub-pixel edges from alpha coverage, zero-line baseline, stacked/grouped detection, categories re-anchored on bar groups when labels are ambiguous.
- scatter: alpha-weighted centroids; touching markers split by distance-transform peaks; circle fit for occluded markers.
## Evaluation
Synthetic charts with exact pixel-level ground truth (`tests/synth.py`). Errors are
fractions of the axis range. Full history and failure analysis: `EVAL_LOG.md`.
```bash
python -m tests.evaluate --n 200 --tier clean --start-seed 5000 # or --tier perturbed
python -m tests.eval_real # charts in tests/real/
pytest # includes the CI accuracy target
```
![accuracy progress](docs/progress.png)
### Public benchmark: PlotQA
[PlotQA](https://github.com/NiteshMethani/PlotQA) charts are real-world data (World
Bank etc.) rendered with Bokeh: line, dot and bar charts with rotated tick labels,
tiny fonts and scientific-notation axes, and no printed values. The copy used is
the Hugging Face dataset `martinsinnona/plotqa` (single-series charts with their
plotted values). RNSS is the chart-to-table metric of ChartQA/DePlot (100 = all
numbers matched exactly).
```bash
python -m tests.bench_plotqa --split test # 100 charts (used for tuning)
python -m tests.bench_plotqa --split train --n 300 # held-out check
python -m tests.plot_progress # redraws docs/progress.png
```
| PlotQA | test split (92 scoreable) | held-out (287 scoreable) before → after |
|---|---|---|
| RNSS | 99.5 | 84.4 → **97.3** |
| point recall | 97% | 50% → **91%** |
| charts with median error < 1% | 100% | 54% → **93%** |
| status `ok` | 93% | 4% → **93%** |
| silent failures | 1.1% | 4.2% → 4.2% |
Charts whose ground truth is degenerate (all values equal, e.g. rounded to 0.0 in
the dataset) are excluded. Most remaining held-out failures are PlotQA renders
whose data lies outside the plotted y range (cut off by the frame).
### Synthetic charts
| 200 charts, auto type | clean (default matplotlib PNG) | perturbed (styles, fonts, 50–150 dpi, JPEG q40–95, log, dashes, markers) |
|---|---|---|
| chart type correct | 100% | 92% |
| series count correct | 99.5% | 90.5% |
| point recall | 98.7% | 85.5% |
| median of per-chart median error | **0.11%** | 0.26% |
| p90 of per-chart median error | 0.24% | 9.2% |
| status `ok` | 97% | 49.5% |
| abstained (`uncalibrated`/`failed`) | 0% | 21% |
| **silent failures** (status `ok` but median error > 2% or recall < 50%) | **0%** | 0.5% |
The CI target (median error < 1% on clean charts) is met for every chart type.
On clean charts the worst single bar value is 0.9% off (150 bar charts); for lines
median error is 0.13% (100 clean line charts).
## Known limitations
- **Perturbed styles**: 21% of perturbed charts abstain and 0.5% are silently
wrong. Weak spots: fivethirtyeight (no spines, panel = figure colour),
frameless legends drawn over data, bmh/classic low-resolution JPEGs, and
heavily overlapping category labels.
- Not yet supported: horizontal bars, area charts, labels at angles other than 0°/90°, dates parsed
as dates (they are treated as categories), dual y axes, pie charts, 3-D charts.
- A series needs its own colour; two series of the same colour (e.g. differing only
by dash pattern) are merged. Very light colours (ΔE < ~15 from the background)
are missed.
- Line charts without markers are reported at polyline vertices. Where lines cross
and occlude each other a vertex can be cut (up to 10–20% error at that point).
- Scatter markers that are more than ~70% hidden by other markers are not recovered.
- Tesseract dominates runtime (about 20–60 calls per chart).
- Real-world accuracy is unmeasured until charts are added to `tests/real/`.