tileupscale 0.6.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.
- tileupscale-0.6.0.dist-info/METADATA +172 -0
- tileupscale-0.6.0.dist-info/RECORD +52 -0
- tileupscale-0.6.0.dist-info/WHEEL +5 -0
- tileupscale-0.6.0.dist-info/entry_points.txt +2 -0
- tileupscale-0.6.0.dist-info/licenses/LICENSE +21 -0
- tileupscale-0.6.0.dist-info/licenses/NOTICE +6 -0
- tileupscale-0.6.0.dist-info/top_level.txt +1 -0
- upscale/__init__.py +30 -0
- upscale/__main__.py +3 -0
- upscale/about.py +170 -0
- upscale/algorithms/__init__.py +166 -0
- upscale/algorithms/classical.py +82 -0
- upscale/algorithms/plugins/__init__.py +52 -0
- upscale/algorithms/plugins/texture_residual.py +117 -0
- upscale/algorithms/plugins/vectorize_scale.py +450 -0
- upscale/alpha_policy.py +140 -0
- upscale/api/__init__.py +19 -0
- upscale/api/compare_routes.py +256 -0
- upscale/api/deps.py +18 -0
- upscale/api/jobs.py +535 -0
- upscale/api/media_routes.py +257 -0
- upscale/api/models_routes.py +107 -0
- upscale/api/system_routes.py +210 -0
- upscale/backends/__init__.py +27 -0
- upscale/backends/onnx_rt.py +291 -0
- upscale/benchmark.py +96 -0
- upscale/checkpoint.py +259 -0
- upscale/cli.py +634 -0
- upscale/compare.py +204 -0
- upscale/config.py +56 -0
- upscale/engine.py +321 -0
- upscale/estimates.py +338 -0
- upscale/filters.py +180 -0
- upscale/help_content.py +95 -0
- upscale/infer_util.py +22 -0
- upscale/io_utils.py +622 -0
- upscale/job_prep.py +318 -0
- upscale/mcp_server.py +287 -0
- upscale/memmap_util.py +70 -0
- upscale/models.py +628 -0
- upscale/naming.py +63 -0
- upscale/pipeline.py +482 -0
- upscale/presets.py +127 -0
- upscale/quality.py +36 -0
- upscale/schema.py +315 -0
- upscale/server.py +893 -0
- upscale/speed_stats.py +273 -0
- upscale/suggest.py +93 -0
- upscale/system.py +102 -0
- upscale/tiling.py +430 -0
- upscale/web.py +118 -0
- upscale/weight_blend.py +75 -0
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Classical resize backends — OpenCV when available, else Pillow."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from PIL import Image
|
|
7
|
+
|
|
8
|
+
BUILTIN_ALGORITHMS = (
|
|
9
|
+
"nearest",
|
|
10
|
+
"bilinear",
|
|
11
|
+
"bicubic",
|
|
12
|
+
"lanczos2",
|
|
13
|
+
"lanczos3",
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
# OpenCV and Pillow only expose one Lanczos kernel (≈3–4 lobe). lanczos2 is
|
|
17
|
+
# an alias of lanczos3 so the public names do not promise a difference.
|
|
18
|
+
_CV_MAP = {
|
|
19
|
+
"nearest": "INTER_NEAREST",
|
|
20
|
+
"bilinear": "INTER_LINEAR",
|
|
21
|
+
"bicubic": "INTER_CUBIC",
|
|
22
|
+
"lanczos2": "INTER_LANCZOS4",
|
|
23
|
+
"lanczos3": "INTER_LANCZOS4",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
_PIL_MAP = {
|
|
27
|
+
"nearest": Image.Resampling.NEAREST,
|
|
28
|
+
"bilinear": Image.Resampling.BILINEAR,
|
|
29
|
+
"bicubic": Image.Resampling.BICUBIC,
|
|
30
|
+
"lanczos2": Image.Resampling.LANCZOS,
|
|
31
|
+
"lanczos3": Image.Resampling.LANCZOS,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _try_cv2():
|
|
36
|
+
try:
|
|
37
|
+
import cv2 # noqa: F401
|
|
38
|
+
|
|
39
|
+
return cv2
|
|
40
|
+
except ImportError:
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def resize_classical(name: str, img: np.ndarray, target_w: int, target_h: int) -> np.ndarray:
|
|
45
|
+
"""Resize with a classical interpolator. Prefers OpenCV (C++/SIMD)."""
|
|
46
|
+
key = name.strip().lower().replace("-", "_")
|
|
47
|
+
if key not in BUILTIN_ALGORITHMS:
|
|
48
|
+
raise ValueError(f"not a built-in classical algorithm: {name}")
|
|
49
|
+
|
|
50
|
+
cv2 = _try_cv2()
|
|
51
|
+
if cv2 is not None:
|
|
52
|
+
return _resize_cv2(cv2, key, img, target_w, target_h)
|
|
53
|
+
return _resize_pil(key, img, target_w, target_h)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _resize_cv2(cv2, key: str, img: np.ndarray, tw: int, th: int) -> np.ndarray:
|
|
57
|
+
flag = getattr(cv2, _CV_MAP[key])
|
|
58
|
+
# Optional CUDA path when a CUDA build of OpenCV is present
|
|
59
|
+
if hasattr(cv2, "cuda") and cv2.cuda.getCudaEnabledDeviceCount() > 0:
|
|
60
|
+
try:
|
|
61
|
+
gpu = cv2.cuda_GpuMat()
|
|
62
|
+
gpu.upload(img)
|
|
63
|
+
out = cv2.cuda.resize(gpu, (tw, th), interpolation=flag)
|
|
64
|
+
return out.download()
|
|
65
|
+
except Exception: # noqa: BLE001
|
|
66
|
+
pass
|
|
67
|
+
return cv2.resize(img, (tw, th), interpolation=flag)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _resize_pil(key: str, img: np.ndarray, tw: int, th: int) -> np.ndarray:
|
|
71
|
+
resample = _PIL_MAP[key]
|
|
72
|
+
if img.ndim == 2:
|
|
73
|
+
pil = Image.fromarray(img, mode="L")
|
|
74
|
+
return np.array(pil.resize((tw, th), resample), dtype=np.uint8)
|
|
75
|
+
if img.shape[2] == 1:
|
|
76
|
+
return _resize_pil(key, img[:, :, 0], tw, th)[:, :, None]
|
|
77
|
+
pil = Image.fromarray(img)
|
|
78
|
+
return np.array(pil.resize((tw, th), resample), dtype=np.uint8)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def backend_name() -> str:
|
|
82
|
+
return "opencv" if _try_cv2() is not None else "pillow"
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Optional paper / native algorithm plugins.
|
|
2
|
+
|
|
3
|
+
``load_plugins()`` imports every non-private submodule in this package so each
|
|
4
|
+
module can call ``register_algorithm``. Failures in optional deps (e.g. missing
|
|
5
|
+
``vtracer``) are skipped; other import errors are logged once.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import importlib
|
|
11
|
+
import logging
|
|
12
|
+
import pkgutil
|
|
13
|
+
from typing import Iterable
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
_LOADED = False
|
|
18
|
+
|
|
19
|
+
# Skip docs / native stubs
|
|
20
|
+
_SKIP = frozenset({"native"})
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _iter_plugin_modules() -> Iterable[str]:
|
|
24
|
+
import upscale.algorithms.plugins as pkg
|
|
25
|
+
|
|
26
|
+
for mod in pkgutil.iter_modules(pkg.__path__, pkg.__name__ + "."):
|
|
27
|
+
short = mod.name.rsplit(".", 1)[-1]
|
|
28
|
+
if short.startswith("_") or short in _SKIP:
|
|
29
|
+
continue
|
|
30
|
+
yield mod.name
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def load_plugins() -> list[str]:
|
|
34
|
+
"""Import plugin modules. Returns list of successfully imported module names."""
|
|
35
|
+
global _LOADED
|
|
36
|
+
if _LOADED:
|
|
37
|
+
return []
|
|
38
|
+
_LOADED = True
|
|
39
|
+
loaded: list[str] = []
|
|
40
|
+
for name in _iter_plugin_modules():
|
|
41
|
+
try:
|
|
42
|
+
importlib.import_module(name)
|
|
43
|
+
loaded.append(name)
|
|
44
|
+
except ImportError as exc:
|
|
45
|
+
# Optional dependency missing (vectorize, etc.)
|
|
46
|
+
logger.debug("Skip plugin %s: %s", name, exc)
|
|
47
|
+
except Exception as exc: # noqa: BLE001
|
|
48
|
+
logger.warning("Plugin %s failed to load: %s", name, exc)
|
|
49
|
+
return loaded
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
__all__ = ["load_plugins"]
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Structure upsample + high-frequency residual (paper-inspired).
|
|
2
|
+
|
|
3
|
+
Inspired by separating a smooth structure layer from a texture residual
|
|
4
|
+
(as in Grimm/Kulla et al. NPR shading, and Efros–Leung / quilting families).
|
|
5
|
+
This is **not** a port of pg2003uts (NPR mesh shading); it adapts the
|
|
6
|
+
structure/texture split for single-image upscaling:
|
|
7
|
+
|
|
8
|
+
1. Structure = Lanczos upsample of the LR image.
|
|
9
|
+
2. Detail = high-pass of LR (image − blur), upsampled with nearest, then
|
|
10
|
+
optionally reinforced by copying LR patch energy (simple self-similarity).
|
|
11
|
+
3. Output = clip(structure + strength * detail).
|
|
12
|
+
|
|
13
|
+
Pure NumPy / Pillow — no Torch.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
from PIL import Image, ImageFilter
|
|
20
|
+
|
|
21
|
+
from upscale.algorithms import register_algorithm
|
|
22
|
+
from upscale.algorithms.classical import resize_classical
|
|
23
|
+
|
|
24
|
+
# Defaults tuned for crop-compare (small regions)
|
|
25
|
+
_DEFAULT_STRENGTH = 0.85
|
|
26
|
+
_DEFAULT_BLUR_RADIUS = 1.2
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _to_rgb(img: np.ndarray) -> np.ndarray:
|
|
30
|
+
if img.ndim == 2:
|
|
31
|
+
return np.stack([img, img, img], axis=-1)
|
|
32
|
+
if img.shape[2] == 1:
|
|
33
|
+
return np.concatenate([img, img, img], axis=2)
|
|
34
|
+
return img[:, :, :3]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _high_pass(rgb: np.ndarray, blur_radius: float = _DEFAULT_BLUR_RADIUS) -> np.ndarray:
|
|
38
|
+
"""LR high-pass as signed float32 (approx image − blur)."""
|
|
39
|
+
pil = Image.fromarray(rgb, mode="RGB")
|
|
40
|
+
blur = pil.filter(ImageFilter.GaussianBlur(radius=blur_radius))
|
|
41
|
+
base = np.asarray(pil, dtype=np.float32)
|
|
42
|
+
smooth = np.asarray(blur, dtype=np.float32)
|
|
43
|
+
return base - smooth
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _upsample(arr: np.ndarray, tw: int, th: int, *, nearest: bool) -> np.ndarray:
|
|
47
|
+
"""Upsample HxWxC float or uint8."""
|
|
48
|
+
if nearest:
|
|
49
|
+
# Channel-wise nearest via PIL
|
|
50
|
+
if arr.dtype != np.uint8:
|
|
51
|
+
# Map signed residual to temp uint8 for resize, then remap — better:
|
|
52
|
+
# resize each channel as float via PIL F mode is awkward; use nearest
|
|
53
|
+
# on a stacked approach with scipy-free indexing.
|
|
54
|
+
h, w = arr.shape[:2]
|
|
55
|
+
ys = (np.arange(th) * h / th).astype(np.int32)
|
|
56
|
+
xs = (np.arange(tw) * w / tw).astype(np.int32)
|
|
57
|
+
ys = np.clip(ys, 0, h - 1)
|
|
58
|
+
xs = np.clip(xs, 0, w - 1)
|
|
59
|
+
return arr[ys][:, xs].astype(np.float32)
|
|
60
|
+
return resize_classical("nearest", arr, tw, th).astype(np.float32)
|
|
61
|
+
if arr.dtype != np.uint8:
|
|
62
|
+
# Lanczos on absolute scaled preview is wrong for signed; use bilinear
|
|
63
|
+
# via float reshape — Pillow RGB only for uint8. Use nearest for HF.
|
|
64
|
+
return _upsample(arr, tw, th, nearest=True)
|
|
65
|
+
return resize_classical("lanczos3", arr, tw, th).astype(np.float32)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def texture_residual_resize(
|
|
69
|
+
img: np.ndarray,
|
|
70
|
+
target_w: int,
|
|
71
|
+
target_h: int,
|
|
72
|
+
*,
|
|
73
|
+
strength: float = _DEFAULT_STRENGTH,
|
|
74
|
+
blur_radius: float = _DEFAULT_BLUR_RADIUS,
|
|
75
|
+
) -> np.ndarray:
|
|
76
|
+
"""Resize with Lanczos structure + amplified high-frequency residual.
|
|
77
|
+
|
|
78
|
+
Accepts HxW (alpha / gray), HxWx1, or HxWx3[+]. Gray inputs return HxW.
|
|
79
|
+
"""
|
|
80
|
+
raw = np.asarray(img, dtype=np.uint8)
|
|
81
|
+
gray_in = raw.ndim == 2 or (raw.ndim == 3 and raw.shape[2] == 1)
|
|
82
|
+
rgb = _to_rgb(raw)
|
|
83
|
+
# Contiguous uint8 required by Pillow mode="RGB"
|
|
84
|
+
rgb = np.ascontiguousarray(rgb, dtype=np.uint8)
|
|
85
|
+
tw, th = int(target_w), int(target_h)
|
|
86
|
+
if tw < 1 or th < 1:
|
|
87
|
+
raise ValueError("target size must be positive")
|
|
88
|
+
|
|
89
|
+
structure = resize_classical("lanczos3", rgb, tw, th).astype(np.float32)
|
|
90
|
+
if abs(strength) < 1e-6:
|
|
91
|
+
out = np.clip(structure, 0, 255).astype(np.uint8)
|
|
92
|
+
else:
|
|
93
|
+
hp = _high_pass(rgb, blur_radius=blur_radius)
|
|
94
|
+
detail = _upsample(hp, tw, th, nearest=True)
|
|
95
|
+
out = np.clip(structure + float(strength) * detail, 0, 255).astype(np.uint8)
|
|
96
|
+
|
|
97
|
+
if gray_in:
|
|
98
|
+
return out[:, :, 0]
|
|
99
|
+
return out
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _entry(img: np.ndarray, tw: int, th: int) -> np.ndarray:
|
|
103
|
+
return texture_residual_resize(img, tw, th)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
register_algorithm(
|
|
107
|
+
"texture_residual",
|
|
108
|
+
_entry,
|
|
109
|
+
overwrite=True,
|
|
110
|
+
label="Texture residual",
|
|
111
|
+
group="paper",
|
|
112
|
+
description=(
|
|
113
|
+
"Lanczos structure plus high-frequency residual from the source "
|
|
114
|
+
"(structure/texture split inspired by NPR texture synthesis). "
|
|
115
|
+
"Adds crisp local detail; can look grainy on smooth photos."
|
|
116
|
+
),
|
|
117
|
+
)
|
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
"""Vectorize (VTracer or PyAutoTrace), then rasterize at the target size.
|
|
2
|
+
|
|
3
|
+
Best for logos / line art / flat graphics — not photographs.
|
|
4
|
+
Optional dependency: ``pip install 'tileupscale[vectorize]'``
|
|
5
|
+
(vtracer + pyautotrace + resvg_py).
|
|
6
|
+
|
|
7
|
+
SVG is produced internally; users still cannot upload SVG as input.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import io
|
|
13
|
+
import logging
|
|
14
|
+
import re
|
|
15
|
+
import xml.etree.ElementTree as ET
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
from PIL import Image, ImageDraw
|
|
19
|
+
|
|
20
|
+
from upscale.algorithms import register_algorithm
|
|
21
|
+
from upscale.algorithms.classical import resize_classical
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
_DEFAULT_TRACE_EDGE = 1024
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _to_rgba(img: np.ndarray) -> np.ndarray:
|
|
29
|
+
if img.ndim == 2:
|
|
30
|
+
rgb = np.stack([img, img, img], axis=-1)
|
|
31
|
+
a = np.full(img.shape, 255, dtype=np.uint8)
|
|
32
|
+
return np.dstack([rgb, a])
|
|
33
|
+
if img.shape[2] == 3:
|
|
34
|
+
a = np.full(img.shape[:2], 255, dtype=np.uint8)
|
|
35
|
+
return np.dstack([img, a])
|
|
36
|
+
return img[:, :, :4]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _maybe_downscale(rgb: np.ndarray, max_trace_edge: int) -> np.ndarray:
|
|
40
|
+
"""Downscale for tracing speed on large images."""
|
|
41
|
+
cap = max(256, int(max_trace_edge))
|
|
42
|
+
h, w = rgb.shape[:2]
|
|
43
|
+
edge = max(h, w)
|
|
44
|
+
if edge <= cap:
|
|
45
|
+
return rgb
|
|
46
|
+
scale = cap / edge
|
|
47
|
+
tw = max(1, int(round(w * scale)))
|
|
48
|
+
th = max(1, int(round(h * scale)))
|
|
49
|
+
return resize_classical("bilinear", rgb, tw, th)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _trace_svg_vtracer(
|
|
53
|
+
rgb: np.ndarray,
|
|
54
|
+
*,
|
|
55
|
+
color_precision: int = 6,
|
|
56
|
+
filter_speckle: int = 4,
|
|
57
|
+
corner_threshold: int = 60,
|
|
58
|
+
mode: str = "spline",
|
|
59
|
+
) -> str:
|
|
60
|
+
import vtracer
|
|
61
|
+
|
|
62
|
+
rgba = _to_rgba(rgb)
|
|
63
|
+
h, w = rgba.shape[:2]
|
|
64
|
+
pixels = [tuple(int(x) for x in px) for px in rgba.reshape(-1, 4)]
|
|
65
|
+
path_mode = mode if mode in ("spline", "polygon") else "spline"
|
|
66
|
+
return vtracer.convert_pixels_to_svg(
|
|
67
|
+
pixels,
|
|
68
|
+
(w, h),
|
|
69
|
+
colormode="color",
|
|
70
|
+
hierarchical="stacked",
|
|
71
|
+
mode=path_mode,
|
|
72
|
+
filter_speckle=int(filter_speckle),
|
|
73
|
+
color_precision=int(color_precision),
|
|
74
|
+
layer_difference=16,
|
|
75
|
+
corner_threshold=int(corner_threshold),
|
|
76
|
+
length_threshold=4.0,
|
|
77
|
+
max_iterations=10,
|
|
78
|
+
splice_threshold=45,
|
|
79
|
+
path_precision=3,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _trace_svg_autotrace(
|
|
84
|
+
rgb: np.ndarray,
|
|
85
|
+
*,
|
|
86
|
+
color_precision: int = 6,
|
|
87
|
+
filter_speckle: int = 4,
|
|
88
|
+
corner_threshold: int = 60,
|
|
89
|
+
) -> str:
|
|
90
|
+
"""Trace with PyAutoTrace (classic AutoTrace). Returns SVG text."""
|
|
91
|
+
try:
|
|
92
|
+
from autotrace import Bitmap, VectorFormat
|
|
93
|
+
except ImportError as exc:
|
|
94
|
+
raise ImportError(
|
|
95
|
+
"autotrace engine requires pyautotrace. "
|
|
96
|
+
"Install with: pip install 'tileupscale[vectorize]'"
|
|
97
|
+
) from exc
|
|
98
|
+
|
|
99
|
+
# Map shared UI knobs onto AutoTrace TraceOptions.
|
|
100
|
+
# color_precision 1..8 → color_count 2..256 (0 = AutoTrace default/auto)
|
|
101
|
+
color_count = int(2 ** max(1, min(8, color_precision)))
|
|
102
|
+
despeckle_level = int(np.clip(filter_speckle, 0, 20))
|
|
103
|
+
# Our UI uses 0–180 with default 60; AutoTrace default is 100.
|
|
104
|
+
at_corner = float(np.clip(corner_threshold, 0, 180))
|
|
105
|
+
|
|
106
|
+
bitmap = Bitmap(np.ascontiguousarray(rgb, dtype=np.uint8))
|
|
107
|
+
vector = bitmap.trace(
|
|
108
|
+
color_count=color_count,
|
|
109
|
+
corner_threshold=at_corner,
|
|
110
|
+
despeckle_level=despeckle_level,
|
|
111
|
+
filter_iterations=4,
|
|
112
|
+
)
|
|
113
|
+
raw = vector.encode(VectorFormat.SVG)
|
|
114
|
+
if isinstance(raw, bytes):
|
|
115
|
+
return raw.decode("utf-8", errors="replace")
|
|
116
|
+
return str(raw)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _trace_svg(
|
|
120
|
+
rgb: np.ndarray,
|
|
121
|
+
*,
|
|
122
|
+
engine: str = "vtracer",
|
|
123
|
+
color_precision: int = 6,
|
|
124
|
+
filter_speckle: int = 4,
|
|
125
|
+
corner_threshold: int = 60,
|
|
126
|
+
mode: str = "spline",
|
|
127
|
+
) -> str:
|
|
128
|
+
eng = (engine or "vtracer").strip().lower()
|
|
129
|
+
if eng == "autotrace":
|
|
130
|
+
return _trace_svg_autotrace(
|
|
131
|
+
rgb,
|
|
132
|
+
color_precision=color_precision,
|
|
133
|
+
filter_speckle=filter_speckle,
|
|
134
|
+
corner_threshold=corner_threshold,
|
|
135
|
+
)
|
|
136
|
+
try:
|
|
137
|
+
import vtracer # noqa: F401
|
|
138
|
+
except ImportError as exc:
|
|
139
|
+
raise ImportError(
|
|
140
|
+
"vtracer engine requires vtracer. "
|
|
141
|
+
"Install with: pip install 'tileupscale[vectorize]'"
|
|
142
|
+
) from exc
|
|
143
|
+
return _trace_svg_vtracer(
|
|
144
|
+
rgb,
|
|
145
|
+
color_precision=color_precision,
|
|
146
|
+
filter_speckle=filter_speckle,
|
|
147
|
+
corner_threshold=corner_threshold,
|
|
148
|
+
mode=mode,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _fit_rgb(arr: np.ndarray, tw: int, th: int) -> np.ndarray:
|
|
153
|
+
rgb = np.ascontiguousarray(arr[:, :, :3], dtype=np.uint8)
|
|
154
|
+
if rgb.shape[0] != th or rgb.shape[1] != tw:
|
|
155
|
+
rgb = resize_classical("lanczos3", rgb, tw, th)
|
|
156
|
+
return np.ascontiguousarray(rgb, dtype=np.uint8)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _rasterize_svg(svg: str, tw: int, th: int) -> np.ndarray:
|
|
160
|
+
"""Rasterize SVG to RGB uint8 at tw×th.
|
|
161
|
+
|
|
162
|
+
Prefers ``resvg_py`` (works on Windows without Cairo). Falls back to
|
|
163
|
+
cairosvg / reportlab / a limited Pillow path.
|
|
164
|
+
"""
|
|
165
|
+
data = svg.encode("utf-8")
|
|
166
|
+
|
|
167
|
+
# 1) resvg (Rust) — primary, Windows-friendly
|
|
168
|
+
try:
|
|
169
|
+
import resvg_py
|
|
170
|
+
|
|
171
|
+
png = resvg_py.svg_to_bytes(svg_string=svg, width=tw, height=th)
|
|
172
|
+
if png:
|
|
173
|
+
with Image.open(io.BytesIO(png)) as im:
|
|
174
|
+
return _fit_rgb(np.asarray(im.convert("RGB")), tw, th)
|
|
175
|
+
except Exception as exc: # noqa: BLE001
|
|
176
|
+
logger.debug("resvg_py rasterize failed: %s", exc)
|
|
177
|
+
|
|
178
|
+
# 2) cairosvg
|
|
179
|
+
try:
|
|
180
|
+
import cairosvg
|
|
181
|
+
|
|
182
|
+
png = cairosvg.svg2png(bytestring=data, output_width=tw, output_height=th)
|
|
183
|
+
with Image.open(io.BytesIO(png)) as im:
|
|
184
|
+
return _fit_rgb(np.asarray(im.convert("RGB")), tw, th)
|
|
185
|
+
except Exception as exc: # noqa: BLE001
|
|
186
|
+
logger.debug("cairosvg rasterize failed: %s", exc)
|
|
187
|
+
|
|
188
|
+
# 3) svglib + reportlab (needs rlPyCairo / _rl_renderPM)
|
|
189
|
+
try:
|
|
190
|
+
from reportlab.graphics import renderPM
|
|
191
|
+
from svglib.svglib import svg2rlg
|
|
192
|
+
|
|
193
|
+
drawing = svg2rlg(io.BytesIO(data))
|
|
194
|
+
if drawing is not None:
|
|
195
|
+
sx = tw / max(float(drawing.width or 1), 1)
|
|
196
|
+
sy = th / max(float(drawing.height or 1), 1)
|
|
197
|
+
drawing.width, drawing.height = tw, th
|
|
198
|
+
drawing.scale(sx, sy)
|
|
199
|
+
pil = renderPM.drawToPIL(drawing)
|
|
200
|
+
return _fit_rgb(np.asarray(pil.convert("RGB")), tw, th)
|
|
201
|
+
except Exception as exc: # noqa: BLE001
|
|
202
|
+
logger.debug("reportlab rasterize failed: %s", exc)
|
|
203
|
+
|
|
204
|
+
# 4) Limited Pillow path (M/L/H/V + translate) — last resort
|
|
205
|
+
logger.warning(
|
|
206
|
+
"SVG rasterizer falling back to limited Pillow path; "
|
|
207
|
+
"install resvg_py for correct Vectorize & scale output "
|
|
208
|
+
"(pip install 'tileupscale[vectorize]')."
|
|
209
|
+
)
|
|
210
|
+
return _rasterize_svg_pillow(svg, tw, th)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _parse_color(style: str | None, fill: str | None) -> tuple[int, int, int] | None:
|
|
214
|
+
raw = (fill or "").strip()
|
|
215
|
+
if style:
|
|
216
|
+
m = re.search(r"fill\s*:\s*([^;]+)", style)
|
|
217
|
+
if m:
|
|
218
|
+
raw = m.group(1).strip()
|
|
219
|
+
if not raw or raw in ("none", "transparent"):
|
|
220
|
+
return None
|
|
221
|
+
if raw.startswith("#") and len(raw) in (4, 7):
|
|
222
|
+
if len(raw) == 4:
|
|
223
|
+
return tuple(int(c * 2, 16) for c in raw[1:]) # type: ignore[return-value]
|
|
224
|
+
return (
|
|
225
|
+
int(raw[1:3], 16),
|
|
226
|
+
int(raw[3:5], 16),
|
|
227
|
+
int(raw[5:7], 16),
|
|
228
|
+
)
|
|
229
|
+
if raw.startswith("rgb"):
|
|
230
|
+
nums = re.findall(r"\d+", raw)
|
|
231
|
+
if len(nums) >= 3:
|
|
232
|
+
return int(nums[0]), int(nums[1]), int(nums[2])
|
|
233
|
+
return (0, 0, 0)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _parse_translate(transform: str | None) -> tuple[float, float]:
|
|
237
|
+
if not transform:
|
|
238
|
+
return 0.0, 0.0
|
|
239
|
+
m = re.search(
|
|
240
|
+
r"translate\(\s*([-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?)\s*[, ]\s*"
|
|
241
|
+
r"([-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?)\s*\)",
|
|
242
|
+
transform,
|
|
243
|
+
)
|
|
244
|
+
if not m:
|
|
245
|
+
return 0.0, 0.0
|
|
246
|
+
return float(m.group(1)), float(m.group(2))
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _path_to_points(
|
|
250
|
+
d: str, sx: float, sy: float, ox: float = 0.0, oy: float = 0.0
|
|
251
|
+
) -> list[tuple[float, float]]:
|
|
252
|
+
"""Subset of SVG path commands including cubic Bezier (C/c) sampling."""
|
|
253
|
+
tokens = re.findall(r"[MmLlHhVvCcZz]|[-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?", d)
|
|
254
|
+
pts: list[tuple[float, float]] = []
|
|
255
|
+
cx = cy = 0.0
|
|
256
|
+
i = 0
|
|
257
|
+
cmd = "M"
|
|
258
|
+
|
|
259
|
+
def emit(x: float, y: float) -> None:
|
|
260
|
+
pts.append(((x + ox) * sx, (y + oy) * sy))
|
|
261
|
+
|
|
262
|
+
while i < len(tokens):
|
|
263
|
+
t = tokens[i]
|
|
264
|
+
if re.match(r"[A-Za-z]", t):
|
|
265
|
+
cmd = t
|
|
266
|
+
i += 1
|
|
267
|
+
continue
|
|
268
|
+
if cmd in ("M", "L", "m", "l"):
|
|
269
|
+
if i + 1 >= len(tokens):
|
|
270
|
+
break
|
|
271
|
+
x, y = float(tokens[i]), float(tokens[i + 1])
|
|
272
|
+
i += 2
|
|
273
|
+
if cmd.islower():
|
|
274
|
+
x, y = cx + x, cy + y
|
|
275
|
+
cx, cy = x, y
|
|
276
|
+
emit(cx, cy)
|
|
277
|
+
if cmd in ("M", "m"):
|
|
278
|
+
cmd = "l" if cmd.islower() else "L"
|
|
279
|
+
elif cmd in ("H", "h"):
|
|
280
|
+
x = float(tokens[i])
|
|
281
|
+
i += 1
|
|
282
|
+
if cmd == "h":
|
|
283
|
+
x = cx + x
|
|
284
|
+
cx = x
|
|
285
|
+
emit(cx, cy)
|
|
286
|
+
elif cmd in ("V", "v"):
|
|
287
|
+
y = float(tokens[i])
|
|
288
|
+
i += 1
|
|
289
|
+
if cmd == "v":
|
|
290
|
+
y = cy + y
|
|
291
|
+
cy = y
|
|
292
|
+
emit(cx, cy)
|
|
293
|
+
elif cmd in ("C", "c"):
|
|
294
|
+
if i + 5 >= len(tokens):
|
|
295
|
+
break
|
|
296
|
+
x1, y1 = float(tokens[i]), float(tokens[i + 1])
|
|
297
|
+
x2, y2 = float(tokens[i + 2]), float(tokens[i + 3])
|
|
298
|
+
x, y = float(tokens[i + 4]), float(tokens[i + 5])
|
|
299
|
+
i += 6
|
|
300
|
+
if cmd == "c":
|
|
301
|
+
x1, y1 = cx + x1, cy + y1
|
|
302
|
+
x2, y2 = cx + x2, cy + y2
|
|
303
|
+
x, y = cx + x, cy + y
|
|
304
|
+
# Sample cubic Bezier
|
|
305
|
+
for s in range(1, 9):
|
|
306
|
+
t_ = s / 8.0
|
|
307
|
+
u = 1.0 - t_
|
|
308
|
+
bx = (
|
|
309
|
+
u * u * u * cx
|
|
310
|
+
+ 3 * u * u * t_ * x1
|
|
311
|
+
+ 3 * u * t_ * t_ * x2
|
|
312
|
+
+ t_ * t_ * t_ * x
|
|
313
|
+
)
|
|
314
|
+
by = (
|
|
315
|
+
u * u * u * cy
|
|
316
|
+
+ 3 * u * u * t_ * y1
|
|
317
|
+
+ 3 * u * t_ * t_ * y2
|
|
318
|
+
+ t_ * t_ * t_ * y
|
|
319
|
+
)
|
|
320
|
+
emit(bx, by)
|
|
321
|
+
cx, cy = x, y
|
|
322
|
+
elif cmd in ("Z", "z"):
|
|
323
|
+
if pts:
|
|
324
|
+
pts.append(pts[0])
|
|
325
|
+
i += 1
|
|
326
|
+
else:
|
|
327
|
+
i += 1
|
|
328
|
+
return pts
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _rasterize_svg_pillow(svg: str, tw: int, th: int) -> np.ndarray:
|
|
332
|
+
root = ET.fromstring(svg)
|
|
333
|
+
vb = root.get("viewBox")
|
|
334
|
+
if vb:
|
|
335
|
+
parts = [float(x) for x in vb.replace(",", " ").split()]
|
|
336
|
+
vw, vh = parts[2], parts[3]
|
|
337
|
+
else:
|
|
338
|
+
vw = float(root.get("width", tw) or tw)
|
|
339
|
+
vh = float(root.get("height", th) or th)
|
|
340
|
+
sx, sy = tw / max(vw, 1e-6), th / max(vh, 1e-6)
|
|
341
|
+
canvas = Image.new("RGB", (tw, th), (255, 255, 255))
|
|
342
|
+
draw = ImageDraw.Draw(canvas)
|
|
343
|
+
|
|
344
|
+
for el in root.iter():
|
|
345
|
+
tag = el.tag.split("}")[-1] if "}" in el.tag else el.tag
|
|
346
|
+
color = _parse_color(el.get("style"), el.get("fill"))
|
|
347
|
+
if color is None:
|
|
348
|
+
continue
|
|
349
|
+
ox, oy = _parse_translate(el.get("transform"))
|
|
350
|
+
if tag == "path" and el.get("d"):
|
|
351
|
+
pts = _path_to_points(el.get("d") or "", sx, sy, ox, oy)
|
|
352
|
+
if len(pts) >= 3:
|
|
353
|
+
draw.polygon(pts, fill=color)
|
|
354
|
+
elif tag == "polygon" and el.get("points"):
|
|
355
|
+
nums = [
|
|
356
|
+
float(x)
|
|
357
|
+
for x in re.findall(r"[-+]?(?:\d*\.\d+|\d+)", el.get("points") or "")
|
|
358
|
+
]
|
|
359
|
+
pts = [
|
|
360
|
+
((nums[i] + ox) * sx, (nums[i + 1] + oy) * sy)
|
|
361
|
+
for i in range(0, len(nums) - 1, 2)
|
|
362
|
+
]
|
|
363
|
+
if len(pts) >= 3:
|
|
364
|
+
draw.polygon(pts, fill=color)
|
|
365
|
+
elif tag == "rect":
|
|
366
|
+
x = (float(el.get("x", 0)) + ox) * sx
|
|
367
|
+
y = (float(el.get("y", 0)) + oy) * sy
|
|
368
|
+
w = float(el.get("width", 0)) * sx
|
|
369
|
+
h = float(el.get("height", 0)) * sy
|
|
370
|
+
draw.rectangle([x, y, x + w, y + h], fill=color)
|
|
371
|
+
return np.asarray(canvas, dtype=np.uint8)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def vectorize_scale_resize(
|
|
375
|
+
img: np.ndarray,
|
|
376
|
+
target_w: int,
|
|
377
|
+
target_h: int,
|
|
378
|
+
*,
|
|
379
|
+
engine: str = "vtracer",
|
|
380
|
+
color_precision: int = 6,
|
|
381
|
+
filter_speckle: int = 4,
|
|
382
|
+
corner_threshold: int = 60,
|
|
383
|
+
mode: str = "spline",
|
|
384
|
+
max_trace_edge: int = _DEFAULT_TRACE_EDGE,
|
|
385
|
+
) -> np.ndarray:
|
|
386
|
+
"""Trace to SVG then rasterize at target size.
|
|
387
|
+
|
|
388
|
+
Gray / alpha (HxW) inputs return HxW; RGB returns HxWx3 uint8.
|
|
389
|
+
``engine`` is ``vtracer`` (default) or ``autotrace`` (PyAutoTrace).
|
|
390
|
+
"""
|
|
391
|
+
eng = (engine or "vtracer").strip().lower()
|
|
392
|
+
if eng == "autotrace":
|
|
393
|
+
try:
|
|
394
|
+
import autotrace # noqa: F401
|
|
395
|
+
except ImportError as exc:
|
|
396
|
+
raise ImportError(
|
|
397
|
+
"vectorize_scale engine=autotrace requires pyautotrace. "
|
|
398
|
+
"Install with: pip install 'tileupscale[vectorize]'"
|
|
399
|
+
) from exc
|
|
400
|
+
else:
|
|
401
|
+
try:
|
|
402
|
+
import vtracer # noqa: F401
|
|
403
|
+
except ImportError as exc:
|
|
404
|
+
raise ImportError(
|
|
405
|
+
"vectorize_scale engine=vtracer requires vtracer. "
|
|
406
|
+
"Install with: pip install 'tileupscale[vectorize]'"
|
|
407
|
+
) from exc
|
|
408
|
+
|
|
409
|
+
raw = np.asarray(img, dtype=np.uint8)
|
|
410
|
+
gray_in = raw.ndim == 2 or (raw.ndim == 3 and raw.shape[2] == 1)
|
|
411
|
+
if gray_in:
|
|
412
|
+
g = raw[:, :, 0] if raw.ndim == 3 else raw
|
|
413
|
+
rgb = np.stack([g, g, g], axis=-1)
|
|
414
|
+
else:
|
|
415
|
+
rgb = raw[:, :, :3]
|
|
416
|
+
rgb = np.ascontiguousarray(rgb, dtype=np.uint8)
|
|
417
|
+
tw, th = int(target_w), int(target_h)
|
|
418
|
+
|
|
419
|
+
small = _maybe_downscale(rgb, max_trace_edge)
|
|
420
|
+
svg = _trace_svg(
|
|
421
|
+
small,
|
|
422
|
+
engine=eng,
|
|
423
|
+
color_precision=color_precision,
|
|
424
|
+
filter_speckle=filter_speckle,
|
|
425
|
+
corner_threshold=corner_threshold,
|
|
426
|
+
mode=mode,
|
|
427
|
+
)
|
|
428
|
+
out = _rasterize_svg(svg, tw, th)
|
|
429
|
+
out = np.ascontiguousarray(out[:, :, :3], dtype=np.uint8)
|
|
430
|
+
if gray_in:
|
|
431
|
+
return out[:, :, 0]
|
|
432
|
+
return out
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _entry(img: np.ndarray, tw: int, th: int) -> np.ndarray:
|
|
436
|
+
return vectorize_scale_resize(img, tw, th)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
register_algorithm(
|
|
440
|
+
"vectorize_scale",
|
|
441
|
+
_entry,
|
|
442
|
+
overwrite=True,
|
|
443
|
+
label="Vectorize & scale",
|
|
444
|
+
group="paper",
|
|
445
|
+
description=(
|
|
446
|
+
"Trace to SVG (VTracer or PyAutoTrace), then rasterize at the target size. "
|
|
447
|
+
"Best for logos and flat graphics — not photos. "
|
|
448
|
+
"Requires: pip install 'tileupscale[vectorize]'."
|
|
449
|
+
),
|
|
450
|
+
)
|