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,200 @@
1
+ """API routes split from server.py."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import shutil
8
+ import tempfile
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from fastapi import APIRouter, File, Form, HTTPException, UploadFile
13
+ from fastapi.responses import JSONResponse
14
+ from pydantic import BaseModel
15
+
16
+ from upscale.api import deps as D
17
+ from upscale.estimates import model_fits_vram
18
+ from upscale.help_content import get_help, list_topics
19
+ from upscale.models import DEFAULT_WEIGHTS_DIR, MODELS, all_models
20
+ from upscale.schema import LANGUAGE_CATALOG
21
+ from upscale.system import gather_system_info
22
+
23
+ router = APIRouter()
24
+
25
+ @router.get("/api/algorithms")
26
+ def api_algorithms_list() -> dict[str, Any]:
27
+ from dataclasses import asdict
28
+
29
+ from upscale.algorithms import list_algorithm_meta, list_algorithms
30
+ from upscale.algorithms.classical import backend_name
31
+
32
+ meta = list_algorithm_meta()
33
+ return {
34
+ "algorithms": list_algorithms(),
35
+ "items": [asdict(m) for m in meta],
36
+ "backend": backend_name(),
37
+ }
38
+
39
+ @router.get("/api/system")
40
+ def api_system(
41
+ device: str = "auto",
42
+ half: bool = False,
43
+ model: str | None = None,
44
+ tile: int | None = None,
45
+ ) -> dict[str, Any]:
46
+ info = gather_system_info(device=device, fp16=half)
47
+ payload = info.model_dump()
48
+ # Optional preflight VRAM fit for a chosen model + tile
49
+ model_bytes = None
50
+ if model:
51
+ meta = all_models().get(model) or MODELS.get(model) or {}
52
+ model_bytes = meta.get("size_bytes")
53
+ if model_bytes is None:
54
+ url_path = (meta.get("url") or "").split("?")[0]
55
+ ext = Path(url_path).suffix or ".pth"
56
+ dest = DEFAULT_WEIGHTS_DIR / f"{model}{ext}"
57
+ if dest.is_file():
58
+ model_bytes = dest.stat().st_size
59
+ use_tile = tile or info.auto_tile or 512
60
+ payload["vram_fit"] = model_fits_vram(
61
+ model_bytes,
62
+ info.vram_free_mb,
63
+ tile=int(use_tile),
64
+ fp16=half,
65
+ )
66
+ payload["vram_fit_tile"] = int(use_tile)
67
+ return payload
68
+
69
+ @router.get("/api/about")
70
+ def api_about() -> dict[str, Any]:
71
+ from upscale.about import about_payload, models_disk_summary
72
+
73
+ payload = about_payload()
74
+ payload["models"] = models_disk_summary()
75
+ return payload
76
+
77
+ @router.get("/api/license")
78
+ def api_license() -> dict[str, Any]:
79
+ from upscale.about import license_text, package_version
80
+
81
+ return {"license": "MIT", "version": package_version(), "text": license_text()}
82
+
83
+ @router.get("/api/updates")
84
+ def api_updates() -> dict[str, Any]:
85
+ from upscale.about import check_for_updates
86
+
87
+ return check_for_updates()
88
+
89
+ @router.get("/api/help")
90
+ def api_help_index(lang: str = "en") -> dict[str, Any]:
91
+ return {"topics": list_topics(lang), "languages": LANGUAGE_CATALOG}
92
+
93
+ @router.get("/api/help/{topic}")
94
+ def api_help_topic(topic: str, lang: str = "en") -> dict[str, str]:
95
+ try:
96
+ body = get_help(topic, lang)
97
+ except FileNotFoundError as exc:
98
+ raise HTTPException(404, str(exc)) from exc
99
+ return {"topic": topic, "lang": lang, "markdown": body}
100
+
101
+ @router.get("/api/presets")
102
+ def api_presets() -> dict[str, Any]:
103
+ from upscale.presets import list_presets
104
+
105
+ return list_presets()
106
+
107
+ class PresetApplyBody(BaseModel):
108
+ id: str
109
+ kind: str = "option" # option | target
110
+
111
+
112
+ @router.post("/api/presets/apply")
113
+ def api_presets_apply(body: PresetApplyBody) -> dict[str, Any]:
114
+ from upscale.presets import _target_settings, resolve_option_preset, resolve_target_preset
115
+
116
+ try:
117
+ if body.kind == "target":
118
+ target = resolve_target_preset(body.id)
119
+ return {
120
+ "id": target.id,
121
+ "kind": "target",
122
+ "label": target.label,
123
+ "settings": _target_settings(target),
124
+ }
125
+ option = resolve_option_preset(body.id)
126
+ return {
127
+ "id": option.id,
128
+ "kind": "option",
129
+ "label": option.label,
130
+ "settings": dict(option.settings),
131
+ }
132
+ except KeyError as exc:
133
+ raise HTTPException(404, str(exc)) from exc
134
+
135
+ @router.post("/api/suggest")
136
+ async def api_suggest(
137
+ file: UploadFile = File(...),
138
+ fast: bool = Form(False),
139
+ ) -> dict[str, Any]:
140
+ from upscale.suggest import suggest_model
141
+
142
+ job_dir = Path(tempfile.mkdtemp(prefix="upscale-suggest-"))
143
+ try:
144
+ suffix = Path(file.filename or "input.png").suffix or ".png"
145
+ dest = job_dir / f"input{suffix}"
146
+ content = await file.read()
147
+ if len(content) > D.MAX_UPLOAD_BYTES:
148
+ raise HTTPException(
149
+ 413, f"Upload exceeds limit of {D.MAX_UPLOAD_BYTES} bytes"
150
+ )
151
+ dest.write_bytes(content)
152
+ return suggest_model(dest, fast=fast)
153
+ finally:
154
+ shutil.rmtree(job_dir, ignore_errors=True)
155
+
156
+ class BenchmarkBody(BaseModel):
157
+ path: str
158
+ model: str = "RealESRGAN_x4plus"
159
+ device: str = "cpu"
160
+ crop_size: int = 64
161
+ scale: float = 2.0
162
+
163
+
164
+ @router.post("/api/benchmark")
165
+ def api_benchmark(body: BenchmarkBody) -> dict[str, Any]:
166
+ from upscale.benchmark import run_benchmark
167
+
168
+ p = Path(body.path).resolve()
169
+ if not p.is_file():
170
+ raise HTTPException(400, "path must be a readable local file")
171
+ # Sandbox: only allow files under D.JOBS_ROOT (or system temp upscale-jobs).
172
+ jobs_root = D.JOBS_ROOT.resolve()
173
+ if not p.is_relative_to(jobs_root):
174
+ raise HTTPException(
175
+ 400,
176
+ "benchmark path must be under the jobs temp directory "
177
+ f"({jobs_root})",
178
+ )
179
+ with D._execute_lock:
180
+ return run_benchmark(
181
+ p,
182
+ model=body.model,
183
+ device=body.device,
184
+ crop_size=body.crop_size,
185
+ scale=body.scale,
186
+ )
187
+
188
+ @router.get("/api/locales/{code}")
189
+ def api_locale(code: str) -> JSONResponse:
190
+ if not re.fullmatch(r"[A-Za-z0-9_-]+", code or ""):
191
+ raise HTTPException(404, "Locale not found")
192
+ locales = D.LOCALES_DIR.resolve()
193
+ path = (locales / f"{code}.json").resolve()
194
+ if not path.is_relative_to(locales):
195
+ raise HTTPException(404, "Locale not found")
196
+ if not path.is_file():
197
+ path = (locales / "en.json").resolve()
198
+ if not path.is_file() or not path.is_relative_to(locales):
199
+ raise HTTPException(404, "Locale not found")
200
+ return JSONResponse(json.loads(path.read_text(encoding="utf-8")))
@@ -0,0 +1,27 @@
1
+ """Inference backends: torch (dev/full) and onnx (slim Windows desktop)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Literal
7
+
8
+ BackendName = Literal["torch", "onnx", "auto"]
9
+
10
+
11
+ def resolve_backend(requested: str | None = None) -> Literal["torch", "onnx"]:
12
+ """Pick backend. Env UPSCALE_BACKEND overrides; auto prefers onnx if importable and no torch."""
13
+ raw = (requested or os.environ.get("UPSCALE_BACKEND") or "auto").strip().lower()
14
+ if raw in ("torch", "pytorch"):
15
+ return "torch"
16
+ if raw in ("onnx", "ort"):
17
+ return "onnx"
18
+ # auto
19
+ try:
20
+ import torch # noqa: F401
21
+
22
+ return "torch"
23
+ except ImportError:
24
+ return "onnx"
25
+
26
+
27
+ __all__ = ["resolve_backend", "BackendName"]
@@ -0,0 +1,265 @@
1
+ """ONNX Runtime upscale path — no PyTorch at runtime."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import warnings
7
+ from pathlib import Path
8
+ from typing import Callable
9
+
10
+ import numpy as np
11
+
12
+ from ..config import UpscaleConfig
13
+ from ..job_prep import clamp_overlap, finalize_result, prepare_job
14
+ from ..models import DEFAULT_WEIGHTS_DIR, FAST_MODEL, registry_scale
15
+ from ..pipeline import compute_passes, run
16
+ from ..tiling import JobCancelled
17
+
18
+ # Optional remote URL for pre-exported ONNX (publish when CI exports).
19
+ # sha256/url filled when a release host is published; until then ensure_onnx_model
20
+ # looks on disk and raises a clear first-run message.
21
+ ONNX_MODELS: dict[str, dict] = {
22
+ "4x-spanx4-ch48": {
23
+ "scale": 4,
24
+ "filename": "4x-spanx4-ch48.onnx",
25
+ "description": "SPAN 4x (ONNX). Preferred slim desktop model.",
26
+ "sha256": None,
27
+ "url": None,
28
+ },
29
+ "RealESRGAN_x4plus": {
30
+ "scale": 4,
31
+ "filename": "RealESRGAN_x4plus.onnx",
32
+ "description": "RealESRGAN x4plus (ONNX).",
33
+ "sha256": None,
34
+ "url": None,
35
+ },
36
+ "RealESRGAN_x4plus_anime_6B": {
37
+ "scale": 4,
38
+ "filename": "RealESRGAN_x4plus_anime_6B.onnx",
39
+ "description": "Anime 6B (ONNX).",
40
+ "sha256": None,
41
+ "url": None,
42
+ },
43
+ "realesr-general-x4v3": {
44
+ "scale": 4,
45
+ "filename": "realesr-general-x4v3.onnx",
46
+ "description": "General x4v3 (ONNX).",
47
+ "sha256": None,
48
+ "url": None,
49
+ },
50
+ "realesr-general-wdn-x4v3": {
51
+ "scale": 4,
52
+ "filename": "realesr-general-wdn-x4v3.onnx",
53
+ "description": "General WDN x4v3 (ONNX).",
54
+ "sha256": None,
55
+ "url": None,
56
+ },
57
+ }
58
+
59
+ # Cache ORT sessions by (path, providers) for the process lifetime.
60
+ _ORT_SESSION_CACHE: dict[tuple[str, tuple[str, ...]], object] = {}
61
+
62
+
63
+ def _weights_dir(cfg: UpscaleConfig | None = None) -> Path:
64
+ env = os.environ.get("UPSCALE_MODELS_DIR")
65
+ if env:
66
+ return Path(env)
67
+ if cfg and cfg.weights_dir:
68
+ return Path(cfg.weights_dir)
69
+ return DEFAULT_WEIGHTS_DIR
70
+
71
+
72
+ def onnx_path_for(name: str, weights_dir: Path) -> Path:
73
+ meta = ONNX_MODELS.get(name)
74
+ filename = meta["filename"] if meta else f"{name}.onnx"
75
+ return Path(weights_dir) / filename
76
+
77
+
78
+ def ensure_onnx_model(name: str, weights_dir: Path | None = None) -> Path:
79
+ """Return path to .onnx weights; download when url+sha256 are configured."""
80
+ wdir = weights_dir or DEFAULT_WEIGHTS_DIR
81
+ wdir = Path(wdir)
82
+ wdir.mkdir(parents=True, exist_ok=True)
83
+ path = onnx_path_for(name, wdir)
84
+ meta = ONNX_MODELS.get(name, {})
85
+ if path.is_file():
86
+ expected = meta.get("sha256")
87
+ if expected:
88
+ from ..models import _sha256
89
+
90
+ if _sha256(path) != expected:
91
+ path.unlink(missing_ok=True)
92
+ else:
93
+ return path
94
+ else:
95
+ return path
96
+ url = meta.get("url")
97
+ sha = meta.get("sha256")
98
+ if url and sha:
99
+ from ..models import _download_with_retries, _sha256
100
+
101
+ _download_with_retries(url, path)
102
+ if _sha256(path) != sha:
103
+ path.unlink(missing_ok=True)
104
+ raise RuntimeError(f"ONNX hash mismatch for {name}")
105
+ return path
106
+ raise FileNotFoundError(
107
+ f"ONNX model not found: {path}\n"
108
+ "First-run: export on a Torch machine with\n"
109
+ f" py -3 scripts/export_onnx.py {name} -o {path}\n"
110
+ "or place a pre-exported .onnx in the models folder."
111
+ )
112
+
113
+
114
+ def _ort_session(model_path: Path):
115
+ import onnxruntime as ort
116
+
117
+ available = set(ort.get_available_providers())
118
+ # Prefer CUDA when present; else DirectML (Windows slim); else CPU.
119
+ preferred = []
120
+ for p in ("CUDAExecutionProvider", "DmlExecutionProvider", "CPUExecutionProvider"):
121
+ if p in available:
122
+ preferred.append(p)
123
+ if not preferred:
124
+ preferred = ["CPUExecutionProvider"]
125
+ key = (str(model_path.resolve()), tuple(preferred))
126
+ cached = _ORT_SESSION_CACHE.get(key)
127
+ if cached is not None:
128
+ return cached, preferred[0]
129
+ opts = ort.SessionOptions()
130
+ opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
131
+ session = ort.InferenceSession(str(model_path), opts, providers=preferred)
132
+ _ORT_SESSION_CACHE[key] = session
133
+ return session, preferred[0]
134
+
135
+
136
+ def make_onnx_infer_fn(session, input_name: str) -> Callable[[np.ndarray], np.ndarray]:
137
+ from ..infer_util import nchw_float_to_uint8, patch_to_nchw_float
138
+
139
+ def infer(patch: np.ndarray) -> np.ndarray:
140
+ x = patch_to_nchw_float(patch)
141
+ out = session.run(None, {input_name: x})[0]
142
+ return nchw_float_to_uint8(out)
143
+
144
+ return infer
145
+
146
+
147
+ def execute_onnx(
148
+ cfg: UpscaleConfig,
149
+ *,
150
+ progress_callback: Callable[[str, float], None] | None = None,
151
+ on_progress: Callable[[dict], None] | None = None,
152
+ echo: Callable[[str], None] | None = None,
153
+ ) -> Path:
154
+ prep = prepare_job(cfg, on_progress=on_progress, echo=echo)
155
+ model_name = FAST_MODEL if cfg.fast else cfg.model
156
+ wdir = _weights_dir(cfg)
157
+
158
+ model_scale = int(
159
+ ONNX_MODELS.get(model_name, {}).get("scale") or registry_scale(model_name)
160
+ )
161
+ if cfg.tile in ("auto", None):
162
+ # Rough RAM-based tile (ORT has no cuda.mem_get_info here).
163
+ try:
164
+ import psutil
165
+
166
+ avail = int(psutil.virtual_memory().available * 0.25)
167
+ except Exception: # noqa: BLE001
168
+ avail = 512 * 1024 * 1024
169
+ bytes_per_px = 8000
170
+ tile_guess = int(max(128, min(512, (avail / bytes_per_px) ** 0.5)))
171
+ tile_int = (tile_guess // 64) * 64 or 256
172
+ else:
173
+ tile_int = int(cfg.tile)
174
+ overlap = clamp_overlap(cfg.overlap, tile_int)
175
+
176
+ infer = None
177
+ provider = "cpu"
178
+ if prep.scale > 1.0:
179
+ path = ensure_onnx_model(model_name, wdir)
180
+ if prep.show:
181
+ prep.log(f"ONNX model: {path.name}")
182
+ session, provider = _ort_session(path)
183
+ input_name = session.get_inputs()[0].name
184
+ infer = make_onnx_infer_fn(session, input_name)
185
+
186
+ passes = compute_passes(prep.scale, model_scale) if prep.scale > 1 else 0
187
+ if prep.show:
188
+ prep.log(
189
+ f"Backend: onnx/{provider} | Model: {model_name} | "
190
+ f"Scale: {prep.scale:.3f}x | Passes: {passes} | Tile: {tile_int}"
191
+ )
192
+
193
+ if cfg.blend_model:
194
+ warnings.warn(
195
+ "blend_model weight interpolation needs Torch; ignored on ONNX. "
196
+ "Export a pre-blended ONNX or use the Torch backend.",
197
+ stacklevel=2,
198
+ )
199
+ if cfg.denoise is not None and abs(cfg.denoise - 0.5) > 1e-6:
200
+ # Soft parity: if the WDN twin is on disk, switch to it when denoise>0.5.
201
+ wdn = "realesr-general-wdn-x4v3"
202
+ general = "realesr-general-x4v3"
203
+ if model_name in (general, wdn) and cfg.denoise > 0.5:
204
+ alt = onnx_path_for(wdn, wdir)
205
+ if alt.is_file() and model_name != wdn:
206
+ model_name = wdn
207
+ path = alt
208
+ session, provider = _ort_session(path)
209
+ input_name = session.get_inputs()[0].name
210
+ infer = make_onnx_infer_fn(session, input_name)
211
+ if prep.show:
212
+ prep.log(f"ONNX denoise>0.5 → switched to {wdn}")
213
+ else:
214
+ warnings.warn(
215
+ "--denoise DNI is not supported on ONNX (no WDN twin on disk); ignored.",
216
+ stacklevel=2,
217
+ )
218
+ else:
219
+ warnings.warn(
220
+ "--denoise DNI is not supported on the ONNX backend yet; ignored.",
221
+ stacklevel=2,
222
+ )
223
+
224
+ from ..job_prep import scaled_size
225
+
226
+ run_tw, run_th = scaled_size(prep.img.shape[1], prep.img.shape[0], prep.scale)
227
+
228
+ try:
229
+ result = run(
230
+ img=prep.img,
231
+ scale=prep.scale,
232
+ descriptor=None,
233
+ device=type("D", (), {"type": "cpu"})(),
234
+ fp16=False,
235
+ tile=tile_int,
236
+ overlap=overlap,
237
+ show_progress=prep.show,
238
+ model_scale=model_scale,
239
+ disk_intermediate_threshold=cfg.disk_intermediate_threshold,
240
+ progress_callback=progress_callback,
241
+ cancel_event=cfg.cancel_event,
242
+ pause_event=cfg.pause_event,
243
+ strength=1.0,
244
+ job_dir=cfg.job_dir,
245
+ resume_from_checkpoint=bool(getattr(cfg, "resume_from_checkpoint", False)),
246
+ mid_pass_previews=cfg.mid_pass_previews and cfg.job_dir is not None,
247
+ on_progress=on_progress,
248
+ target_w=run_tw,
249
+ target_h=run_th,
250
+ infer_fn=infer,
251
+ )
252
+ except JobCancelled:
253
+ if on_progress:
254
+ on_progress({"type": "cancelled", "pct": 0, "message": "cancelled"})
255
+ raise
256
+
257
+ # Alpha: Lanczos only on slim path
258
+ out_alpha = prep.alpha
259
+ return finalize_result(
260
+ prep,
261
+ result,
262
+ on_progress=on_progress,
263
+ model_label=model_name,
264
+ out_alpha=out_alpha,
265
+ )
upscale/benchmark.py ADDED
@@ -0,0 +1,96 @@
1
+ """Tiny-crop inference timing saved to user config."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import time
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from .config import UpscaleConfig
12
+ from .engine import execute
13
+
14
+
15
+ def user_config_dir() -> Path:
16
+ if os.name == "nt":
17
+ base = os.environ.get("APPDATA") or os.path.expanduser("~")
18
+ root = Path(base) / "upscale"
19
+ else:
20
+ root = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "upscale"
21
+ root.mkdir(parents=True, exist_ok=True)
22
+ return root
23
+
24
+
25
+ def benchmark_path() -> Path:
26
+ return user_config_dir() / "benchmark.json"
27
+
28
+
29
+ def load_benchmark_history() -> list[dict[str, Any]]:
30
+ path = benchmark_path()
31
+ if not path.is_file():
32
+ return []
33
+ try:
34
+ data = json.loads(path.read_text(encoding="utf-8"))
35
+ except (json.JSONDecodeError, OSError):
36
+ return []
37
+ if isinstance(data, list):
38
+ return data
39
+ return data.get("runs", [])
40
+
41
+
42
+ def save_benchmark_entry(entry: dict[str, Any]) -> None:
43
+ history = load_benchmark_history()
44
+ history.append(entry)
45
+ history = history[-50:]
46
+ benchmark_path().write_text(json.dumps({"runs": history}, indent=2), encoding="utf-8")
47
+
48
+
49
+ def run_benchmark(
50
+ image: Path | str,
51
+ *,
52
+ model: str = "RealESRGAN_x4plus",
53
+ device: str = "cpu",
54
+ crop_size: int = 64,
55
+ scale: float = 2.0,
56
+ ) -> dict[str, Any]:
57
+ """
58
+ Time a small centered crop upscale (mock-friendly when execute is patched).
59
+ """
60
+ from PIL import Image
61
+
62
+ src = Path(image)
63
+ with Image.open(src) as im:
64
+ w, h = im.size
65
+ cs = min(crop_size, w, h)
66
+ x = max(0, (w - cs) // 2)
67
+ y = max(0, (h - cs) // 2)
68
+ out = user_config_dir() / f"bench_{int(time.time())}.png"
69
+ cfg = UpscaleConfig(
70
+ input=src,
71
+ output=out,
72
+ scale=scale,
73
+ model=model,
74
+ device=device,
75
+ cpu=device == "cpu",
76
+ quiet=True,
77
+ crop=(x, y, cs, cs),
78
+ )
79
+ t0 = time.perf_counter()
80
+ try:
81
+ result = execute(cfg)
82
+ seconds = round(time.perf_counter() - t0, 3)
83
+ entry = {
84
+ "model": model,
85
+ "device": device,
86
+ "crop_size": cs,
87
+ "scale": scale,
88
+ "seconds": seconds,
89
+ "output": str(result),
90
+ "image": str(src),
91
+ }
92
+ save_benchmark_entry(entry)
93
+ return entry
94
+ finally:
95
+ if out.is_file():
96
+ out.unlink(missing_ok=True)