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
|
@@ -0,0 +1,291 @@
|
|
|
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
|
+
# Prefer CUDA free VRAM when ORT uses a CUDA EP; else host RAM heuristic.
|
|
163
|
+
avail = None
|
|
164
|
+
try:
|
|
165
|
+
import torch
|
|
166
|
+
|
|
167
|
+
if torch.cuda.is_available():
|
|
168
|
+
free_b, _ = torch.cuda.mem_get_info()
|
|
169
|
+
avail = int(free_b * 0.50)
|
|
170
|
+
except Exception: # noqa: BLE001
|
|
171
|
+
avail = None
|
|
172
|
+
if avail is None:
|
|
173
|
+
try:
|
|
174
|
+
import psutil
|
|
175
|
+
|
|
176
|
+
avail = int(psutil.virtual_memory().available * 0.25)
|
|
177
|
+
except Exception: # noqa: BLE001
|
|
178
|
+
avail = 512 * 1024 * 1024
|
|
179
|
+
bytes_per_px = 8000
|
|
180
|
+
tile_guess = int(max(128, min(512, (avail / bytes_per_px) ** 0.5)))
|
|
181
|
+
tile_int = (tile_guess // 64) * 64 or 256
|
|
182
|
+
else:
|
|
183
|
+
tile_int = int(cfg.tile)
|
|
184
|
+
overlap = clamp_overlap(cfg.overlap, tile_int)
|
|
185
|
+
|
|
186
|
+
infer = None
|
|
187
|
+
provider = "cpu"
|
|
188
|
+
if prep.scale > 1.0:
|
|
189
|
+
path = ensure_onnx_model(model_name, wdir)
|
|
190
|
+
if prep.show:
|
|
191
|
+
prep.log(f"ONNX model: {path.name}")
|
|
192
|
+
session, provider = _ort_session(path)
|
|
193
|
+
input_name = session.get_inputs()[0].name
|
|
194
|
+
infer = make_onnx_infer_fn(session, input_name)
|
|
195
|
+
|
|
196
|
+
passes = compute_passes(prep.scale, model_scale) if prep.scale > 1 else 0
|
|
197
|
+
if prep.show:
|
|
198
|
+
prep.log(
|
|
199
|
+
f"Backend: onnx/{provider} | Model: {model_name} | "
|
|
200
|
+
f"Scale: {prep.scale:.3f}x | Passes: {passes} | Tile: {tile_int}"
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
if cfg.blend_model:
|
|
204
|
+
warnings.warn(
|
|
205
|
+
"blend_model weight interpolation needs Torch; ignored on ONNX. "
|
|
206
|
+
"Export a pre-blended ONNX or use the Torch backend.",
|
|
207
|
+
stacklevel=2,
|
|
208
|
+
)
|
|
209
|
+
if cfg.denoise is not None and abs(cfg.denoise - 0.5) > 1e-6:
|
|
210
|
+
# Soft parity: if the WDN twin is on disk, switch to it when denoise>0.5.
|
|
211
|
+
wdn = "realesr-general-wdn-x4v3"
|
|
212
|
+
general = "realesr-general-x4v3"
|
|
213
|
+
if model_name in (general, wdn) and cfg.denoise > 0.5:
|
|
214
|
+
alt = onnx_path_for(wdn, wdir)
|
|
215
|
+
if alt.is_file() and model_name != wdn:
|
|
216
|
+
model_name = wdn
|
|
217
|
+
path = alt
|
|
218
|
+
session, provider = _ort_session(path)
|
|
219
|
+
input_name = session.get_inputs()[0].name
|
|
220
|
+
infer = make_onnx_infer_fn(session, input_name)
|
|
221
|
+
if prep.show:
|
|
222
|
+
prep.log(f"ONNX denoise>0.5 → switched to {wdn}")
|
|
223
|
+
else:
|
|
224
|
+
warnings.warn(
|
|
225
|
+
"--denoise DNI is not supported on ONNX (no WDN twin on disk); ignored.",
|
|
226
|
+
stacklevel=2,
|
|
227
|
+
)
|
|
228
|
+
else:
|
|
229
|
+
warnings.warn(
|
|
230
|
+
"--denoise DNI is not supported on the ONNX backend yet; ignored.",
|
|
231
|
+
stacklevel=2,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
from ..job_prep import scaled_size
|
|
235
|
+
|
|
236
|
+
run_tw, run_th = scaled_size(prep.img.shape[1], prep.img.shape[0], prep.scale)
|
|
237
|
+
|
|
238
|
+
try:
|
|
239
|
+
result = run(
|
|
240
|
+
img=prep.img,
|
|
241
|
+
scale=prep.scale,
|
|
242
|
+
descriptor=None,
|
|
243
|
+
device=type("D", (), {"type": "cpu"})(),
|
|
244
|
+
fp16=False,
|
|
245
|
+
tile=tile_int,
|
|
246
|
+
overlap=overlap,
|
|
247
|
+
show_progress=prep.show,
|
|
248
|
+
model_scale=model_scale,
|
|
249
|
+
disk_intermediate_threshold=cfg.disk_intermediate_threshold,
|
|
250
|
+
progress_callback=progress_callback,
|
|
251
|
+
cancel_event=cfg.cancel_event,
|
|
252
|
+
pause_event=cfg.pause_event,
|
|
253
|
+
strength=1.0,
|
|
254
|
+
job_dir=cfg.job_dir,
|
|
255
|
+
resume_from_checkpoint=bool(getattr(cfg, "resume_from_checkpoint", False)),
|
|
256
|
+
mid_pass_previews=cfg.mid_pass_previews and cfg.job_dir is not None,
|
|
257
|
+
on_progress=on_progress,
|
|
258
|
+
target_w=run_tw,
|
|
259
|
+
target_h=run_th,
|
|
260
|
+
infer_fn=infer,
|
|
261
|
+
)
|
|
262
|
+
except JobCancelled:
|
|
263
|
+
if on_progress:
|
|
264
|
+
on_progress({"type": "cancelled", "pct": 0, "message": "cancelled"})
|
|
265
|
+
raise
|
|
266
|
+
|
|
267
|
+
# Alpha: Lanczos only on slim/ONNX path (sr_alpha not supported — see docs/help/backends.md).
|
|
268
|
+
out_alpha = prep.alpha
|
|
269
|
+
if prep.alpha is not None and prep.original_mode in ("RGBA", "LA") and prep.scale != 1.0:
|
|
270
|
+
from ..alpha_policy import upsample_alpha
|
|
271
|
+
|
|
272
|
+
if cfg.sr_alpha:
|
|
273
|
+
warnings.warn(
|
|
274
|
+
"--sr-alpha is not supported on the ONNX backend; using Lanczos for alpha.",
|
|
275
|
+
stacklevel=2,
|
|
276
|
+
)
|
|
277
|
+
out_alpha = upsample_alpha(
|
|
278
|
+
prep.alpha,
|
|
279
|
+
scale=prep.scale,
|
|
280
|
+
target_w=run_tw,
|
|
281
|
+
target_h=run_th,
|
|
282
|
+
sr_alpha=False,
|
|
283
|
+
allow_sr=False,
|
|
284
|
+
)
|
|
285
|
+
return finalize_result(
|
|
286
|
+
prep,
|
|
287
|
+
result,
|
|
288
|
+
on_progress=on_progress,
|
|
289
|
+
model_label=model_name,
|
|
290
|
+
out_alpha=out_alpha,
|
|
291
|
+
)
|
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)
|
upscale/checkpoint.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""Strip checkpoints for resumable long jobs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from dataclasses import asdict, dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class StripCheckpoint:
|
|
16
|
+
"""Flush-row progress for strip-based tiled_upscale."""
|
|
17
|
+
|
|
18
|
+
pass_index: int
|
|
19
|
+
flush_row: int
|
|
20
|
+
out_h: int
|
|
21
|
+
out_w: int
|
|
22
|
+
channels: int
|
|
23
|
+
model_scale: int
|
|
24
|
+
tile: int
|
|
25
|
+
overlap: int
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def checkpoint_dir(job_dir: Path | str) -> Path:
|
|
29
|
+
d = Path(job_dir) / "checkpoints"
|
|
30
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
31
|
+
return d
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def list_checkpoints(job_dir: Path | str) -> list[dict[str, Any]]:
|
|
35
|
+
root = checkpoint_dir(job_dir)
|
|
36
|
+
items: list[dict[str, Any]] = []
|
|
37
|
+
strip = root / "strip.json"
|
|
38
|
+
if strip.is_file():
|
|
39
|
+
try:
|
|
40
|
+
items.append(json.loads(strip.read_text(encoding="utf-8")))
|
|
41
|
+
except (OSError, json.JSONDecodeError, UnicodeDecodeError, TypeError, ValueError):
|
|
42
|
+
# Corrupt leftover — ignore rather than crash API / resume listing.
|
|
43
|
+
pass
|
|
44
|
+
return items
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _fsync_path(path: Path) -> None:
|
|
48
|
+
try:
|
|
49
|
+
with open(path, "rb") as f:
|
|
50
|
+
os.fsync(f.fileno())
|
|
51
|
+
except OSError:
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def save_strip_checkpoint(
|
|
56
|
+
job_dir: Path | str,
|
|
57
|
+
meta: StripCheckpoint,
|
|
58
|
+
*,
|
|
59
|
+
result_mmap_path: Path | None = None,
|
|
60
|
+
carry_canvas: np.ndarray | None = None,
|
|
61
|
+
carry_weight: np.ndarray | None = None,
|
|
62
|
+
carry_top: int = 0,
|
|
63
|
+
) -> Path:
|
|
64
|
+
"""Save flush_row + optional carry buffers after a strip band.
|
|
65
|
+
|
|
66
|
+
Carry is written first (temp → replace), then strip.json is replaced
|
|
67
|
+
atomically so a crash cannot leave metadata ahead of the carry file.
|
|
68
|
+
"""
|
|
69
|
+
root = checkpoint_dir(job_dir)
|
|
70
|
+
meta_path = root / "strip.json"
|
|
71
|
+
carry_path = root / "strip_carry.npz"
|
|
72
|
+
payload = asdict(meta)
|
|
73
|
+
payload["carry_top"] = carry_top
|
|
74
|
+
payload["result_mmap"] = str(result_mmap_path) if result_mmap_path else None
|
|
75
|
+
payload["has_carry"] = carry_canvas is not None and carry_weight is not None
|
|
76
|
+
|
|
77
|
+
if carry_canvas is not None and carry_weight is not None:
|
|
78
|
+
tmp_carry = root / "strip_carry.npz.tmp"
|
|
79
|
+
# Uncompressed .npy archive — faster than zip on the hot path.
|
|
80
|
+
np.savez(
|
|
81
|
+
tmp_carry,
|
|
82
|
+
canvas=carry_canvas,
|
|
83
|
+
weight=carry_weight,
|
|
84
|
+
carry_top=np.array([carry_top], dtype=np.int64),
|
|
85
|
+
)
|
|
86
|
+
# np.savez may append .npz
|
|
87
|
+
if not tmp_carry.is_file() and (root / "strip_carry.npz.tmp.npz").is_file():
|
|
88
|
+
(root / "strip_carry.npz.tmp.npz").replace(tmp_carry)
|
|
89
|
+
_fsync_path(tmp_carry)
|
|
90
|
+
os.replace(tmp_carry, carry_path)
|
|
91
|
+
_fsync_path(carry_path)
|
|
92
|
+
elif carry_path.is_file():
|
|
93
|
+
carry_path.unlink(missing_ok=True)
|
|
94
|
+
|
|
95
|
+
tmp_meta = root / "strip.json.tmp"
|
|
96
|
+
tmp_meta.write_text(json.dumps(payload, indent=2), encoding="utf-8")
|
|
97
|
+
_fsync_path(tmp_meta)
|
|
98
|
+
os.replace(tmp_meta, meta_path)
|
|
99
|
+
return meta_path
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def load_strip_checkpoint(
|
|
103
|
+
job_dir: Path | str,
|
|
104
|
+
*,
|
|
105
|
+
expect_tile: int | None = None,
|
|
106
|
+
expect_overlap: int | None = None,
|
|
107
|
+
expect_pass: int | None = None,
|
|
108
|
+
expect_out_h: int | None = None,
|
|
109
|
+
expect_out_w: int | None = None,
|
|
110
|
+
expect_channels: int | None = None,
|
|
111
|
+
expect_model_scale: int | None = None,
|
|
112
|
+
) -> tuple[StripCheckpoint, dict[str, Any]] | None:
|
|
113
|
+
"""Load strip checkpoint; return None if missing or inconsistent."""
|
|
114
|
+
root = checkpoint_dir(job_dir)
|
|
115
|
+
meta_path = root / "strip.json"
|
|
116
|
+
if not meta_path.is_file():
|
|
117
|
+
return None
|
|
118
|
+
try:
|
|
119
|
+
raw = json.loads(meta_path.read_text(encoding="utf-8"))
|
|
120
|
+
meta = StripCheckpoint(
|
|
121
|
+
pass_index=int(raw["pass_index"]),
|
|
122
|
+
flush_row=int(raw["flush_row"]),
|
|
123
|
+
out_h=int(raw["out_h"]),
|
|
124
|
+
out_w=int(raw["out_w"]),
|
|
125
|
+
channels=int(raw["channels"]),
|
|
126
|
+
model_scale=int(raw["model_scale"]),
|
|
127
|
+
tile=int(raw["tile"]),
|
|
128
|
+
overlap=int(raw["overlap"]),
|
|
129
|
+
)
|
|
130
|
+
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
if expect_tile is not None and meta.tile != expect_tile:
|
|
134
|
+
return None
|
|
135
|
+
if expect_overlap is not None and meta.overlap != expect_overlap:
|
|
136
|
+
return None
|
|
137
|
+
if expect_pass is not None and meta.pass_index != expect_pass:
|
|
138
|
+
return None
|
|
139
|
+
if expect_out_h is not None and meta.out_h != expect_out_h:
|
|
140
|
+
return None
|
|
141
|
+
if expect_out_w is not None and meta.out_w != expect_out_w:
|
|
142
|
+
return None
|
|
143
|
+
if expect_channels is not None and meta.channels != expect_channels:
|
|
144
|
+
return None
|
|
145
|
+
if expect_model_scale is not None and meta.model_scale != expect_model_scale:
|
|
146
|
+
return None
|
|
147
|
+
|
|
148
|
+
extras: dict[str, Any] = {
|
|
149
|
+
"carry_top": int(raw.get("carry_top") or 0),
|
|
150
|
+
"result_mmap": raw.get("result_mmap"),
|
|
151
|
+
"carry_canvas": None,
|
|
152
|
+
"carry_weight": None,
|
|
153
|
+
"has_carry": bool(raw.get("has_carry")),
|
|
154
|
+
}
|
|
155
|
+
carry_path = root / "strip_carry.npz"
|
|
156
|
+
needs_carry = bool(raw.get("has_carry")) or meta.flush_row > 0
|
|
157
|
+
if carry_path.is_file():
|
|
158
|
+
try:
|
|
159
|
+
with np.load(carry_path) as z:
|
|
160
|
+
extras["carry_canvas"] = np.array(z["canvas"])
|
|
161
|
+
extras["carry_weight"] = np.array(z["weight"])
|
|
162
|
+
if "carry_top" in z.files:
|
|
163
|
+
extras["carry_top"] = int(z["carry_top"][0])
|
|
164
|
+
except (OSError, ValueError, KeyError):
|
|
165
|
+
return None
|
|
166
|
+
elif needs_carry and meta.flush_row > 0 and meta.flush_row < meta.out_h:
|
|
167
|
+
# Metadata claims progress past row 0 but carry is missing — unsafe.
|
|
168
|
+
if bool(raw.get("has_carry", True)):
|
|
169
|
+
return None
|
|
170
|
+
return meta, extras
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def clear_strip_checkpoint(job_dir: Path | str) -> None:
|
|
174
|
+
root = checkpoint_dir(job_dir)
|
|
175
|
+
for name in ("strip.json", "strip_carry.npz", "strip.json.tmp", "strip_carry.npz.tmp"):
|
|
176
|
+
p = root / name
|
|
177
|
+
if p.is_file():
|
|
178
|
+
p.unlink(missing_ok=True)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def pass_complete_meta_path(job_dir: Path | str, pass_index: int) -> Path:
|
|
182
|
+
return Path(job_dir) / f"pass_{pass_index}_complete.json"
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def pass_complete_mmap_path(job_dir: Path | str, pass_index: int) -> Path:
|
|
186
|
+
return Path(job_dir) / f"pass_{pass_index}_out.uint8.mmap"
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def save_pass_complete(
|
|
190
|
+
job_dir: Path | str,
|
|
191
|
+
pass_index: int,
|
|
192
|
+
arr: np.ndarray,
|
|
193
|
+
) -> Path:
|
|
194
|
+
"""Persist a finished pass output under the job dir for multi-pass resume."""
|
|
195
|
+
jd = Path(job_dir)
|
|
196
|
+
jd.mkdir(parents=True, exist_ok=True)
|
|
197
|
+
shape = tuple(int(x) for x in arr.shape)
|
|
198
|
+
mmap_path = pass_complete_mmap_path(jd, pass_index)
|
|
199
|
+
meta_path = pass_complete_meta_path(jd, pass_index)
|
|
200
|
+
# tiled_upscale already file-backs into this path when job_dir is set —
|
|
201
|
+
# flush + metadata only. Rewriting via os.replace fails on Windows while
|
|
202
|
+
# the caller's memmap still holds the destination open.
|
|
203
|
+
existing = getattr(arr, "filename", None)
|
|
204
|
+
already = False
|
|
205
|
+
if existing is not None:
|
|
206
|
+
try:
|
|
207
|
+
already = Path(existing).resolve() == mmap_path.resolve()
|
|
208
|
+
except OSError:
|
|
209
|
+
already = False
|
|
210
|
+
if already:
|
|
211
|
+
try:
|
|
212
|
+
arr.flush()
|
|
213
|
+
except Exception: # noqa: BLE001
|
|
214
|
+
pass
|
|
215
|
+
else:
|
|
216
|
+
tmp_mmap = jd / f"pass_{pass_index}_out.uint8.mmap.tmp"
|
|
217
|
+
if tmp_mmap.is_file():
|
|
218
|
+
tmp_mmap.unlink(missing_ok=True)
|
|
219
|
+
# Prefer plain file I/O so Windows can replace without an open memmap handle.
|
|
220
|
+
from .memmap_util import spill_uint8_rows
|
|
221
|
+
|
|
222
|
+
spill_uint8_rows(arr, tmp_mmap, chunk=64)
|
|
223
|
+
if mmap_path.is_file():
|
|
224
|
+
mmap_path.unlink(missing_ok=True)
|
|
225
|
+
os.replace(tmp_mmap, mmap_path)
|
|
226
|
+
tmp_meta = jd / f"pass_{pass_index}_complete.json.tmp"
|
|
227
|
+
tmp_meta.write_text(
|
|
228
|
+
json.dumps({"pass_index": pass_index, "shape": list(shape)}, indent=2),
|
|
229
|
+
encoding="utf-8",
|
|
230
|
+
)
|
|
231
|
+
os.replace(tmp_meta, meta_path)
|
|
232
|
+
return mmap_path
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def load_pass_complete(
|
|
236
|
+
job_dir: Path | str, pass_index: int
|
|
237
|
+
) -> np.ndarray | None:
|
|
238
|
+
jd = Path(job_dir)
|
|
239
|
+
meta_path = pass_complete_meta_path(jd, pass_index)
|
|
240
|
+
mmap_path = pass_complete_mmap_path(jd, pass_index)
|
|
241
|
+
if not meta_path.is_file() or not mmap_path.is_file():
|
|
242
|
+
return None
|
|
243
|
+
try:
|
|
244
|
+
raw = json.loads(meta_path.read_text(encoding="utf-8"))
|
|
245
|
+
shape = tuple(int(x) for x in raw["shape"])
|
|
246
|
+
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
|
|
247
|
+
return None
|
|
248
|
+
need = int(np.prod(shape))
|
|
249
|
+
if mmap_path.stat().st_size < need:
|
|
250
|
+
return None
|
|
251
|
+
return np.memmap(mmap_path, dtype=np.uint8, mode="r", shape=shape)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def first_incomplete_pass(job_dir: Path | str, passes: int) -> int:
|
|
255
|
+
"""Return 0-based index of the first pass without a complete output."""
|
|
256
|
+
for p in range(1, passes + 1):
|
|
257
|
+
if load_pass_complete(job_dir, p) is None:
|
|
258
|
+
return p - 1
|
|
259
|
+
return passes
|