upscale 0.5.1__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.
Files changed (48) hide show
  1. upscale/__init__.py +30 -0
  2. upscale/__main__.py +3 -0
  3. upscale/about.py +168 -0
  4. upscale/algorithms/__init__.py +166 -0
  5. upscale/algorithms/classical.py +82 -0
  6. upscale/algorithms/plugins/__init__.py +52 -0
  7. upscale/algorithms/plugins/texture_residual.py +117 -0
  8. upscale/algorithms/plugins/vectorize_scale.py +450 -0
  9. upscale/api/__init__.py +17 -0
  10. upscale/api/compare_routes.py +243 -0
  11. upscale/api/deps.py +18 -0
  12. upscale/api/jobs.py +516 -0
  13. upscale/api/models_routes.py +107 -0
  14. upscale/api/system_routes.py +200 -0
  15. upscale/backends/__init__.py +27 -0
  16. upscale/backends/onnx_rt.py +265 -0
  17. upscale/benchmark.py +96 -0
  18. upscale/checkpoint.py +258 -0
  19. upscale/cli.py +608 -0
  20. upscale/compare.py +202 -0
  21. upscale/config.py +56 -0
  22. upscale/engine.py +348 -0
  23. upscale/estimates.py +338 -0
  24. upscale/filters.py +180 -0
  25. upscale/help_content.py +94 -0
  26. upscale/infer_util.py +22 -0
  27. upscale/io_utils.py +616 -0
  28. upscale/job_prep.py +318 -0
  29. upscale/mcp_server.py +287 -0
  30. upscale/models.py +628 -0
  31. upscale/naming.py +63 -0
  32. upscale/pipeline.py +485 -0
  33. upscale/presets.py +127 -0
  34. upscale/quality.py +36 -0
  35. upscale/schema.py +315 -0
  36. upscale/server.py +1056 -0
  37. upscale/speed_stats.py +273 -0
  38. upscale/suggest.py +93 -0
  39. upscale/system.py +102 -0
  40. upscale/tiling.py +392 -0
  41. upscale/web.py +118 -0
  42. upscale-0.5.1.dist-info/METADATA +149 -0
  43. upscale-0.5.1.dist-info/RECORD +48 -0
  44. upscale-0.5.1.dist-info/WHEEL +5 -0
  45. upscale-0.5.1.dist-info/entry_points.txt +2 -0
  46. upscale-0.5.1.dist-info/licenses/LICENSE +21 -0
  47. upscale-0.5.1.dist-info/licenses/NOTICE +6 -0
  48. upscale-0.5.1.dist-info/top_level.txt +1 -0
upscale/__init__.py ADDED
@@ -0,0 +1,30 @@
1
+ """AI image upscaler — multi-pass Real-ESRGAN with feather-blended tiles."""
2
+
3
+ from .config import UpscaleConfig
4
+ from .engine import execute
5
+ from .io_utils import lanczos_resize, load_rgba, save_image
6
+ from .models import DEFAULT_WEIGHTS_DIR, MODELS, ensure_model, load_model, resolve_device
7
+ from .pipeline import compute_passes, resolve_model_scale, run, upscale_alpha
8
+ from .schema import JobSettings, NamePattern, ProgressEvent
9
+
10
+ __all__ = [
11
+ "UpscaleConfig",
12
+ "JobSettings",
13
+ "NamePattern",
14
+ "ProgressEvent",
15
+ "MODELS",
16
+ "DEFAULT_WEIGHTS_DIR",
17
+ "compute_passes",
18
+ "run",
19
+ "resolve_model_scale",
20
+ "upscale_alpha",
21
+ "execute",
22
+ "load_rgba",
23
+ "save_image",
24
+ "lanczos_resize",
25
+ "ensure_model",
26
+ "load_model",
27
+ "resolve_device",
28
+ ]
29
+
30
+ __version__ = "0.5.1"
upscale/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import cli
2
+
3
+ cli()
upscale/about.py ADDED
@@ -0,0 +1,168 @@
1
+ """About, license, and update-check helpers for UI / desktop."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import urllib.error
8
+ import urllib.request
9
+ from importlib import metadata
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from .models import DEFAULT_WEIGHTS_DIR, all_models, model_status
14
+
15
+ PROJECT_ROOT = Path(__file__).resolve().parent.parent
16
+ LICENSE_PATH = PROJECT_ROOT / "LICENSE"
17
+
18
+ # Optional: GitHub Releases API URL or a static JSON with tag_name / html_url
19
+ DEFAULT_RELEASES_URL = os.environ.get("UPSCALE_RELEASES_URL", "").strip()
20
+
21
+
22
+ def package_version() -> str:
23
+ try:
24
+ return metadata.version("upscale")
25
+ except metadata.PackageNotFoundError:
26
+ from . import __version__
27
+
28
+ return __version__
29
+
30
+
31
+ def license_text() -> str:
32
+ if LICENSE_PATH.is_file():
33
+ return LICENSE_PATH.read_text(encoding="utf-8")
34
+ return (
35
+ "MIT License\n\n"
36
+ "Copyright (c) 2026 Upscale contributors\n\n"
37
+ "Permission is hereby granted, free of charge, to any person obtaining a copy "
38
+ "of this software..."
39
+ )
40
+
41
+
42
+ def about_payload() -> dict[str, Any]:
43
+ models_dir = Path(os.environ.get("UPSCALE_MODELS_DIR", DEFAULT_WEIGHTS_DIR))
44
+ return {
45
+ "name": "Upscale",
46
+ "version": package_version(),
47
+ "license": "MIT",
48
+ "description": (
49
+ "AI image upscaler — chained Real-ESRGAN / HAT / SPAN with "
50
+ "feather-blended tiles. Classical resize via OpenCV when available."
51
+ ),
52
+ "models_dir": str(models_dir),
53
+ "models_policy": (
54
+ "Model weights are downloaded on demand into the models folder "
55
+ "(desktop: %LOCALAPPDATA%\\Upscale\\models). They are not baked into "
56
+ "the slim installer. Optional tiny SPAN may ship later for offline first run."
57
+ ),
58
+ }
59
+
60
+
61
+ def models_disk_summary(weights_dir: Path | None = None) -> dict[str, Any]:
62
+ wdir = weights_dir or Path(os.environ.get("UPSCALE_MODELS_DIR", DEFAULT_WEIGHTS_DIR))
63
+ catalog = all_models(wdir)
64
+ installed: list[dict[str, Any]] = []
65
+ total = 0
66
+ for name, meta in sorted(catalog.items()):
67
+ st = model_status(name, wdir)
68
+ if st != "installed":
69
+ continue
70
+ url_path = (meta.get("url") or "").split("?")[0]
71
+ ext = Path(url_path).suffix or ".pth"
72
+ dest = Path(meta["path"]) if meta.get("path") else wdir / f"{name}{ext}"
73
+ size = dest.stat().st_size if dest.is_file() else int(meta.get("size_bytes") or 0)
74
+ total += size
75
+ installed.append({"name": name, "path": str(dest), "size_bytes": size})
76
+ return {
77
+ "models_dir": str(wdir),
78
+ "installed_count": len(installed),
79
+ "total_bytes": total,
80
+ "models": installed,
81
+ }
82
+
83
+
84
+ def _parse_version(tag: str) -> tuple[int, ...]:
85
+ s = tag.strip().lstrip("vV")
86
+ parts: list[int] = []
87
+ for p in s.split("."):
88
+ num = ""
89
+ for ch in p:
90
+ if ch.isdigit():
91
+ num += ch
92
+ else:
93
+ break
94
+ parts.append(int(num) if num else 0)
95
+ return tuple(parts) or (0,)
96
+
97
+
98
+ def check_for_updates(
99
+ *,
100
+ releases_url: str | None = None,
101
+ timeout: float = 8.0,
102
+ ) -> dict[str, Any]:
103
+ """Compare local version to latest release tag.
104
+
105
+ ``releases_url`` may be a GitHub Releases API endpoint
106
+ (``…/repos/OWNER/REPO/releases/latest``) or any JSON with ``tag_name``.
107
+ """
108
+ current = package_version()
109
+ url = (releases_url if releases_url is not None else DEFAULT_RELEASES_URL).strip()
110
+ if not url:
111
+ return {
112
+ "status": "unconfigured",
113
+ "current": current,
114
+ "latest": None,
115
+ "update_available": False,
116
+ "message": "Set UPSCALE_RELEASES_URL to enable update checks.",
117
+ "url": None,
118
+ }
119
+ try:
120
+ req = urllib.request.Request(
121
+ url,
122
+ headers={"Accept": "application/vnd.github+json", "User-Agent": "upscale"},
123
+ )
124
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
125
+ raw = resp.read().decode("utf-8")
126
+ data = json.loads(raw)
127
+ if isinstance(data, list) and data:
128
+ data = data[0]
129
+ tag = str(data.get("tag_name") or data.get("version") or "")
130
+ html = data.get("html_url") or data.get("url")
131
+ if not tag:
132
+ return {
133
+ "status": "error",
134
+ "current": current,
135
+ "latest": None,
136
+ "update_available": False,
137
+ "message": "Release JSON missing tag_name",
138
+ "url": html,
139
+ }
140
+ newer = _parse_version(tag) > _parse_version(current)
141
+ return {
142
+ "status": "ok",
143
+ "current": current,
144
+ "latest": tag.lstrip("vV"),
145
+ "update_available": newer,
146
+ "message": (
147
+ f"Update available: {tag}" if newer else f"Up to date ({current})"
148
+ ),
149
+ "url": html,
150
+ }
151
+ except urllib.error.URLError as exc:
152
+ return {
153
+ "status": "error",
154
+ "current": current,
155
+ "latest": None,
156
+ "update_available": False,
157
+ "message": f"Could not reach releases: {exc}",
158
+ "url": None,
159
+ }
160
+ except (json.JSONDecodeError, TypeError, ValueError) as exc:
161
+ return {
162
+ "status": "error",
163
+ "current": current,
164
+ "latest": None,
165
+ "update_available": False,
166
+ "message": f"Bad releases response: {exc}",
167
+ "url": None,
168
+ }
@@ -0,0 +1,166 @@
1
+ """Classical and plugin upscale algorithms (non-neural)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Callable
7
+
8
+ import numpy as np
9
+
10
+ from .classical import BUILTIN_ALGORITHMS, resize_classical
11
+
12
+ AlgorithmFn = Callable[[np.ndarray, int, int], np.ndarray]
13
+
14
+ _BUILTIN_META: dict[str, tuple[str, str]] = {
15
+ "nearest": ("Nearest-neighbor", "Blocky, preserves hard edges — good for pixel art."),
16
+ "bilinear": ("Bilinear", "Smooth linear interpolation."),
17
+ "bicubic": ("Bicubic", "Smoother curves than bilinear; common photo default."),
18
+ "lanczos2": ("Lanczos-2", "Sharper Lanczos (approx.)."),
19
+ "lanczos3": ("Lanczos-3", "High-quality Lanczos — good general classical choice."),
20
+ }
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class AlgorithmInfo:
25
+ name: str
26
+ label: str
27
+ group: str # "builtin" | "paper" | "plugin"
28
+ description: str = ""
29
+
30
+
31
+ _REGISTRY: dict[str, AlgorithmFn] = {}
32
+ _META: dict[str, AlgorithmInfo] = {}
33
+ _PLUGINS_LOADED = False
34
+
35
+
36
+ def _norm_algo(name: str) -> str:
37
+ return name.strip().lower().replace(" ", "_").replace("-", "_")
38
+
39
+
40
+ def register_algorithm(
41
+ name: str,
42
+ fn: AlgorithmFn,
43
+ *,
44
+ overwrite: bool = False,
45
+ label: str | None = None,
46
+ group: str = "plugin",
47
+ description: str = "",
48
+ ) -> None:
49
+ """Register a custom algorithm for later use (paper plugins, etc.)."""
50
+ key = _norm_algo(name)
51
+ if not key:
52
+ raise ValueError("algorithm name required")
53
+ if key in _REGISTRY and not overwrite:
54
+ raise ValueError(f"algorithm already registered: {key}")
55
+ _REGISTRY[key] = fn
56
+ pretty = label or key.replace("_", " ").title()
57
+ g = group if group in ("builtin", "paper", "plugin") else "plugin"
58
+ if key in BUILTIN_ALGORITHMS:
59
+ g = "builtin"
60
+ bl, bd = _BUILTIN_META.get(key, (pretty, description))
61
+ pretty = label or bl
62
+ description = description or bd
63
+ _META[key] = AlgorithmInfo(
64
+ name=key, label=pretty, group=g, description=description or ""
65
+ )
66
+
67
+
68
+ def unregister_algorithm(name: str) -> None:
69
+ key = _norm_algo(name)
70
+ _REGISTRY.pop(key, None)
71
+ _META.pop(key, None)
72
+
73
+
74
+ def list_algorithms() -> list[str]:
75
+ """Built-ins first (stable order), then any extra plugins."""
76
+ ensure_plugins_loaded()
77
+ builtins = list(BUILTIN_ALGORITHMS)
78
+ extras = sorted(k for k in _REGISTRY if k not in BUILTIN_ALGORITHMS)
79
+ return builtins + extras
80
+
81
+
82
+ def list_algorithm_meta() -> list[AlgorithmInfo]:
83
+ """Metadata for UI / API: builtins then paper/plugin (sorted within group)."""
84
+ ensure_plugins_loaded()
85
+ out: list[AlgorithmInfo] = []
86
+ for name in BUILTIN_ALGORITHMS:
87
+ info = _META.get(name)
88
+ if info:
89
+ out.append(info)
90
+ else:
91
+ bl, bd = _BUILTIN_META.get(name, (name, ""))
92
+ out.append(AlgorithmInfo(name=name, label=bl, group="builtin", description=bd))
93
+ extras = [k for k in _REGISTRY if k not in BUILTIN_ALGORITHMS]
94
+ extras.sort(key=lambda k: (_META[k].group if k in _META else "plugin", k))
95
+ for k in extras:
96
+ out.append(
97
+ _META.get(k)
98
+ or AlgorithmInfo(name=k, label=k.replace("_", " ").title(), group="plugin")
99
+ )
100
+ return out
101
+
102
+
103
+ def get_algorithm(name: str) -> AlgorithmFn | None:
104
+ ensure_plugins_loaded()
105
+ key = _norm_algo(name)
106
+ if key in _REGISTRY:
107
+ return _REGISTRY[key]
108
+ if key in BUILTIN_ALGORITHMS:
109
+ return lambda img, tw, th, _k=key: resize_classical(_k, img, tw, th)
110
+ return None
111
+
112
+
113
+ def resize_with_algorithm(
114
+ name: str, img: np.ndarray, target_w: int, target_h: int
115
+ ) -> np.ndarray:
116
+ """Resize HWC uint8 RGB (or single-channel) with a named algorithm."""
117
+ fn = get_algorithm(name)
118
+ if fn is None:
119
+ raise ValueError(
120
+ f"Unknown algorithm {name!r}. Available: {', '.join(list_algorithms())}"
121
+ )
122
+ tw, th = int(target_w), int(target_h)
123
+ if tw < 1 or th < 1:
124
+ raise ValueError("target size must be positive")
125
+ return fn(img, tw, th)
126
+
127
+
128
+ def ensure_plugins_loaded() -> None:
129
+ """Import plugin modules once so they can register_algorithm."""
130
+ global _PLUGINS_LOADED
131
+ if _PLUGINS_LOADED:
132
+ return
133
+ _PLUGINS_LOADED = True
134
+ try:
135
+ from . import plugins as _plugins
136
+
137
+ _plugins.load_plugins()
138
+ except Exception: # noqa: BLE001
139
+ # Plugins are optional; classical built-ins still work.
140
+ pass
141
+
142
+
143
+ # Register built-ins so plugins see a full catalog
144
+ for _name in BUILTIN_ALGORITHMS:
145
+ _bl, _bd = _BUILTIN_META.get(_name, (_name, ""))
146
+ register_algorithm(
147
+ _name,
148
+ lambda img, tw, th, _n=_name: resize_classical(_n, img, tw, th),
149
+ overwrite=True,
150
+ label=_bl,
151
+ group="builtin",
152
+ description=_bd,
153
+ )
154
+
155
+ __all__ = [
156
+ "AlgorithmFn",
157
+ "AlgorithmInfo",
158
+ "BUILTIN_ALGORITHMS",
159
+ "ensure_plugins_loaded",
160
+ "get_algorithm",
161
+ "list_algorithm_meta",
162
+ "list_algorithms",
163
+ "register_algorithm",
164
+ "resize_with_algorithm",
165
+ "unregister_algorithm",
166
+ ]
@@ -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
+ )