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.
- upscale/__init__.py +30 -0
- upscale/__main__.py +3 -0
- upscale/about.py +168 -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/api/__init__.py +17 -0
- upscale/api/compare_routes.py +243 -0
- upscale/api/deps.py +18 -0
- upscale/api/jobs.py +516 -0
- upscale/api/models_routes.py +107 -0
- upscale/api/system_routes.py +200 -0
- upscale/backends/__init__.py +27 -0
- upscale/backends/onnx_rt.py +265 -0
- upscale/benchmark.py +96 -0
- upscale/checkpoint.py +258 -0
- upscale/cli.py +608 -0
- upscale/compare.py +202 -0
- upscale/config.py +56 -0
- upscale/engine.py +348 -0
- upscale/estimates.py +338 -0
- upscale/filters.py +180 -0
- upscale/help_content.py +94 -0
- upscale/infer_util.py +22 -0
- upscale/io_utils.py +616 -0
- upscale/job_prep.py +318 -0
- upscale/mcp_server.py +287 -0
- upscale/models.py +628 -0
- upscale/naming.py +63 -0
- upscale/pipeline.py +485 -0
- upscale/presets.py +127 -0
- upscale/quality.py +36 -0
- upscale/schema.py +315 -0
- upscale/server.py +1056 -0
- upscale/speed_stats.py +273 -0
- upscale/suggest.py +93 -0
- upscale/system.py +102 -0
- upscale/tiling.py +392 -0
- upscale/web.py +118 -0
- upscale-0.5.1.dist-info/METADATA +149 -0
- upscale-0.5.1.dist-info/RECORD +48 -0
- upscale-0.5.1.dist-info/WHEEL +5 -0
- upscale-0.5.1.dist-info/entry_points.txt +2 -0
- upscale-0.5.1.dist-info/licenses/LICENSE +21 -0
- upscale-0.5.1.dist-info/licenses/NOTICE +6 -0
- upscale-0.5.1.dist-info/top_level.txt +1 -0
upscale/compare.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
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
|
+
variants.append(
|
|
85
|
+
{
|
|
86
|
+
"id": f"filt:{fk}",
|
|
87
|
+
"label": label,
|
|
88
|
+
"kind": "filter",
|
|
89
|
+
"model": base_model,
|
|
90
|
+
"algorithm": base_algorithm,
|
|
91
|
+
"filters": _filters_for_key(fk, filter_amounts),
|
|
92
|
+
}
|
|
93
|
+
)
|
|
94
|
+
return variants
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def compare_variants(
|
|
98
|
+
image: Path,
|
|
99
|
+
out_dir: Path,
|
|
100
|
+
*,
|
|
101
|
+
variants: list[dict[str, Any]],
|
|
102
|
+
crop: CropRect | tuple[int, int, int, int],
|
|
103
|
+
scale: float = 4.0,
|
|
104
|
+
device: str = "auto",
|
|
105
|
+
half: bool = False,
|
|
106
|
+
progress: Callable[[str, float], None] | None = None,
|
|
107
|
+
cancel_event: Any | None = None,
|
|
108
|
+
) -> list[dict]:
|
|
109
|
+
"""
|
|
110
|
+
Upscale the same crop for each variant. Returns list of
|
|
111
|
+
{id, model, label, path, seconds, error, kind}.
|
|
112
|
+
``model`` mirrors ``id`` for API path compatibility.
|
|
113
|
+
|
|
114
|
+
When ``cancel_event`` is set, stops between variants (and mid-variant via
|
|
115
|
+
``execute``) and returns whatever finished so far.
|
|
116
|
+
"""
|
|
117
|
+
import time
|
|
118
|
+
|
|
119
|
+
from .tiling import JobCancelled
|
|
120
|
+
|
|
121
|
+
if isinstance(crop, tuple):
|
|
122
|
+
crop = CropRect(x=crop[0], y=crop[1], w=crop[2], h=crop[3])
|
|
123
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
124
|
+
results: list[dict] = []
|
|
125
|
+
n = max(len(variants), 1)
|
|
126
|
+
for i, var in enumerate(variants):
|
|
127
|
+
if cancel_event is not None and cancel_event.is_set():
|
|
128
|
+
break
|
|
129
|
+
vid = str(var.get("id") or var.get("model") or f"v{i}")
|
|
130
|
+
label = str(var.get("label") or vid)
|
|
131
|
+
kind = str(var.get("kind") or "model")
|
|
132
|
+
if progress:
|
|
133
|
+
progress(f"compare {label}", i / n)
|
|
134
|
+
out = out_dir / f"compare_{_safe_id(vid)}.png"
|
|
135
|
+
t0 = time.perf_counter()
|
|
136
|
+
err = None
|
|
137
|
+
path = None
|
|
138
|
+
try:
|
|
139
|
+
algorithm = var.get("algorithm")
|
|
140
|
+
filt = var.get("filters")
|
|
141
|
+
if not isinstance(filt, FilterSettings):
|
|
142
|
+
filt = FilterSettings.model_validate(filt or {})
|
|
143
|
+
cfg = UpscaleConfig(
|
|
144
|
+
input=image,
|
|
145
|
+
output=out,
|
|
146
|
+
scale=scale,
|
|
147
|
+
model=str(var.get("model") or "RealESRGAN_x4plus"),
|
|
148
|
+
algorithm=algorithm,
|
|
149
|
+
device=device,
|
|
150
|
+
half=half,
|
|
151
|
+
quiet=True,
|
|
152
|
+
crop=(crop.x, crop.y, crop.w, crop.h),
|
|
153
|
+
filters=filt,
|
|
154
|
+
cancel_event=cancel_event,
|
|
155
|
+
)
|
|
156
|
+
path = execute(cfg)
|
|
157
|
+
except JobCancelled:
|
|
158
|
+
err = "cancelled"
|
|
159
|
+
break
|
|
160
|
+
except Exception as exc: # noqa: BLE001 — collect per-variant failures
|
|
161
|
+
err = str(exc)
|
|
162
|
+
results.append(
|
|
163
|
+
{
|
|
164
|
+
"id": vid,
|
|
165
|
+
"model": vid, # back-compat for /api/compare/{id}/{model}
|
|
166
|
+
"label": label,
|
|
167
|
+
"kind": kind,
|
|
168
|
+
"path": str(path) if path else None,
|
|
169
|
+
"seconds": round(time.perf_counter() - t0, 2),
|
|
170
|
+
"error": err,
|
|
171
|
+
}
|
|
172
|
+
)
|
|
173
|
+
if err == "cancelled":
|
|
174
|
+
break
|
|
175
|
+
if progress:
|
|
176
|
+
progress("compare done", 1.0)
|
|
177
|
+
return results
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def compare_models(
|
|
181
|
+
image: Path,
|
|
182
|
+
out_dir: Path,
|
|
183
|
+
*,
|
|
184
|
+
models: list[str],
|
|
185
|
+
crop: CropRect | tuple[int, int, int, int],
|
|
186
|
+
scale: float = 4.0,
|
|
187
|
+
device: str = "auto",
|
|
188
|
+
half: bool = False,
|
|
189
|
+
progress: Callable[[str, float], None] | None = None,
|
|
190
|
+
) -> list[dict]:
|
|
191
|
+
"""Back-compat wrapper: neural models only."""
|
|
192
|
+
variants = build_variants(models=models)
|
|
193
|
+
return compare_variants(
|
|
194
|
+
image,
|
|
195
|
+
out_dir,
|
|
196
|
+
variants=variants,
|
|
197
|
+
crop=crop,
|
|
198
|
+
scale=scale,
|
|
199
|
+
device=device,
|
|
200
|
+
half=half,
|
|
201
|
+
progress=progress,
|
|
202
|
+
)
|
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,348 @@
|
|
|
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 .backends import resolve_backend
|
|
13
|
+
from .config import UpscaleConfig
|
|
14
|
+
from .job_prep import clamp_overlap, finalize_result, prepare_job
|
|
15
|
+
from .models import (
|
|
16
|
+
FAST_MODEL,
|
|
17
|
+
auto_tile_size,
|
|
18
|
+
ensure_model,
|
|
19
|
+
load_model,
|
|
20
|
+
registry_scale,
|
|
21
|
+
resolve_device,
|
|
22
|
+
)
|
|
23
|
+
from .pipeline import compute_passes, resolve_model_scale, run, upscale_alpha
|
|
24
|
+
from .tiling import JobCancelled
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _execute_classical(
|
|
28
|
+
cfg: UpscaleConfig,
|
|
29
|
+
*,
|
|
30
|
+
progress_callback: Callable[[str, float], None] | None = None,
|
|
31
|
+
on_progress: Callable[[dict], None] | None = None,
|
|
32
|
+
echo: Callable[[str], None] | None = None,
|
|
33
|
+
) -> Path:
|
|
34
|
+
"""Torch-free classical / plugin resize path."""
|
|
35
|
+
from .algorithms import resize_with_algorithm
|
|
36
|
+
from .algorithms.classical import backend_name
|
|
37
|
+
from .tiling import JobCancelled as JC
|
|
38
|
+
|
|
39
|
+
prep = prepare_job(cfg, on_progress=on_progress, echo=echo)
|
|
40
|
+
algorithm = str(cfg.algorithm)
|
|
41
|
+
if prep.show:
|
|
42
|
+
prep.log(
|
|
43
|
+
f"Classical algorithm: {algorithm} ({backend_name()}) → "
|
|
44
|
+
f"{prep.target_w}×{prep.target_h}"
|
|
45
|
+
)
|
|
46
|
+
if on_progress:
|
|
47
|
+
on_progress(
|
|
48
|
+
{"type": "progress", "pct": 0.1, "message": f"Classical {algorithm}…"}
|
|
49
|
+
)
|
|
50
|
+
if algorithm == "vectorize_scale":
|
|
51
|
+
h0, w0 = prep.img.shape[:2]
|
|
52
|
+
if max(h0, w0) > 512:
|
|
53
|
+
msg = (
|
|
54
|
+
"Vectorize & scale works best on logos / flat graphics — "
|
|
55
|
+
"large photos may look posterized and take longer."
|
|
56
|
+
)
|
|
57
|
+
if prep.show:
|
|
58
|
+
prep.log(msg)
|
|
59
|
+
if on_progress:
|
|
60
|
+
on_progress({"type": "progress", "pct": 0.12, "message": msg})
|
|
61
|
+
if cfg.cancel_event is not None and cfg.cancel_event.is_set():
|
|
62
|
+
raise JC("cancelled")
|
|
63
|
+
|
|
64
|
+
# Resize padded (or not) canvas; finalize unwraps + exact size.
|
|
65
|
+
from .job_prep import scaled_size
|
|
66
|
+
|
|
67
|
+
tw, th = scaled_size(prep.img.shape[1], prep.img.shape[0], prep.scale)
|
|
68
|
+
if algorithm == "vectorize_scale":
|
|
69
|
+
from .algorithms.plugins.vectorize_scale import vectorize_scale_resize
|
|
70
|
+
from .schema import VectorizeSettings
|
|
71
|
+
|
|
72
|
+
vz = getattr(cfg, "vectorize", None) or VectorizeSettings()
|
|
73
|
+
result = vectorize_scale_resize(
|
|
74
|
+
prep.img,
|
|
75
|
+
tw,
|
|
76
|
+
th,
|
|
77
|
+
engine=vz.engine,
|
|
78
|
+
color_precision=vz.color_precision,
|
|
79
|
+
filter_speckle=vz.filter_speckle,
|
|
80
|
+
corner_threshold=vz.corner_threshold,
|
|
81
|
+
mode=vz.mode,
|
|
82
|
+
max_trace_edge=vz.max_trace_edge,
|
|
83
|
+
)
|
|
84
|
+
else:
|
|
85
|
+
result = resize_with_algorithm(algorithm, prep.img, tw, th)
|
|
86
|
+
|
|
87
|
+
# Keep alpha at the padded geometry; finalize_result unwraps + resizes.
|
|
88
|
+
out_alpha = prep.alpha
|
|
89
|
+
|
|
90
|
+
path = finalize_result(
|
|
91
|
+
prep,
|
|
92
|
+
result,
|
|
93
|
+
on_progress=on_progress,
|
|
94
|
+
model_label=algorithm,
|
|
95
|
+
out_alpha=out_alpha,
|
|
96
|
+
)
|
|
97
|
+
if progress_callback:
|
|
98
|
+
progress_callback("done", 1.0)
|
|
99
|
+
return path
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def resolve_tile(tile: str | int, device, half: bool) -> int:
|
|
103
|
+
if tile == "auto" or tile is None:
|
|
104
|
+
return auto_tile_size(device, half)
|
|
105
|
+
try:
|
|
106
|
+
return int(tile)
|
|
107
|
+
except (TypeError, ValueError) as exc:
|
|
108
|
+
raise click.UsageError(
|
|
109
|
+
f"Invalid --tile value: {tile!r}. Use 'auto' or an integer."
|
|
110
|
+
) from exc
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def blend_parameters(dst_model, src_model, alpha: float) -> None:
|
|
114
|
+
"""Atomically blend ``src`` into ``dst``: dst ← (1-α)·dst + α·src.
|
|
115
|
+
|
|
116
|
+
Builds a full replacement state dict and assigns it only after every
|
|
117
|
+
parameter name and shape matches. Raises on mismatch (caller may warn).
|
|
118
|
+
"""
|
|
119
|
+
import torch
|
|
120
|
+
|
|
121
|
+
a = float(np.clip(alpha, 0.0, 1.0))
|
|
122
|
+
dst_sd = {k: v.detach() for k, v in dst_model.state_dict().items()}
|
|
123
|
+
src_sd = {k: v.detach() for k, v in src_model.state_dict().items()}
|
|
124
|
+
if set(dst_sd) != set(src_sd):
|
|
125
|
+
raise ValueError("blend_parameters: state dict keys differ")
|
|
126
|
+
blended = {}
|
|
127
|
+
for k, v_dst in dst_sd.items():
|
|
128
|
+
v_src = src_sd[k]
|
|
129
|
+
if v_dst.shape != v_src.shape:
|
|
130
|
+
raise ValueError(f"blend_parameters: shape mismatch on {k}")
|
|
131
|
+
if not torch.is_floating_point(v_dst):
|
|
132
|
+
blended[k] = v_dst.clone()
|
|
133
|
+
else:
|
|
134
|
+
blended[k] = v_dst.float().mul(1.0 - a).add_(v_src.float(), alpha=a).to(
|
|
135
|
+
dtype=v_dst.dtype
|
|
136
|
+
)
|
|
137
|
+
dst_model.load_state_dict(blended, strict=True)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _apply_denoise_dni(descriptor, cfg: UpscaleConfig, model_name: str, device, half, log, show) -> None:
|
|
141
|
+
"""Blend general / WDN weights when --denoise is set for the general pair.
|
|
142
|
+
|
|
143
|
+
``denoise=0.5`` (the config default) is a sentinel meaning "leave the base
|
|
144
|
+
weights alone" — not a 50/50 mix. Endpoints: 0 → general, 1 → full WDN.
|
|
145
|
+
"""
|
|
146
|
+
import torch
|
|
147
|
+
|
|
148
|
+
dni = cfg.denoise
|
|
149
|
+
if dni is None or abs(dni - 0.5) < 1e-6:
|
|
150
|
+
return
|
|
151
|
+
general = "realesr-general-x4v3"
|
|
152
|
+
wdn = "realesr-general-wdn-x4v3"
|
|
153
|
+
if model_name not in (general, wdn):
|
|
154
|
+
warnings.warn(
|
|
155
|
+
f"--denoise is only applied for {general}/{wdn}; ignored for {model_name}.",
|
|
156
|
+
stacklevel=2,
|
|
157
|
+
)
|
|
158
|
+
return
|
|
159
|
+
try:
|
|
160
|
+
other_name = wdn if model_name == general else general
|
|
161
|
+
# denoise=1 → full WDN, denoise=0 → full general
|
|
162
|
+
w_wdn = float(np.clip(dni, 0.0, 1.0))
|
|
163
|
+
if model_name == wdn:
|
|
164
|
+
other_path = ensure_model(other_name, cfg.resolved_weights_dir())
|
|
165
|
+
other = load_model(other_path, device, half)
|
|
166
|
+
a = 1.0 - w_wdn # weight of other (general)
|
|
167
|
+
else:
|
|
168
|
+
other_path = ensure_model(wdn, cfg.resolved_weights_dir())
|
|
169
|
+
other = load_model(other_path, device, half)
|
|
170
|
+
a = w_wdn # weight of WDN into general
|
|
171
|
+
# Blend on CPU tensors when possible to avoid two full GPU residents.
|
|
172
|
+
other.model.to("cpu")
|
|
173
|
+
descriptor.model.to("cpu")
|
|
174
|
+
blend_parameters(descriptor.model, other.model, a)
|
|
175
|
+
descriptor.model.to(device)
|
|
176
|
+
if show:
|
|
177
|
+
log(f"Denoise DNI: {model_name} blended with {other_name} @ {dni:.2f}")
|
|
178
|
+
del other
|
|
179
|
+
import gc
|
|
180
|
+
|
|
181
|
+
gc.collect()
|
|
182
|
+
if getattr(device, "type", None) == "cuda":
|
|
183
|
+
torch.cuda.empty_cache()
|
|
184
|
+
except Exception as exc: # noqa: BLE001
|
|
185
|
+
warnings.warn(f"Denoise DNI skipped: {exc}", stacklevel=2)
|
|
186
|
+
try:
|
|
187
|
+
descriptor.model.to(device)
|
|
188
|
+
except Exception: # noqa: BLE001
|
|
189
|
+
pass
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def execute(
|
|
193
|
+
cfg: UpscaleConfig,
|
|
194
|
+
*,
|
|
195
|
+
progress_callback: Callable[[str, float], None] | None = None,
|
|
196
|
+
on_progress: Callable[[dict], None] | None = None,
|
|
197
|
+
echo: Callable[[str], None] | None = None,
|
|
198
|
+
) -> Path:
|
|
199
|
+
"""Run a single upscale from cfg.input → cfg.output. Returns path written."""
|
|
200
|
+
if getattr(cfg, "algorithm", None):
|
|
201
|
+
return _execute_classical(
|
|
202
|
+
cfg, progress_callback=progress_callback, on_progress=on_progress, echo=echo
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
backend = resolve_backend()
|
|
206
|
+
if backend == "onnx":
|
|
207
|
+
from .backends.onnx_rt import execute_onnx
|
|
208
|
+
|
|
209
|
+
return execute_onnx(
|
|
210
|
+
cfg,
|
|
211
|
+
progress_callback=progress_callback,
|
|
212
|
+
on_progress=on_progress,
|
|
213
|
+
echo=echo,
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
import torch
|
|
217
|
+
|
|
218
|
+
prep = prepare_job(cfg, on_progress=on_progress, echo=echo)
|
|
219
|
+
model_name = FAST_MODEL if cfg.fast else cfg.model
|
|
220
|
+
if cfg.fast and prep.show:
|
|
221
|
+
prep.log(f"Fast mode: using model {model_name}")
|
|
222
|
+
|
|
223
|
+
dev = resolve_device(cfg.resolved_device_str())
|
|
224
|
+
half = cfg.half
|
|
225
|
+
if half and getattr(dev, "type", None) == "cpu":
|
|
226
|
+
warnings.warn("--half is ignored on CPU (fp16 not accelerated there).", stacklevel=2)
|
|
227
|
+
half = False
|
|
228
|
+
|
|
229
|
+
tile_int = resolve_tile(cfg.tile, dev, half)
|
|
230
|
+
if prep.show and cfg.tile == "auto":
|
|
231
|
+
prep.log(f"Auto tile size: {tile_int}")
|
|
232
|
+
overlap = clamp_overlap(cfg.overlap, tile_int)
|
|
233
|
+
if overlap != cfg.overlap and prep.show:
|
|
234
|
+
prep.log(f"Overlap clamped to {overlap} (must be < tile/2).")
|
|
235
|
+
|
|
236
|
+
model_scale = registry_scale(model_name)
|
|
237
|
+
descriptor = None
|
|
238
|
+
if prep.scale > 1.0:
|
|
239
|
+
if cfg.cancel_event is not None and cfg.cancel_event.is_set():
|
|
240
|
+
raise JobCancelled("cancelled")
|
|
241
|
+
if prep.show:
|
|
242
|
+
prep.log("Loading model ...")
|
|
243
|
+
if on_progress:
|
|
244
|
+
on_progress(
|
|
245
|
+
{"type": "loading_model", "pct": 0.02, "message": "Loading model…"}
|
|
246
|
+
)
|
|
247
|
+
model_path = ensure_model(model_name, cfg.resolved_weights_dir())
|
|
248
|
+
if cfg.cancel_event is not None and cfg.cancel_event.is_set():
|
|
249
|
+
raise JobCancelled("cancelled")
|
|
250
|
+
descriptor = load_model(model_path, dev, half)
|
|
251
|
+
if cfg.cancel_event is not None and cfg.cancel_event.is_set():
|
|
252
|
+
raise JobCancelled("cancelled")
|
|
253
|
+
model_scale = resolve_model_scale(descriptor, fallback=model_scale)
|
|
254
|
+
_apply_denoise_dni(descriptor, cfg, model_name, dev, half, prep.log, prep.show)
|
|
255
|
+
|
|
256
|
+
if cfg.blend_model and 0.0 < cfg.blend < 1.0:
|
|
257
|
+
try:
|
|
258
|
+
other_path = ensure_model(cfg.blend_model, cfg.resolved_weights_dir())
|
|
259
|
+
other = load_model(other_path, dev, half)
|
|
260
|
+
other.model.to("cpu")
|
|
261
|
+
descriptor.model.to("cpu")
|
|
262
|
+
blend_parameters(descriptor.model, other.model, float(cfg.blend))
|
|
263
|
+
descriptor.model.to(dev)
|
|
264
|
+
if prep.show:
|
|
265
|
+
prep.log(f"Blended with {cfg.blend_model} @ {cfg.blend:.2f}")
|
|
266
|
+
del other
|
|
267
|
+
import gc
|
|
268
|
+
|
|
269
|
+
gc.collect()
|
|
270
|
+
if getattr(dev, "type", None) == "cuda":
|
|
271
|
+
torch.cuda.empty_cache()
|
|
272
|
+
except Exception as exc: # noqa: BLE001
|
|
273
|
+
warnings.warn(f"Model blend skipped: {exc}", stacklevel=2)
|
|
274
|
+
try:
|
|
275
|
+
descriptor.model.to(dev)
|
|
276
|
+
except Exception: # noqa: BLE001
|
|
277
|
+
pass
|
|
278
|
+
|
|
279
|
+
passes = compute_passes(prep.scale, model_scale)
|
|
280
|
+
if prep.show:
|
|
281
|
+
prep.log(
|
|
282
|
+
f"Device: {dev} | Model: {model_name} | "
|
|
283
|
+
f"Scale: {prep.scale:.3f}x | Passes: {passes} | Model scale: {model_scale}x"
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
# Targets for run include seamless pad so unwrap can peel correctly.
|
|
287
|
+
from .job_prep import scaled_size
|
|
288
|
+
|
|
289
|
+
run_tw, run_th = scaled_size(prep.img.shape[1], prep.img.shape[0], prep.scale)
|
|
290
|
+
|
|
291
|
+
try:
|
|
292
|
+
result = run(
|
|
293
|
+
img=prep.img,
|
|
294
|
+
scale=prep.scale,
|
|
295
|
+
descriptor=descriptor,
|
|
296
|
+
device=dev,
|
|
297
|
+
fp16=half,
|
|
298
|
+
tile=tile_int,
|
|
299
|
+
overlap=overlap,
|
|
300
|
+
show_progress=prep.show,
|
|
301
|
+
model_scale=model_scale,
|
|
302
|
+
disk_intermediate_threshold=cfg.disk_intermediate_threshold,
|
|
303
|
+
progress_callback=progress_callback,
|
|
304
|
+
cancel_event=cfg.cancel_event,
|
|
305
|
+
pause_event=cfg.pause_event,
|
|
306
|
+
strength=1.0, # strength applied in finalize against unpadded source
|
|
307
|
+
job_dir=cfg.job_dir,
|
|
308
|
+
resume_from_checkpoint=bool(getattr(cfg, "resume_from_checkpoint", False)),
|
|
309
|
+
mid_pass_previews=cfg.mid_pass_previews and cfg.job_dir is not None,
|
|
310
|
+
on_progress=on_progress,
|
|
311
|
+
target_w=run_tw,
|
|
312
|
+
target_h=run_th,
|
|
313
|
+
)
|
|
314
|
+
except JobCancelled:
|
|
315
|
+
if on_progress:
|
|
316
|
+
on_progress({"type": "cancelled", "pct": 0, "message": "cancelled"})
|
|
317
|
+
raise
|
|
318
|
+
|
|
319
|
+
out_alpha = prep.alpha
|
|
320
|
+
if prep.alpha is not None and prep.original_mode in ("RGBA", "LA") and prep.scale != 1.0:
|
|
321
|
+
if cfg.sr_alpha and descriptor is not None and prep.scale > 1.0:
|
|
322
|
+
if prep.show:
|
|
323
|
+
prep.log("Upscaling alpha via SR ...")
|
|
324
|
+
# Target the padded canvas; finalize unwraps with the same margins as RGB.
|
|
325
|
+
out_alpha = upscale_alpha(
|
|
326
|
+
prep.alpha,
|
|
327
|
+
scale=prep.scale,
|
|
328
|
+
descriptor=descriptor,
|
|
329
|
+
device=dev,
|
|
330
|
+
fp16=half,
|
|
331
|
+
tile=tile_int,
|
|
332
|
+
overlap=overlap,
|
|
333
|
+
show_progress=False,
|
|
334
|
+
model_scale=model_scale,
|
|
335
|
+
disk_intermediate_threshold=cfg.disk_intermediate_threshold,
|
|
336
|
+
cancel_event=cfg.cancel_event,
|
|
337
|
+
pause_event=cfg.pause_event,
|
|
338
|
+
target_w=run_tw,
|
|
339
|
+
target_h=run_th,
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
return finalize_result(
|
|
343
|
+
prep,
|
|
344
|
+
result,
|
|
345
|
+
on_progress=on_progress,
|
|
346
|
+
model_label=model_name,
|
|
347
|
+
out_alpha=out_alpha,
|
|
348
|
+
)
|