pydfig 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.
- pydfig/__init__.py +43 -0
- pydfig/__main__.py +7 -0
- pydfig/cli.py +88 -0
- pydfig/decoder.py +109 -0
- pydfig/encoder.py +103 -0
- pydfig/html.py +191 -0
- pydfig/matplotlib_converter.py +213 -0
- pydfig-0.1.0.dist-info/METADATA +154 -0
- pydfig-0.1.0.dist-info/RECORD +13 -0
- pydfig-0.1.0.dist-info/WHEEL +5 -0
- pydfig-0.1.0.dist-info/entry_points.txt +2 -0
- pydfig-0.1.0.dist-info/licenses/LICENSE +21 -0
- pydfig-0.1.0.dist-info/top_level.txt +1 -0
pydfig/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""
|
|
2
|
+
pydfig — self-describing scientific figures (Figure-as-Data).
|
|
3
|
+
|
|
4
|
+
A pydfig figure looks like a normal SVG/PNG in any viewer, but carries its
|
|
5
|
+
exact underlying data as structured JSON that parsers and LLM agents read
|
|
6
|
+
losslessly — no OCR, no pixel digitization, no error.
|
|
7
|
+
|
|
8
|
+
* SVG -> JSON payload inside the standard W3C <metadata> element
|
|
9
|
+
(renderers ignore it; parsers/LLMs read it losslessly),
|
|
10
|
+
plus per-element `data-*` attribute redundancy.
|
|
11
|
+
* PNG -> JSON payload inside a private ancillary chunk `dDat`
|
|
12
|
+
(a legal PNG; any viewer opens it).
|
|
13
|
+
|
|
14
|
+
Pure standard library for encode/decode; matplotlib is an optional extra for
|
|
15
|
+
the matplotlib export helper.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from .decoder import (
|
|
19
|
+
decode_svg,
|
|
20
|
+
decode_png,
|
|
21
|
+
decode_any,
|
|
22
|
+
extract_datapoints,
|
|
23
|
+
)
|
|
24
|
+
from .encoder import (
|
|
25
|
+
build_payload,
|
|
26
|
+
embed_in_svg,
|
|
27
|
+
inject_png_ddat,
|
|
28
|
+
PYDFIG_NS,
|
|
29
|
+
SCHEMA_VERSION,
|
|
30
|
+
)
|
|
31
|
+
from .html import render_html, write_html
|
|
32
|
+
from .matplotlib_converter import convert, quick_convert
|
|
33
|
+
|
|
34
|
+
__version__ = "0.1.0"
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"decode_svg", "decode_png", "decode_any", "extract_datapoints",
|
|
38
|
+
"build_payload", "embed_in_svg", "inject_png_ddat",
|
|
39
|
+
"PYDFIG_NS", "SCHEMA_VERSION",
|
|
40
|
+
"render_html", "write_html",
|
|
41
|
+
"convert", "quick_convert",
|
|
42
|
+
"__version__",
|
|
43
|
+
]
|
pydfig/__main__.py
ADDED
pydfig/cli.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""
|
|
2
|
+
pydfig.cli — command line interface.
|
|
3
|
+
|
|
4
|
+
Usage:
|
|
5
|
+
python -m pydfig encode <file.svg|file.png> --payload P.json [-o OUT]
|
|
6
|
+
inject a pydfig payload into an SVG or PNG file.
|
|
7
|
+
|
|
8
|
+
python -m pydfig decode <file.svg|file.png> [-o OUT_BASE]
|
|
9
|
+
decode the payload and write two files:
|
|
10
|
+
OUT_BASE.json — machine-readable JSON for AI / pipelines
|
|
11
|
+
OUT_BASE.html — human-friendly HTML view of the data
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import sys
|
|
18
|
+
|
|
19
|
+
from .decoder import decode_any
|
|
20
|
+
from .encoder import embed_in_svg, inject_png_ddat
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _info(payload):
|
|
24
|
+
ft = payload.get("figure_type", "?")
|
|
25
|
+
n_pts = len(payload.get("points", []))
|
|
26
|
+
n_curves = len(payload.get("curves", []))
|
|
27
|
+
return f"type={ft} points={n_pts} curves={n_curves}"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def main(argv=None):
|
|
31
|
+
ap = argparse.ArgumentParser(prog="pydfig", description="pydfig self-describing figure toolkit")
|
|
32
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
33
|
+
|
|
34
|
+
p_enc = sub.add_parser("encode", help="inject a pydfig payload into an SVG or PNG")
|
|
35
|
+
p_enc.add_argument("file", help="input SVG or PNG file")
|
|
36
|
+
p_enc.add_argument("--payload", required=True, help="JSON file with the pydfig payload")
|
|
37
|
+
p_enc.add_argument("-o", "--out", default=None, help="output file (default: <input>_pydfig.<ext>)")
|
|
38
|
+
|
|
39
|
+
p_dec = sub.add_parser("decode", help="decode payload -> JSON (AI) + HTML (human)")
|
|
40
|
+
p_dec.add_argument("file", help="input SVG or PNG file")
|
|
41
|
+
p_dec.add_argument("-o", "--out", default=None, help="output base name (default: <input>_pydfig)")
|
|
42
|
+
|
|
43
|
+
args = ap.parse_args(argv)
|
|
44
|
+
|
|
45
|
+
if args.cmd == "encode":
|
|
46
|
+
with open(args.payload, encoding="utf-8") as f:
|
|
47
|
+
payload = json.load(f)
|
|
48
|
+
ext = os.path.splitext(args.file)[1].lower()
|
|
49
|
+
if ext == ".svg":
|
|
50
|
+
with open(args.file, "r", encoding="utf-8") as f:
|
|
51
|
+
svg_text = f.read()
|
|
52
|
+
out = args.out or (os.path.splitext(args.file)[0] + "_pydfig.svg")
|
|
53
|
+
with open(out, "w", encoding="utf-8") as f:
|
|
54
|
+
f.write(embed_in_svg(svg_text, payload))
|
|
55
|
+
elif ext == ".png":
|
|
56
|
+
with open(args.file, "rb") as f:
|
|
57
|
+
png_bytes = f.read()
|
|
58
|
+
out = args.out or (os.path.splitext(args.file)[0] + "_pydfig.png")
|
|
59
|
+
with open(out, "wb") as f:
|
|
60
|
+
f.write(inject_png_ddat(png_bytes, payload))
|
|
61
|
+
else:
|
|
62
|
+
print("unsupported input extension; use .svg or .png", file=sys.stderr)
|
|
63
|
+
return 1
|
|
64
|
+
print("pydfig payload injected ->", out)
|
|
65
|
+
return 0
|
|
66
|
+
|
|
67
|
+
if args.cmd == "decode":
|
|
68
|
+
payload = decode_any(args.file)
|
|
69
|
+
if payload is None:
|
|
70
|
+
print("no pydfig payload found in", args.file, file=sys.stderr)
|
|
71
|
+
return 1
|
|
72
|
+
base = args.out or (os.path.splitext(args.file)[0] + "_pydfig")
|
|
73
|
+
json_path = base + ".json"
|
|
74
|
+
html_path = base + ".html"
|
|
75
|
+
with open(json_path, "w", encoding="utf-8") as f:
|
|
76
|
+
json.dump(payload, f, ensure_ascii=False, indent=2)
|
|
77
|
+
from .html import write_html
|
|
78
|
+
write_html(payload, html_path)
|
|
79
|
+
print("decoded:", _info(payload))
|
|
80
|
+
print(" ->", json_path, "(machine-readable JSON)")
|
|
81
|
+
print(" ->", html_path, "(human-friendly HTML)")
|
|
82
|
+
return 0
|
|
83
|
+
|
|
84
|
+
return 1
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
if __name__ == "__main__":
|
|
88
|
+
sys.exit(main())
|
pydfig/decoder.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""
|
|
2
|
+
pydfig.decoder — read pydfig payloads from SVG / PNG files.
|
|
3
|
+
|
|
4
|
+
Two embedding channels are supported:
|
|
5
|
+
|
|
6
|
+
1. SVG ``<metadata>`` JSON payload (primary channel).
|
|
7
|
+
2. SVG per-element ``data-*`` attributes (redundancy channel; useful for
|
|
8
|
+
spot-checking and as a fallback when the metadata block is stripped).
|
|
9
|
+
3. PNG private ancillary chunk ``dDat``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import re
|
|
14
|
+
import struct
|
|
15
|
+
|
|
16
|
+
_PNG_SIG = b"\x89PNG\r\n\x1a\n"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _read_text(source):
|
|
20
|
+
"""Accept a filesystem path, raw text, or bytes; return text."""
|
|
21
|
+
if isinstance(source, (bytes, bytearray)):
|
|
22
|
+
return bytes(source).decode("utf-8")
|
|
23
|
+
if isinstance(source, str) and source.lstrip().startswith("<"):
|
|
24
|
+
return source
|
|
25
|
+
with open(source, "r", encoding="utf-8") as f:
|
|
26
|
+
return f.read()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def decode_svg(source):
|
|
30
|
+
"""Extract the pydfig JSON payload from an SVG file/string.
|
|
31
|
+
|
|
32
|
+
Returns the payload dict, or None if no <metadata> payload is present.
|
|
33
|
+
"""
|
|
34
|
+
text = _read_text(source)
|
|
35
|
+
m = re.search(r"<metadata>(.*?)</metadata>", text, re.S)
|
|
36
|
+
if not m:
|
|
37
|
+
return None
|
|
38
|
+
inner = m.group(1)
|
|
39
|
+
cdata = re.search(r"<!\[CDATA\[(.*?)\]\]>", inner, re.S)
|
|
40
|
+
js = cdata.group(1) if cdata else re.sub(r"<[^>]+>", "", inner)
|
|
41
|
+
return json.loads(js)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def extract_datapoints(source):
|
|
45
|
+
"""Extract per-element ``data-*`` attributes (the redundancy channel).
|
|
46
|
+
|
|
47
|
+
Every graphical element a pydfig encoder produces carries its own copy of
|
|
48
|
+
the underlying values, e.g. ``<circle ... data-x="-1.95" data-y="0.42"
|
|
49
|
+
data-material="NiO"/>``. This function collects them all.
|
|
50
|
+
|
|
51
|
+
Returns a list of dicts; numeric-looking values are converted to float.
|
|
52
|
+
"""
|
|
53
|
+
text = _read_text(source)
|
|
54
|
+
out = []
|
|
55
|
+
for m in re.finditer(r"<(circle|rect|path|line|polyline|text)\b[^>]*>", text):
|
|
56
|
+
tag = m.group(0)
|
|
57
|
+
attrs = dict(re.findall(r'(data-[\w-]+)="([^"]*)"', tag))
|
|
58
|
+
if not attrs:
|
|
59
|
+
continue
|
|
60
|
+
rec = {}
|
|
61
|
+
for k, v in attrs.items():
|
|
62
|
+
key = k[len("data-"):]
|
|
63
|
+
try:
|
|
64
|
+
rec[key] = float(v)
|
|
65
|
+
except ValueError:
|
|
66
|
+
rec[key] = v
|
|
67
|
+
out.append(rec)
|
|
68
|
+
return out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def decode_png(source):
|
|
72
|
+
"""Extract the JSON payload from a PNG ``dDat`` private chunk.
|
|
73
|
+
|
|
74
|
+
Accepts a path or raw PNG bytes. Returns the payload dict or None.
|
|
75
|
+
"""
|
|
76
|
+
if isinstance(source, (bytes, bytearray)):
|
|
77
|
+
data = bytes(source)
|
|
78
|
+
else:
|
|
79
|
+
with open(source, "rb") as f:
|
|
80
|
+
data = f.read()
|
|
81
|
+
if data[:8] != _PNG_SIG:
|
|
82
|
+
raise ValueError("not a PNG/pydfig file")
|
|
83
|
+
i = 8
|
|
84
|
+
while i < len(data):
|
|
85
|
+
length = struct.unpack(">I", data[i:i + 4])[0]
|
|
86
|
+
ctype = data[i + 4:i + 8]
|
|
87
|
+
cdata = data[i + 8:i + 8 + length]
|
|
88
|
+
if ctype == b"dDat":
|
|
89
|
+
return json.loads(cdata.decode("utf-8"))
|
|
90
|
+
i += 12 + length
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def decode_any(source):
|
|
95
|
+
"""Auto-detect the container and decode the payload.
|
|
96
|
+
|
|
97
|
+
Dispatch order: PNG signature -> SVG text probe.
|
|
98
|
+
Returns the payload dict or None.
|
|
99
|
+
"""
|
|
100
|
+
if isinstance(source, (bytes, bytearray)) and bytes(source)[:8] == _PNG_SIG:
|
|
101
|
+
return decode_png(source)
|
|
102
|
+
if isinstance(source, str):
|
|
103
|
+
if source.lstrip().startswith("<"):
|
|
104
|
+
return decode_svg(source)
|
|
105
|
+
with open(source, "rb") as f:
|
|
106
|
+
head = f.read(8)
|
|
107
|
+
if head == _PNG_SIG:
|
|
108
|
+
return decode_png(source)
|
|
109
|
+
return decode_svg(source)
|
pydfig/encoder.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""
|
|
2
|
+
pydfig.encoder — minimal pydfig writer (pure standard library).
|
|
3
|
+
|
|
4
|
+
Embedding primitives:
|
|
5
|
+
|
|
6
|
+
* ``embed_in_svg`` : insert a <metadata> JSON payload into existing SVG text
|
|
7
|
+
* ``inject_png_ddat``: insert a `dDat` private chunk into existing PNG bytes
|
|
8
|
+
|
|
9
|
+
A pydfig figure looks identical to a normal SVG/PNG in any viewer, but carries
|
|
10
|
+
its exact underlying data as structured JSON that parsers and LLM agents read
|
|
11
|
+
losslessly.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
import struct
|
|
17
|
+
import zlib
|
|
18
|
+
from datetime import datetime, timezone
|
|
19
|
+
|
|
20
|
+
PYDFIG_NS = "https://pydfig.ai4c/schema"
|
|
21
|
+
SCHEMA_VERSION = "2.0"
|
|
22
|
+
|
|
23
|
+
_PNG_SIG = b"\x89PNG\r\n\x1a\n"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build_payload(figure_type, points=None, curves=None, axes=None,
|
|
27
|
+
provenance=None, extra=None, caption=None, version=SCHEMA_VERSION):
|
|
28
|
+
"""Construct a pydfig metadata payload.
|
|
29
|
+
|
|
30
|
+
Parameters
|
|
31
|
+
----------
|
|
32
|
+
figure_type : str Semantic figure type (scatter, line, xrd, volcano, ...).
|
|
33
|
+
points : list Exact data points (dicts with numeric x, y).
|
|
34
|
+
curves : list Continuous curves as {"x": [...], "y": [...], "label": ...}.
|
|
35
|
+
axes : dict {"x": {"label", "unit", "range"}, "y": {...}}.
|
|
36
|
+
provenance : dict Free-form domain/technique/method/project metadata.
|
|
37
|
+
extra : dict Domain-specific extension fields.
|
|
38
|
+
caption : str Human-readable figure caption.
|
|
39
|
+
"""
|
|
40
|
+
payload = {
|
|
41
|
+
"format": "pydfig",
|
|
42
|
+
"version": version,
|
|
43
|
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
|
44
|
+
"figure_type": figure_type,
|
|
45
|
+
"caption": caption or "",
|
|
46
|
+
"axes": axes or {},
|
|
47
|
+
"points": points or [],
|
|
48
|
+
"curves": curves or [],
|
|
49
|
+
"provenance": provenance or {},
|
|
50
|
+
}
|
|
51
|
+
if extra:
|
|
52
|
+
payload["extra"] = extra
|
|
53
|
+
return payload
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def metadata_block(payload):
|
|
57
|
+
"""Render the payload as an SVG <metadata> block (JSON inside CDATA)."""
|
|
58
|
+
js = json.dumps(payload, ensure_ascii=False, indent=2)
|
|
59
|
+
return (
|
|
60
|
+
"<metadata>\n"
|
|
61
|
+
f' <pydfig:payload xmlns:pydfig="{PYDFIG_NS}" format="pydfig" '
|
|
62
|
+
f'version="{payload.get("version", SCHEMA_VERSION)}">\n'
|
|
63
|
+
f" <![CDATA[\n{js}\n]]>\n"
|
|
64
|
+
" </pydfig:payload>\n"
|
|
65
|
+
"</metadata>\n"
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def embed_in_svg(svg_text, payload):
|
|
70
|
+
"""Insert a pydfig <metadata> block right after the root <svg ...> tag.
|
|
71
|
+
|
|
72
|
+
The visual content is untouched: every compliant SVG renderer ignores
|
|
73
|
+
<metadata>, so the figure looks identical while becoming machine-readable.
|
|
74
|
+
"""
|
|
75
|
+
if "<metadata>" in svg_text:
|
|
76
|
+
raise ValueError("SVG already contains a <metadata> block; refusing to duplicate")
|
|
77
|
+
m = re.search(r"<svg\b[^>]*>", svg_text)
|
|
78
|
+
if m is None:
|
|
79
|
+
raise ValueError("no root <svg> tag found")
|
|
80
|
+
insert_at = m.end()
|
|
81
|
+
return svg_text[:insert_at] + metadata_block(payload) + svg_text[insert_at:]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _chunk(chunk_type, data):
|
|
85
|
+
return (struct.pack(">I", len(data)) + chunk_type + data
|
|
86
|
+
+ struct.pack(">I", zlib.crc32(chunk_type + data) & 0xFFFFFFFF))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def inject_png_ddat(png_bytes, payload):
|
|
90
|
+
"""Insert a `dDat` private chunk (JSON payload) before IEND; return new PNG bytes.
|
|
91
|
+
|
|
92
|
+
`dDat` is a legal ancillary/private PNG chunk (lowercase second letter),
|
|
93
|
+
so the result remains a valid PNG that any viewer can open.
|
|
94
|
+
"""
|
|
95
|
+
png_bytes = bytes(png_bytes)
|
|
96
|
+
if png_bytes[:8] != _PNG_SIG:
|
|
97
|
+
raise ValueError("not a PNG file")
|
|
98
|
+
idx = png_bytes.rfind(b"IEND")
|
|
99
|
+
if idx < 4:
|
|
100
|
+
raise ValueError("PNG has no IEND chunk")
|
|
101
|
+
chunk_start = idx - 4 # step back to the IEND length field
|
|
102
|
+
ddat = _chunk(b"dDat", json.dumps(payload, ensure_ascii=False).encode("utf-8"))
|
|
103
|
+
return png_bytes[:chunk_start] + ddat + png_bytes[chunk_start:]
|
pydfig/html.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""
|
|
2
|
+
pydfig.html — render a decoded pydfig payload as a human-friendly HTML file.
|
|
3
|
+
|
|
4
|
+
The HTML is fully self-contained (inline CSS + a reconstructed SVG plot built
|
|
5
|
+
from the embedded data), so the user can open it in any browser and *see* the
|
|
6
|
+
exact data without re-running any parser.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _bounds(payload):
|
|
13
|
+
xs, ys = [], []
|
|
14
|
+
for p in payload.get("points", []):
|
|
15
|
+
if isinstance(p.get("x"), (int, float)):
|
|
16
|
+
xs.append(p["x"])
|
|
17
|
+
if isinstance(p.get("y"), (int, float)):
|
|
18
|
+
ys.append(p["y"])
|
|
19
|
+
for c in payload.get("curves", []):
|
|
20
|
+
xs.extend([v for v in c.get("x", []) if isinstance(v, (int, float))])
|
|
21
|
+
ys.extend([v for v in c.get("y", []) if isinstance(v, (int, float))])
|
|
22
|
+
if not xs or not ys:
|
|
23
|
+
return None
|
|
24
|
+
return [min(xs), max(xs), min(ys), max(ys)]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _reconstructed_plot(payload):
|
|
28
|
+
b = _bounds(payload)
|
|
29
|
+
if not b:
|
|
30
|
+
return ""
|
|
31
|
+
xmin, xmax, ymin, ymax = b
|
|
32
|
+
W, H = 640, 380
|
|
33
|
+
pad = 48
|
|
34
|
+
def sx(x):
|
|
35
|
+
if xmax == xmin:
|
|
36
|
+
return pad + (W - 2 * pad) / 2
|
|
37
|
+
return pad + (x - xmin) / (xmax - xmin) * (W - 2 * pad)
|
|
38
|
+
def sy(y):
|
|
39
|
+
if ymax == ymin:
|
|
40
|
+
return H - pad - (H - 2 * pad) / 2
|
|
41
|
+
return H - pad - (y - ymin) / (ymax - ymin) * (H - 2 * pad)
|
|
42
|
+
|
|
43
|
+
parts = [f'<svg viewBox="0 0 {W} {H}" class="plot" preserveAspectRatio="xMidYMid meet">']
|
|
44
|
+
# axes
|
|
45
|
+
parts.append(f'<line x1="{pad}" y1="{H-pad}" x2="{W-pad}" y2="{H-pad}" class="axis"/>')
|
|
46
|
+
parts.append(f'<line x1="{pad}" y1="{pad}" x2="{pad}" y2="{H-pad}" class="axis"/>')
|
|
47
|
+
# curves
|
|
48
|
+
for c in payload.get("curves", []):
|
|
49
|
+
cx = [v for v in c.get("x", []) if isinstance(v, (int, float))]
|
|
50
|
+
cy = [v for v in c.get("y", []) if isinstance(v, (int, float))]
|
|
51
|
+
if len(cx) != len(cy) or not cx:
|
|
52
|
+
continue
|
|
53
|
+
pts = " ".join(f"{sx(x):.1f},{sy(y):.1f}" for x, y in zip(cx, cy))
|
|
54
|
+
parts.append(f'<polyline points="{pts}" class="curve"/>')
|
|
55
|
+
# points
|
|
56
|
+
for p in payload.get("points", []):
|
|
57
|
+
if not isinstance(p.get("x"), (int, float)) or not isinstance(p.get("y"), (int, float)):
|
|
58
|
+
continue
|
|
59
|
+
parts.append(f'<circle cx="{sx(p["x"]):.1f}" cy="{sy(p["y"]):.1f}" r="3.2" class="pt"/>')
|
|
60
|
+
# axis labels
|
|
61
|
+
ax = payload.get("axes", {})
|
|
62
|
+
xl = ax.get("x", {}).get("label", "")
|
|
63
|
+
yl = ax.get("y", {}).get("label", "")
|
|
64
|
+
if xl:
|
|
65
|
+
parts.append(f'<text x="{W/2}" y="{H-12}" class="axlabel">{_esc(xl)}</text>')
|
|
66
|
+
if yl:
|
|
67
|
+
parts.append(f'<text x="14" y="{H/2}" class="axlabel" transform="rotate(-90 14 {H/2})">{_esc(yl)}</text>')
|
|
68
|
+
parts.append("</svg>")
|
|
69
|
+
return "\n".join(parts)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _esc(s):
|
|
73
|
+
return (str(s).replace("&", "&").replace("<", "<").replace(">", ">"))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _points_table(payload):
|
|
77
|
+
pts = payload.get("points", [])
|
|
78
|
+
if not pts:
|
|
79
|
+
return ""
|
|
80
|
+
cols = []
|
|
81
|
+
for p in pts:
|
|
82
|
+
for k in p:
|
|
83
|
+
if k not in cols:
|
|
84
|
+
cols.append(k)
|
|
85
|
+
rows = "".join(
|
|
86
|
+
"<tr>" + "".join(f"<td>{_esc(p.get(c, ''))}</td>" for c in cols) + "</tr>"
|
|
87
|
+
for p in pts
|
|
88
|
+
)
|
|
89
|
+
head = "".join(f"<th>{_esc(c)}</th>" for c in cols)
|
|
90
|
+
return f'<table class="data"><thead><tr>{head}</tr></thead><tbody>{rows}</tbody></table>'
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _meta_rows(payload):
|
|
94
|
+
rows = []
|
|
95
|
+
rows.append(("Figure type", _esc(payload.get("figure_type", ""))))
|
|
96
|
+
rows.append(("Format", f'pydfig {_esc(payload.get("version", ""))}'))
|
|
97
|
+
if payload.get("caption"):
|
|
98
|
+
rows.append(("Caption", _esc(payload["caption"])))
|
|
99
|
+
ax = payload.get("axes", {})
|
|
100
|
+
if ax.get("x"):
|
|
101
|
+
rows.append(("X axis", _esc(ax["x"].get("label", "")) +
|
|
102
|
+
(f' ({ax["x"]["unit"]})' if ax["x"].get("unit") else "")))
|
|
103
|
+
if ax.get("y"):
|
|
104
|
+
rows.append(("Y axis", _esc(ax["y"].get("label", "")) +
|
|
105
|
+
(f' ({ax["y"]["unit"]})' if ax["y"].get("unit") else "")))
|
|
106
|
+
if payload.get("provenance"):
|
|
107
|
+
rows.append(("Provenance", _esc(json.dumps(payload["provenance"], ensure_ascii=False))))
|
|
108
|
+
body = "".join(f"<tr><th>{k}</th><td>{v}</td></tr>" for k, v in rows)
|
|
109
|
+
return f'<table class="meta"><tbody>{body}</tbody></table>'
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def render_html(payload):
|
|
113
|
+
"""Return a self-contained HTML string describing the pydfig payload."""
|
|
114
|
+
ptype = _esc(payload.get("figure_type", "figure"))
|
|
115
|
+
caption = _esc(payload.get("caption") or f"pydfig {ptype} figure")
|
|
116
|
+
plot = _reconstructed_plot(payload)
|
|
117
|
+
points_tbl = _points_table(payload)
|
|
118
|
+
curves = payload.get("curves", [])
|
|
119
|
+
curves_info = ""
|
|
120
|
+
if curves:
|
|
121
|
+
items = "".join(f"<li><code>{_esc(c.get('label', 'curve'))}</code> — "
|
|
122
|
+
f"{len(c.get('x', []))} samples</li>" for c in curves)
|
|
123
|
+
curves_info = f"<h3>Curves</h3><ul class='curves'>{items}</ul>"
|
|
124
|
+
n_pts = len(payload.get("points", []))
|
|
125
|
+
|
|
126
|
+
return f"""<!DOCTYPE html>
|
|
127
|
+
<html lang="en">
|
|
128
|
+
<head>
|
|
129
|
+
<meta charset="utf-8">
|
|
130
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
131
|
+
<title>{caption}</title>
|
|
132
|
+
<style>
|
|
133
|
+
:root {{
|
|
134
|
+
--bg: #f4f6f9; --card: #ffffff; --ink: #1f2933; --muted: #6b7280;
|
|
135
|
+
--line: #e3e8ef; --accent: #2f6f9f; --accent2: #4f9d8c;
|
|
136
|
+
}}
|
|
137
|
+
* {{ box-sizing: border-box; }}
|
|
138
|
+
body {{
|
|
139
|
+
margin: 0; background: var(--bg); color: var(--ink);
|
|
140
|
+
font: 15px/1.55 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
|
141
|
+
padding: 32px 16px;
|
|
142
|
+
}}
|
|
143
|
+
.wrap {{ max-width: 760px; margin: 0 auto; }}
|
|
144
|
+
.card {{
|
|
145
|
+
background: var(--card); border: 1px solid var(--line); border-radius: 14px;
|
|
146
|
+
padding: 22px 24px; margin-bottom: 18px; box-shadow: 0 1px 3px rgba(20,30,50,.05);
|
|
147
|
+
}}
|
|
148
|
+
h1 {{ font-size: 20px; margin: 0 0 4px; }}
|
|
149
|
+
.badge {{
|
|
150
|
+
display: inline-block; font-size: 12px; padding: 2px 10px; border-radius: 999px;
|
|
151
|
+
background: rgba(47,111,159,.12); color: var(--accent); border: 1px solid rgba(47,111,159,.25);
|
|
152
|
+
}}
|
|
153
|
+
h3 {{ font-size: 14px; text-transform: uppercase; letter-spacing: .04em;
|
|
154
|
+
color: var(--muted); margin: 22px 0 8px; }}
|
|
155
|
+
table {{ border-collapse: collapse; width: 100%; font-size: 13.5px; }}
|
|
156
|
+
.meta th, .meta td {{ text-align: left; padding: 7px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }}
|
|
157
|
+
.meta th {{ color: var(--muted); font-weight: 600; width: 130px; }}
|
|
158
|
+
.data {{ margin-top: 6px; overflow-x: auto; display: block; }}
|
|
159
|
+
.data th, .data td {{ padding: 5px 10px; border-bottom: 1px solid var(--line); text-align: right; }}
|
|
160
|
+
.data th {{ color: var(--muted); font-weight: 600; }}
|
|
161
|
+
.plot {{ width: 100%; height: auto; background: #fbfcfe; border: 1px solid var(--line); border-radius: 10px; }}
|
|
162
|
+
.axis {{ stroke: #c4ccd6; stroke-width: 1; }}
|
|
163
|
+
.curve {{ fill: none; stroke: var(--accent2); stroke-width: 2; }}
|
|
164
|
+
.pt {{ fill: var(--accent); }}
|
|
165
|
+
.axlabel {{ fill: var(--muted); font-size: 12px; }}
|
|
166
|
+
ul.curves {{ margin: 4px 0; padding-left: 18px; color: var(--muted); }}
|
|
167
|
+
code {{ background: #eef2f7; padding: 1px 5px; border-radius: 5px; font-size: 12.5px; }}
|
|
168
|
+
.foot {{ color: var(--muted); font-size: 12px; text-align: center; margin-top: 8px; }}
|
|
169
|
+
</style>
|
|
170
|
+
</head>
|
|
171
|
+
<body>
|
|
172
|
+
<div class="wrap">
|
|
173
|
+
<div class="card">
|
|
174
|
+
<span class="badge">{_esc(payload.get('figure_type', ''))}</span>
|
|
175
|
+
<h1>{caption}</h1>
|
|
176
|
+
{_meta_rows(payload)}
|
|
177
|
+
</div>
|
|
178
|
+
{f'<div class="card"><h3>Reconstructed from embedded data</h3>{plot}</div>' if plot else ''}
|
|
179
|
+
{f'<div class="card"><h3>Data points ({n_pts})</h3>{points_tbl}</div>' if points_tbl else ''}
|
|
180
|
+
{f'<div class="card">{curves_info}</div>' if curves_info else ''}
|
|
181
|
+
<div class="foot">Generated by pydfig — exact data decoded losslessly from the figure file.</div>
|
|
182
|
+
</div>
|
|
183
|
+
</body>
|
|
184
|
+
</html>"""
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def write_html(payload, path):
|
|
188
|
+
"""Write the HTML rendering of *payload* to *path*."""
|
|
189
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
190
|
+
f.write(render_html(payload))
|
|
191
|
+
return path
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""
|
|
2
|
+
pydfig.matplotlib_converter — export a matplotlib Figure as a pydfig figure.
|
|
3
|
+
|
|
4
|
+
Extract exact data from matplotlib Axes and embed it into a pydfig SVG or PNG.
|
|
5
|
+
No matplotlib import at module level — only needed when user calls convert().
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
from pydfig.matplotlib_converter import convert
|
|
10
|
+
|
|
11
|
+
fig, ax = plt.subplots()
|
|
12
|
+
ax.plot([1, 2, 3], [4, 5, 6])
|
|
13
|
+
convert(fig, "output.svg", caption="My experiment")
|
|
14
|
+
convert(fig, "output.png", caption="My experiment")
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import math
|
|
18
|
+
import os
|
|
19
|
+
from .encoder import metadata_block, inject_png_ddat
|
|
20
|
+
|
|
21
|
+
SVG_NS = "http://www.w3.org/2000/svg"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _with_correct_ext(output_path, fmt):
|
|
25
|
+
"""Ensure the output path carries the extension matching the chosen format."""
|
|
26
|
+
base, _ = os.path.splitext(output_path)
|
|
27
|
+
return base + (".png" if fmt == "png" else ".svg")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _extract_points(ax):
|
|
31
|
+
"""Extract scatter/line data points from a matplotlib Axes."""
|
|
32
|
+
points = []
|
|
33
|
+
curves = []
|
|
34
|
+
for line in ax.get_lines():
|
|
35
|
+
xdata = list(line.get_xdata())
|
|
36
|
+
ydata = list(line.get_ydata())
|
|
37
|
+
label = line.get_label() if line.get_label() else None
|
|
38
|
+
clean = [(x, y) for x, y in zip(xdata, ydata)
|
|
39
|
+
if x is not None and y is not None
|
|
40
|
+
and not (isinstance(x, float) and math.isnan(x))]
|
|
41
|
+
if not clean:
|
|
42
|
+
continue
|
|
43
|
+
xs = [float(x) for x, _ in clean]
|
|
44
|
+
ys = [float(y) for _, y in clean]
|
|
45
|
+
linestyle = line.get_linestyle()
|
|
46
|
+
if linestyle in (None, "", " ", "None", "none"):
|
|
47
|
+
for x, y in clean:
|
|
48
|
+
points.append({"x": float(x), "y": float(y)})
|
|
49
|
+
else:
|
|
50
|
+
curve = {"x": xs, "y": ys}
|
|
51
|
+
if label:
|
|
52
|
+
curve["label"] = label
|
|
53
|
+
curves.append(curve)
|
|
54
|
+
for coll in ax.collections:
|
|
55
|
+
try:
|
|
56
|
+
offsets = coll.get_offsets()
|
|
57
|
+
for i in range(len(offsets)):
|
|
58
|
+
x, y = offsets[i][0], offsets[i][1]
|
|
59
|
+
if not (isinstance(x, float) and math.isnan(x)):
|
|
60
|
+
points.append({"x": float(x), "y": float(y)})
|
|
61
|
+
except Exception:
|
|
62
|
+
pass
|
|
63
|
+
return points, curves
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _extract_axes(ax):
|
|
67
|
+
"""Extract axis metadata."""
|
|
68
|
+
xlabel = ax.get_xlabel()
|
|
69
|
+
ylabel = ax.get_ylabel()
|
|
70
|
+
title = ax.get_title()
|
|
71
|
+
xlim = ax.get_xlim()
|
|
72
|
+
ylim = ax.get_ylim()
|
|
73
|
+
|
|
74
|
+
axes = {}
|
|
75
|
+
if xlabel:
|
|
76
|
+
axes["x"] = {"label": xlabel, "range": [float(xlim[0]), float(xlim[1])]}
|
|
77
|
+
if ylabel:
|
|
78
|
+
axes["y"] = {"label": ylabel, "range": [float(ylim[0]), float(ylim[1])]}
|
|
79
|
+
if ax.get_xscale() == "log":
|
|
80
|
+
axes.setdefault("x", {})["scale"] = "log"
|
|
81
|
+
if ax.get_yscale() == "log":
|
|
82
|
+
axes.setdefault("y", {})["scale"] = "log"
|
|
83
|
+
|
|
84
|
+
info = {}
|
|
85
|
+
if title:
|
|
86
|
+
info["title"] = title
|
|
87
|
+
return axes, info
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _guess_figure_type(ax):
|
|
91
|
+
"""Heuristic: guess the scientific figure type from axis labels."""
|
|
92
|
+
xl = (ax.get_xlabel() or "").lower()
|
|
93
|
+
yl = (ax.get_ylabel() or "").lower()
|
|
94
|
+
combined = f"{xl} {yl}"
|
|
95
|
+
if "2theta" in combined or "xrd" in combined or "diffraction" in combined:
|
|
96
|
+
return "xrd"
|
|
97
|
+
if "wavenumber" in combined or "ftir" in combined:
|
|
98
|
+
return "ftir"
|
|
99
|
+
if "wavelength" in combined and ("absorbance" in combined or "intensity" in combined):
|
|
100
|
+
return "uvvis"
|
|
101
|
+
if "binding energy" in combined or "xps" in combined:
|
|
102
|
+
return "xps"
|
|
103
|
+
if "temperature" in combined and ("weight" in combined or "deriv" in combined):
|
|
104
|
+
return "tga"
|
|
105
|
+
if "potential" in combined and ("current" in combined or "current density" in combined):
|
|
106
|
+
if "cycle" in combined or "cv" in combined:
|
|
107
|
+
return "cv"
|
|
108
|
+
return "tafel"
|
|
109
|
+
if "frequency" in combined and ("impedance" in combined or "z" in combined):
|
|
110
|
+
return "nyquist"
|
|
111
|
+
if "overpotential" in combined or "volcano" in combined:
|
|
112
|
+
return "volcano"
|
|
113
|
+
if "rdf" in combined or "radial distribution" in combined:
|
|
114
|
+
return "rdf"
|
|
115
|
+
if "dos" in combined or "density of states" in combined:
|
|
116
|
+
return "dos"
|
|
117
|
+
if "band" in combined and ("energy" in combined or "k-path" in combined):
|
|
118
|
+
return "band_structure"
|
|
119
|
+
if "p/p0" in combined or "bet" in combined or ("relative pressure" in combined):
|
|
120
|
+
return "bet"
|
|
121
|
+
if "heat flow" in combined or "dsc" in combined:
|
|
122
|
+
return "dsc"
|
|
123
|
+
if "1000/t" in combined or "ln(k)" in combined or "arrhenius" in combined:
|
|
124
|
+
return "arrhenius"
|
|
125
|
+
return "scatter_generic"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def convert(fig, output_path, caption=None, figure_type=None, provenance=None,
|
|
129
|
+
width=680, height=480, fmt=None):
|
|
130
|
+
"""
|
|
131
|
+
Convert a matplotlib Figure to a pydfig self-describing figure.
|
|
132
|
+
|
|
133
|
+
The SAME payload (exact points/curves/axes) is embedded regardless of the
|
|
134
|
+
container format; only the carrier differs:
|
|
135
|
+
|
|
136
|
+
* fmt="svg" (default) -> SVG file, payload inside the <metadata> element
|
|
137
|
+
* fmt="png" -> PNG file, payload inside a `dDat` private chunk
|
|
138
|
+
|
|
139
|
+
Parameters:
|
|
140
|
+
fig: matplotlib.figure.Figure
|
|
141
|
+
output_path: str — output path (extension is auto-fixed to match fmt)
|
|
142
|
+
caption: str — figure caption (optional)
|
|
143
|
+
figure_type: str — override the auto-detected figure type (optional)
|
|
144
|
+
provenance: dict — {tool, version, date, doi, ...} (optional)
|
|
145
|
+
width: int — SVG width in px (ignored for PNG)
|
|
146
|
+
height: int — SVG height in px (ignored for PNG)
|
|
147
|
+
fmt: str — "svg" (default) or "png". If None, inferred from the
|
|
148
|
+
output_path extension (.png -> png, otherwise svg).
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
dict — the embedded payload
|
|
152
|
+
"""
|
|
153
|
+
ext = os.path.splitext(output_path)[1].lower()
|
|
154
|
+
if fmt is None:
|
|
155
|
+
fmt = "png" if ext == ".png" else "svg"
|
|
156
|
+
else:
|
|
157
|
+
fmt = fmt.lower()
|
|
158
|
+
if fmt not in ("svg", "png"):
|
|
159
|
+
raise ValueError("fmt must be 'svg' or 'png'")
|
|
160
|
+
out_path = _with_correct_ext(output_path, fmt)
|
|
161
|
+
|
|
162
|
+
axes_list = fig.get_axes()
|
|
163
|
+
if not axes_list:
|
|
164
|
+
raise ValueError("Figure has no axes")
|
|
165
|
+
ax = axes_list[0]
|
|
166
|
+
|
|
167
|
+
points, curves = _extract_points(ax)
|
|
168
|
+
axes_info, extra_info = _extract_axes(ax)
|
|
169
|
+
ftype = figure_type or _guess_figure_type(ax)
|
|
170
|
+
|
|
171
|
+
payload = {
|
|
172
|
+
"format": "pydfig",
|
|
173
|
+
"version": "2.0",
|
|
174
|
+
"figure_type": ftype,
|
|
175
|
+
"caption": caption or "",
|
|
176
|
+
"axes": axes_info,
|
|
177
|
+
"points": points,
|
|
178
|
+
"curves": curves,
|
|
179
|
+
}
|
|
180
|
+
if provenance:
|
|
181
|
+
payload["provenance"] = provenance
|
|
182
|
+
if extra_info:
|
|
183
|
+
payload["extra"] = extra_info
|
|
184
|
+
|
|
185
|
+
if fmt == "svg":
|
|
186
|
+
import io
|
|
187
|
+
import re
|
|
188
|
+
buf = io.StringIO()
|
|
189
|
+
fig.savefig(buf, format="svg", bbox_inches="tight")
|
|
190
|
+
svg_text = buf.getvalue()
|
|
191
|
+
meta = metadata_block(payload)
|
|
192
|
+
m = re.search(r"<svg\b[^>]*>", svg_text)
|
|
193
|
+
if m:
|
|
194
|
+
insert_pos = m.end()
|
|
195
|
+
svg_text = svg_text[:insert_pos] + meta + svg_text[insert_pos:]
|
|
196
|
+
with open(out_path, "w", encoding="utf-8") as f:
|
|
197
|
+
f.write(svg_text)
|
|
198
|
+
else: # png
|
|
199
|
+
import io
|
|
200
|
+
buf = io.BytesIO()
|
|
201
|
+
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight")
|
|
202
|
+
png_bytes = buf.getvalue()
|
|
203
|
+
pydfig_png = inject_png_ddat(png_bytes, payload)
|
|
204
|
+
with open(out_path, "wb") as f:
|
|
205
|
+
f.write(pydfig_png)
|
|
206
|
+
|
|
207
|
+
return payload
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def quick_convert(output_path, **kwargs):
|
|
211
|
+
"""Convert the current matplotlib figure (plt.gcf()) to pydfig."""
|
|
212
|
+
import matplotlib.pyplot as plt
|
|
213
|
+
return convert(plt.gcf(), output_path, **kwargs)
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pydfig
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Self-describing scientific figures (Figure-as-Data): embed exact data in SVG/PNG, decode losslessly to JSON (for AI) and HTML (for humans).
|
|
5
|
+
Author-email: Fenglong Li <15340666394@163.com>, Siyang Li <15340666394@163.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://pydfig.ai4c/schema
|
|
8
|
+
Keywords: scientific figures,Figure-as-Data,FAIR data,machine-readable,AI4Science,SVG,PNG,metadata
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Science/Research
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Visualization
|
|
20
|
+
Requires-Python: >=3.8
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Provides-Extra: matplotlib
|
|
24
|
+
Requires-Dist: matplotlib; extra == "matplotlib"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# pydfig — Make your scientific figures carry their own data
|
|
28
|
+
|
|
29
|
+
A normal chart is just a **picture**. **pydfig** makes the same chart also
|
|
30
|
+
**contain its exact numbers** — so a computer can read them back perfectly,
|
|
31
|
+
without guessing from pixels (no OCR, no digitizing error).
|
|
32
|
+
|
|
33
|
+
> One sentence: pydfig hides a small JSON with your exact data *inside* the
|
|
34
|
+
> image file. The picture still looks identical; a parser reads the JSON back
|
|
35
|
+
> losslessly.
|
|
36
|
+
|
|
37
|
+
## Why does this matter?
|
|
38
|
+
|
|
39
|
+
Scientific figures in papers and PDFs are images. If an AI agent — or a
|
|
40
|
+
colleague — wants the real data points, they usually have to scrape the PDF
|
|
41
|
+
or eyeball the pixels, and both lose precision. pydfig embeds the **exact
|
|
42
|
+
data** inside the figure file itself, invisibly.
|
|
43
|
+
|
|
44
|
+
## How it works
|
|
45
|
+
|
|
46
|
+
| Carrier | Where the data lives | Still a normal file? |
|
|
47
|
+
|---------|----------------------|----------------------|
|
|
48
|
+
| **SVG** | the standard `<metadata>` element (renderers ignore it) | ✅ opens in any SVG viewer |
|
|
49
|
+
| **PNG** | a legal private chunk called `dDat` | ✅ opens in any image viewer |
|
|
50
|
+
|
|
51
|
+
## Two things pydfig does
|
|
52
|
+
|
|
53
|
+
1. **Encode** — export a PNG or SVG that carries your exact data (from a
|
|
54
|
+
`payload` dict, or directly from a matplotlib figure).
|
|
55
|
+
2. **Decode** — read a pydfig PNG/SVG and write out:
|
|
56
|
+
- a **`.json`** file — machine-readable, for AI / data pipelines
|
|
57
|
+
- an **`.html`** file — human-readable, opens in any browser and shows the
|
|
58
|
+
data plus a reconstructed plot
|
|
59
|
+
|
|
60
|
+
## Install
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pip install pydfig
|
|
64
|
+
# optional: to export directly from a matplotlib figure
|
|
65
|
+
pip install "pydfig[matplotlib]"
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
The core encode/decode path is **pure Python standard library** — no heavy
|
|
69
|
+
dependencies required.
|
|
70
|
+
|
|
71
|
+
## Quick start
|
|
72
|
+
|
|
73
|
+
### Command line
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
# Encode: inject a data JSON into an existing SVG or PNG
|
|
77
|
+
python -m pydfig encode chart.png --payload payload.json -o chart_pydfig.png
|
|
78
|
+
|
|
79
|
+
# Decode: get back JSON (for AI) + HTML (for humans)
|
|
80
|
+
python -m pydfig decode chart_pydfig.png -o result
|
|
81
|
+
# result.json <- exact data, machine-readable
|
|
82
|
+
# result.html <- open in a browser to see the data and a reconstructed chart
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### In Python
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from pydfig import build_payload, embed_in_svg, inject_png_ddat, decode_any
|
|
89
|
+
|
|
90
|
+
payload = build_payload(
|
|
91
|
+
"scatter",
|
|
92
|
+
points=[{"x": -1.95, "y": 0.42, "material": "NiO"}],
|
|
93
|
+
axes={"x": {"label": "d-band", "unit": "eV"}},
|
|
94
|
+
caption="My figure",
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
svg = embed_in_svg(open("chart.svg").read(), payload) # data in <metadata>
|
|
98
|
+
png = inject_png_ddat(open("chart.png", "rb").read(), payload) # data in dDat chunk
|
|
99
|
+
|
|
100
|
+
data = decode_any("chart_pydfig.png") # exact, lossless
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### From a matplotlib figure (needs the `matplotlib` extra)
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
import matplotlib.pyplot as plt
|
|
107
|
+
from pydfig.matplotlib_converter import convert
|
|
108
|
+
|
|
109
|
+
fig, ax = plt.subplots()
|
|
110
|
+
ax.plot([1, 2, 3], [4, 5, 6])
|
|
111
|
+
ax.set_xlabel("d-band (eV)")
|
|
112
|
+
ax.set_ylabel("E_ads (eV)")
|
|
113
|
+
|
|
114
|
+
convert(fig, "out.svg", caption="experiment") # -> out.svg
|
|
115
|
+
convert(fig, "out.png", caption="experiment") # -> out.png
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
`convert()` chooses PNG vs SVG automatically from the output file extension.
|
|
119
|
+
|
|
120
|
+
### Decode to a readable HTML page
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
from pydfig import decode_any, write_html
|
|
124
|
+
|
|
125
|
+
payload = decode_any("out.png")
|
|
126
|
+
write_html(payload, "out.html") # self-contained, light-theme viewer
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## What the embedded data looks like
|
|
130
|
+
|
|
131
|
+
```json
|
|
132
|
+
{
|
|
133
|
+
"format": "pydfig",
|
|
134
|
+
"version": "2.0",
|
|
135
|
+
"figure_type": "xrd",
|
|
136
|
+
"caption": "XRD pattern",
|
|
137
|
+
"axes": {"x": {"label": "2θ", "unit": "degree"}, "y": {"label": "Intensity"}},
|
|
138
|
+
"points": [{"x": 44.0, "y": 20.0}, {"x": 64.0, "y": 12.0}],
|
|
139
|
+
"curves": [{"x": [0, 1, 2], "y": [10, 12, 11], "label": "intensity"}]
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Examples
|
|
144
|
+
|
|
145
|
+
The `examples/` folder ships `demo_volcano`, `demo_xrd`, and `demo_dband` as
|
|
146
|
+
both `.svg` and `.png` — each carrying its exact data. Regenerate them with:
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
python examples/gen_examples.py
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## License
|
|
153
|
+
|
|
154
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
pydfig/__init__.py,sha256=PxMMasCv-4PTFJC1wBVSFNd48SLdVGlR2iykxsXJw-s,1284
|
|
2
|
+
pydfig/__main__.py,sha256=8CmTEo6ZGNOzmYks62vytUz4emqnOQM8SgX_dCtTyxI,122
|
|
3
|
+
pydfig/cli.py,sha256=ekDqrwhSZA45N3yPX9xRfRlLp-8BfZN-iX55Wz9QH5w,3329
|
|
4
|
+
pydfig/decoder.py,sha256=MDA2-w3umHH9O45X2vP62iO-C5-RMf1m04lCxXvRj5A,3429
|
|
5
|
+
pydfig/encoder.py,sha256=qxUAXc0P3LBnTjpUZD5t1OrAFFOqUAAafZaKlXhV3uQ,3696
|
|
6
|
+
pydfig/html.py,sha256=0yd-CpoDlDKZY_HhkKgGp8itMm-dVhY2kq4agIa5XRk,7826
|
|
7
|
+
pydfig/matplotlib_converter.py,sha256=UjzQh-8ZbdvVK8q6MC7dRASC7dbW13f0nUuyL1Bsg7k,7519
|
|
8
|
+
pydfig-0.1.0.dist-info/licenses/LICENSE,sha256=e2gyWjB9IrhELWVNco6He1qbuAnXI5qrWJEuA2vNvyY,1079
|
|
9
|
+
pydfig-0.1.0.dist-info/METADATA,sha256=wP1Y3r36yUZ5A0nc6j6hKqKcKzcHWV0w0UX7_kdJ6Es,5099
|
|
10
|
+
pydfig-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
11
|
+
pydfig-0.1.0.dist-info/entry_points.txt,sha256=C0URwJBmiO3UBePuHLAQUVrwTTe-9xm1VUI5jNAaf2o,43
|
|
12
|
+
pydfig-0.1.0.dist-info/top_level.txt,sha256=Mo4caJpo1qp8Obh2_ojP1x5-WDl8MxQ1jkfqU97hOpw,7
|
|
13
|
+
pydfig-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fenglong Li, Siyang Li
|
|
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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pydfig
|