chartduck-mcp 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- chartduck_client.py +181 -0
- chartduck_mcp-0.1.0.dist-info/METADATA +164 -0
- chartduck_mcp-0.1.0.dist-info/RECORD +9 -0
- chartduck_mcp-0.1.0.dist-info/WHEEL +5 -0
- chartduck_mcp-0.1.0.dist-info/entry_points.txt +3 -0
- chartduck_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
- chartduck_mcp-0.1.0.dist-info/top_level.txt +3 -0
- cli.py +75 -0
- mcp_server.py +106 -0
chartduck_client.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""ChartDuck REST 客户端:MCP server 与 CLI 共用。
|
|
3
|
+
|
|
4
|
+
传输是**裸字节**(`Content-Type` 决定解码方式),与 serve.py 的 `/extract`
|
|
5
|
+
`/extract_pdf` 一致,不做 base64 包装。仅用标准库(urllib),除 MCP server
|
|
6
|
+
本身外不需要第三方依赖。
|
|
7
|
+
"""
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.request
|
|
12
|
+
|
|
13
|
+
MAX_IMAGE_BYTES = 20 * 1024 * 1024
|
|
14
|
+
MAX_PDF_BYTES = 100 * 1024 * 1024
|
|
15
|
+
DEFAULT_TIMEOUT = 180
|
|
16
|
+
|
|
17
|
+
ERRORS = {
|
|
18
|
+
400: "invalid_input",
|
|
19
|
+
401: "unauthorized",
|
|
20
|
+
402: "quota_exceeded",
|
|
21
|
+
413: "too_large",
|
|
22
|
+
415: "unsupported_format",
|
|
23
|
+
422: "unreadable",
|
|
24
|
+
429: "rate_limited",
|
|
25
|
+
500: "upstream_error",
|
|
26
|
+
503: "upstream_error",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
_IMAGE_CTYPES = {
|
|
30
|
+
".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
|
|
31
|
+
".webp": "image/webp", ".bmp": "image/bmp", ".tif": "image/tiff",
|
|
32
|
+
".tiff": "image/tiff", ".gif": "image/gif",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ChartDuckError(RuntimeError):
|
|
37
|
+
def __init__(self, code, message, status=None):
|
|
38
|
+
super().__init__("%s: %s" % (code, message))
|
|
39
|
+
self.code = code
|
|
40
|
+
self.message = message
|
|
41
|
+
self.status = status
|
|
42
|
+
|
|
43
|
+
def as_dict(self):
|
|
44
|
+
return {"code": self.code, "message": self.message, "status": self.status}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _ctype_for(data, filename=None, default="application/octet-stream"):
|
|
48
|
+
"""按魔数猜类型,猜不出再看扩展名。"""
|
|
49
|
+
if data[:8] == b"\x89PNG\r\n\x1a\n":
|
|
50
|
+
return "image/png"
|
|
51
|
+
if data[:3] == b"\xff\xd8\xff":
|
|
52
|
+
return "image/jpeg"
|
|
53
|
+
if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
|
54
|
+
return "image/webp"
|
|
55
|
+
if data[:2] == b"BM":
|
|
56
|
+
return "image/bmp"
|
|
57
|
+
if data[:4] in (b"II*\x00", b"MM\x00*"):
|
|
58
|
+
return "image/tiff"
|
|
59
|
+
if data[:6] in (b"GIF87a", b"GIF89a"):
|
|
60
|
+
return "image/gif"
|
|
61
|
+
if data[:4] == b"%PDF":
|
|
62
|
+
return "application/pdf"
|
|
63
|
+
if filename:
|
|
64
|
+
for ext, ct in _IMAGE_CTYPES.items():
|
|
65
|
+
if filename.lower().endswith(ext):
|
|
66
|
+
return ct
|
|
67
|
+
return default
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _open(req, timeout):
|
|
71
|
+
try:
|
|
72
|
+
return urllib.request.urlopen(req, timeout=timeout)
|
|
73
|
+
except urllib.error.HTTPError as e:
|
|
74
|
+
raw = e.read()
|
|
75
|
+
try:
|
|
76
|
+
body = json.loads(raw)
|
|
77
|
+
except ValueError:
|
|
78
|
+
body = {}
|
|
79
|
+
code = body.get("error") or body.get("code") or ERRORS.get(e.code, "http_%d" % e.code)
|
|
80
|
+
msg = body.get("detail") or body.get("message") or raw[:300].decode("utf-8", "replace")
|
|
81
|
+
raise ChartDuckError(code, msg, e.code)
|
|
82
|
+
except urllib.error.URLError as e:
|
|
83
|
+
raise ChartDuckError("upstream_error", str(e.reason))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _fetch(url, max_bytes, what):
|
|
87
|
+
"""下载远端文件。只允许 https(本地开发可设 CHARTDUCK_ALLOW_HTTP=1)。"""
|
|
88
|
+
if not (url.startswith("https://") or
|
|
89
|
+
(os.environ.get("CHARTDUCK_ALLOW_HTTP") == "1" and url.startswith("http://"))):
|
|
90
|
+
raise ChartDuckError("invalid_input", "only https URLs are accepted: %s" % url)
|
|
91
|
+
req = urllib.request.Request(url, headers={"User-Agent": "chartduck-mcp/0.1"})
|
|
92
|
+
with _open(req, 30) as r:
|
|
93
|
+
data = r.read(max_bytes + 1)
|
|
94
|
+
if len(data) > max_bytes:
|
|
95
|
+
raise ChartDuckError("too_large", "%s exceeds %d bytes" % (what, max_bytes))
|
|
96
|
+
return data
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class ChartDuck:
|
|
100
|
+
def __init__(self, api_url=None, token=None, timeout=DEFAULT_TIMEOUT):
|
|
101
|
+
self.api_url = (api_url or os.environ.get("CHARTDUCK_API_URL", "")).rstrip("/")
|
|
102
|
+
self.token = token or os.environ.get("CHARTDUCK_TOKEN", "")
|
|
103
|
+
self.timeout = timeout
|
|
104
|
+
if not self.api_url:
|
|
105
|
+
raise ChartDuckError("invalid_input", "CHARTDUCK_API_URL is not set")
|
|
106
|
+
|
|
107
|
+
def _headers(self, ctype=None):
|
|
108
|
+
h = {"Content-Type": ctype} if ctype else {}
|
|
109
|
+
if self.token:
|
|
110
|
+
# 引擎现在认 X-Chartlab-Token;改名后认 X-Chartduck-Token。两个都发,
|
|
111
|
+
# 服务端切换时客户端不用跟着发版。
|
|
112
|
+
h["X-Chartlab-Token"] = self.token
|
|
113
|
+
h["X-Chartduck-Token"] = self.token
|
|
114
|
+
return h
|
|
115
|
+
|
|
116
|
+
def _post_raw(self, path, data, ctype):
|
|
117
|
+
req = urllib.request.Request(self.api_url + path, data=data,
|
|
118
|
+
headers=self._headers(ctype), method="POST")
|
|
119
|
+
with _open(req, self.timeout) as r:
|
|
120
|
+
res = json.loads(r.read().decode("utf-8"))
|
|
121
|
+
if isinstance(res, dict) and res.get("ok") is False:
|
|
122
|
+
raise ChartDuckError(res.get("error") or "unreadable",
|
|
123
|
+
res.get("detail") or res.get("error") or "extraction failed")
|
|
124
|
+
return res
|
|
125
|
+
|
|
126
|
+
# ---- images -----------------------------------------------------------
|
|
127
|
+
def extract_image_bytes(self, data, filename=None, include_geometry=True):
|
|
128
|
+
if len(data) > MAX_IMAGE_BYTES:
|
|
129
|
+
raise ChartDuckError("too_large", "image exceeds %d bytes" % MAX_IMAGE_BYTES)
|
|
130
|
+
res = self._post_raw("/extract", data, _ctype_for(data, filename, "image/png"))
|
|
131
|
+
if not include_geometry and isinstance(res.get("panels"), list):
|
|
132
|
+
for p in res["panels"]:
|
|
133
|
+
p.pop("geometry", None)
|
|
134
|
+
return res
|
|
135
|
+
|
|
136
|
+
def extract_image_file(self, path, include_geometry=True):
|
|
137
|
+
with open(path, "rb") as f:
|
|
138
|
+
return self.extract_image_bytes(f.read(), os.path.basename(path), include_geometry)
|
|
139
|
+
|
|
140
|
+
def extract_image_url(self, url, include_geometry=True):
|
|
141
|
+
return self.extract_image_bytes(_fetch(url, MAX_IMAGE_BYTES, "image"),
|
|
142
|
+
url.rsplit("/", 1)[-1], include_geometry)
|
|
143
|
+
|
|
144
|
+
# ---- pdfs -------------------------------------------------------------
|
|
145
|
+
def extract_pdf_bytes(self, data, pages=None, filename=None):
|
|
146
|
+
if len(data) > MAX_PDF_BYTES:
|
|
147
|
+
raise ChartDuckError("too_large", "pdf exceeds %d bytes" % MAX_PDF_BYTES)
|
|
148
|
+
res = self._post_raw("/extract_pdf", data,
|
|
149
|
+
_ctype_for(data, filename, "application/pdf"))
|
|
150
|
+
# 服务端当前解析前 N 页,选页在客户端过滤(不省解析开销,契约里写明)。
|
|
151
|
+
if pages and isinstance(res.get("pages"), list):
|
|
152
|
+
want = set(int(p) for p in pages)
|
|
153
|
+
res["pages"] = [p for p in res["pages"] if p.get("page") in want]
|
|
154
|
+
return res
|
|
155
|
+
|
|
156
|
+
def extract_pdf_file(self, path, pages=None):
|
|
157
|
+
with open(path, "rb") as f:
|
|
158
|
+
return self.extract_pdf_bytes(f.read(), pages, os.path.basename(path))
|
|
159
|
+
|
|
160
|
+
def extract_pdf_url(self, url, pages=None):
|
|
161
|
+
return self.extract_pdf_bytes(_fetch(url, MAX_PDF_BYTES, "pdf"), pages,
|
|
162
|
+
url.rsplit("/", 1)[-1])
|
|
163
|
+
|
|
164
|
+
# ---- misc -------------------------------------------------------------
|
|
165
|
+
def health(self):
|
|
166
|
+
req = urllib.request.Request(self.api_url + "/health", headers=self._headers())
|
|
167
|
+
with _open(req, 15) as r:
|
|
168
|
+
return json.loads(r.read().decode("utf-8"))
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def load_mock(path=None):
|
|
172
|
+
here = os.path.dirname(os.path.abspath(__file__))
|
|
173
|
+
path = path or os.path.join(here, "examples", "sample_response.json")
|
|
174
|
+
if not os.path.exists(path):
|
|
175
|
+
raise ChartDuckError(
|
|
176
|
+
"invalid_input",
|
|
177
|
+
"--mock needs examples/sample_response.json; it ships with the "
|
|
178
|
+
"source repository, not the wheel",
|
|
179
|
+
)
|
|
180
|
+
with open(path, encoding="utf-8") as f:
|
|
181
|
+
return json.load(f)
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: chartduck-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MCP server and CLI for ChartDuck chart data extraction
|
|
5
|
+
Author: ChartDuck
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://chartduck.com
|
|
8
|
+
Project-URL: Repository, https://github.com/MoDongla/chartduck-mcp
|
|
9
|
+
Project-URL: Issues, https://github.com/MoDongla/chartduck-mcp/issues
|
|
10
|
+
Keywords: mcp,model-context-protocol,chart,ocr,pdf,data-extraction
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Image Recognition
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: mcp<3,>=1.10
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# ChartDuck MCP
|
|
21
|
+
|
|
22
|
+
Open-source MCP server and CLI for [ChartDuck](https://chartduck.com) — chart data
|
|
23
|
+
extraction from scientific figures and document pages. The extraction engine runs on
|
|
24
|
+
the hosted service; this repository is the thin client (MCP + CLI + Python SDK).
|
|
25
|
+
|
|
26
|
+
> **Status: pre-release.** Version 0.1.0 reserves the package name; the hosted API is
|
|
27
|
+
> not publicly available yet, so the client cannot reach a live service. The contract,
|
|
28
|
+
> code and error semantics below are implemented and tested against a mock and a local
|
|
29
|
+
> engine.
|
|
30
|
+
|
|
31
|
+
## What it does
|
|
32
|
+
|
|
33
|
+
Given a chart image (or a PDF page), return structured data per panel:
|
|
34
|
+
|
|
35
|
+
- panel box, chart type (`bar` / `barh` / `line` / `scatter` / `box`)
|
|
36
|
+
- data series (values in data coordinates when the axes can be calibrated)
|
|
37
|
+
- geometry for panels without a value axis (`normalized_box` units)
|
|
38
|
+
- recognized axis titles (beta)
|
|
39
|
+
|
|
40
|
+
```json
|
|
41
|
+
{
|
|
42
|
+
"panels": [
|
|
43
|
+
{
|
|
44
|
+
"box": [100.0, 19.0, 474.0, 393.0],
|
|
45
|
+
"chart_type": "line",
|
|
46
|
+
"axis_labels": {
|
|
47
|
+
"x": {"text": "Baseline Fgas", "score": 0.98},
|
|
48
|
+
"y": {"text": "Change in Fgas", "score": 1.0}
|
|
49
|
+
},
|
|
50
|
+
"data": {"series": [{"kind": "line", "points": [[0.5022, -0.0007], "..."]}]}
|
|
51
|
+
}
|
|
52
|
+
],
|
|
53
|
+
"meta": {"engine_version": "1.4.0", "elapsed_ms": 2640}
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Honest capability statement
|
|
58
|
+
|
|
59
|
+
Measured on public ICPR2022-style documents (unseen distribution):
|
|
60
|
+
|
|
61
|
+
- **~65-70% of figures yield data automatically**; the rest return `data: null`.
|
|
62
|
+
- Supported types: vertical bar, line, scatter, vertical box, horizontal bar.
|
|
63
|
+
`scatter-line` is partially supported. Other types are refused, not guessed.
|
|
64
|
+
- **If the extractor is not confident, it returns `null` instead of a wrong table.**
|
|
65
|
+
This is a design choice: a missing value is recoverable, a plausible wrong value is not.
|
|
66
|
+
- Axis titles are beta: x-axis content accuracy 91.7%, y-axis 76.9% — not covered by any
|
|
67
|
+
support commitment.
|
|
68
|
+
|
|
69
|
+
Full benchmark methodology: <https://chartduck.com/benchmarks> (site launch pending).
|
|
70
|
+
|
|
71
|
+
## Install
|
|
72
|
+
|
|
73
|
+
Requires Python 3.10+.
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
pip install chartduck-mcp # 0.1.0: name reservation, no live API yet
|
|
77
|
+
# or from source
|
|
78
|
+
git clone https://github.com/MoDongla/chartduck-mcp && cd chartduck-mcp && pip install -e .
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Configure
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
export CHARTDUCK_API_URL="https://api.chartduck.com" # hosted service base URL
|
|
85
|
+
export CHARTDUCK_TOKEN="..." # pilot API token
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Use as an MCP server
|
|
89
|
+
|
|
90
|
+
Claude Code:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
claude mcp add chartduck -- chartduck-mcp
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Claude Desktop / generic JSON config:
|
|
97
|
+
|
|
98
|
+
```json
|
|
99
|
+
{
|
|
100
|
+
"mcpServers": {
|
|
101
|
+
"chartduck": {
|
|
102
|
+
"command": "chartduck-mcp",
|
|
103
|
+
"env": {
|
|
104
|
+
"CHARTDUCK_API_URL": "https://api.chartduck.com",
|
|
105
|
+
"CHARTDUCK_TOKEN": "..."
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Streamable HTTP mode (for hosting):
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
chartduck-mcp --http # listens on 0.0.0.0:8000/mcp by default
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### Tools
|
|
119
|
+
|
|
120
|
+
| Tool | Input | Returns |
|
|
121
|
+
|---|---|---|
|
|
122
|
+
| `extract_chart` | `image_base64` or `image_url`, `include_geometry` | `{panels: [...], meta}` |
|
|
123
|
+
| `extract_chart_pdf` | `pdf_base64` or `pdf_url`, `pages` (`"1-5"`, `"3"`, `"1,3"`) | `{pages: [{page, panels}], meta}` |
|
|
124
|
+
|
|
125
|
+
Tool failures come back as MCP `isError` results with text `code: message`
|
|
126
|
+
(`invalid_input`, `unauthorized`, `quota_exceeded`, `unreadable`, `rate_limited`, ...);
|
|
127
|
+
full table in `docs/mcp-contract.md`.
|
|
128
|
+
|
|
129
|
+
## Use as a CLI
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
chartduck extract figure.png -o figure.json
|
|
133
|
+
chartduck extract-pdf paper.pdf --pages 1-3 -o paper.json
|
|
134
|
+
chartduck health
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Add `--mock` to parse `examples/sample_response.json` without a service
|
|
138
|
+
(useful for wiring integrations).
|
|
139
|
+
|
|
140
|
+
## SDK
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from chartduck_client import ChartDuck
|
|
144
|
+
|
|
145
|
+
client = ChartDuck() # reads CHARTDUCK_API_URL / CHARTDUCK_TOKEN
|
|
146
|
+
result = client.extract_image_file("figure.png")
|
|
147
|
+
for panel in result["panels"]:
|
|
148
|
+
print(panel["chart_type"], panel.get("data"))
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Layout
|
|
152
|
+
|
|
153
|
+
```
|
|
154
|
+
chartduck_client.py # REST client (stdlib urllib; the only third-party dep is `mcp`)
|
|
155
|
+
mcp_server.py # MCP server (FastMCP, stdio or streamable HTTP)
|
|
156
|
+
cli.py # command line
|
|
157
|
+
docs/mcp-contract.md # tool contract, error codes, limits (Chinese)
|
|
158
|
+
examples/ # sample response
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## License
|
|
162
|
+
|
|
163
|
+
MIT. The hosted ChartDuck service, extraction engine, and evaluation corpus are not
|
|
164
|
+
part of this repository.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
chartduck_client.py,sha256=E_ONJiiv9tGBFjjU1-WVtBoEiLcc1miFD5iazZO38dE,7329
|
|
2
|
+
cli.py,sha256=Ys5nzpBHsPVuaWs4_GBWhIrto3w95lkQUz-uNsXLI9M,2277
|
|
3
|
+
mcp_server.py,sha256=6N4LPz94K3bGGhh6L_iGU94h2yyGoIpVWMcnqS9BnbA,3600
|
|
4
|
+
chartduck_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=vlHWThwwphnKWqGnB4xbjoAt_qrQOXULvL39S8SrZsA,1066
|
|
5
|
+
chartduck_mcp-0.1.0.dist-info/METADATA,sha256=h2x5AypPTkCacXiJhnOWGAA0bYbmxguX_dYP3NUyPGM,5196
|
|
6
|
+
chartduck_mcp-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
chartduck_mcp-0.1.0.dist-info/entry_points.txt,sha256=a2iLoTvdOfLqM9Wh0xQmxpwqTsNdG-VE7DU1unkpjS0,71
|
|
8
|
+
chartduck_mcp-0.1.0.dist-info/top_level.txt,sha256=oxbQdI99juMaoFq6bM8RXFPuBINoII5CuUf6t5qUUpw,32
|
|
9
|
+
chartduck_mcp-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ChartDuck
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
cli.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""ChartDuck CLI。
|
|
3
|
+
|
|
4
|
+
chartduck extract figure.png -o figure.json
|
|
5
|
+
chartduck extract-pdf paper.pdf --pages 1-3 -o paper.json
|
|
6
|
+
chartduck health
|
|
7
|
+
"""
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
from chartduck_client import ChartDuck, ChartDuckError, load_mock
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _emit(obj, out):
|
|
16
|
+
text = json.dumps(obj, ensure_ascii=False, indent=1)
|
|
17
|
+
if out:
|
|
18
|
+
with open(out, "w", encoding="utf-8") as f:
|
|
19
|
+
f.write(text + "\n")
|
|
20
|
+
print("->", out)
|
|
21
|
+
else:
|
|
22
|
+
print(text)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _run(fn, out):
|
|
26
|
+
try:
|
|
27
|
+
_emit(fn(), out)
|
|
28
|
+
return 0
|
|
29
|
+
except ChartDuckError as e:
|
|
30
|
+
print(json.dumps(e.as_dict(), ensure_ascii=False), file=sys.stderr)
|
|
31
|
+
return 1
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def main(argv=None):
|
|
35
|
+
ap = argparse.ArgumentParser(prog="chartduck")
|
|
36
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
37
|
+
|
|
38
|
+
e = sub.add_parser("extract", help="extract chart data from an image")
|
|
39
|
+
e.add_argument("path")
|
|
40
|
+
e.add_argument("-o", "--out")
|
|
41
|
+
e.add_argument("--no-geometry", action="store_true")
|
|
42
|
+
e.add_argument("--mock", action="store_true", help="use examples/sample_response.json")
|
|
43
|
+
|
|
44
|
+
p = sub.add_parser("extract-pdf", help="extract chart data from a PDF")
|
|
45
|
+
p.add_argument("path")
|
|
46
|
+
p.add_argument("--pages", help='"1-5", "3", or "1,3,7"')
|
|
47
|
+
p.add_argument("-o", "--out")
|
|
48
|
+
p.add_argument("--mock", action="store_true")
|
|
49
|
+
|
|
50
|
+
sub.add_parser("health", help="check the hosted service")
|
|
51
|
+
args = ap.parse_args(argv)
|
|
52
|
+
|
|
53
|
+
if args.cmd == "health":
|
|
54
|
+
return _run(lambda: ChartDuck().health(), None)
|
|
55
|
+
if args.mock:
|
|
56
|
+
return _run(load_mock, args.out)
|
|
57
|
+
if args.cmd == "extract":
|
|
58
|
+
return _run(lambda: ChartDuck().extract_image_file(args.path, not args.no_geometry),
|
|
59
|
+
args.out)
|
|
60
|
+
if args.cmd == "extract-pdf":
|
|
61
|
+
pages = None
|
|
62
|
+
if args.pages:
|
|
63
|
+
pages = []
|
|
64
|
+
for part in args.pages.split(","):
|
|
65
|
+
if "-" in part:
|
|
66
|
+
a, b = part.split("-", 1)
|
|
67
|
+
pages.extend(range(int(a), int(b) + 1))
|
|
68
|
+
elif part:
|
|
69
|
+
pages.append(int(part))
|
|
70
|
+
return _run(lambda: ChartDuck().extract_pdf_file(args.path, pages), args.out)
|
|
71
|
+
return 2
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
if __name__ == "__main__":
|
|
75
|
+
sys.exit(main())
|
mcp_server.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""ChartDuck MCP server(FastMCP)。
|
|
3
|
+
|
|
4
|
+
工具名用 snake_case(MCP 客户端对工具名的字符集有约束,不用点号命名空间;
|
|
5
|
+
服务器名 `chartduck` 本身就是命名空间)。
|
|
6
|
+
|
|
7
|
+
chartduck-mcp # stdio
|
|
8
|
+
chartduck-mcp --http # streamable HTTP, 0.0.0.0:8000/mcp
|
|
9
|
+
"""
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
try: # mcp >= 2 把 FastMCP 改名为 MCPServer
|
|
13
|
+
from mcp.server.mcpserver import MCPServer as _Server
|
|
14
|
+
from mcp.server.mcpserver.exceptions import ToolError as _ToolError
|
|
15
|
+
except ImportError: # mcp 1.x
|
|
16
|
+
from mcp.server.fastmcp import FastMCP as _Server
|
|
17
|
+
from mcp.server.fastmcp.exceptions import ToolError as _ToolError
|
|
18
|
+
|
|
19
|
+
from chartduck_client import ChartDuck, ChartDuckError
|
|
20
|
+
|
|
21
|
+
mcp = _Server("chartduck")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _fail(e):
|
|
25
|
+
# ToolError 是「预期内失败」:客户端拿到 isError=true,文本里带 code,
|
|
26
|
+
# 服务端只记一行日志、不打 traceback(普通异常会被 SDK 换成通用文案)。
|
|
27
|
+
raise _ToolError("%s: %s" % (e.code, e.message))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@mcp.tool()
|
|
31
|
+
def extract_chart(image_base64: str = "", image_url: str = "",
|
|
32
|
+
include_geometry: bool = True) -> dict:
|
|
33
|
+
"""Extract chart data from an image.
|
|
34
|
+
|
|
35
|
+
Provide exactly one of image_base64 (raw base64, no data: prefix) or image_url.
|
|
36
|
+
Returns {panels: [{box, chart_type, axis, data, geometry, axis_labels}], meta}.
|
|
37
|
+
When the extractor is not confident a panel returns data: null — never guessed.
|
|
38
|
+
"""
|
|
39
|
+
try:
|
|
40
|
+
if bool(image_base64) == bool(image_url):
|
|
41
|
+
raise ChartDuckError("invalid_input",
|
|
42
|
+
"provide exactly one of image_base64 or image_url")
|
|
43
|
+
client = ChartDuck()
|
|
44
|
+
if image_url:
|
|
45
|
+
return client.extract_image_url(image_url, include_geometry)
|
|
46
|
+
return client.extract_image_bytes(_b64(image_base64), None, include_geometry)
|
|
47
|
+
except ChartDuckError as e:
|
|
48
|
+
_fail(e)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@mcp.tool()
|
|
52
|
+
def extract_chart_pdf(pdf_base64: str = "", pdf_url: str = "", pages: str = "") -> dict:
|
|
53
|
+
"""Extract chart data from a PDF.
|
|
54
|
+
|
|
55
|
+
Provide exactly one of pdf_base64 or pdf_url. `pages` accepts "1-5", "3", or "1,3,7".
|
|
56
|
+
Returns {pages: [{page, panels: [...]}], meta}.
|
|
57
|
+
"""
|
|
58
|
+
try:
|
|
59
|
+
if bool(pdf_base64) == bool(pdf_url):
|
|
60
|
+
raise ChartDuckError("invalid_input",
|
|
61
|
+
"provide exactly one of pdf_base64 or pdf_url")
|
|
62
|
+
client = ChartDuck()
|
|
63
|
+
spec = _pages(pages)
|
|
64
|
+
if pdf_url:
|
|
65
|
+
return client.extract_pdf_url(pdf_url, spec)
|
|
66
|
+
return client.extract_pdf_bytes(_b64(pdf_base64), spec)
|
|
67
|
+
except ChartDuckError as e:
|
|
68
|
+
_fail(e)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _b64(s):
|
|
72
|
+
import base64
|
|
73
|
+
try:
|
|
74
|
+
return base64.b64decode(s, validate=True)
|
|
75
|
+
except Exception:
|
|
76
|
+
raise ChartDuckError("invalid_input", "input is not valid base64")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _pages(s):
|
|
80
|
+
if not s:
|
|
81
|
+
return None
|
|
82
|
+
out = []
|
|
83
|
+
try:
|
|
84
|
+
for part in str(s).split(","):
|
|
85
|
+
part = part.strip()
|
|
86
|
+
if "-" in part:
|
|
87
|
+
a, b = part.split("-", 1)
|
|
88
|
+
out.extend(range(int(a), int(b) + 1))
|
|
89
|
+
elif part:
|
|
90
|
+
out.append(int(part))
|
|
91
|
+
except ValueError:
|
|
92
|
+
raise ChartDuckError("invalid_input", "invalid pages spec: %s" % s)
|
|
93
|
+
if not out or any(p < 1 for p in out):
|
|
94
|
+
raise ChartDuckError("invalid_input", "invalid pages spec: %s" % s)
|
|
95
|
+
return out
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def main():
|
|
99
|
+
if "--http" in sys.argv:
|
|
100
|
+
mcp.run(transport="streamable-http")
|
|
101
|
+
else:
|
|
102
|
+
mcp.run()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
if __name__ == "__main__":
|
|
106
|
+
main()
|