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
upscale/compare.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""Crop compare: same region through models, classical algos, or filters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Callable
|
|
7
|
+
|
|
8
|
+
from .config import UpscaleConfig
|
|
9
|
+
from .engine import execute
|
|
10
|
+
from .schema import CropRect, FilterSettings
|
|
11
|
+
|
|
12
|
+
# UI filter key → FilterSettings field
|
|
13
|
+
FILTER_UI_TO_SCHEMA = {
|
|
14
|
+
"denoise": "pre_denoise",
|
|
15
|
+
"jpeg": "jpeg_clean",
|
|
16
|
+
"deblur": "deblur",
|
|
17
|
+
"edge": "edge",
|
|
18
|
+
"grain": "grain",
|
|
19
|
+
"color": "color_contrast",
|
|
20
|
+
"halo": "halo_reduce",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _safe_id(name: str) -> str:
|
|
25
|
+
return "".join(c if c.isalnum() or c in "-_" else "_" for c in name)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _filters_for_key(
|
|
29
|
+
key: str | None, amounts: dict[str, float] | None
|
|
30
|
+
) -> FilterSettings:
|
|
31
|
+
"""Build FilterSettings with at most one UI filter enabled (or all off)."""
|
|
32
|
+
amounts = amounts or {}
|
|
33
|
+
kwargs: dict[str, Any] = {v: 0.0 for v in FILTER_UI_TO_SCHEMA.values()}
|
|
34
|
+
kwargs["seamless"] = False
|
|
35
|
+
kwargs["face_restore"] = 0.0
|
|
36
|
+
if key and key != "none" and key in FILTER_UI_TO_SCHEMA:
|
|
37
|
+
field = FILTER_UI_TO_SCHEMA[key]
|
|
38
|
+
amt = float(amounts.get(key, 0.35))
|
|
39
|
+
kwargs[field] = max(0.0, min(1.0, amt))
|
|
40
|
+
return FilterSettings(**kwargs)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def build_variants(
|
|
44
|
+
*,
|
|
45
|
+
models: list[str] | None = None,
|
|
46
|
+
algorithms: list[str] | None = None,
|
|
47
|
+
filters: list[str] | None = None,
|
|
48
|
+
filter_amounts: dict[str, float] | None = None,
|
|
49
|
+
base_model: str = "RealESRGAN_x4plus",
|
|
50
|
+
base_algorithm: str | None = None,
|
|
51
|
+
) -> list[dict[str, Any]]:
|
|
52
|
+
"""Normalize UI selections into executable compare variants."""
|
|
53
|
+
variants: list[dict[str, Any]] = []
|
|
54
|
+
for m in models or []:
|
|
55
|
+
if not m:
|
|
56
|
+
continue
|
|
57
|
+
variants.append(
|
|
58
|
+
{
|
|
59
|
+
"id": m,
|
|
60
|
+
"label": m,
|
|
61
|
+
"kind": "model",
|
|
62
|
+
"model": m,
|
|
63
|
+
"algorithm": None,
|
|
64
|
+
"filters": FilterSettings(),
|
|
65
|
+
}
|
|
66
|
+
)
|
|
67
|
+
for a in algorithms or []:
|
|
68
|
+
if not a:
|
|
69
|
+
continue
|
|
70
|
+
variants.append(
|
|
71
|
+
{
|
|
72
|
+
"id": f"algo:{a}",
|
|
73
|
+
"label": f"Classical · {a}",
|
|
74
|
+
"kind": "algorithm",
|
|
75
|
+
"model": base_model,
|
|
76
|
+
"algorithm": a,
|
|
77
|
+
"filters": FilterSettings(),
|
|
78
|
+
}
|
|
79
|
+
)
|
|
80
|
+
for fk in filters or []:
|
|
81
|
+
if not fk:
|
|
82
|
+
continue
|
|
83
|
+
label = "No filters" if fk == "none" else f"Filter · {fk}"
|
|
84
|
+
# Filter-only variants use a cheap classical resize so we do not load neural weights.
|
|
85
|
+
algo = base_algorithm if base_algorithm else "lanczos3"
|
|
86
|
+
variants.append(
|
|
87
|
+
{
|
|
88
|
+
"id": f"filt:{fk}",
|
|
89
|
+
"label": label,
|
|
90
|
+
"kind": "filter",
|
|
91
|
+
"model": base_model,
|
|
92
|
+
"algorithm": algo,
|
|
93
|
+
"filters": _filters_for_key(fk, filter_amounts),
|
|
94
|
+
}
|
|
95
|
+
)
|
|
96
|
+
return variants
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def compare_variants(
|
|
100
|
+
image: Path,
|
|
101
|
+
out_dir: Path,
|
|
102
|
+
*,
|
|
103
|
+
variants: list[dict[str, Any]],
|
|
104
|
+
crop: CropRect | tuple[int, int, int, int],
|
|
105
|
+
scale: float = 4.0,
|
|
106
|
+
device: str = "auto",
|
|
107
|
+
half: bool = False,
|
|
108
|
+
progress: Callable[[str, float], None] | None = None,
|
|
109
|
+
cancel_event: Any | None = None,
|
|
110
|
+
) -> list[dict]:
|
|
111
|
+
"""
|
|
112
|
+
Upscale the same crop for each variant. Returns list of
|
|
113
|
+
{id, model, label, path, seconds, error, kind}.
|
|
114
|
+
``model`` mirrors ``id`` for API path compatibility.
|
|
115
|
+
|
|
116
|
+
When ``cancel_event`` is set, stops between variants (and mid-variant via
|
|
117
|
+
``execute``) and returns whatever finished so far.
|
|
118
|
+
"""
|
|
119
|
+
import time
|
|
120
|
+
|
|
121
|
+
from .tiling import JobCancelled
|
|
122
|
+
|
|
123
|
+
if isinstance(crop, tuple):
|
|
124
|
+
crop = CropRect(x=crop[0], y=crop[1], w=crop[2], h=crop[3])
|
|
125
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
126
|
+
results: list[dict] = []
|
|
127
|
+
n = max(len(variants), 1)
|
|
128
|
+
for i, var in enumerate(variants):
|
|
129
|
+
if cancel_event is not None and cancel_event.is_set():
|
|
130
|
+
break
|
|
131
|
+
vid = str(var.get("id") or var.get("model") or f"v{i}")
|
|
132
|
+
label = str(var.get("label") or vid)
|
|
133
|
+
kind = str(var.get("kind") or "model")
|
|
134
|
+
if progress:
|
|
135
|
+
progress(f"compare {label}", i / n)
|
|
136
|
+
out = out_dir / f"compare_{_safe_id(vid)}.png"
|
|
137
|
+
t0 = time.perf_counter()
|
|
138
|
+
err = None
|
|
139
|
+
path = None
|
|
140
|
+
try:
|
|
141
|
+
algorithm = var.get("algorithm")
|
|
142
|
+
filt = var.get("filters")
|
|
143
|
+
if not isinstance(filt, FilterSettings):
|
|
144
|
+
filt = FilterSettings.model_validate(filt or {})
|
|
145
|
+
cfg = UpscaleConfig(
|
|
146
|
+
input=image,
|
|
147
|
+
output=out,
|
|
148
|
+
scale=scale,
|
|
149
|
+
model=str(var.get("model") or "RealESRGAN_x4plus"),
|
|
150
|
+
algorithm=algorithm,
|
|
151
|
+
device=device,
|
|
152
|
+
half=half,
|
|
153
|
+
quiet=True,
|
|
154
|
+
crop=(crop.x, crop.y, crop.w, crop.h),
|
|
155
|
+
filters=filt,
|
|
156
|
+
cancel_event=cancel_event,
|
|
157
|
+
)
|
|
158
|
+
path = execute(cfg)
|
|
159
|
+
except JobCancelled:
|
|
160
|
+
err = "cancelled"
|
|
161
|
+
break
|
|
162
|
+
except Exception as exc: # noqa: BLE001 — collect per-variant failures
|
|
163
|
+
err = str(exc)
|
|
164
|
+
results.append(
|
|
165
|
+
{
|
|
166
|
+
"id": vid,
|
|
167
|
+
"model": vid, # back-compat for /api/compare/{id}/{model}
|
|
168
|
+
"label": label,
|
|
169
|
+
"kind": kind,
|
|
170
|
+
"path": str(path) if path else None,
|
|
171
|
+
"seconds": round(time.perf_counter() - t0, 2),
|
|
172
|
+
"error": err,
|
|
173
|
+
}
|
|
174
|
+
)
|
|
175
|
+
if err == "cancelled":
|
|
176
|
+
break
|
|
177
|
+
if progress:
|
|
178
|
+
progress("compare done", 1.0)
|
|
179
|
+
return results
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def compare_models(
|
|
183
|
+
image: Path,
|
|
184
|
+
out_dir: Path,
|
|
185
|
+
*,
|
|
186
|
+
models: list[str],
|
|
187
|
+
crop: CropRect | tuple[int, int, int, int],
|
|
188
|
+
scale: float = 4.0,
|
|
189
|
+
device: str = "auto",
|
|
190
|
+
half: bool = False,
|
|
191
|
+
progress: Callable[[str, float], None] | None = None,
|
|
192
|
+
) -> list[dict]:
|
|
193
|
+
"""Back-compat wrapper: neural models only."""
|
|
194
|
+
variants = build_variants(models=models)
|
|
195
|
+
return compare_variants(
|
|
196
|
+
image,
|
|
197
|
+
out_dir,
|
|
198
|
+
variants=variants,
|
|
199
|
+
crop=crop,
|
|
200
|
+
scale=scale,
|
|
201
|
+
device=device,
|
|
202
|
+
half=half,
|
|
203
|
+
progress=progress,
|
|
204
|
+
)
|
upscale/config.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Shared configuration for CLI and web UI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .models import DEFAULT_WEIGHTS_DIR
|
|
9
|
+
from .pipeline import DEFAULT_DISK_INTERMEDIATE_THRESHOLD
|
|
10
|
+
from .schema import FilterSettings, NamePattern, VectorizeSettings
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class UpscaleConfig:
|
|
15
|
+
input: Path | None = None
|
|
16
|
+
output: Path | None = None
|
|
17
|
+
scale: float | None = None
|
|
18
|
+
target_size: int | None = None
|
|
19
|
+
width: int | None = None
|
|
20
|
+
height: int | None = None
|
|
21
|
+
model: str = "RealESRGAN_x4plus"
|
|
22
|
+
algorithm: str | None = None
|
|
23
|
+
tile: str | int = "auto"
|
|
24
|
+
overlap: int = 32
|
|
25
|
+
device: str = "auto"
|
|
26
|
+
cpu: bool = False
|
|
27
|
+
half: bool = False
|
|
28
|
+
weights_dir: Path | None = None
|
|
29
|
+
tiff_compression: str = "lzw"
|
|
30
|
+
quiet: bool = False
|
|
31
|
+
fast: bool = False
|
|
32
|
+
sr_alpha: bool = False
|
|
33
|
+
disk_intermediate_threshold: int = DEFAULT_DISK_INTERMEDIATE_THRESHOLD
|
|
34
|
+
# Phase 1+
|
|
35
|
+
crop: tuple[int, int, int, int] | None = None
|
|
36
|
+
strength: float = 1.0
|
|
37
|
+
denoise: float = 0.5
|
|
38
|
+
blend_model: str | None = None
|
|
39
|
+
blend: float = 0.5
|
|
40
|
+
format: str = "auto"
|
|
41
|
+
quality: int = 90
|
|
42
|
+
image_meta: object | None = None # io_utils.ImageMeta, set by engine on load
|
|
43
|
+
filters: FilterSettings = field(default_factory=FilterSettings)
|
|
44
|
+
vectorize: VectorizeSettings = field(default_factory=VectorizeSettings)
|
|
45
|
+
name_pattern: NamePattern | None = None
|
|
46
|
+
job_dir: Path | None = None
|
|
47
|
+
resume_from_checkpoint: bool = False
|
|
48
|
+
mid_pass_previews: bool = True
|
|
49
|
+
cancel_event: object | None = None
|
|
50
|
+
pause_event: object | None = None
|
|
51
|
+
|
|
52
|
+
def resolved_weights_dir(self) -> Path:
|
|
53
|
+
return self.weights_dir or DEFAULT_WEIGHTS_DIR
|
|
54
|
+
|
|
55
|
+
def resolved_device_str(self) -> str:
|
|
56
|
+
return "cpu" if self.cpu else self.device
|
upscale/engine.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
"""Shared upscale execution path for CLI, batch, and web UI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import warnings
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Callable
|
|
8
|
+
|
|
9
|
+
import click
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
from .alpha_policy import upsample_alpha
|
|
13
|
+
from .backends import resolve_backend
|
|
14
|
+
from .config import UpscaleConfig
|
|
15
|
+
from .job_prep import clamp_overlap, finalize_result, prepare_job
|
|
16
|
+
from .models import (
|
|
17
|
+
FAST_MODEL,
|
|
18
|
+
_model_param_bytes,
|
|
19
|
+
auto_tile_size,
|
|
20
|
+
ensure_model,
|
|
21
|
+
load_model,
|
|
22
|
+
registry_scale,
|
|
23
|
+
resolve_device,
|
|
24
|
+
)
|
|
25
|
+
from .pipeline import compute_passes, resolve_model_scale, run
|
|
26
|
+
from .tiling import JobCancelled
|
|
27
|
+
from .weight_blend import (
|
|
28
|
+
blend_parameters, # noqa: F401 — re-export for tests
|
|
29
|
+
blend_secondary_into,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _execute_classical(
|
|
34
|
+
cfg: UpscaleConfig,
|
|
35
|
+
*,
|
|
36
|
+
progress_callback: Callable[[str, float], None] | None = None,
|
|
37
|
+
on_progress: Callable[[dict], None] | None = None,
|
|
38
|
+
echo: Callable[[str], None] | None = None,
|
|
39
|
+
) -> Path:
|
|
40
|
+
"""Torch-free classical / plugin resize path."""
|
|
41
|
+
from .algorithms import resize_with_algorithm
|
|
42
|
+
from .algorithms.classical import backend_name
|
|
43
|
+
from .tiling import JobCancelled as JC
|
|
44
|
+
|
|
45
|
+
prep = prepare_job(cfg, on_progress=on_progress, echo=echo)
|
|
46
|
+
algorithm = str(cfg.algorithm)
|
|
47
|
+
if prep.show:
|
|
48
|
+
prep.log(
|
|
49
|
+
f"Classical algorithm: {algorithm} ({backend_name()}) → "
|
|
50
|
+
f"{prep.target_w}×{prep.target_h}"
|
|
51
|
+
)
|
|
52
|
+
if on_progress:
|
|
53
|
+
on_progress(
|
|
54
|
+
{"type": "progress", "pct": 0.1, "message": f"Classical {algorithm}…"}
|
|
55
|
+
)
|
|
56
|
+
if algorithm == "vectorize_scale":
|
|
57
|
+
h0, w0 = prep.img.shape[:2]
|
|
58
|
+
if max(h0, w0) > 512:
|
|
59
|
+
msg = (
|
|
60
|
+
"Vectorize & scale works best on logos / flat graphics — "
|
|
61
|
+
"large photos may look posterized and take longer."
|
|
62
|
+
)
|
|
63
|
+
if prep.show:
|
|
64
|
+
prep.log(msg)
|
|
65
|
+
if on_progress:
|
|
66
|
+
on_progress({"type": "progress", "pct": 0.12, "message": msg})
|
|
67
|
+
if cfg.cancel_event is not None and cfg.cancel_event.is_set():
|
|
68
|
+
raise JC("cancelled")
|
|
69
|
+
|
|
70
|
+
# Resize padded (or not) canvas; finalize unwraps + exact size.
|
|
71
|
+
from .job_prep import scaled_size
|
|
72
|
+
|
|
73
|
+
tw, th = scaled_size(prep.img.shape[1], prep.img.shape[0], prep.scale)
|
|
74
|
+
if algorithm == "vectorize_scale":
|
|
75
|
+
from .algorithms.plugins.vectorize_scale import vectorize_scale_resize
|
|
76
|
+
from .schema import VectorizeSettings
|
|
77
|
+
|
|
78
|
+
vz = getattr(cfg, "vectorize", None) or VectorizeSettings()
|
|
79
|
+
result = vectorize_scale_resize(
|
|
80
|
+
prep.img,
|
|
81
|
+
tw,
|
|
82
|
+
th,
|
|
83
|
+
engine=vz.engine,
|
|
84
|
+
color_precision=vz.color_precision,
|
|
85
|
+
filter_speckle=vz.filter_speckle,
|
|
86
|
+
corner_threshold=vz.corner_threshold,
|
|
87
|
+
mode=vz.mode,
|
|
88
|
+
max_trace_edge=vz.max_trace_edge,
|
|
89
|
+
)
|
|
90
|
+
else:
|
|
91
|
+
result = resize_with_algorithm(algorithm, prep.img, tw, th)
|
|
92
|
+
|
|
93
|
+
# Keep alpha at the padded geometry; finalize_result unwraps + resizes.
|
|
94
|
+
out_alpha = prep.alpha
|
|
95
|
+
|
|
96
|
+
path = finalize_result(
|
|
97
|
+
prep,
|
|
98
|
+
result,
|
|
99
|
+
on_progress=on_progress,
|
|
100
|
+
model_label=algorithm,
|
|
101
|
+
out_alpha=out_alpha,
|
|
102
|
+
)
|
|
103
|
+
if progress_callback:
|
|
104
|
+
progress_callback("done", 1.0)
|
|
105
|
+
return path
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def resolve_tile(
|
|
109
|
+
tile: str | int,
|
|
110
|
+
device,
|
|
111
|
+
half: bool,
|
|
112
|
+
*,
|
|
113
|
+
model_bytes: int | None = None,
|
|
114
|
+
) -> int:
|
|
115
|
+
if tile == "auto" or tile is None:
|
|
116
|
+
return auto_tile_size(device, half, model_bytes=model_bytes)
|
|
117
|
+
try:
|
|
118
|
+
return int(tile)
|
|
119
|
+
except (TypeError, ValueError) as exc:
|
|
120
|
+
raise click.UsageError(
|
|
121
|
+
f"Invalid --tile value: {tile!r}. Use 'auto' or an integer."
|
|
122
|
+
) from exc
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _apply_denoise_dni(descriptor, cfg: UpscaleConfig, model_name: str, device, half, log, show) -> None:
|
|
126
|
+
"""Blend general / WDN weights when --denoise is set for the general pair.
|
|
127
|
+
|
|
128
|
+
``denoise=0.5`` (the config default) is a sentinel meaning "leave the base
|
|
129
|
+
weights alone" — not a 50/50 mix. Endpoints: 0 → general, 1 → full WDN.
|
|
130
|
+
"""
|
|
131
|
+
dni = cfg.denoise
|
|
132
|
+
if dni is None or abs(dni - 0.5) < 1e-6:
|
|
133
|
+
return
|
|
134
|
+
general = "realesr-general-x4v3"
|
|
135
|
+
wdn = "realesr-general-wdn-x4v3"
|
|
136
|
+
if model_name not in (general, wdn):
|
|
137
|
+
warnings.warn(
|
|
138
|
+
f"--denoise is only applied for {general}/{wdn}; ignored for {model_name}.",
|
|
139
|
+
stacklevel=2,
|
|
140
|
+
)
|
|
141
|
+
return
|
|
142
|
+
other_name = wdn if model_name == general else general
|
|
143
|
+
w_wdn = float(np.clip(dni, 0.0, 1.0))
|
|
144
|
+
# denoise=1 → full WDN into general; when already on WDN, blend toward general.
|
|
145
|
+
a = (1.0 - w_wdn) if model_name == wdn else w_wdn
|
|
146
|
+
blend_secondary_into(
|
|
147
|
+
descriptor,
|
|
148
|
+
other_name=other_name,
|
|
149
|
+
alpha=a,
|
|
150
|
+
weights_dir=cfg.resolved_weights_dir(),
|
|
151
|
+
device=device,
|
|
152
|
+
half=half,
|
|
153
|
+
ensure_model=ensure_model,
|
|
154
|
+
load_model=load_model,
|
|
155
|
+
log=log,
|
|
156
|
+
show=show,
|
|
157
|
+
label=f"Denoise DNI ({model_name})",
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def execute(
|
|
162
|
+
cfg: UpscaleConfig,
|
|
163
|
+
*,
|
|
164
|
+
progress_callback: Callable[[str, float], None] | None = None,
|
|
165
|
+
on_progress: Callable[[dict], None] | None = None,
|
|
166
|
+
echo: Callable[[str], None] | None = None,
|
|
167
|
+
) -> Path:
|
|
168
|
+
"""Run a single upscale from cfg.input → cfg.output. Returns path written."""
|
|
169
|
+
if getattr(cfg, "algorithm", None):
|
|
170
|
+
return _execute_classical(
|
|
171
|
+
cfg, progress_callback=progress_callback, on_progress=on_progress, echo=echo
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
backend = resolve_backend()
|
|
175
|
+
if backend == "onnx":
|
|
176
|
+
from .backends.onnx_rt import execute_onnx
|
|
177
|
+
|
|
178
|
+
return execute_onnx(
|
|
179
|
+
cfg,
|
|
180
|
+
progress_callback=progress_callback,
|
|
181
|
+
on_progress=on_progress,
|
|
182
|
+
echo=echo,
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
prep = prepare_job(cfg, on_progress=on_progress, echo=echo)
|
|
187
|
+
model_name = FAST_MODEL if cfg.fast else cfg.model
|
|
188
|
+
if cfg.fast and prep.show:
|
|
189
|
+
prep.log(f"Fast mode: using model {model_name}")
|
|
190
|
+
|
|
191
|
+
dev = resolve_device(cfg.resolved_device_str())
|
|
192
|
+
half = cfg.half
|
|
193
|
+
if half and getattr(dev, "type", None) == "cpu":
|
|
194
|
+
warnings.warn("--half is ignored on CPU (fp16 not accelerated there).", stacklevel=2)
|
|
195
|
+
half = False
|
|
196
|
+
|
|
197
|
+
model_scale = registry_scale(model_name)
|
|
198
|
+
descriptor = None
|
|
199
|
+
model_path = None
|
|
200
|
+
if prep.scale > 1.0:
|
|
201
|
+
if cfg.cancel_event is not None and cfg.cancel_event.is_set():
|
|
202
|
+
raise JobCancelled("cancelled")
|
|
203
|
+
if prep.show:
|
|
204
|
+
prep.log("Loading model ...")
|
|
205
|
+
if on_progress:
|
|
206
|
+
on_progress(
|
|
207
|
+
{"type": "loading_model", "pct": 0.02, "message": "Loading model…"}
|
|
208
|
+
)
|
|
209
|
+
model_path = ensure_model(model_name, cfg.resolved_weights_dir())
|
|
210
|
+
if cfg.cancel_event is not None and cfg.cancel_event.is_set():
|
|
211
|
+
raise JobCancelled("cancelled")
|
|
212
|
+
descriptor = load_model(model_path, dev, half)
|
|
213
|
+
if cfg.cancel_event is not None and cfg.cancel_event.is_set():
|
|
214
|
+
raise JobCancelled("cancelled")
|
|
215
|
+
model_scale = resolve_model_scale(descriptor, fallback=model_scale)
|
|
216
|
+
_apply_denoise_dni(descriptor, cfg, model_name, dev, half, prep.log, prep.show)
|
|
217
|
+
|
|
218
|
+
# Auto-tile after load: cuda.mem_get_info free already excludes resident
|
|
219
|
+
# weights. Pass _model_param_bytes only as a soft headroom hint (15% in
|
|
220
|
+
# auto_tile_size) so large models leave room for activations.
|
|
221
|
+
resident = _model_param_bytes(dev) if descriptor is not None else 0
|
|
222
|
+
tile_int = resolve_tile(
|
|
223
|
+
cfg.tile,
|
|
224
|
+
dev,
|
|
225
|
+
half,
|
|
226
|
+
model_bytes=resident if resident > 0 else None,
|
|
227
|
+
)
|
|
228
|
+
if prep.show and cfg.tile == "auto":
|
|
229
|
+
prep.log(f"Auto tile size: {tile_int}")
|
|
230
|
+
overlap = clamp_overlap(cfg.overlap, tile_int)
|
|
231
|
+
if overlap != cfg.overlap and prep.show:
|
|
232
|
+
prep.log(f"Overlap clamped to {overlap} (must be < tile/2).")
|
|
233
|
+
|
|
234
|
+
if descriptor is not None and cfg.blend_model and 0.0 < cfg.blend < 1.0:
|
|
235
|
+
blend_secondary_into(
|
|
236
|
+
descriptor,
|
|
237
|
+
other_name=cfg.blend_model,
|
|
238
|
+
alpha=float(cfg.blend),
|
|
239
|
+
weights_dir=cfg.resolved_weights_dir(),
|
|
240
|
+
device=dev,
|
|
241
|
+
half=half,
|
|
242
|
+
ensure_model=ensure_model,
|
|
243
|
+
load_model=load_model,
|
|
244
|
+
log=prep.log,
|
|
245
|
+
show=prep.show,
|
|
246
|
+
label="Model blend",
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
passes = compute_passes(prep.scale, model_scale)
|
|
250
|
+
if prep.show:
|
|
251
|
+
prep.log(
|
|
252
|
+
f"Device: {dev} | Model: {model_name} | "
|
|
253
|
+
f"Scale: {prep.scale:.3f}x | Passes: {passes} | Model scale: {model_scale}x"
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
# Targets for run include seamless pad so unwrap can peel correctly.
|
|
257
|
+
from .job_prep import scaled_size
|
|
258
|
+
|
|
259
|
+
run_tw, run_th = scaled_size(prep.img.shape[1], prep.img.shape[0], prep.scale)
|
|
260
|
+
|
|
261
|
+
try:
|
|
262
|
+
result = run(
|
|
263
|
+
img=prep.img,
|
|
264
|
+
scale=prep.scale,
|
|
265
|
+
descriptor=descriptor,
|
|
266
|
+
device=dev,
|
|
267
|
+
fp16=half,
|
|
268
|
+
tile=tile_int,
|
|
269
|
+
overlap=overlap,
|
|
270
|
+
show_progress=prep.show,
|
|
271
|
+
model_scale=model_scale,
|
|
272
|
+
disk_intermediate_threshold=cfg.disk_intermediate_threshold,
|
|
273
|
+
progress_callback=progress_callback,
|
|
274
|
+
cancel_event=cfg.cancel_event,
|
|
275
|
+
pause_event=cfg.pause_event,
|
|
276
|
+
strength=1.0, # strength applied in finalize against unpadded source
|
|
277
|
+
job_dir=cfg.job_dir,
|
|
278
|
+
resume_from_checkpoint=bool(getattr(cfg, "resume_from_checkpoint", False)),
|
|
279
|
+
mid_pass_previews=cfg.mid_pass_previews and cfg.job_dir is not None,
|
|
280
|
+
on_progress=on_progress,
|
|
281
|
+
target_w=run_tw,
|
|
282
|
+
target_h=run_th,
|
|
283
|
+
)
|
|
284
|
+
except JobCancelled:
|
|
285
|
+
if on_progress:
|
|
286
|
+
on_progress({"type": "cancelled", "pct": 0, "message": "cancelled"})
|
|
287
|
+
raise
|
|
288
|
+
|
|
289
|
+
out_alpha = prep.alpha
|
|
290
|
+
if prep.alpha is not None and prep.original_mode in ("RGBA", "LA") and prep.scale != 1.0:
|
|
291
|
+
if cfg.sr_alpha and descriptor is not None and prep.scale > 1.0:
|
|
292
|
+
if prep.show:
|
|
293
|
+
prep.log("Upscaling alpha via SR ...")
|
|
294
|
+
# Target the padded canvas when SR; finalize unwraps with the same margins as RGB.
|
|
295
|
+
# Without --sr-alpha, Lanczos to padded size keeps unwrap aligned.
|
|
296
|
+
out_alpha = upsample_alpha(
|
|
297
|
+
prep.alpha,
|
|
298
|
+
scale=prep.scale,
|
|
299
|
+
target_w=run_tw,
|
|
300
|
+
target_h=run_th,
|
|
301
|
+
sr_alpha=bool(cfg.sr_alpha),
|
|
302
|
+
descriptor=descriptor,
|
|
303
|
+
device=dev,
|
|
304
|
+
fp16=half,
|
|
305
|
+
tile=tile_int,
|
|
306
|
+
overlap=overlap,
|
|
307
|
+
show_progress=False,
|
|
308
|
+
model_scale=model_scale,
|
|
309
|
+
disk_intermediate_threshold=cfg.disk_intermediate_threshold,
|
|
310
|
+
cancel_event=cfg.cancel_event,
|
|
311
|
+
pause_event=cfg.pause_event,
|
|
312
|
+
allow_sr=True,
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
return finalize_result(
|
|
316
|
+
prep,
|
|
317
|
+
result,
|
|
318
|
+
on_progress=on_progress,
|
|
319
|
+
model_label=model_name,
|
|
320
|
+
out_alpha=out_alpha,
|
|
321
|
+
)
|