ipolypad 1.0.2__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.
ipolypad/__init__.py ADDED
@@ -0,0 +1,29 @@
1
+ """ipolypad — image/SVG to padded polygon hull. See SPEC.md."""
2
+ # this_file: ipolypad_py/src/ipolypad/__init__.py
3
+ from __future__ import annotations
4
+
5
+ from .errors import (
6
+ EmptyMaskError,
7
+ FormatError,
8
+ IpolypadError,
9
+ OnlyFrameError,
10
+ SourceError,
11
+ TraceEmptyError,
12
+ )
13
+ from .pipeline import trace
14
+
15
+ try:
16
+ from .__version__ import __version__
17
+ except ImportError:
18
+ __version__ = "0.0.0+unknown"
19
+
20
+ __all__ = [
21
+ "EmptyMaskError",
22
+ "FormatError",
23
+ "IpolypadError",
24
+ "OnlyFrameError",
25
+ "SourceError",
26
+ "TraceEmptyError",
27
+ "__version__",
28
+ "trace",
29
+ ]
ipolypad/__main__.py ADDED
@@ -0,0 +1,174 @@
1
+ """Fire CLI. SPEC §7."""
2
+ # this_file: ipolypad_py/src/ipolypad/__main__.py
3
+ from __future__ import annotations
4
+
5
+ import json as _json
6
+ import sys
7
+ from concurrent.futures import ProcessPoolExecutor, as_completed
8
+ from glob import glob
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import fire
13
+
14
+ from .errors import IpolypadError
15
+ from .pipeline import trace as _trace
16
+
17
+ _FORMAT_EXT = {"json": "json", "css": "css", "svg": "svg", "png": "png", "html": "html"}
18
+
19
+
20
+ def _formats(format: str) -> list[str]:
21
+ return [f.strip().lower() for f in format.split(",") if f.strip()]
22
+
23
+
24
+ def _write_one(fmt: str, content: str | bytes | dict, out_path: Path) -> None:
25
+ if fmt == "json":
26
+ text = _json.dumps(content, indent=2, sort_keys=True, ensure_ascii=False) if isinstance(content, dict) else content
27
+ out_path.write_text(text) # type: ignore[arg-type]
28
+ elif fmt == "png":
29
+ out_path.write_bytes(content) # type: ignore[arg-type]
30
+ else:
31
+ out_path.write_text(content) # type: ignore[arg-type]
32
+
33
+
34
+ def trace(
35
+ src: str,
36
+ *,
37
+ size: int = 200,
38
+ margin: int = 20,
39
+ pad: int | None = None,
40
+ pad_pct: float | None = None,
41
+ max_points: int = 32,
42
+ samples_per_curve: int = 4,
43
+ hull: bool = True,
44
+ enhance: bool | None = None,
45
+ bg_tolerance: float = 12.0,
46
+ smart_mask: bool = True,
47
+ format: str = "json",
48
+ selector: str | None = None,
49
+ out: str | None = None,
50
+ ) -> Any:
51
+ """Trace one source into one or more output formats.
52
+
53
+ `format` may be a single name or a comma-separated list (e.g. `json,css,svg`).
54
+ When multiple formats are requested with `--out`, `out` is treated as a base
55
+ path: ``out.json``, ``out.css``, …
56
+ """
57
+ fmts = _formats(format)
58
+ multi = len(fmts) > 1
59
+ results: dict[str, Any] = {}
60
+ for fmt in fmts:
61
+ if fmt not in _FORMAT_EXT:
62
+ sys.stderr.write(f"unknown format: {fmt}\n")
63
+ sys.exit(2)
64
+ try:
65
+ result = _trace(
66
+ src,
67
+ size=size,
68
+ margin=margin,
69
+ pad=pad,
70
+ pad_pct=pad_pct,
71
+ max_points=max_points,
72
+ samples_per_curve=samples_per_curve,
73
+ hull=hull,
74
+ enhance=enhance,
75
+ bg_tolerance=bg_tolerance,
76
+ smart_mask=smart_mask,
77
+ format=fmt, # type: ignore[arg-type]
78
+ selector=selector,
79
+ out=None, # we'll write below
80
+ )
81
+ except IpolypadError as e:
82
+ sys.stderr.write(f"error: {e}\n")
83
+ sys.exit(3)
84
+ results[fmt] = result
85
+ if out:
86
+ if multi:
87
+ base = Path(out)
88
+ target = base.with_suffix("." + _FORMAT_EXT[fmt])
89
+ else:
90
+ target = Path(out)
91
+ _write_one(fmt, result, target)
92
+ if multi:
93
+ return {k: (v if not isinstance(v, bytes) else f"<{len(v)} bytes>") for k, v in results.items()}
94
+ only = results[fmts[0]]
95
+ return only
96
+
97
+
98
+ def _batch_one(args: tuple[str, str, dict[str, Any]]) -> tuple[str, str | None]:
99
+ src, out_dir, opts = args
100
+ try:
101
+ fmts = _formats(opts.get("format", "json"))
102
+ for fmt in fmts:
103
+ opts_one = {**opts, "format": fmt}
104
+ result = _trace(src, **opts_one)
105
+ stem = Path(src).stem
106
+ target = Path(out_dir) / f"{stem}.{_FORMAT_EXT[fmt]}"
107
+ _write_one(fmt, result, target)
108
+ return src, None
109
+ except Exception as e: # noqa: BLE001
110
+ return src, str(e)
111
+
112
+
113
+ def batch(
114
+ pattern: str,
115
+ *,
116
+ out_dir: str,
117
+ size: int = 200,
118
+ margin: int = 20,
119
+ pad: int | None = None,
120
+ pad_pct: float | None = None,
121
+ max_points: int = 32,
122
+ samples_per_curve: int = 4,
123
+ hull: bool = True,
124
+ enhance: bool | None = None,
125
+ bg_tolerance: float = 12.0,
126
+ smart_mask: bool = True,
127
+ format: str = "json",
128
+ selector: str | None = None,
129
+ workers: int | None = None,
130
+ ) -> None:
131
+ """Process many sources in parallel.
132
+
133
+ `pattern` is a glob (e.g. ``'assets/*.svg'``). Outputs land in ``out_dir/``
134
+ with the same stem and the format extension.
135
+ """
136
+ paths = sorted(glob(pattern))
137
+ if not paths:
138
+ sys.stderr.write(f"no files match {pattern!r}\n")
139
+ sys.exit(2)
140
+ Path(out_dir).mkdir(parents=True, exist_ok=True)
141
+ opts: dict[str, Any] = dict(
142
+ size=size,
143
+ margin=margin,
144
+ pad=pad,
145
+ pad_pct=pad_pct,
146
+ max_points=max_points,
147
+ samples_per_curve=samples_per_curve,
148
+ hull=hull,
149
+ enhance=enhance,
150
+ bg_tolerance=bg_tolerance,
151
+ smart_mask=smart_mask,
152
+ format=format,
153
+ selector=selector,
154
+ )
155
+ fail = 0
156
+ with ProcessPoolExecutor(max_workers=workers) as ex:
157
+ futs = [ex.submit(_batch_one, (p, out_dir, opts)) for p in paths]
158
+ for fut in as_completed(futs):
159
+ src, err = fut.result()
160
+ if err:
161
+ sys.stderr.write(f"FAIL {src}: {err}\n")
162
+ fail += 1
163
+ else:
164
+ sys.stdout.write(f"OK {src}\n")
165
+ if fail:
166
+ sys.exit(3)
167
+
168
+
169
+ def main() -> None:
170
+ fire.Fire({"trace": trace, "batch": batch})
171
+
172
+
173
+ if __name__ == "__main__":
174
+ main()
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '1.0.2'
22
+ __version_tuple__ = version_tuple = (1, 0, 2)
23
+
24
+ __commit_id__ = commit_id = None
ipolypad/color.py ADDED
@@ -0,0 +1,138 @@
1
+ """Color-aware mask + auto-contrast. SPEC §4.1, §4.2."""
2
+ # this_file: ipolypad_py/src/ipolypad/color.py
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ from PIL import Image, ImageOps
7
+
8
+
9
+ def _has_alpha(img: Image.Image) -> bool:
10
+ a = np.array(img.split()[-1], dtype=np.uint8)
11
+ # Treat fully opaque as "no alpha information" — colour route applies.
12
+ return bool(a.min() < 250 and a.max() > 5)
13
+
14
+
15
+ def _otsu(a: np.ndarray) -> int | None:
16
+ """Otsu threshold on a uint8 channel. Returns None if degenerate."""
17
+ hist = np.bincount(a.ravel(), minlength=256).astype(np.float64)
18
+ total = a.size
19
+ if total == 0:
20
+ return None
21
+ cum = np.cumsum(hist)
22
+ cum_mean = np.cumsum(hist * np.arange(256))
23
+ # Between-class variance for each candidate threshold
24
+ w0 = cum / total
25
+ w1 = 1.0 - w0
26
+ # avoid div-by-zero
27
+ with np.errstate(divide="ignore", invalid="ignore"):
28
+ m0 = np.where(cum > 0, cum_mean / np.maximum(cum, 1), 0.0)
29
+ m1 = np.where(
30
+ total - cum > 0,
31
+ (cum_mean[-1] - cum_mean) / np.maximum(total - cum, 1),
32
+ 0.0,
33
+ )
34
+ sigma_b = w0 * w1 * (m0 - m1) ** 2
35
+ if not np.isfinite(sigma_b).any():
36
+ return None
37
+ t = int(np.nanargmax(sigma_b))
38
+ if t in (0, 255):
39
+ return None
40
+ return t
41
+
42
+
43
+ def _bg_color_from_corners(rgb: np.ndarray) -> np.ndarray:
44
+ """Estimate background colour from a corner+edge sample. Returns float (3,)."""
45
+ h, w, _ = rgb.shape
46
+ band = max(2, min(h, w) // 32)
47
+ samples = np.concatenate(
48
+ [
49
+ rgb[:band, :, :].reshape(-1, 3),
50
+ rgb[-band:, :, :].reshape(-1, 3),
51
+ rgb[:, :band, :].reshape(-1, 3),
52
+ rgb[:, -band:, :].reshape(-1, 3),
53
+ ]
54
+ )
55
+ # Median is robust to mixed edges (e.g. text bleeding into the frame).
56
+ return np.median(samples, axis=0).astype(np.float64)
57
+
58
+
59
+ def _rgb_to_lab(rgb: np.ndarray) -> np.ndarray:
60
+ """Lazy import of scikit-image. Returns float H×W×3."""
61
+ from skimage.color import rgb2lab
62
+
63
+ return rgb2lab(rgb / 255.0)
64
+
65
+
66
+ def _sauvola(lab_l: np.ndarray) -> np.ndarray:
67
+ """Adaptive Sauvola threshold on L channel. Returns boolean foreground mask."""
68
+ from skimage.filters import threshold_sauvola
69
+
70
+ win = max(15, (min(lab_l.shape) // 16) | 1)
71
+ t = threshold_sauvola(lab_l, window_size=win, k=0.2)
72
+ return lab_l < t # darker than local threshold = foreground
73
+
74
+
75
+ def autoenhance(img: Image.Image) -> Image.Image:
76
+ """Auto-levels + mild gamma. SPEC §4.2. Idempotent in practice (one pass)."""
77
+ rgb = img.convert("RGB")
78
+ # Per-channel stretch via PIL autocontrast on L-equivalent; cheaper than scikit.
79
+ rgb = ImageOps.autocontrast(rgb, cutoff=2, preserve_tone=True)
80
+ # Mild gamma toward darker midtones (γ ≈ 0.85).
81
+ arr = np.asarray(rgb, dtype=np.float32) / 255.0
82
+ arr = np.power(arr, 1.0 / 0.85)
83
+ rgb = Image.fromarray((np.clip(arr, 0.0, 1.0) * 255.0).astype(np.uint8))
84
+ # Reattach original alpha if present.
85
+ if img.mode == "RGBA":
86
+ a = img.split()[-1]
87
+ out = rgb.convert("RGBA")
88
+ out.putalpha(a)
89
+ return out
90
+ return rgb
91
+
92
+
93
+ def mask_smart(
94
+ img: Image.Image,
95
+ *,
96
+ bg_tolerance: float = 12.0,
97
+ ) -> np.ndarray:
98
+ """Boolean H×W foreground mask, content-aware (SPEC §4.1).
99
+
100
+ Routing:
101
+ 1. Has alpha → Otsu on alpha, fallback to 24.
102
+ 2. No alpha → corner background colour, ΔE > bg_tolerance in Lab.
103
+ 3. Degenerate (<2% or >98% coverage) → Sauvola on L channel.
104
+ """
105
+ rgba = np.asarray(img.convert("RGBA"))
106
+ alpha = rgba[..., 3]
107
+ rgb = rgba[..., :3]
108
+
109
+ candidates: list[np.ndarray] = []
110
+
111
+ if _has_alpha(img):
112
+ t = _otsu(alpha)
113
+ if t is None:
114
+ t = 24
115
+ candidates.append(alpha > t)
116
+
117
+ bg = _bg_color_from_corners(rgb)
118
+ lab_img = _rgb_to_lab(rgb)
119
+ lab_bg = _rgb_to_lab(bg.reshape(1, 1, 3).astype(np.uint8))[0, 0]
120
+ de = np.linalg.norm(lab_img - lab_bg[None, None, :], axis=-1)
121
+ candidates.append(de > bg_tolerance)
122
+
123
+ def coverage(m: np.ndarray) -> float:
124
+ return float(m.mean())
125
+
126
+ for m in candidates:
127
+ c = coverage(m)
128
+ if 0.02 < c < 0.98:
129
+ return m
130
+
131
+ # Escalate to Sauvola on L.
132
+ return _sauvola(lab_img[..., 0])
133
+
134
+
135
+ def mask_fixed(img: Image.Image, *, threshold: int = 24) -> np.ndarray:
136
+ """Fixed-threshold mask on alpha. SPEC §2.3 (also JS parity path)."""
137
+ alpha = np.array(img.split()[-1], dtype=np.uint8)
138
+ return alpha > threshold
ipolypad/emit.py ADDED
@@ -0,0 +1,187 @@
1
+ """Output formatters. SPEC §3."""
2
+ # this_file: ipolypad_py/src/ipolypad/emit.py
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import json
7
+ import re
8
+ from typing import Any
9
+
10
+ Point = tuple[float, float]
11
+
12
+ # Match floats in scientific notation produced by Python's json.dumps for very
13
+ # small values (e.g. "1e-06"). We convert them to plain decimal so that JSON
14
+ # output is byte-identical to the JavaScript implementation (SPEC §10).
15
+ _SCIENTIFIC_RE = re.compile(r"\b(-?)(\d+(?:\.\d+)?)e([+-])(\d+)\b")
16
+
17
+
18
+ def _expand_scientific(match: re.Match[str]) -> str:
19
+ sign, mantissa, exp_sign, exp_digits = match.groups()
20
+ exp = int(exp_digits)
21
+ # Split mantissa into integer/fraction
22
+ if "." in mantissa:
23
+ int_part, frac_part = mantissa.split(".")
24
+ else:
25
+ int_part, frac_part = mantissa, ""
26
+ digits = int_part + frac_part
27
+ if exp_sign == "-":
28
+ # shift decimal point left by exp
29
+ zeros = exp - len(int_part)
30
+ if zeros >= 0:
31
+ out = "0." + "0" * zeros + digits.lstrip("0") or "0"
32
+ if out.endswith("."):
33
+ out += "0"
34
+ else:
35
+ split = len(int_part) - exp
36
+ out = digits[:split] + "." + digits[split:]
37
+ else:
38
+ # shift decimal point right by exp
39
+ zeros = exp - len(frac_part)
40
+ if zeros >= 0:
41
+ out = digits + "0" * zeros
42
+ else:
43
+ split = len(digits) + zeros
44
+ out = digits[:split] + "." + digits[split:]
45
+ return sign + out
46
+
47
+
48
+ def _decimalize(s: str) -> str:
49
+ """Post-process json output to remove scientific notation for parity."""
50
+ return _SCIENTIFIC_RE.sub(_expand_scientific, s)
51
+
52
+
53
+ def _round_points(pts: list[Point], decimals: int = 6) -> list[list[float]]:
54
+ return [[round(x, decimals), round(y, decimals)] for x, y in pts]
55
+
56
+
57
+ def to_json(
58
+ *,
59
+ src: str,
60
+ width: int,
61
+ height: int,
62
+ pad: int,
63
+ max_points: int,
64
+ points: list[Point],
65
+ indent: int | None = 2,
66
+ ) -> str:
67
+ """Canonical JSON. 6-decimal points, sorted keys, no BOM. Parity surface."""
68
+ payload: dict[str, Any] = {
69
+ "src": src,
70
+ "raster": {"width": int(width), "height": int(height), "pad": int(pad)},
71
+ "max_points": int(max_points),
72
+ "n_points": len(points),
73
+ "points": _round_points(points),
74
+ }
75
+ return _decimalize(json.dumps(payload, indent=indent, sort_keys=True, ensure_ascii=False))
76
+
77
+
78
+ def to_css(points: list[Point], *, selector: str | None = None) -> str:
79
+ """CSS polygon. 2-decimal percentages. Parity surface."""
80
+ coords = ", ".join(f"{x * 100:.2f}% {y * 100:.2f}%" for x, y in points)
81
+ polygon = f"polygon({coords})"
82
+ if not selector:
83
+ return polygon + ";\n"
84
+ return (
85
+ f"{selector} {{\n"
86
+ f" shape-outside: {polygon};\n"
87
+ f" clip-path: {polygon};\n"
88
+ f"}}\n"
89
+ )
90
+
91
+
92
+ def to_svg(points: list[Point], *, width: int, height: int) -> str:
93
+ """SVG with one <polygon>, dimensioned to (width, height) px."""
94
+ coords = " ".join(f"{x * width:.2f},{y * height:.2f}" for x, y in points)
95
+ return (
96
+ f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" '
97
+ f'width="{width}" height="{height}">\n'
98
+ f' <polygon points="{coords}" fill="#000000" fill-opacity="0.35" '
99
+ f'stroke="#000000" stroke-width="1"/>\n'
100
+ f"</svg>\n"
101
+ )
102
+
103
+
104
+ def to_png(points: list[Point], *, width: int, height: int) -> bytes:
105
+ """Rasterized SVG polygon overlay."""
106
+ import resvg_py
107
+
108
+ svg = to_svg(points, width=width, height=height)
109
+ return bytes(resvg_py.svg_to_bytes(svg_string=svg, width=width, height=height))
110
+
111
+
112
+ def to_html(
113
+ *,
114
+ points: list[Point],
115
+ width: int,
116
+ height: int,
117
+ src: str | None = None,
118
+ src_data_url: str | None = None,
119
+ ) -> str:
120
+ """Self-contained HTML overlaying the polygon on top of the source.
121
+
122
+ Pass `src_data_url` for inline image, or `src` for an external URL.
123
+ """
124
+ coords_pct = ", ".join(f"{x * 100:.2f}% {y * 100:.2f}%" for x, y in points)
125
+ coords_xy = " ".join(f"{x * width:.2f},{y * height:.2f}" for x, y in points)
126
+ img_src = src_data_url or src or ""
127
+ return f"""<!DOCTYPE html>
128
+ <html lang="en">
129
+ <head>
130
+ <meta charset="utf-8">
131
+ <title>ipolypad preview</title>
132
+ <style>
133
+ body {{ font-family: -apple-system, system-ui, sans-serif; padding: 24px; background: #f6f7f9; }}
134
+ .stage {{ position: relative; width: {width}px; height: {height}px; }}
135
+ .stage img {{ position: absolute; inset: 0; width: 100%; height: 100%; }}
136
+ .stage svg {{ position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }}
137
+ code {{ display: block; white-space: pre-wrap; background: #fff; padding: 12px; border: 1px solid #e2e6ec; border-radius: 6px; }}
138
+ </style>
139
+ </head>
140
+ <body>
141
+ <h1>ipolypad preview</h1>
142
+ <div class="stage">
143
+ {'<img src="' + img_src + '" alt="source">' if img_src else ''}
144
+ <svg viewBox="0 0 {width} {height}"><polygon points="{coords_xy}" fill="rgba(255, 64, 64, 0.35)" stroke="rgba(255, 64, 64, 0.9)" stroke-width="1.5"/></svg>
145
+ </div>
146
+ <h2>CSS</h2>
147
+ <code>shape-outside: polygon({coords_pct});</code>
148
+ </body>
149
+ </html>
150
+ """
151
+
152
+
153
+ # convenience for callers that hold a polygon plus the canonical metadata
154
+ def emit(
155
+ fmt: str,
156
+ *,
157
+ points: list[Point],
158
+ src: str,
159
+ width: int,
160
+ height: int,
161
+ pad: int,
162
+ max_points: int,
163
+ selector: str | None = None,
164
+ ) -> str | bytes:
165
+ fmt = fmt.lower()
166
+ if fmt == "json":
167
+ return to_json(
168
+ src=src,
169
+ width=width,
170
+ height=height,
171
+ pad=pad,
172
+ max_points=max_points,
173
+ points=points,
174
+ )
175
+ if fmt == "css":
176
+ return to_css(points, selector=selector)
177
+ if fmt == "svg":
178
+ return to_svg(points, width=width, height=height)
179
+ if fmt == "png":
180
+ return to_png(points, width=width, height=height)
181
+ if fmt == "html":
182
+ return to_html(points=points, width=width, height=height, src=src)
183
+ raise ValueError(f"unsupported format: {fmt!r}")
184
+
185
+
186
+ # silence unused-import warning if rasterizer isn't loaded
187
+ _ = io
ipolypad/errors.py ADDED
@@ -0,0 +1,27 @@
1
+ """Typed errors. SPEC §8."""
2
+ # this_file: ipolypad_py/src/ipolypad/errors.py
3
+ from __future__ import annotations
4
+
5
+
6
+ class IpolypadError(Exception):
7
+ """Base."""
8
+
9
+
10
+ class SourceError(IpolypadError):
11
+ """Cannot fetch or read input source."""
12
+
13
+
14
+ class FormatError(IpolypadError):
15
+ """Unsupported content type."""
16
+
17
+
18
+ class EmptyMaskError(IpolypadError):
19
+ """No foreground pixels above the threshold."""
20
+
21
+
22
+ class TraceEmptyError(IpolypadError):
23
+ """potrace returned zero curves."""
24
+
25
+
26
+ class OnlyFrameError(IpolypadError):
27
+ """All curves are the bitmap-frame artifact (≥ 95% canvas)."""
ipolypad/fetch.py ADDED
@@ -0,0 +1,46 @@
1
+ """Fetch + content-type sniffing. SPEC §1, §2.1."""
2
+ # this_file: ipolypad_py/src/ipolypad/fetch.py
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import binascii
7
+ import urllib.error
8
+ import urllib.request
9
+ from pathlib import Path
10
+
11
+ from .errors import SourceError
12
+
13
+
14
+ def fetch(src: str) -> bytes:
15
+ """Resolve a source to bytes. Local path, http(s)://, or data: URL."""
16
+ if src.startswith(("http://", "https://")):
17
+ try:
18
+ with urllib.request.urlopen(src, timeout=30) as r: # noqa: S310
19
+ return r.read()
20
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError) as e:
21
+ raise SourceError(f"failed to fetch {src!r}: {e}") from e
22
+ if src.startswith("data:"):
23
+ try:
24
+ header, payload = src.split(",", 1)
25
+ if ";base64" in header:
26
+ return base64.b64decode(payload)
27
+ return payload.encode("utf-8")
28
+ except (ValueError, binascii.Error) as e:
29
+ raise SourceError(f"malformed data: URL: {e}") from e
30
+ p = Path(src)
31
+ if not p.exists():
32
+ raise SourceError(f"file not found: {src!r}")
33
+ try:
34
+ return p.read_bytes()
35
+ except OSError as e:
36
+ raise SourceError(f"failed to read {src!r}: {e}") from e
37
+
38
+
39
+ def is_svg(src: str, data: bytes) -> bool:
40
+ """Content-based first, extension fallback."""
41
+ head = data[:512].lstrip()
42
+ if head.startswith(b"<?xml") or head.startswith(b"<svg") or head.startswith(b"<!--"):
43
+ return True
44
+ if src.lower().endswith(".svg"):
45
+ return True
46
+ return False
ipolypad/pipeline.py ADDED
@@ -0,0 +1,175 @@
1
+ """Top-level pipeline. SPEC §2."""
2
+ # this_file: ipolypad_py/src/ipolypad/pipeline.py
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any, Literal
7
+
8
+ import numpy as np
9
+
10
+ from .color import autoenhance, mask_fixed, mask_smart
11
+ from .emit import emit
12
+ from .errors import EmptyMaskError, OnlyFrameError, TraceEmptyError
13
+ from .fetch import fetch, is_svg
14
+ from .rasterize import alpha_array, rasterize
15
+ from .simplify import convex_hull, decimate, normalize, pick_outer_shell, polygon_area
16
+ from .trace import dilate_circular, trace_mask
17
+
18
+ Format = Literal["json", "css", "svg", "png", "html"]
19
+
20
+
21
+ def _resolve_pad(*, pad: int | None, pad_pct: float | None, size: int) -> int:
22
+ if pad is not None and pad_pct is not None:
23
+ raise ValueError("pass either pad or pad_pct, not both")
24
+ if pad_pct is not None:
25
+ return max(0, round(pad_pct / 100.0 * size))
26
+ if pad is None:
27
+ return 6
28
+ return int(pad)
29
+
30
+
31
+ def trace(
32
+ src: str,
33
+ *,
34
+ size: int = 200,
35
+ margin: int = 20,
36
+ pad: int | None = None,
37
+ pad_pct: float | None = None,
38
+ max_points: int = 32,
39
+ samples_per_curve: int = 4,
40
+ hull: bool = True,
41
+ enhance: bool | None = None,
42
+ bg_tolerance: float = 12.0,
43
+ smart_mask: bool = True,
44
+ format: Format = "json",
45
+ selector: str | None = None,
46
+ out: str | None = None,
47
+ ) -> dict[str, Any] | str | bytes:
48
+ """Trace an image/SVG into a padded polygon hull.
49
+
50
+ See SPEC §2 for the pipeline and §6 for option defaults.
51
+
52
+ Returns the decoded JSON payload (dict) when ``format='json'`` and no
53
+ ``out`` path is given; otherwise returns the formatted string/bytes.
54
+ """
55
+ pad_px = _resolve_pad(pad=pad, pad_pct=pad_pct, size=size)
56
+ data = fetch(src)
57
+ svg_flag = is_svg(src, data)
58
+
59
+ if enhance is None:
60
+ enhance = not svg_flag
61
+
62
+ img = rasterize(data, size=size, margin=margin, is_svg=svg_flag)
63
+ if enhance:
64
+ img = autoenhance(img)
65
+
66
+ if smart_mask:
67
+ mask = mask_smart(img, bg_tolerance=bg_tolerance)
68
+ else:
69
+ mask = mask_fixed(img, threshold=24)
70
+
71
+ if not mask.any():
72
+ raise EmptyMaskError(
73
+ "no foreground above threshold; lower --bg-tolerance or check source"
74
+ )
75
+
76
+ h, w = mask.shape
77
+ work_mask = (
78
+ np.pad(mask, ((pad_px, pad_px), (pad_px, pad_px)), constant_values=False)
79
+ if pad_px > 0
80
+ else mask
81
+ )
82
+ work_mask = dilate_circular(work_mask, radius=pad_px)
83
+ work_h, work_w = work_mask.shape
84
+ polygons = trace_mask(work_mask, samples_per_curve=samples_per_curve)
85
+ if not polygons:
86
+ raise TraceEmptyError("potrace produced no curves")
87
+
88
+ canvas_area = float(work_h * work_w)
89
+ best = pick_outer_shell(polygons, canvas_area=canvas_area)
90
+ if best is None:
91
+ raise OnlyFrameError("only the bitmap-frame curve was traced")
92
+
93
+ pts = convex_hull(best) if hull else best
94
+ pts = decimate(pts, max_points)
95
+ pts = normalize(pts, w, h, offset_x=pad_px, offset_y=pad_px)
96
+
97
+ if format == "json":
98
+ payload_str = emit(
99
+ "json",
100
+ points=pts,
101
+ src=src,
102
+ width=w,
103
+ height=h,
104
+ pad=pad_px,
105
+ max_points=max_points,
106
+ )
107
+ if out:
108
+ Path(out).write_text(payload_str) # type: ignore[arg-type]
109
+ # Return parsed dict for ergonomic library use.
110
+ import json as _json
111
+
112
+ return _json.loads(payload_str) # type: ignore[arg-type]
113
+
114
+ if format == "css":
115
+ css = emit(
116
+ "css",
117
+ points=pts,
118
+ src=src,
119
+ width=w,
120
+ height=h,
121
+ pad=pad_px,
122
+ max_points=max_points,
123
+ selector=selector,
124
+ )
125
+ if out:
126
+ Path(out).write_text(css) # type: ignore[arg-type]
127
+ return css
128
+
129
+ if format == "svg":
130
+ svg = emit(
131
+ "svg",
132
+ points=pts,
133
+ src=src,
134
+ width=w,
135
+ height=h,
136
+ pad=pad_px,
137
+ max_points=max_points,
138
+ )
139
+ if out:
140
+ Path(out).write_text(svg) # type: ignore[arg-type]
141
+ return svg
142
+
143
+ if format == "png":
144
+ png = emit(
145
+ "png",
146
+ points=pts,
147
+ src=src,
148
+ width=w,
149
+ height=h,
150
+ pad=pad_px,
151
+ max_points=max_points,
152
+ )
153
+ if out:
154
+ Path(out).write_bytes(png) # type: ignore[arg-type]
155
+ return png
156
+
157
+ if format == "html":
158
+ html = emit(
159
+ "html",
160
+ points=pts,
161
+ src=src,
162
+ width=w,
163
+ height=h,
164
+ pad=pad_px,
165
+ max_points=max_points,
166
+ )
167
+ if out:
168
+ Path(out).write_text(html) # type: ignore[arg-type]
169
+ return html
170
+
171
+ raise ValueError(f"unsupported format: {format!r}")
172
+
173
+
174
+ # Re-export for clarity; consumed by __main__.py
175
+ _ = (alpha_array, polygon_area)
ipolypad/rasterize.py ADDED
@@ -0,0 +1,47 @@
1
+ """Rasterize SVG/raster input to an alpha mask. SPEC §2.2."""
2
+ # this_file: ipolypad_py/src/ipolypad/rasterize.py
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import re
7
+
8
+ import numpy as np
9
+ import resvg_py
10
+ from PIL import Image
11
+
12
+ _RESAMPLE = getattr(Image, "Resampling", Image).LANCZOS
13
+
14
+
15
+ def _strip_root_attrs(svg_str: str) -> str:
16
+ """Strip width/height/style from the root <svg>. Load-bearing for Qt SVGs."""
17
+ svg_str = re.sub(r'(<svg\b[^>]*?)\s+width="[^"]*"', r"\1", svg_str, count=1)
18
+ svg_str = re.sub(r'(<svg\b[^>]*?)\s+height="[^"]*"', r"\1", svg_str, count=1)
19
+ svg_str = re.sub(r'(<svg\b[^>]*?)\s+style="[^"]*"', r"\1", svg_str, count=1)
20
+ return svg_str
21
+
22
+
23
+ def rasterize(data: bytes, *, size: int, margin: int, is_svg: bool) -> Image.Image:
24
+ """Render to RGBA size×size canvas with `margin`-px transparent gutter.
25
+
26
+ Returns the centered RGBA composite. Use ``.split()[-1]`` for alpha.
27
+ Raster inputs are scaled to fit ``inner × inner`` preserving aspect.
28
+ """
29
+ inner = max(8, size - 2 * margin)
30
+ if is_svg:
31
+ svg_str = _strip_root_attrs(data.decode("utf-8"))
32
+ png_bytes = bytes(
33
+ resvg_py.svg_to_bytes(svg_string=svg_str, width=inner, height=inner)
34
+ )
35
+ inner_img = Image.open(io.BytesIO(png_bytes)).convert("RGBA")
36
+ else:
37
+ inner_img = Image.open(io.BytesIO(data)).convert("RGBA")
38
+ inner_img.thumbnail((inner, inner), _RESAMPLE)
39
+ canvas = Image.new("RGBA", (size, size), (0, 0, 0, 0))
40
+ off = ((size - inner_img.width) // 2, (size - inner_img.height) // 2)
41
+ canvas.paste(inner_img, off, inner_img)
42
+ return canvas
43
+
44
+
45
+ def alpha_array(img: Image.Image) -> np.ndarray:
46
+ """Alpha channel as uint8 H×W."""
47
+ return np.array(img.split()[-1], dtype=np.uint8)
ipolypad/simplify.py ADDED
@@ -0,0 +1,111 @@
1
+ """Polygon utilities: area, convex hull, RDP, vertex-count-targeted decimation. SPEC §2.6–§2.8."""
2
+ # this_file: ipolypad_py/src/ipolypad/simplify.py
3
+ from __future__ import annotations
4
+
5
+ import math
6
+
7
+ Point = tuple[float, float]
8
+
9
+
10
+ def polygon_area(pts: list[Point]) -> float:
11
+ """Unsigned shoelace area."""
12
+ a = 0.0
13
+ n = len(pts)
14
+ for i in range(n):
15
+ x0, y0 = pts[i]
16
+ x1, y1 = pts[(i + 1) % n]
17
+ a += x0 * y1 - x1 * y0
18
+ return abs(a) / 2.0
19
+
20
+
21
+ def pick_outer_shell(
22
+ polygons: list[list[Point]], *, canvas_area: float, frame_fraction: float = 0.95
23
+ ) -> list[Point] | None:
24
+ """Largest non-frame curve. SPEC §2.6."""
25
+ polygons = [p for p in polygons if polygon_area(p) < frame_fraction * canvas_area]
26
+ if not polygons:
27
+ return None
28
+ polygons.sort(key=polygon_area, reverse=True)
29
+ return polygons[0]
30
+
31
+
32
+ def convex_hull(pts: list[Point]) -> list[Point]:
33
+ """Andrew's monotone chain. CCW, no closing duplicate. SPEC §2.7."""
34
+ sorted_pts = sorted(set(pts))
35
+ if len(sorted_pts) <= 1:
36
+ return sorted_pts
37
+
38
+ def cross(o: Point, a: Point, b: Point) -> float:
39
+ return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
40
+
41
+ lower: list[Point] = []
42
+ for p in sorted_pts:
43
+ while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
44
+ lower.pop()
45
+ lower.append(p)
46
+ upper: list[Point] = []
47
+ for p in reversed(sorted_pts):
48
+ while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
49
+ upper.pop()
50
+ upper.append(p)
51
+ return lower[:-1] + upper[:-1]
52
+
53
+
54
+ def rdp(pts: list[Point], eps: float) -> list[Point]:
55
+ """Iterative Ramer-Douglas-Peucker."""
56
+ if len(pts) < 3:
57
+ return pts[:]
58
+ keep = [False] * len(pts)
59
+ keep[0] = keep[-1] = True
60
+ stack = [(0, len(pts) - 1)]
61
+ while stack:
62
+ s, e = stack.pop()
63
+ if e - s < 2:
64
+ continue
65
+ x0, y0 = pts[s]
66
+ x1, y1 = pts[e]
67
+ dx, dy = x1 - x0, y1 - y0
68
+ denom = math.hypot(dx, dy) or 1.0
69
+ best_i, best_d = -1, -1.0
70
+ for i in range(s + 1, e):
71
+ x, y = pts[i]
72
+ d = abs(dy * x - dx * y + x1 * y0 - y1 * x0) / denom
73
+ if d > best_d:
74
+ best_d, best_i = d, i
75
+ if best_d > eps:
76
+ keep[best_i] = True
77
+ stack.append((s, best_i))
78
+ stack.append((best_i, e))
79
+ return [pts[i] for i, k in enumerate(keep) if k]
80
+
81
+
82
+ def decimate(pts: list[Point], max_points: int) -> list[Point]:
83
+ """Hit a target vertex count by binary-searching RDP epsilon. SPEC §2.8."""
84
+ if len(pts) >= 2 and pts[0] == pts[-1]:
85
+ pts = pts[:-1]
86
+ if len(pts) <= max_points:
87
+ return pts
88
+ xs = [p[0] for p in pts]
89
+ ys = [p[1] for p in pts]
90
+ diag = math.hypot(max(xs) - min(xs), max(ys) - min(ys)) or 1.0
91
+ lo, hi = 0.0, diag * 0.25
92
+ for _ in range(24):
93
+ mid = (lo + hi) / 2
94
+ out = rdp(pts, mid)
95
+ if len(out) > max_points:
96
+ lo = mid
97
+ else:
98
+ hi = mid
99
+ return rdp(pts, hi)
100
+
101
+
102
+ def normalize(
103
+ pts: list[Point],
104
+ width: int,
105
+ height: int,
106
+ *,
107
+ offset_x: float = 0.0,
108
+ offset_y: float = 0.0,
109
+ ) -> list[Point]:
110
+ """Normalize over the original image box, optionally undoing work-canvas offset."""
111
+ return [((x - offset_x) / width, (y - offset_y) / height) for (x, y) in pts]
ipolypad/trace.py ADDED
@@ -0,0 +1,69 @@
1
+ """Dilate, potrace, flatten curves. SPEC §2.4–§2.5."""
2
+ # this_file: ipolypad_py/src/ipolypad/trace.py
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ from potrace import Bitmap
7
+ from scipy.ndimage import binary_dilation
8
+
9
+
10
+ def dilate_circular(mask: np.ndarray, *, radius: int) -> np.ndarray:
11
+ """Binary dilation with a circular (Euclidean) structuring element."""
12
+ if radius <= 0:
13
+ return mask
14
+ r = radius
15
+ y, x = np.ogrid[-r : r + 1, -r : r + 1]
16
+ struct = (x * x + y * y) <= r * r
17
+ return binary_dilation(mask, structure=struct)
18
+
19
+
20
+ def flatten_curve(curve, *, samples_per_curve: int) -> list[tuple[float, float]]:
21
+ """potrace curve → polyline. Beziers are flattened at fixed sample count."""
22
+ pts: list[tuple[float, float]] = []
23
+ p0 = (curve.start_point.x, curve.start_point.y)
24
+ pts.append(p0)
25
+ cur = p0
26
+ for seg in curve.segments:
27
+ if seg.is_corner:
28
+ pts.append((seg.c.x, seg.c.y))
29
+ pts.append((seg.end_point.x, seg.end_point.y))
30
+ cur = (seg.end_point.x, seg.end_point.y)
31
+ else:
32
+ c1 = (seg.c1.x, seg.c1.y)
33
+ c2 = (seg.c2.x, seg.c2.y)
34
+ end = (seg.end_point.x, seg.end_point.y)
35
+ for i in range(1, samples_per_curve + 1):
36
+ t = i / samples_per_curve
37
+ u = 1 - t
38
+ bx = (
39
+ u**3 * cur[0]
40
+ + 3 * u**2 * t * c1[0]
41
+ + 3 * u * t**2 * c2[0]
42
+ + t**3 * end[0]
43
+ )
44
+ by = (
45
+ u**3 * cur[1]
46
+ + 3 * u**2 * t * c1[1]
47
+ + 3 * u * t**2 * c2[1]
48
+ + t**3 * end[1]
49
+ )
50
+ pts.append((bx, by))
51
+ cur = end
52
+ return pts
53
+
54
+
55
+ def trace_mask(
56
+ mask: np.ndarray, *, samples_per_curve: int
57
+ ) -> list[list[tuple[float, float]]]:
58
+ """Run potrace and flatten each curve to a polyline.
59
+
60
+ Required potrace parameters (SPEC §2.5): turdsize=2, turnpolicy=0, alphamax=1.0.
61
+ """
62
+ bm = Bitmap(mask)
63
+ plist = bm.trace(turdsize=2, turnpolicy=0, alphamax=1.0)
64
+ polygons: list[list[tuple[float, float]]] = []
65
+ for curve in plist:
66
+ pts = flatten_curve(curve, samples_per_curve=samples_per_curve)
67
+ if len(pts) >= 3:
68
+ polygons.append(pts)
69
+ return polygons
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: ipolypad
3
+ Version: 1.0.2
4
+ Summary: Convert an image or SVG into a padded polygon hull for CSS shape-outside / text-wrap.
5
+ Project-URL: Homepage, https://github.com/twardoch/ipolypad
6
+ Project-URL: Documentation, https://code.twardoch.com/ipolypad/
7
+ Project-URL: Repository, https://github.com/twardoch/ipolypad
8
+ Project-URL: Issues, https://github.com/twardoch/ipolypad/issues
9
+ Author-email: Adam Twardoch <adam+github@twardoch.com>
10
+ License-Expression: Apache-2.0
11
+ Keywords: image-processing,polygon,potrace,shape-outside,svg,text-wrap
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Multimedia :: Graphics
20
+ Classifier: Topic :: Text Processing :: Markup :: HTML
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: fire>=0.6
23
+ Requires-Dist: numpy>=1.24
24
+ Requires-Dist: pillow>=10.0
25
+ Requires-Dist: potracer>=0.0.4
26
+ Requires-Dist: resvg-py>=0.1.5
27
+ Requires-Dist: scikit-image>=0.22
28
+ Requires-Dist: scipy>=1.10
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest-cov>=5; extra == 'test'
31
+ Requires-Dist: pytest>=8; extra == 'test'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # ipolypad
35
+
36
+ Convert an image or SVG into a **padded polygon hull** suitable for CSS
37
+ `shape-outside` and HTML/canvas text-wrap engines. Reference implementation.
38
+
39
+ See the project root [`README.md`](../README.md) and [`SPEC.md`](../SPEC.md) for
40
+ the full design. This package is the Python side — smart, batteries-included,
41
+ multi-format output.
42
+
43
+ ## Install
44
+
45
+ ```bash
46
+ uvx ipolypad trace dragon.svg --pad 6 --max-points 32 --out dragon.json
47
+ # or
48
+ uv pip install ipolypad
49
+ ```
50
+
51
+ ## CLI
52
+
53
+ ```bash
54
+ ipolypad trace <src> [--size 200] [--pad 6] [--max-points 32] \
55
+ [--hull / --no-hull] [--format json,css,svg,png,html] \
56
+ [--enhance / --no-enhance] [--bg-tolerance 12] \
57
+ [--selector .figure] [--out path]
58
+
59
+ ipolypad batch '*.svg' --out-dir dist/ [trace options...]
60
+ ```
61
+
62
+ `src` may be a local path, an `http(s)://` URL, or a `data:` URL.
63
+
64
+ ## Library
65
+
66
+ ```python
67
+ from ipolypad import trace
68
+
69
+ result = trace("dragon.svg", size=200, pad=6, max_points=32, format="json")
70
+ print(result["points"])
71
+ ```
72
+
73
+ ## Output
74
+
75
+ Default JSON:
76
+
77
+ ```json
78
+ {
79
+ "src": "dragon.svg",
80
+ "raster": { "width": 200, "height": 200, "pad": 6 },
81
+ "max_points": 32,
82
+ "n_points": 18,
83
+ "points": [[0.500000, 0.020000], ...]
84
+ }
85
+ ```
86
+
87
+ `points` are normalized 0..1 against the rasterization box, six decimals,
88
+ no trailing closing vertex (polygon is implicitly closed).
89
+
90
+ ## License
91
+
92
+ Apache-2.0. See [LICENSE](../LICENSE).
@@ -0,0 +1,15 @@
1
+ ipolypad/__init__.py,sha256=6tKmY1zjxM0W2N1Eu6rH938WMkFZA1W1P5CvLrI_bww,592
2
+ ipolypad/__main__.py,sha256=u5Ob3WtQgGKms9iK5gu4LQg_Y5s_m0amm-Scw8yX7No,5238
3
+ ipolypad/__version__.py,sha256=913Ea4P4y2ZD15ebE66os1ChbBKutOXqQ54_tjABoS0,520
4
+ ipolypad/color.py,sha256=xaNFAzcXiKnKlyqco3kjQZ30LW_MjcMEFfeaMF2yqXY,4506
5
+ ipolypad/emit.py,sha256=jLDqLEjhcJEqYgjHXxTu95Thj8511ZBNIRycyzzqMtQ,6105
6
+ ipolypad/errors.py,sha256=6bVNr79-_PgKgpr2VBn3SrLJNQ_eOMMcmt42hin1uAI,595
7
+ ipolypad/fetch.py,sha256=CHcmQN3eBx2RmMjyWJZoqBkdIOVIWYpdjybI-sZUe_Y,1569
8
+ ipolypad/pipeline.py,sha256=Yh45inNJ6F566_oxNCWuSvWd2OBfbBBgdy39o_YbjHo,4921
9
+ ipolypad/rasterize.py,sha256=66FvJw4UErUDJ7PSc5nqDSjXY8CUZUD3OjkHWqnXQVs,1762
10
+ ipolypad/simplify.py,sha256=xbamgIeO2eYoEfbZETjPAhUDAHiGR-SZvtruu1mNIhs,3383
11
+ ipolypad/trace.py,sha256=XXahRTfbEg-YF2huvr9_2NzRU6jh5NSk2rRjLDsDwfY,2365
12
+ ipolypad-1.0.2.dist-info/METADATA,sha256=3J1KSjVxf3YPF9LDGo87ay9zF4sbcxQ7l-SmfrnBQkQ,2805
13
+ ipolypad-1.0.2.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
14
+ ipolypad-1.0.2.dist-info/entry_points.txt,sha256=MogkKTgpggHGCs4npwXcf7rI09O4je7CEQvVAHyxkoM,52
15
+ ipolypad-1.0.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ipolypad = ipolypad.__main__:main