Spaces:
Runtime error
Runtime error
Deploy e846010: AI chat access: GET /api/extract?url= with plain-text result, AI instructions on the page, local file MCP tool
Browse files- README.md +43 -3
- plotscribe/mcp_server.py +96 -0
- plotscribe/service.py +107 -0
- plotscribe/web.py +95 -38
- pyproject.toml +2 -1
- tests/test_web.py +73 -0
README.md
CHANGED
|
@@ -116,10 +116,50 @@ docker build -t plotscribe . && docker run -p 8000:8000 plotscribe
|
|
| 116 |
```
|
| 117 |
|
| 118 |
`GET /` serves a single upload page. `POST /api/extract` (multipart `file`,
|
| 119 |
-
optional `chart_type`) returns JSON with `status`, `warnings`, `csv`,
|
| 120 |
-
`diagnostics` and a base64 `debug_png`. Uploads are limited to 10 MB / 25 MP.
|
| 121 |
The Docker image is `python:3.12-slim` + `tesseract-ocr`. Each request is CPU-bound
|
| 122 |
-
for a few seconds, so scale with uvicorn workers.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
## How it works
|
| 125 |
|
|
|
|
| 116 |
```
|
| 117 |
|
| 118 |
`GET /` serves a single upload page. `POST /api/extract` (multipart `file`,
|
| 119 |
+
optional `chart_type`, `resample`) returns JSON with `status`, `warnings`, `csv`,
|
| 120 |
+
`diagnostics`, re-plot data and a base64 `debug_png`. Uploads are limited to 10 MB / 25 MP.
|
| 121 |
The Docker image is `python:3.12-slim` + `tesseract-ocr`. Each request is CPU-bound
|
| 122 |
+
for a few seconds, so scale with uvicorn workers. Interactive API docs are at `/docs`,
|
| 123 |
+
and `/llms.txt` describes the tool for AI crawlers.
|
| 124 |
+
|
| 125 |
+
```bash
|
| 126 |
+
curl -F file=@chart.png https://jkos9-plotscribe.hf.space/api/extract
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
## Use from AI assistants
|
| 130 |
+
|
| 131 |
+
**In any AI chat that can open web pages** (ChatGPT, Claude, Gemini, Perplexity, ...), for a
|
| 132 |
+
chart image that is online:
|
| 133 |
+
|
| 134 |
+
> Use https://jkos9-plotscribe.hf.space/api/extract?url=IMAGE_URL to extract the data from this
|
| 135 |
+
> figure: https://example.org/figure.png
|
| 136 |
+
|
| 137 |
+
The reply is plain text (status, warnings and the data as CSV); add `&format=json` for
|
| 138 |
+
JSON. Give the AI the `jkos9-plotscribe.hf.space` address, not the Hugging Face page:
|
| 139 |
+
that page only embeds the app, so a chat tool opening it sees almost nothing.
|
| 140 |
+
|
| 141 |
+
**As an MCP tool** (works with images in more places, and the AI calls it by itself
|
| 142 |
+
when needed). The server is `https://jkos9-plotscribe.hf.space/mcp` (streamable HTTP, no
|
| 143 |
+
authentication), with one tool, `extract_chart_data(image_url | image_base64,
|
| 144 |
+
chart_type, resample)`, which returns `status`, `chart_type`, `confidence`, `warnings`,
|
| 145 |
+
`n_rows` and the `csv`. `image_url` must be a public http(s) address.
|
| 146 |
+
|
| 147 |
+
- Claude (web/desktop): Settings → Connectors → Add custom connector → paste the URL.
|
| 148 |
+
- ChatGPT: Settings → Apps & Connectors → enable developer mode → create a connector
|
| 149 |
+
with the URL, no authentication.
|
| 150 |
+
- Claude Code: `claude mcp add --transport http plotscribe https://jkos9-plotscribe.hf.space/mcp`
|
| 151 |
+
- Cursor / VS Code: add it as a remote (HTTP) MCP server with the same URL.
|
| 152 |
+
|
| 153 |
+
**Images on your own computer**: run the server locally (after `pip install -e ".[web]"`),
|
| 154 |
+
which adds a second tool, `extract_chart_file(image_path, ...)`:
|
| 155 |
+
|
| 156 |
+
```json
|
| 157 |
+
{"mcpServers": {"plotscribe": {"command": "plotscribe-mcp"}}}
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
(Claude Desktop: `claude_desktop_config.json`; Cursor: `.cursor/mcp.json`; Claude Code:
|
| 161 |
+
`claude mcp add plotscribe -- plotscribe-mcp`.) Set `PLOTSCRIBE_PUBLIC_URL` when the web
|
| 162 |
+
app is served from another address, so its AI instructions point there.
|
| 163 |
|
| 164 |
## How it works
|
| 165 |
|
plotscribe/mcp_server.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MCP server: lets AI assistants (Claude, Cursor, ...) extract data from chart images.
|
| 2 |
+
|
| 3 |
+
Served over streamable HTTP at ``/mcp`` by the web app, or run locally over stdio:
|
| 4 |
+
python -m plotscribe.mcp_server
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import base64
|
| 10 |
+
import binascii
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import anyio
|
| 14 |
+
from mcp.server.mcpserver import MCPServer
|
| 15 |
+
from mcp.server.mcpserver.exceptions import ToolError
|
| 16 |
+
|
| 17 |
+
from .service import InputError, analyse, fetch_image
|
| 18 |
+
|
| 19 |
+
mcp = MCPServer(
|
| 20 |
+
name="plotscribe",
|
| 21 |
+
title="plotscribe: chart image to CSV",
|
| 22 |
+
description="Automatic plot digitizer: extract the data behind line, bar and scatter chart images.",
|
| 23 |
+
instructions=(
|
| 24 |
+
"Use extract_chart_data to read the numbers out of a chart image (PNG/JPG). Pass a public "
|
| 25 |
+
"image_url, or image_base64. Check `status` and `warnings` before trusting the CSV."
|
| 26 |
+
),
|
| 27 |
+
website_url="https://huggingface.co/spaces/jkos9/plotscribe",
|
| 28 |
+
version="0.1.0",
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _decode_base64(text: str) -> bytes:
|
| 33 |
+
if text.startswith("data:"):
|
| 34 |
+
text = text.partition(",")[2]
|
| 35 |
+
try:
|
| 36 |
+
return base64.b64decode(text, validate=True)
|
| 37 |
+
except (binascii.Error, ValueError):
|
| 38 |
+
raise InputError(400, "image_base64 is not valid base64") from None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@mcp.tool()
|
| 42 |
+
async def extract_chart_data(image_url: str = "", image_base64: str = "", chart_type: str = "",
|
| 43 |
+
resample: int = 0) -> dict:
|
| 44 |
+
"""Extract the data from a chart image (line, bar, stacked/grouped bar or scatter plot) as CSV.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
image_url: public http(s) URL of a PNG or JPG chart image.
|
| 48 |
+
image_base64: the PNG/JPG image as base64 (alternative to image_url; a data: URI is accepted).
|
| 49 |
+
chart_type: optional hint: line, bar, stacked_bar, grouped_bar or scatter. Empty = auto-detect.
|
| 50 |
+
resample: for line charts, report about this many evenly spaced x values (e.g. 40). 0 = off.
|
| 51 |
+
|
| 52 |
+
Returns status ("ok" or a reason not to trust the result), detected chart_type, confidence,
|
| 53 |
+
warnings, n_rows and the data as CSV text.
|
| 54 |
+
"""
|
| 55 |
+
if bool(image_url) == bool(image_base64):
|
| 56 |
+
raise ToolError("pass exactly one of image_url or image_base64")
|
| 57 |
+
try:
|
| 58 |
+
data = (await anyio.to_thread.run_sync(fetch_image, image_url) if image_url
|
| 59 |
+
else _decode_base64(image_base64))
|
| 60 |
+
except InputError as e:
|
| 61 |
+
raise ToolError(str(e)) from None
|
| 62 |
+
return await _run(data, chart_type, resample)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
async def extract_chart_file(image_path: str, chart_type: str = "", resample: int = 0) -> dict:
|
| 66 |
+
"""Extract the data from a chart image file on this computer (PNG/JPG) as CSV.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
image_path: path to a local PNG or JPG chart image.
|
| 70 |
+
chart_type: optional hint: line, bar, stacked_bar, grouped_bar or scatter. Empty = auto-detect.
|
| 71 |
+
resample: for line charts, report about this many evenly spaced x values (e.g. 40). 0 = off.
|
| 72 |
+
|
| 73 |
+
Returns status, chart_type, confidence, warnings, n_rows and the data as CSV text.
|
| 74 |
+
"""
|
| 75 |
+
path = Path(image_path).expanduser()
|
| 76 |
+
if not path.is_file():
|
| 77 |
+
raise ToolError(f"no such file: {path}")
|
| 78 |
+
return await _run(path.read_bytes(), chart_type, resample)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
async def _run(data: bytes, chart_type: str, resample: int) -> dict:
|
| 82 |
+
try:
|
| 83 |
+
out = await anyio.to_thread.run_sync(lambda: analyse(data, chart_type, resample, overlay=False))
|
| 84 |
+
except InputError as e:
|
| 85 |
+
raise ToolError(str(e)) from None # ToolError messages reach the client; other exceptions are hidden
|
| 86 |
+
return {k: out[k] for k in ("status", "chart_type", "confidence", "warnings", "n_rows", "csv")}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def main() -> None:
|
| 90 |
+
"""Local stdio server (Claude Desktop, Claude Code, Cursor): also offers reading image files from disk."""
|
| 91 |
+
mcp.add_tool(extract_chart_file) # local only: the public HTTP server must not read its own files
|
| 92 |
+
mcp.run()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
if __name__ == "__main__":
|
| 96 |
+
main()
|
plotscribe/service.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared request handling for the web page and the MCP server: validate image bytes and run the pipeline."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import base64
|
| 6 |
+
import ipaddress
|
| 7 |
+
import json
|
| 8 |
+
import socket
|
| 9 |
+
import tempfile
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from urllib.error import HTTPError, URLError
|
| 12 |
+
from urllib.parse import urljoin, urlsplit
|
| 13 |
+
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
| 14 |
+
|
| 15 |
+
import cv2
|
| 16 |
+
|
| 17 |
+
from . import export, pipeline
|
| 18 |
+
|
| 19 |
+
MAX_BYTES = 10 * 1024 * 1024
|
| 20 |
+
MAX_PIXELS = 25_000_000
|
| 21 |
+
CHART_TYPES = ("line", "bar", "stacked_bar", "grouped_bar", "scatter")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class InputError(ValueError):
|
| 25 |
+
"""Bad input from the caller; ``status`` is the HTTP status the web API reports."""
|
| 26 |
+
|
| 27 |
+
def __init__(self, status: int, message: str):
|
| 28 |
+
super().__init__(message)
|
| 29 |
+
self.status = status
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def image_suffix(data: bytes) -> str:
|
| 33 |
+
"""File suffix from the magic bytes; only PNG and JPEG are accepted."""
|
| 34 |
+
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
| 35 |
+
return ".png"
|
| 36 |
+
if data.startswith(b"\xff\xd8\xff"):
|
| 37 |
+
return ".jpg"
|
| 38 |
+
raise InputError(400, "only PNG or JPG images are supported")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class _NoRedirect(HTTPRedirectHandler):
|
| 42 |
+
def redirect_request(self, *args, **kwargs):
|
| 43 |
+
return None # redirects surface as HTTPError so each hop is re-checked
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _check_host(url: str) -> None:
|
| 47 |
+
"""Only fetch public http(s) addresses (no localhost / private network)."""
|
| 48 |
+
parts = urlsplit(url)
|
| 49 |
+
if parts.scheme not in ("http", "https") or not parts.hostname:
|
| 50 |
+
raise InputError(400, "image_url must be an http(s) URL")
|
| 51 |
+
try:
|
| 52 |
+
infos = socket.getaddrinfo(parts.hostname, parts.port or 443, proto=socket.IPPROTO_TCP)
|
| 53 |
+
except socket.gaierror:
|
| 54 |
+
raise InputError(400, f"cannot resolve host {parts.hostname}") from None
|
| 55 |
+
if not all(ipaddress.ip_address(info[4][0]).is_global for info in infos):
|
| 56 |
+
raise InputError(400, "image_url must point to a public address")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def fetch_image(url: str, max_redirects: int = 3) -> bytes:
|
| 60 |
+
opener = build_opener(_NoRedirect)
|
| 61 |
+
for _ in range(max_redirects + 1):
|
| 62 |
+
_check_host(url)
|
| 63 |
+
try:
|
| 64 |
+
with opener.open(Request(url, headers={"User-Agent": "plotscribe"}), timeout=15) as resp:
|
| 65 |
+
data = resp.read(MAX_BYTES + 1)
|
| 66 |
+
except HTTPError as e:
|
| 67 |
+
if e.code in (301, 302, 303, 307, 308) and e.headers.get("Location"):
|
| 68 |
+
url = urljoin(url, e.headers["Location"])
|
| 69 |
+
continue
|
| 70 |
+
raise InputError(400, f"could not fetch image_url (HTTP {e.code})") from None
|
| 71 |
+
except (URLError, TimeoutError) as e:
|
| 72 |
+
raise InputError(400, f"could not fetch image_url ({e})") from None
|
| 73 |
+
if len(data) > MAX_BYTES:
|
| 74 |
+
raise InputError(413, "image too large (max 10 MB)")
|
| 75 |
+
return data
|
| 76 |
+
raise InputError(400, "too many redirects")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def analyse(data: bytes, chart_type: str = "", resample: int = 0, overlay: bool = True) -> dict:
|
| 80 |
+
"""Run the pipeline on image bytes; returns status, CSV text, diagnostics, re-plot data and (optionally) overlay PNG."""
|
| 81 |
+
if len(data) > MAX_BYTES:
|
| 82 |
+
raise InputError(413, "image too large (max 10 MB)")
|
| 83 |
+
if chart_type and chart_type not in CHART_TYPES:
|
| 84 |
+
raise InputError(400, "invalid chart_type")
|
| 85 |
+
suffix = image_suffix(data)
|
| 86 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 87 |
+
path = Path(tmp) / f"upload{suffix}"
|
| 88 |
+
path.write_bytes(data)
|
| 89 |
+
img = cv2.imread(str(path))
|
| 90 |
+
if img is None:
|
| 91 |
+
raise InputError(400, "could not decode image")
|
| 92 |
+
if img.shape[0] * img.shape[1] > MAX_PIXELS:
|
| 93 |
+
raise InputError(413, "image has too many pixels")
|
| 94 |
+
res = pipeline.run(path, chart_type=chart_type or None,
|
| 95 |
+
resample=min(max(resample, 5), 400) if resample else None)
|
| 96 |
+
out = {
|
| 97 |
+
"status": res.extra.get("status", "ok"), "chart_type": res.chart_type,
|
| 98 |
+
"confidence": res.confidence, "warnings": res.warnings,
|
| 99 |
+
"csv": res.table.to_csv(index=False) if res.table is not None else "",
|
| 100 |
+
"n_rows": 0 if res.table is None else int(len(res.table)),
|
| 101 |
+
"diagnostics": json.loads(json.dumps(export.diagnostics(res), default=export._json_default)),
|
| 102 |
+
"plot": json.loads(json.dumps(export.plot_payload(res), default=export._json_default)),
|
| 103 |
+
}
|
| 104 |
+
if overlay:
|
| 105 |
+
ok, png = cv2.imencode(".png", cv2.cvtColor(export.debug_overlay(res), cv2.COLOR_RGB2BGR))
|
| 106 |
+
out["debug_png"] = base64.b64encode(png.tobytes()).decode() if ok else ""
|
| 107 |
+
return out
|
plotscribe/web.py
CHANGED
|
@@ -6,21 +6,38 @@ Requires the optional ``web`` extras (fastapi, uvicorn, python-multipart).
|
|
| 6 |
|
| 7 |
from __future__ import annotations
|
| 8 |
|
| 9 |
-
import
|
| 10 |
-
import
|
| 11 |
-
import tempfile
|
| 12 |
-
from pathlib import Path
|
| 13 |
|
| 14 |
-
import
|
| 15 |
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
| 16 |
-
from fastapi.responses import HTMLResponse, JSONResponse
|
| 17 |
|
| 18 |
-
from . import
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
_PAGE = r"""<!doctype html>
|
| 26 |
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
@@ -48,6 +65,8 @@ _PAGE = r"""<!doctype html>
|
|
| 48 |
.tip{position:absolute;pointer-events:none;background:#fff;border:1px solid rgba(11,11,11,.15);border-radius:6px;
|
| 49 |
padding:.35rem .5rem;font-size:.8rem;color:var(--ink);box-shadow:0 2px 8px rgba(0,0,0,.08);white-space:nowrap}
|
| 50 |
.note{font-size:.8rem;color:var(--muted);margin:.4rem 0 0}
|
|
|
|
|
|
|
| 51 |
.scroll{overflow-x:auto} pre{background:#f3f2ee;padding:.75rem;margin:0;font-size:.8rem}
|
| 52 |
details{margin:.75rem 0}
|
| 53 |
</style></head><body>
|
|
@@ -62,6 +81,17 @@ _PAGE = r"""<!doctype html>
|
|
| 62 |
<button>Extract</button>
|
| 63 |
</form>
|
| 64 |
<div id="out"></div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
<script>
|
| 66 |
const NS = "http://www.w3.org/2000/svg";
|
| 67 |
const $ = (tag, attrs = {}, parent) => {
|
|
@@ -284,7 +314,24 @@ f.onsubmit = async e => {
|
|
| 284 |
document.getElementById("orig").src = URL.createObjectURL(file);
|
| 285 |
drawChart(document.getElementById("replot"), d.plot);
|
| 286 |
};
|
| 287 |
-
</script></body></html>"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
|
| 289 |
|
| 290 |
@app.get("/", response_class=HTMLResponse)
|
|
@@ -297,35 +344,45 @@ def healthz() -> dict[str, str]:
|
|
| 297 |
return {"status": "ok"}
|
| 298 |
|
| 299 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
@app.post("/api/extract")
|
| 301 |
async def extract(file: UploadFile = File(...), chart_type: str = Form(""), resample: int = Form(0)
|
| 302 |
) -> JSONResponse:
|
| 303 |
"""Run the pipeline on an uploaded image; returns CSV text, diagnostics and overlay PNG."""
|
| 304 |
data = await file.read()
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
raise HTTPException(
|
| 309 |
-
|
| 310 |
-
if suffix not in (".png", ".jpg", ".jpeg"):
|
| 311 |
-
raise HTTPException(400, "only PNG or JPG images are supported")
|
| 312 |
-
with tempfile.TemporaryDirectory() as tmp:
|
| 313 |
-
path = Path(tmp) / f"upload{suffix}"
|
| 314 |
-
path.write_bytes(data)
|
| 315 |
-
img = cv2.imread(str(path))
|
| 316 |
-
if img is None:
|
| 317 |
-
raise HTTPException(400, "could not decode image")
|
| 318 |
-
if img.shape[0] * img.shape[1] > MAX_PIXELS:
|
| 319 |
-
raise HTTPException(413, "image has too many pixels")
|
| 320 |
-
res = pipeline.run(path, chart_type=chart_type or None,
|
| 321 |
-
resample=min(max(resample, 5), 400) if resample else None)
|
| 322 |
-
csv = res.table.to_csv(index=False) if res.table is not None else ""
|
| 323 |
-
ok, png = cv2.imencode(".png", cv2.cvtColor(export.debug_overlay(res), cv2.COLOR_RGB2BGR))
|
| 324 |
-
diag = json.loads(json.dumps(export.diagnostics(res), default=export._json_default))
|
| 325 |
-
plot = json.loads(json.dumps(export.plot_payload(res), default=export._json_default))
|
| 326 |
-
return JSONResponse({
|
| 327 |
-
"status": res.extra.get("status", "ok"), "chart_type": res.chart_type,
|
| 328 |
-
"confidence": res.confidence, "warnings": res.warnings, "csv": csv, "diagnostics": diag,
|
| 329 |
-
"debug_png": base64.b64encode(png.tobytes()).decode() if ok else "", "plot": plot,
|
| 330 |
-
"n_rows": 0 if res.table is None else int(len(res.table)),
|
| 331 |
-
})
|
|
|
|
| 6 |
|
| 7 |
from __future__ import annotations
|
| 8 |
|
| 9 |
+
import os
|
| 10 |
+
from contextlib import asynccontextmanager
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
import anyio
|
| 13 |
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
| 14 |
+
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, Response
|
| 15 |
|
| 16 |
+
from .service import InputError, analyse, fetch_image
|
| 17 |
|
| 18 |
+
# Absolute address used in the instructions for AI assistants (set it when serving from a custom domain).
|
| 19 |
+
PUBLIC_URL = os.environ.get("PLOTSCRIBE_PUBLIC_URL", "https://jkos9-plotscribe.hf.space").rstrip("/")
|
| 20 |
|
| 21 |
+
try: # MCP endpoint at /mcp when the ``mcp`` package is installed (part of the ``web`` extras)
|
| 22 |
+
from .mcp_server import mcp
|
| 23 |
+
_mcp_app = mcp.streamable_http_app(streamable_http_path="/mcp", stateless_http=True, json_response=True,
|
| 24 |
+
host="0.0.0.0")
|
| 25 |
+
except ImportError:
|
| 26 |
+
mcp = _mcp_app = None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@asynccontextmanager
|
| 30 |
+
async def _lifespan(_app):
|
| 31 |
+
if mcp is None:
|
| 32 |
+
yield
|
| 33 |
+
else:
|
| 34 |
+
async with mcp.session_manager.run():
|
| 35 |
+
yield
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
app = FastAPI(title="plotscribe", lifespan=_lifespan)
|
| 39 |
+
if _mcp_app is not None:
|
| 40 |
+
app.router.routes.extend(_mcp_app.routes)
|
| 41 |
|
| 42 |
_PAGE = r"""<!doctype html>
|
| 43 |
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
|
|
| 65 |
.tip{position:absolute;pointer-events:none;background:#fff;border:1px solid rgba(11,11,11,.15);border-radius:6px;
|
| 66 |
padding:.35rem .5rem;font-size:.8rem;color:var(--ink);box-shadow:0 2px 8px rgba(0,0,0,.08);white-space:nowrap}
|
| 67 |
.note{font-size:.8rem;color:var(--muted);margin:.4rem 0 0}
|
| 68 |
+
.ai{margin-top:2.5rem;border-top:1px solid var(--grid);padding-top:.5rem;color:var(--ink2);font-size:.9rem}
|
| 69 |
+
.ai code{overflow-wrap:anywhere}
|
| 70 |
.scroll{overflow-x:auto} pre{background:#f3f2ee;padding:.75rem;margin:0;font-size:.8rem}
|
| 71 |
details{margin:.75rem 0}
|
| 72 |
</style></head><body>
|
|
|
|
| 81 |
<button>Extract</button>
|
| 82 |
</form>
|
| 83 |
<div id="out"></div>
|
| 84 |
+
<section class="ai" id="for-ai-assistants">
|
| 85 |
+
<h2>For AI assistants and scripts</h2>
|
| 86 |
+
<p>To extract the data from a chart image that is online, open
|
| 87 |
+
<code>@PUBLIC_URL@/api/extract?url=IMAGE_URL</code> with the image address URL-encoded.
|
| 88 |
+
The reply is plain text: status, warnings and the data as CSV. Optional parameters:
|
| 89 |
+
<code>chart_type=line|bar|stacked_bar|grouped_bar|scatter</code>, <code>resample=40</code> (evenly spaced x values
|
| 90 |
+
for smooth line charts) and <code>format=json</code>. Check the status and warnings before trusting the numbers.</p>
|
| 91 |
+
<p>MCP server for Claude, ChatGPT, Cursor and other MCP clients: <code>@PUBLIC_URL@/mcp</code>
|
| 92 |
+
(streamable HTTP, no authentication), tool <code>extract_chart_data</code>.
|
| 93 |
+
API documentation: <a href="/docs">/docs</a>.</p>
|
| 94 |
+
</section>
|
| 95 |
<script>
|
| 96 |
const NS = "http://www.w3.org/2000/svg";
|
| 97 |
const $ = (tag, attrs = {}, parent) => {
|
|
|
|
| 314 |
document.getElementById("orig").src = URL.createObjectURL(file);
|
| 315 |
drawChart(document.getElementById("replot"), d.plot);
|
| 316 |
};
|
| 317 |
+
</script></body></html>""".replace("@PUBLIC_URL@", PUBLIC_URL)
|
| 318 |
+
|
| 319 |
+
_LLMS_TXT = """# plotscribe
|
| 320 |
+
|
| 321 |
+
> Free, open, fully automatic chart digitizer: converts an image of a line chart, bar chart (simple,
|
| 322 |
+
> grouped, stacked) or scatter plot into a CSV of its data. Classical computer vision and OCR, no
|
| 323 |
+
> neural networks; about 3-4 s per chart. Reports a status and warnings when the result should not be
|
| 324 |
+
> trusted.
|
| 325 |
+
|
| 326 |
+
- Web app: https://huggingface.co/spaces/jkos9/plotscribe
|
| 327 |
+
- Chart image online: GET @PUBLIC_URL@/api/extract?url=IMAGE_URL (URL-encoded; optional chart_type,
|
| 328 |
+
resample, format=json). Returns plain text: status, warnings and the data as CSV.
|
| 329 |
+
- Upload: POST @PUBLIC_URL@/api/extract (multipart: file=PNG/JPG, optional chart_type, resample);
|
| 330 |
+
returns JSON with status, chart_type, confidence, warnings, csv, diagnostics
|
| 331 |
+
- MCP server (streamable HTTP, no auth): @PUBLIC_URL@/mcp, tool
|
| 332 |
+
`extract_chart_data(image_url | image_base64, chart_type, resample)`
|
| 333 |
+
- API docs: @PUBLIC_URL@/docs
|
| 334 |
+
""".replace("@PUBLIC_URL@", PUBLIC_URL)
|
| 335 |
|
| 336 |
|
| 337 |
@app.get("/", response_class=HTMLResponse)
|
|
|
|
| 344 |
return {"status": "ok"}
|
| 345 |
|
| 346 |
|
| 347 |
+
@app.get("/llms.txt", response_class=PlainTextResponse)
|
| 348 |
+
def llms_txt() -> str:
|
| 349 |
+
return _LLMS_TXT
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
@app.get("/api/extract")
|
| 353 |
+
async def extract_url(url: str, chart_type: str = "", resample: int = 0, format: str = "text") -> Response:
|
| 354 |
+
"""Fetch a public chart image by URL and extract its data.
|
| 355 |
+
|
| 356 |
+
Meant for AI chat tools that can only open URLs: the default reply is plain text, and input errors
|
| 357 |
+
are reported in the text with status 200, because many of those tools drop the body of a 4xx reply.
|
| 358 |
+
"""
|
| 359 |
+
try:
|
| 360 |
+
out = await anyio.to_thread.run_sync(
|
| 361 |
+
lambda: analyse(fetch_image(url), chart_type, resample, overlay=False))
|
| 362 |
+
except InputError as e:
|
| 363 |
+
if format == "json":
|
| 364 |
+
raise HTTPException(e.status, str(e)) from None
|
| 365 |
+
return PlainTextResponse(f"plotscribe: could not process {url}\nstatus: error\nerror: {e}\n")
|
| 366 |
+
if format == "json":
|
| 367 |
+
return JSONResponse({k: out[k] for k in ("status", "chart_type", "confidence", "warnings", "n_rows",
|
| 368 |
+
"csv", "diagnostics")})
|
| 369 |
+
warnings = "".join(f"\n- {w}" for w in out["warnings"]) or " none"
|
| 370 |
+
return PlainTextResponse(
|
| 371 |
+
f"plotscribe result for {url}\n"
|
| 372 |
+
f"status: {out['status']} (anything other than ok means: do not trust the numbers blindly)\n"
|
| 373 |
+
f"chart type: {out['chart_type']} (confidence {out['confidence']:.2f})\n"
|
| 374 |
+
f"warnings:{warnings}\n"
|
| 375 |
+
f"rows: {out['n_rows']}\n\n"
|
| 376 |
+
f"CSV:\n{out['csv']}")
|
| 377 |
+
|
| 378 |
+
|
| 379 |
@app.post("/api/extract")
|
| 380 |
async def extract(file: UploadFile = File(...), chart_type: str = Form(""), resample: int = Form(0)
|
| 381 |
) -> JSONResponse:
|
| 382 |
"""Run the pipeline on an uploaded image; returns CSV text, diagnostics and overlay PNG."""
|
| 383 |
data = await file.read()
|
| 384 |
+
try:
|
| 385 |
+
out = await anyio.to_thread.run_sync(lambda: analyse(data, chart_type, resample))
|
| 386 |
+
except InputError as e:
|
| 387 |
+
raise HTTPException(e.status, str(e)) from None
|
| 388 |
+
return JSONResponse(out)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pyproject.toml
CHANGED
|
@@ -21,10 +21,11 @@ dependencies = [
|
|
| 21 |
[project.optional-dependencies]
|
| 22 |
dev = ["pytest>=8", "matplotlib>=3.8", "pillow>=10", "pyarrow>=14"]
|
| 23 |
paddle = ["paddleocr>=2.7"]
|
| 24 |
-
web = ["fastapi>=0.110", "uvicorn>=0.29", "python-multipart>=0.0.9"]
|
| 25 |
|
| 26 |
[project.scripts]
|
| 27 |
plotscribe = "plotscribe.cli:app"
|
|
|
|
| 28 |
|
| 29 |
[tool.setuptools]
|
| 30 |
packages = ["plotscribe"]
|
|
|
|
| 21 |
[project.optional-dependencies]
|
| 22 |
dev = ["pytest>=8", "matplotlib>=3.8", "pillow>=10", "pyarrow>=14"]
|
| 23 |
paddle = ["paddleocr>=2.7"]
|
| 24 |
+
web = ["fastapi>=0.110", "uvicorn>=0.29", "python-multipart>=0.0.9", "mcp>=2.3,<3"]
|
| 25 |
|
| 26 |
[project.scripts]
|
| 27 |
plotscribe = "plotscribe.cli:app"
|
| 28 |
+
plotscribe-mcp = "plotscribe.mcp_server:main"
|
| 29 |
|
| 30 |
[tool.setuptools]
|
| 31 |
packages = ["plotscribe"]
|
tests/test_web.py
CHANGED
|
@@ -24,3 +24,76 @@ def test_upload_roundtrip(tmp_path):
|
|
| 24 |
def test_rejects_non_image():
|
| 25 |
r = TestClient(app).post("/api/extract", files={"file": ("x.txt", b"hello", "text/plain")})
|
| 26 |
assert r.status_code == 400
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
def test_rejects_non_image():
|
| 25 |
r = TestClient(app).post("/api/extract", files={"file": ("x.txt", b"hello", "text/plain")})
|
| 26 |
assert r.status_code == 400
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _mcp_call(client, method, params, id_=1):
|
| 30 |
+
r = client.post("/mcp", json={"jsonrpc": "2.0", "id": id_, "method": method, "params": params},
|
| 31 |
+
headers={"Accept": "application/json, text/event-stream"})
|
| 32 |
+
assert r.status_code == 200, r.text
|
| 33 |
+
return r.json()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_mcp_extract_base64(tmp_path):
|
| 37 |
+
pytest.importorskip("mcp")
|
| 38 |
+
import base64
|
| 39 |
+
import json
|
| 40 |
+
img = synth.generate(9101, tmp_path, "clean", "bar")
|
| 41 |
+
with TestClient(app) as client:
|
| 42 |
+
tools = _mcp_call(client, "tools/list", {})["result"]["tools"]
|
| 43 |
+
assert [t["name"] for t in tools] == ["extract_chart_data"]
|
| 44 |
+
res = _mcp_call(client, "tools/call", {"name": "extract_chart_data", "arguments": {
|
| 45 |
+
"image_base64": base64.b64encode(img.read_bytes()).decode()}}, 2)["result"]
|
| 46 |
+
assert not res.get("isError"), res
|
| 47 |
+
out = res.get("structuredContent") or json.loads(res["content"][0]["text"])
|
| 48 |
+
assert out["status"] == "ok" and out["csv"].startswith("category") and out["n_rows"] > 0
|
| 49 |
+
bad = _mcp_call(client, "tools/call", {"name": "extract_chart_data", "arguments": {
|
| 50 |
+
"image_base64": base64.b64encode(b"hello").decode()}}, 3)["result"]
|
| 51 |
+
assert bad["isError"] and "PNG or JPG" in bad["content"][0]["text"]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_mcp_rejects_private_url():
|
| 55 |
+
pytest.importorskip("mcp")
|
| 56 |
+
from plotscribe.service import InputError, fetch_image
|
| 57 |
+
for url in ("http://127.0.0.1/x.png", "http://169.254.169.254/latest", "file:///etc/passwd"):
|
| 58 |
+
with pytest.raises(InputError):
|
| 59 |
+
fetch_image(url)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_llms_txt():
|
| 63 |
+
r = TestClient(app).get("/llms.txt")
|
| 64 |
+
assert r.status_code == 200 and "extract_chart_data" in r.text
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_extract_by_url(tmp_path, monkeypatch):
|
| 68 |
+
import plotscribe.web as web
|
| 69 |
+
img = synth.generate(9102, tmp_path, "clean", "bar")
|
| 70 |
+
monkeypatch.setattr(web, "fetch_image", lambda url: img.read_bytes())
|
| 71 |
+
client = TestClient(app)
|
| 72 |
+
r = client.get("/api/extract", params={"url": "https://example.org/chart.png"})
|
| 73 |
+
assert r.status_code == 200 and r.headers["content-type"].startswith("text/plain")
|
| 74 |
+
assert "status: ok" in r.text and "\ncategory," in r.text
|
| 75 |
+
d = client.get("/api/extract", params={"url": "https://example.org/chart.png", "format": "json"}).json()
|
| 76 |
+
assert d["status"] == "ok" and d["csv"].startswith("category")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_extract_by_url_errors_readable():
|
| 80 |
+
client = TestClient(app)
|
| 81 |
+
r = client.get("/api/extract", params={"url": "http://127.0.0.1/x.png"})
|
| 82 |
+
assert r.status_code == 200 and "status: error" in r.text and "public address" in r.text
|
| 83 |
+
assert client.get("/api/extract", params={"url": "http://127.0.0.1/x.png", "format": "json"}).status_code == 400
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_page_has_ai_instructions():
|
| 87 |
+
from plotscribe.web import PUBLIC_URL
|
| 88 |
+
page = TestClient(app).get("/").text
|
| 89 |
+
assert f"{PUBLIC_URL}/api/extract?url=" in page and f"{PUBLIC_URL}/mcp" in page and "@PUBLIC_URL@" not in page
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_mcp_local_file_tool(tmp_path):
|
| 93 |
+
pytest.importorskip("mcp")
|
| 94 |
+
import anyio
|
| 95 |
+
|
| 96 |
+
from plotscribe.mcp_server import extract_chart_file
|
| 97 |
+
img = synth.generate(9103, tmp_path, "clean", "bar")
|
| 98 |
+
out = anyio.run(extract_chart_file, str(img))
|
| 99 |
+
assert out["status"] == "ok" and out["n_rows"] > 0
|