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
@@ -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 'upscale[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 'upscale[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 'upscale[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 'upscale[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 'upscale[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 'upscale[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 'upscale[vectorize]'."
449
+ ),
450
+ )
@@ -0,0 +1,17 @@
1
+ """FastAPI route modules (included from server.app)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import FastAPI
6
+
7
+
8
+ def include_routers(app: FastAPI) -> None:
9
+ from .compare_routes import router as compare_router
10
+ from .jobs import router as jobs_router
11
+ from .models_routes import router as models_router
12
+ from .system_routes import router as system_router
13
+
14
+ app.include_router(jobs_router)
15
+ app.include_router(compare_router)
16
+ app.include_router(models_router)
17
+ app.include_router(system_router)
@@ -0,0 +1,243 @@
1
+ """API routes split from server.py."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import shutil
7
+ import threading
8
+ import uuid
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from fastapi import APIRouter, File, Form, HTTPException, UploadFile
14
+ from fastapi.responses import FileResponse, Response
15
+ from pydantic import BaseModel, Field
16
+
17
+ from upscale.api import deps as D
18
+ from upscale.tiling import JobCancelled
19
+
20
+ router = APIRouter()
21
+
22
+ class ZipBody(BaseModel):
23
+ job_ids: list[str]
24
+
25
+
26
+ @router.post("/api/zip")
27
+ def api_zip(body: ZipBody) -> Response:
28
+ """Zip completed job result files for batch download."""
29
+ import io
30
+ import zipfile
31
+
32
+ if not body.job_ids:
33
+ raise HTTPException(400, "job_ids required")
34
+ if len(body.job_ids) > 64:
35
+ raise HTTPException(400, "too many jobs")
36
+ buf = io.BytesIO()
37
+ added = 0
38
+ with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
39
+ for jid in body.job_ids:
40
+ result: Path | None = None
41
+ with D._jobs_lock:
42
+ job = D._jobs.get(jid)
43
+ if job is not None and job.output_path is not None and job.output_path.is_file():
44
+ result = job.output_path
45
+ else:
46
+ try:
47
+ result = D._find_result_file(D._safe_job_dir(jid))
48
+ except HTTPException:
49
+ continue
50
+ if result is None or not result.is_file():
51
+ continue
52
+ arc = f"{jid}_{result.name}"
53
+ zf.write(result, arcname=arc)
54
+ added += 1
55
+ if added == 0:
56
+ raise HTTPException(404, "No completed results to zip")
57
+ return Response(
58
+ content=buf.getvalue(),
59
+ media_type="application/zip",
60
+ headers={"Content-Disposition": 'attachment; filename="upscale-batch.zip"'},
61
+ )
62
+
63
+ class CompareBody(BaseModel):
64
+ models: list[str] = Field(default_factory=list)
65
+ algorithms: list[str] = Field(default_factory=list)
66
+ filters: list[str] = Field(default_factory=list)
67
+ filter_amounts: dict[str, float] = Field(default_factory=dict)
68
+ base_model: str = "RealESRGAN_x4plus"
69
+ base_algorithm: str | None = None
70
+ crop: dict[str, int]
71
+ scale: float = 4.0
72
+ device: str = "auto"
73
+ half: bool = False
74
+
75
+
76
+ @dataclass
77
+ class CompareRun:
78
+ id: str
79
+ dir: Path
80
+ cancel_event: threading.Event = field(default_factory=threading.Event)
81
+ state: str = "running" # running | done | cancelled | error
82
+ results: list[dict[str, Any]] = field(default_factory=list)
83
+ error: str | None = None
84
+ message: str = ""
85
+ created_at: float = field(default_factory=lambda: __import__("time").time())
86
+
87
+
88
+
89
+
90
+ def _compare_worker(
91
+ run: CompareRun,
92
+ input_path: Path,
93
+ variants: list[dict[str, Any]],
94
+ crop: Any,
95
+ scale: float,
96
+ device: str,
97
+ half: bool,
98
+ ) -> None:
99
+ from upscale.compare import compare_variants
100
+
101
+ try:
102
+ # Share the process-wide execute lock so compare never overlaps a job.
103
+ with D._execute_lock:
104
+ results = compare_variants(
105
+ input_path,
106
+ run.dir,
107
+ variants=variants,
108
+ crop=crop,
109
+ scale=scale,
110
+ device=device,
111
+ half=half,
112
+ cancel_event=run.cancel_event,
113
+ progress=lambda msg, _frac: setattr(run, "message", msg),
114
+ )
115
+ run.results = results
116
+ # Persist results for status after in-memory eviction
117
+ try:
118
+ (run.dir / "compare_results.json").write_text(
119
+ json.dumps(results), encoding="utf-8"
120
+ )
121
+ except OSError:
122
+ pass
123
+ if run.cancel_event.is_set():
124
+ run.state = "cancelled"
125
+ run.message = "cancelled"
126
+ else:
127
+ run.state = "done"
128
+ run.message = ""
129
+ except JobCancelled:
130
+ run.state = "cancelled"
131
+ run.message = "cancelled"
132
+ except Exception as exc: # noqa: BLE001 — surface to status poller
133
+ run.state = "error"
134
+ run.error = str(exc)
135
+ run.message = str(exc)
136
+
137
+
138
+ @router.post("/api/compare")
139
+ async def api_compare(
140
+ file: UploadFile = File(...),
141
+ body: str = Form("{}"),
142
+ ) -> dict[str, Any]:
143
+ """Start a crop compare; poll ``GET /api/compare/{id}/status`` until done."""
144
+ from upscale.compare import build_variants
145
+ from upscale.schema import CropRect
146
+
147
+ try:
148
+ raw = json.loads(body) if body.strip() else {}
149
+ cb = CompareBody.model_validate(raw)
150
+ except (json.JSONDecodeError, ValueError) as exc:
151
+ raise HTTPException(400, f"Invalid compare body: {exc}") from exc
152
+ variants = build_variants(
153
+ models=cb.models,
154
+ algorithms=cb.algorithms,
155
+ filters=cb.filters,
156
+ filter_amounts=cb.filter_amounts,
157
+ base_model=cb.base_model,
158
+ base_algorithm=cb.base_algorithm,
159
+ )
160
+ if not variants:
161
+ raise HTTPException(
162
+ 400, "Select at least one model, classical algorithm, or filter"
163
+ )
164
+
165
+ run_id = uuid.uuid4().hex
166
+ run_dir = D.JOBS_ROOT / f"compare-{run_id}"
167
+ run_dir.mkdir(parents=True, exist_ok=True)
168
+ suffix = Path(file.filename or "input.png").suffix or ".png"
169
+ input_path = run_dir / f"input{suffix}"
170
+ content = await file.read()
171
+ if len(content) > D.MAX_UPLOAD_BYTES:
172
+ shutil.rmtree(run_dir, ignore_errors=True)
173
+ raise HTTPException(413, f"Upload exceeds limit of {D.MAX_UPLOAD_BYTES} bytes")
174
+ input_path.write_bytes(content)
175
+ crop = CropRect(
176
+ x=int(cb.crop.get("x", 0)),
177
+ y=int(cb.crop.get("y", 0)),
178
+ w=int(cb.crop.get("w", 64)),
179
+ h=int(cb.crop.get("h", 64)),
180
+ )
181
+ run = CompareRun(id=run_id, dir=run_dir, message="starting")
182
+ with D._compare_lock:
183
+ D._compare_jobs[run_id] = run
184
+ D._compare_runs[run_id] = run_dir
185
+ threading.Thread(
186
+ target=_compare_worker,
187
+ args=(run, input_path, variants, crop, cb.scale, cb.device, cb.half),
188
+ name=f"compare-{run_id[:8]}",
189
+ daemon=True,
190
+ ).start()
191
+ return {"id": run_id, "state": "running"}
192
+
193
+ @router.get("/api/compare/{run_id}/status")
194
+ def api_compare_status(run_id: str) -> dict[str, Any]:
195
+ with D._compare_lock:
196
+ run = D._compare_jobs.get(run_id)
197
+ if run is None:
198
+ run_dir = D._compare_runs.get(run_id) or (D.JOBS_ROOT / f"compare-{run_id}")
199
+ run_dir = Path(run_dir)
200
+ if not run_dir.is_dir():
201
+ raise HTTPException(404, "Compare run not found")
202
+ results: list[dict[str, Any]] = []
203
+ meta = run_dir / "compare_results.json"
204
+ if meta.is_file():
205
+ try:
206
+ results = json.loads(meta.read_text(encoding="utf-8"))
207
+ except (OSError, json.JSONDecodeError):
208
+ results = []
209
+ return {
210
+ "id": run_id,
211
+ "state": "done" if results else "error",
212
+ "results": results,
213
+ "message": "" if results else "Compare results unavailable after restart",
214
+ "error": None if results else "results missing",
215
+ }
216
+ return {
217
+ "id": run.id,
218
+ "state": run.state,
219
+ "results": run.results,
220
+ "error": run.error,
221
+ "message": run.message,
222
+ }
223
+
224
+ @router.post("/api/compare/{run_id}/cancel")
225
+ def api_compare_cancel(run_id: str) -> dict[str, str]:
226
+ with D._compare_lock:
227
+ run = D._compare_jobs.get(run_id)
228
+ if run is None:
229
+ raise HTTPException(404, "Compare run not found")
230
+ run.cancel_event.set()
231
+ run.message = "cancelling"
232
+ return {"status": "cancelling"}
233
+
234
+ @router.get("/api/compare/{run_id}/{model:path}")
235
+ def api_compare_result(run_id: str, model: str) -> FileResponse:
236
+ run_dir = D._compare_runs.get(run_id)
237
+ if run_dir is None:
238
+ run_dir = D.JOBS_ROOT / f"compare-{run_id}"
239
+ safe = "".join(c if c.isalnum() or c in "-_" else "_" for c in model)
240
+ path = run_dir / f"compare_{safe}.png"
241
+ if not path.is_file():
242
+ raise HTTPException(404, "Compare result not found")
243
+ return FileResponse(path, media_type="image/png")