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/estimates.py ADDED
@@ -0,0 +1,338 @@
1
+ """Output size, print size, file-size and time estimate helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ from .io_utils import LONG_EDGE_TIFF_THRESHOLD
8
+ from .pipeline import compute_passes
9
+ from .schema import PrintSize, ResourceCheck, ResourceRow, ResourceStatus
10
+
11
+ VramFit = Literal["ok", "tight", "spill"]
12
+
13
+
14
+ # Rough megapixel/sec factors (calibrated later by benchmark).
15
+ SPEED_MP_S = {
16
+ "cuda": {"RealESRGAN_x4plus": 2.5, "default": 3.0, "4x-spanx4-ch48": 8.0},
17
+ "cpu": {"default": 0.15},
18
+ "mps": {"default": 1.5},
19
+ }
20
+
21
+ BYTES_PER_PIXEL = {
22
+ "png": (2.5, 4.0),
23
+ "jpeg": (0.15, 0.4),
24
+ "webp": (0.12, 0.35),
25
+ "tiff": (3.0, 4.0),
26
+ "bmp": (3.0, 3.0),
27
+ "tga": (3.0, 4.0),
28
+ "auto": (2.5, 4.0),
29
+ }
30
+
31
+
32
+ def output_dimensions(
33
+ src_w: int,
34
+ src_h: int,
35
+ *,
36
+ scale: float | None = None,
37
+ target_size: int | None = None,
38
+ width: int | None = None,
39
+ height: int | None = None,
40
+ ) -> tuple[int, int, float]:
41
+ """Return (out_w, out_h, effective_scale)."""
42
+ if width is not None and height is not None:
43
+ eff = max(width / src_w, height / src_h)
44
+ return width, height, eff
45
+ if target_size is not None:
46
+ long_edge = max(src_w, src_h)
47
+ eff = target_size / long_edge
48
+ return round(src_w * eff), round(src_h * eff), eff
49
+ if scale is None:
50
+ raise ValueError("Need scale, target_size, or width×height")
51
+ return round(src_w * scale), round(src_h * scale), float(scale)
52
+
53
+
54
+ def megapixels(w: int, h: int) -> float:
55
+ return (w * h) / 1_000_000
56
+
57
+
58
+ def print_sizes(w: int, h: int, dpis: tuple[int, ...] = (72, 150, 300, 600)) -> list[PrintSize]:
59
+ out: list[PrintSize] = []
60
+ for dpi in dpis:
61
+ wi = w / dpi
62
+ hi = h / dpi
63
+ out.append(
64
+ PrintSize(
65
+ dpi=dpi,
66
+ width_in=round(wi, 2),
67
+ height_in=round(hi, 2),
68
+ width_cm=round(wi * 2.54, 2),
69
+ height_cm=round(hi * 2.54, 2),
70
+ )
71
+ )
72
+ return out
73
+
74
+
75
+ def estimate_file_size_bytes(
76
+ w: int,
77
+ h: int,
78
+ fmt: str = "auto",
79
+ ) -> tuple[int, int]:
80
+ """Return (low, high) estimated file size in bytes."""
81
+ use = fmt
82
+ if fmt == "auto" and max(w, h) > LONG_EDGE_TIFF_THRESHOLD:
83
+ use = "tiff"
84
+ elif fmt == "auto":
85
+ use = "png"
86
+ elif fmt == "jpeg_exif":
87
+ use = "jpeg"
88
+ elif fmt == "jp2":
89
+ use = "jpeg"
90
+ elif fmt in ("psd", "psb"):
91
+ use = "tiff"
92
+ elif fmt == "bmp":
93
+ use = "bmp"
94
+ elif fmt == "tga":
95
+ use = "tga"
96
+ lo, hi = BYTES_PER_PIXEL.get(use, BYTES_PER_PIXEL["png"])
97
+ px = w * h
98
+ return int(px * lo), int(px * hi)
99
+
100
+
101
+ def estimate_time_seconds(
102
+ src_w: int,
103
+ src_h: int,
104
+ scale: float,
105
+ *,
106
+ model: str = "RealESRGAN_x4plus",
107
+ device: str = "cuda",
108
+ model_scale: int = 4,
109
+ speed_table: dict | None = None,
110
+ model_ready: bool = True,
111
+ model_bytes: int | None = None,
112
+ filter_factor: float = 1.0,
113
+ measured_mp_s: float | None = None,
114
+ model_load_seconds: float | None = None,
115
+ algorithm: str | None = None,
116
+ calibrated: bool = False,
117
+ ) -> tuple[float, float]:
118
+ """Return (low, high) seconds using MP/s factors (table or learned).
119
+
120
+ Includes model-load overhead and optional download time when weights
121
+ are not on disk yet. ``filter_factor`` multiplies compute time (from
122
+ ``filters.estimate_time_factor``). When ``calibrated`` is true (stats from
123
+ past runs on this machine), the range is tighter and load overhead is
124
+ treated as warm-start.
125
+ """
126
+ from .speed_stats import normalize_device, work_megapixels
127
+
128
+ table = speed_table or SPEED_MP_S
129
+ dev = normalize_device(device)
130
+ if dev not in table:
131
+ dev = "cpu"
132
+ factors = table.get(dev, table["cpu"])
133
+ if algorithm:
134
+ # Classical resize is typically much faster than neural SR.
135
+ default_mp = 40.0 if dev == "cpu" else 120.0
136
+ mp_s = measured_mp_s or factors.get(f"algo:{algorithm}", default_mp)
137
+ work_mp = work_megapixels(
138
+ src_w, src_h, scale, model_scale=model_scale, algorithm=algorithm
139
+ )
140
+ if work_mp <= 0:
141
+ return 0.1, 0.5
142
+ compute = (work_mp / max(mp_s, 1e-6)) * max(filter_factor, 1.0)
143
+ load_s = 0.2 if calibrated else 0.5
144
+ download_s = 0.0
145
+ else:
146
+ passes = compute_passes(scale, model_scale)
147
+ if passes == 0:
148
+ return 0.1, 0.5
149
+ mp_s = measured_mp_s or factors.get(model, factors.get("default", 1.0))
150
+ work_mp = work_megapixels(src_w, src_h, scale, model_scale=model_scale)
151
+ compute = (work_mp / max(mp_s, 1e-6)) * max(filter_factor, 1.0)
152
+ if model_load_seconds is not None:
153
+ load_s = model_load_seconds
154
+ elif calibrated:
155
+ # Learned mp/s already includes some load amortization; keep a small warm bump.
156
+ load_s = 2.0 if dev == "cpu" else 1.0
157
+ else:
158
+ load_s = 8.0 if dev == "cpu" else 4.0
159
+ if model_bytes and model_bytes > 80_000_000:
160
+ load_s *= 1.5
161
+ download_s = 0.0
162
+ if not model_ready:
163
+ mb = (model_bytes or 67_000_000) / 1e6
164
+ download_s = max(5.0, mb / 10.0)
165
+ base = compute + load_s + download_s
166
+ lo_f, hi_f = (0.85, 1.25) if calibrated else (0.7, 1.5)
167
+ return round(base * lo_f, 1), round(base * hi_f, 1)
168
+
169
+
170
+ def model_fits_vram(
171
+ model_bytes: int | None,
172
+ free_vram_mb: int | None,
173
+ *,
174
+ tile: int = 512,
175
+ fp16: bool = False,
176
+ ) -> VramFit:
177
+ """Classify whether model weights + one tile fit in free VRAM.
178
+
179
+ ``ok`` — comfortable headroom · ``tight`` — may need smaller tile/fp16 ·
180
+ ``spill`` — likely OOM / host spill; prefer smaller tile, CPU, or classical.
181
+ """
182
+ if free_vram_mb is None:
183
+ return "ok"
184
+ weights_mb = (model_bytes if model_bytes is not None else 67_000_000) / (1024 * 1024)
185
+ bpp = 2 if fp16 else 4
186
+ # ~8× activations vs raw RGB tile (conv features); weights inflate ~1.5× on device
187
+ act_mb = (tile * tile * 3 * bpp * 8) / (1024 * 1024)
188
+ need_mb = weights_mb * 1.5 + act_mb
189
+ if free_vram_mb < need_mb * 0.55:
190
+ return "spill"
191
+ if free_vram_mb < need_mb:
192
+ return "tight"
193
+ return "ok"
194
+
195
+
196
+ def resource_check(
197
+ *,
198
+ out_w: int,
199
+ out_h: int,
200
+ tile: int,
201
+ fp16: bool,
202
+ model_bytes: int | None,
203
+ vram_free_mb: int | None,
204
+ ram_available_mb: int | None,
205
+ disk_free_mb: int | None,
206
+ model_ready: bool,
207
+ ) -> ResourceCheck:
208
+ rows: list[ResourceRow] = []
209
+ blocked = False
210
+
211
+ # Strip peak ≈ full-width × tile×model_scale float canvas + weight + uint8.
212
+ # Default model_scale 4 matches shipped weights; clamp to output height.
213
+ model_scale_guess = 4
214
+ strip_h = max(64, min(tile * model_scale_guess, out_h))
215
+ need_ram = (
216
+ (out_w * strip_h * 3 * 4) # float canvas
217
+ + (out_w * strip_h * 4) # weight map
218
+ + (out_w * out_h * 3) # uint8 result (often memmap)
219
+ + (out_w * out_h * 3 * 0.25) # spill / misc
220
+ ) / (1024 * 1024)
221
+ if ram_available_mb is None:
222
+ rows.append(ResourceRow(name="RAM", status=ResourceStatus.ok, detail="unknown"))
223
+ elif ram_available_mb < need_ram * 0.5:
224
+ blocked = True
225
+ rows.append(
226
+ ResourceRow(
227
+ name="RAM",
228
+ status=ResourceStatus.not_enough,
229
+ detail=f"~{need_ram:.0f} MB needed, {ram_available_mb} free",
230
+ advice="Lower scale, enable disk intermediates, or close other apps",
231
+ )
232
+ )
233
+ elif ram_available_mb < need_ram:
234
+ rows.append(
235
+ ResourceRow(
236
+ name="RAM",
237
+ status=ResourceStatus.tight,
238
+ detail=f"~{need_ram:.0f} MB needed, {ram_available_mb} free",
239
+ advice="Consider lower scale or smaller tile",
240
+ )
241
+ )
242
+ else:
243
+ rows.append(
244
+ ResourceRow(
245
+ name="RAM",
246
+ status=ResourceStatus.ok,
247
+ detail=f"~{need_ram:.0f} MB est., {ram_available_mb} free",
248
+ )
249
+ )
250
+
251
+ # VRAM: weights + tile activations (model_fits_vram)
252
+ fit = model_fits_vram(
253
+ model_bytes, vram_free_mb, tile=tile, fp16=fp16
254
+ )
255
+ bpp = 2 if fp16 else 4
256
+ tile_vram = (tile * tile * 3 * bpp * 8) / (1024 * 1024)
257
+ weights_mb = (model_bytes or 0) / (1024 * 1024)
258
+ detail = (
259
+ f"tile {tile}, ~{tile_vram:.0f} MB act"
260
+ + (f" + ~{weights_mb:.0f} MB weights" if weights_mb else "")
261
+ + (f", {vram_free_mb} free" if vram_free_mb is not None else "")
262
+ )
263
+ if vram_free_mb is None:
264
+ rows.append(ResourceRow(name="VRAM", status=ResourceStatus.ok, detail="CPU or unknown"))
265
+ elif fit == "spill":
266
+ blocked = True
267
+ rows.append(
268
+ ResourceRow(
269
+ name="VRAM",
270
+ status=ResourceStatus.not_enough,
271
+ detail=detail,
272
+ advice="Smaller tile, enable fp16, use CPU, or classical Method",
273
+ )
274
+ )
275
+ elif fit == "tight":
276
+ rows.append(
277
+ ResourceRow(
278
+ name="VRAM",
279
+ status=ResourceStatus.tight,
280
+ detail=detail,
281
+ advice="Prefer smaller tile or fp16",
282
+ )
283
+ )
284
+ else:
285
+ rows.append(
286
+ ResourceRow(
287
+ name="VRAM",
288
+ status=ResourceStatus.ok,
289
+ detail=detail,
290
+ )
291
+ )
292
+
293
+ out_mb = (out_w * out_h * 3) / (1024 * 1024)
294
+ if disk_free_mb is None:
295
+ rows.append(ResourceRow(name="Disk", status=ResourceStatus.ok, detail="unknown"))
296
+ elif disk_free_mb < out_mb * 2:
297
+ blocked = True
298
+ rows.append(
299
+ ResourceRow(
300
+ name="Disk",
301
+ status=ResourceStatus.not_enough,
302
+ detail=f"need ~{out_mb * 2:.0f} MB free",
303
+ advice="Free disk space or use JPEG/WebP",
304
+ )
305
+ )
306
+ else:
307
+ rows.append(
308
+ ResourceRow(
309
+ name="Disk",
310
+ status=ResourceStatus.ok,
311
+ detail=f"{disk_free_mb} MB free",
312
+ )
313
+ )
314
+
315
+ if not model_ready:
316
+ mb = (model_bytes or 0) / (1024 * 1024)
317
+ rows.append(
318
+ ResourceRow(
319
+ name="Model",
320
+ status=ResourceStatus.tight,
321
+ detail=f"will download (~{mb:.0f} MB)" if mb else "will download",
322
+ advice="Download before run or allow download-on-start",
323
+ )
324
+ )
325
+ else:
326
+ rows.append(ResourceRow(name="Model", status=ResourceStatus.ok, detail="ready"))
327
+
328
+ return ResourceCheck(rows=rows, blocked=blocked)
329
+
330
+
331
+ def format_bytes(n: int) -> str:
332
+ if n < 1024:
333
+ return f"{n} B"
334
+ if n < 1024**2:
335
+ return f"{n / 1024:.1f} KB"
336
+ if n < 1024**3:
337
+ return f"{n / 1024**2:.1f} MB"
338
+ return f"{n / 1024**3:.2f} GB"
upscale/filters.py ADDED
@@ -0,0 +1,180 @@
1
+ """Pre/post image filters for the upscale pipeline."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ from PIL import Image, ImageEnhance, ImageFilter
7
+
8
+ from .schema import FilterSettings
9
+
10
+
11
+ def apply_pre_filters(img: np.ndarray, settings: FilterSettings) -> np.ndarray:
12
+ """Denoise / JPEG clean / deblur before the model."""
13
+ out = img
14
+ if settings.jpeg_clean > 0:
15
+ out = _jpeg_clean(out, settings.jpeg_clean)
16
+ if settings.pre_denoise > 0:
17
+ out = _denoise(out, settings.pre_denoise)
18
+ if settings.deblur > 0:
19
+ out = _deblur(out, settings.deblur)
20
+ return out
21
+
22
+
23
+ def apply_post_filters(img: np.ndarray, settings: FilterSettings) -> np.ndarray:
24
+ """Edge enhance / grain / color / halo reduce after the model."""
25
+ out = img
26
+ if settings.edge > 0:
27
+ out = _edge_enhance(out, settings.edge)
28
+ if settings.halo_reduce > 0:
29
+ out = _halo_reduce(out, settings.halo_reduce)
30
+ if settings.color_contrast > 0:
31
+ out = _color_contrast(out, settings.color_contrast)
32
+ if settings.grain > 0:
33
+ out = _film_grain(out, settings.grain)
34
+ # face_restore intentionally unused until a restorer is registered
35
+ return out
36
+
37
+
38
+ def estimate_time_factor(settings: FilterSettings) -> float:
39
+ """Rough multiplier for time estimates when filters are on."""
40
+ f = 1.0
41
+ if settings.pre_denoise > 0:
42
+ f += 0.05 * settings.pre_denoise
43
+ if settings.jpeg_clean > 0:
44
+ f += 0.08 * settings.jpeg_clean
45
+ if settings.deblur > 0:
46
+ f += 0.06 * settings.deblur
47
+ if settings.edge > 0:
48
+ f += 0.03 * settings.edge
49
+ if settings.grain > 0:
50
+ f += 0.02 * settings.grain
51
+ if settings.color_contrast > 0:
52
+ f += 0.02 * settings.color_contrast
53
+ if settings.halo_reduce > 0:
54
+ f += 0.04 * settings.halo_reduce
55
+ # face_restore is a stub — do not inflate ETA until a restorer is wired.
56
+ return f
57
+
58
+
59
+ def any_pre_filters(settings: FilterSettings) -> bool:
60
+ return (
61
+ settings.pre_denoise > 0
62
+ or settings.jpeg_clean > 0
63
+ or settings.deblur > 0
64
+ or settings.seamless
65
+ )
66
+
67
+
68
+ def any_post_filters(settings: FilterSettings) -> bool:
69
+ # face_restore is a stub until a restorer is wired — omit from the predicate.
70
+ return (
71
+ settings.edge > 0
72
+ or settings.grain > 0
73
+ or settings.color_contrast > 0
74
+ or settings.halo_reduce > 0
75
+ )
76
+
77
+
78
+ def _denoise(img: np.ndarray, amount: float) -> np.ndarray:
79
+ radius = max(0.5, 2.0 * amount)
80
+ pil = Image.fromarray(img)
81
+ blurred = pil.filter(ImageFilter.GaussianBlur(radius=radius))
82
+ a = float(np.clip(amount, 0, 1))
83
+ mix = Image.blend(pil, blurred, a * 0.6)
84
+ return np.array(mix, dtype=np.uint8)
85
+
86
+
87
+ def _jpeg_clean(img: np.ndarray, amount: float) -> np.ndarray:
88
+ # Mild bilateral-like: median then blend
89
+ pil = Image.fromarray(img)
90
+ cleaned = pil.filter(ImageFilter.MedianFilter(size=3 if amount < 0.7 else 5))
91
+ a = float(np.clip(amount, 0, 1))
92
+ return np.array(Image.blend(pil, cleaned, a * 0.7), dtype=np.uint8)
93
+
94
+
95
+ def _deblur(img: np.ndarray, amount: float) -> np.ndarray:
96
+ """Unsharp-mask style sharpening before SR (helps soft / motion-soft sources)."""
97
+ a = float(np.clip(amount, 0, 1))
98
+ radius = 1.0 + 1.5 * a
99
+ percent = int(80 + 120 * a)
100
+ pil = Image.fromarray(img)
101
+ sharp = pil.filter(ImageFilter.UnsharpMask(radius=radius, percent=percent, threshold=2))
102
+ return np.array(Image.blend(pil, sharp, a * 0.85), dtype=np.uint8)
103
+
104
+
105
+ def _edge_enhance(img: np.ndarray, amount: float) -> np.ndarray:
106
+ pil = Image.fromarray(img)
107
+ sharp = pil.filter(ImageFilter.EDGE_ENHANCE_MORE if amount > 0.5 else ImageFilter.EDGE_ENHANCE)
108
+ a = float(np.clip(amount, 0, 1))
109
+ return np.array(Image.blend(pil, sharp, a), dtype=np.uint8)
110
+
111
+
112
+ def _film_grain(img: np.ndarray, amount: float) -> np.ndarray:
113
+ rng = np.random.default_rng(0)
114
+ noise = rng.normal(0, 12.0 * amount, img.shape).astype(np.float32)
115
+ out = np.clip(img.astype(np.float32) + noise, 0, 255)
116
+ return out.astype(np.uint8)
117
+
118
+
119
+ def _color_contrast(img: np.ndarray, amount: float) -> np.ndarray:
120
+ """Mild color + contrast boost after SR (0 = identity, 1 = strong)."""
121
+ a = float(np.clip(amount, 0, 1))
122
+ pil = Image.fromarray(img)
123
+ # Enhance factors: 1.0 = unchanged; map amount → up to ~1.35
124
+ factor = 1.0 + 0.35 * a
125
+ pil = ImageEnhance.Contrast(pil).enhance(factor)
126
+ pil = ImageEnhance.Color(pil).enhance(1.0 + 0.25 * a)
127
+ return np.array(pil, dtype=np.uint8)
128
+
129
+
130
+ def _halo_reduce(img: np.ndarray, amount: float) -> np.ndarray:
131
+ """Pull bright/dark overshoots toward a median neighborhood (reduces ringing)."""
132
+ a = float(np.clip(amount, 0, 1))
133
+ pil = Image.fromarray(img)
134
+ soft = pil.filter(ImageFilter.MedianFilter(size=3))
135
+ soft_a = np.asarray(soft, dtype=np.float32)
136
+ src = np.asarray(img, dtype=np.float32)
137
+ # Fuse into soft_a: where |src - median| is large, blend toward median.
138
+ strength = np.clip(np.abs(src - soft_a) / 40.0, 0.0, 1.0) * a * 0.75
139
+ soft_a *= strength
140
+ soft_a += src * (1.0 - strength)
141
+ return np.clip(soft_a, 0, 255).astype(np.uint8)
142
+
143
+
144
+ def wrap_seamless(img: np.ndarray, pad: int) -> np.ndarray:
145
+ """Pad image with wraparound for seamless texture mode."""
146
+ if pad <= 0:
147
+ return img
148
+ if img.ndim == 2:
149
+ return np.pad(img, ((pad, pad), (pad, pad)), mode="wrap")
150
+ return np.pad(img, ((pad, pad), (pad, pad), (0, 0)), mode="wrap")
151
+
152
+
153
+ def unwrap_seamless(
154
+ img: np.ndarray,
155
+ pad: int,
156
+ scale: int | None = None,
157
+ *,
158
+ margins: tuple[int, int] | None = None,
159
+ ) -> np.ndarray:
160
+ """Crop wrap pad from an upscaled (or padded) image.
161
+
162
+ Prefer ``margins=(pad_y, pad_x)`` in output pixels. Integer ``scale`` is
163
+ kept for callers that still pass ``pad * factor``.
164
+ """
165
+ if pad <= 0:
166
+ return img
167
+ if margins is not None:
168
+ py, px = margins
169
+ elif scale is not None:
170
+ py = px = int(pad) * int(scale)
171
+ else:
172
+ raise TypeError("unwrap_seamless requires scale or margins")
173
+ if py <= 0 and px <= 0:
174
+ return img
175
+ h, w = img.shape[:2]
176
+ y0, y1 = py, h - py
177
+ x0, x1 = px, w - px
178
+ if y1 <= y0 or x1 <= x0:
179
+ return img
180
+ return img[y0:y1, x0:x1]
@@ -0,0 +1,94 @@
1
+ """Load canonical help markdown from docs/help for API, UI, and MCP."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from pathlib import Path
7
+
8
+ HELP_TOPICS = [
9
+ "size",
10
+ "crop",
11
+ "model",
12
+ "filters",
13
+ "output",
14
+ "advanced",
15
+ "preflight",
16
+ "batch",
17
+ "settings",
18
+ "run",
19
+ "cli",
20
+ "mcp",
21
+ "presets",
22
+ "first_run",
23
+ "shortcuts",
24
+ "resume",
25
+ "quality",
26
+ ]
27
+
28
+ _SAFE_SEGMENT = re.compile(r"^[A-Za-z0-9_-]+$")
29
+
30
+
31
+ def docs_root() -> Path:
32
+ import os
33
+
34
+ override = os.environ.get("UPSCALE_DOCS_DIR")
35
+ if override:
36
+ return Path(override) / "help"
37
+ return Path(__file__).resolve().parent.parent / "docs" / "help"
38
+
39
+
40
+ def _require_safe(name: str, kind: str) -> str:
41
+ if not name or not _SAFE_SEGMENT.match(name):
42
+ raise ValueError(f"Invalid {kind}: {name!r}")
43
+ return name
44
+
45
+
46
+ def _confined_file(root: Path, *rel_parts: str) -> Path:
47
+ """Resolve file under root; raise if it escapes."""
48
+ root_r = root.resolve()
49
+ path = root_r.joinpath(*rel_parts).resolve()
50
+ if not path.is_relative_to(root_r):
51
+ raise ValueError(f"Path escapes docs root: {path}")
52
+ return path
53
+
54
+
55
+ def topic_path(topic: str, lang: str = "en") -> Path:
56
+ root = docs_root()
57
+ topic = _require_safe(topic, "topic")
58
+ if lang and lang != "en":
59
+ lang = _require_safe(lang, "lang")
60
+ candidate = _confined_file(root, lang, f"{topic}.md")
61
+ if candidate.is_file():
62
+ return candidate
63
+ return _confined_file(root, f"{topic}.md")
64
+
65
+
66
+ def list_topics(lang: str = "en") -> list[dict[str, str]]:
67
+ items = []
68
+ for topic in HELP_TOPICS:
69
+ try:
70
+ path = topic_path(topic, lang)
71
+ except ValueError:
72
+ path = topic_path(topic, "en")
73
+ title = topic.replace("_", " ").title()
74
+ if path.is_file():
75
+ first = path.read_text(encoding="utf-8").strip().splitlines()
76
+ if first and first[0].startswith("# "):
77
+ title = first[0][2:].strip()
78
+ items.append({"id": topic, "title": title})
79
+ return items
80
+
81
+
82
+ def get_help(topic: str, lang: str = "en") -> str:
83
+ try:
84
+ path = topic_path(topic, lang)
85
+ except ValueError as exc:
86
+ raise FileNotFoundError(f"Help topic not found: {topic}") from exc
87
+ if not path.is_file():
88
+ try:
89
+ path = topic_path(topic, "en")
90
+ except ValueError as exc:
91
+ raise FileNotFoundError(f"Help topic not found: {topic}") from exc
92
+ if not path.is_file():
93
+ raise FileNotFoundError(f"Help topic not found: {topic}")
94
+ return path.read_text(encoding="utf-8")
upscale/infer_util.py ADDED
@@ -0,0 +1,22 @@
1
+ """Shared patch normalize / denormalize for Torch and ONNX infer wrappers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+
8
+ def patch_to_nchw_float(patch: np.ndarray) -> np.ndarray:
9
+ """uint8 HWC → float32 NCHW in [0, 1]."""
10
+ t = patch.astype(np.float32) / 255.0
11
+ if t.ndim == 2:
12
+ t = t[:, :, None]
13
+ return np.transpose(t, (2, 0, 1))[None, ...]
14
+
15
+
16
+ def nchw_float_to_uint8(out: np.ndarray) -> np.ndarray:
17
+ """float NCHW or CHW in [0, 1] → uint8 HWC."""
18
+ arr = np.asarray(out, dtype=np.float32)
19
+ if arr.ndim == 4:
20
+ arr = arr[0]
21
+ arr = np.transpose(arr, (1, 2, 0))
22
+ return np.clip(arr * 255.0, 0, 255).astype(np.uint8)