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,257 @@
|
|
|
1
|
+
"""Estimate + decode-preview routes (split from server.py)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from fastapi import APIRouter, File, HTTPException, UploadFile
|
|
9
|
+
from fastapi.responses import Response
|
|
10
|
+
from pydantic import BaseModel, Field
|
|
11
|
+
|
|
12
|
+
from upscale.api import deps as D
|
|
13
|
+
from upscale.schema import FilterSettings
|
|
14
|
+
|
|
15
|
+
router = APIRouter()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class EstimateBody(BaseModel):
|
|
19
|
+
src_w: int = Field(gt=0)
|
|
20
|
+
src_h: int = Field(gt=0)
|
|
21
|
+
scale: float = Field(gt=0)
|
|
22
|
+
model: str = "RealESRGAN_x4plus"
|
|
23
|
+
device: str = "auto"
|
|
24
|
+
model_ready: bool | None = None
|
|
25
|
+
filters: FilterSettings | None = None
|
|
26
|
+
measured_mp_s: float | None = None
|
|
27
|
+
tile: int | None = None
|
|
28
|
+
half: bool = False
|
|
29
|
+
algorithm: str | None = None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@router.post("/api/estimate")
|
|
33
|
+
def api_estimate(body: EstimateBody) -> dict[str, Any]:
|
|
34
|
+
"""Honest time range; prefers learned MP/s from past jobs on this machine."""
|
|
35
|
+
from upscale.estimates import estimate_time_seconds, model_fits_vram
|
|
36
|
+
from upscale.filters import estimate_time_factor
|
|
37
|
+
from upscale.models import DEFAULT_WEIGHTS_DIR, MODELS, all_models, model_status, registry_scale
|
|
38
|
+
from upscale.speed_stats import lookup_measured_mp_s, normalize_device, work_megapixels
|
|
39
|
+
from upscale.system import gather_system_info
|
|
40
|
+
|
|
41
|
+
name = body.model
|
|
42
|
+
ready = body.model_ready
|
|
43
|
+
if ready is None:
|
|
44
|
+
ready = model_status(name) == "installed"
|
|
45
|
+
meta = all_models().get(name) or MODELS.get(name) or {}
|
|
46
|
+
model_bytes = meta.get("size_bytes")
|
|
47
|
+
if model_bytes is None and ready:
|
|
48
|
+
url_path = (meta.get("url") or "").split("?")[0]
|
|
49
|
+
ext = Path(url_path).suffix or ".pth"
|
|
50
|
+
dest = DEFAULT_WEIGHTS_DIR / f"{name}{ext}"
|
|
51
|
+
if dest.is_file():
|
|
52
|
+
model_bytes = dest.stat().st_size
|
|
53
|
+
mscale = int(meta.get("scale") or registry_scale(name) or 4)
|
|
54
|
+
filt = body.filters or FilterSettings()
|
|
55
|
+
factor = estimate_time_factor(filt)
|
|
56
|
+
sys_info = gather_system_info(device=body.device, fp16=body.half)
|
|
57
|
+
device = normalize_device(sys_info.device or body.device)
|
|
58
|
+
work_mp = work_megapixels(
|
|
59
|
+
body.src_w,
|
|
60
|
+
body.src_h,
|
|
61
|
+
body.scale,
|
|
62
|
+
model_scale=mscale,
|
|
63
|
+
algorithm=body.algorithm,
|
|
64
|
+
)
|
|
65
|
+
measured = body.measured_mp_s
|
|
66
|
+
calibrated = False
|
|
67
|
+
samples = 0
|
|
68
|
+
stats_key = None
|
|
69
|
+
if measured is None:
|
|
70
|
+
hit = lookup_measured_mp_s(
|
|
71
|
+
model=name,
|
|
72
|
+
device=device,
|
|
73
|
+
half=body.half,
|
|
74
|
+
algorithm=body.algorithm,
|
|
75
|
+
work_mp=work_mp,
|
|
76
|
+
)
|
|
77
|
+
if hit is not None:
|
|
78
|
+
measured = float(hit["mp_s"])
|
|
79
|
+
calibrated = True
|
|
80
|
+
samples = int(hit["n"])
|
|
81
|
+
stats_key = hit.get("key")
|
|
82
|
+
elif measured > 0:
|
|
83
|
+
calibrated = True
|
|
84
|
+
lo, hi = estimate_time_seconds(
|
|
85
|
+
body.src_w,
|
|
86
|
+
body.src_h,
|
|
87
|
+
body.scale,
|
|
88
|
+
model=name,
|
|
89
|
+
device=device,
|
|
90
|
+
model_scale=mscale,
|
|
91
|
+
model_ready=bool(ready),
|
|
92
|
+
model_bytes=model_bytes,
|
|
93
|
+
filter_factor=factor,
|
|
94
|
+
measured_mp_s=measured,
|
|
95
|
+
algorithm=body.algorithm,
|
|
96
|
+
calibrated=calibrated,
|
|
97
|
+
)
|
|
98
|
+
tile = body.tile or sys_info.auto_tile or 512
|
|
99
|
+
vram_fit = model_fits_vram(
|
|
100
|
+
model_bytes,
|
|
101
|
+
sys_info.vram_free_mb,
|
|
102
|
+
tile=int(tile),
|
|
103
|
+
fp16=body.half,
|
|
104
|
+
)
|
|
105
|
+
return {
|
|
106
|
+
"seconds_low": lo,
|
|
107
|
+
"seconds_high": hi,
|
|
108
|
+
"seconds": round((lo + hi) / 2, 1),
|
|
109
|
+
"model_ready": bool(ready),
|
|
110
|
+
"filter_factor": factor,
|
|
111
|
+
"vram_fit": vram_fit,
|
|
112
|
+
"vram_free_mb": sys_info.vram_free_mb,
|
|
113
|
+
"tile": int(tile),
|
|
114
|
+
"calibrated": calibrated,
|
|
115
|
+
"samples": samples,
|
|
116
|
+
"mp_s": measured,
|
|
117
|
+
"device": device,
|
|
118
|
+
"work_mp": round(work_mp, 4),
|
|
119
|
+
"stats_key": stats_key,
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class PreflightBody(BaseModel):
|
|
124
|
+
src_w: int = Field(gt=0)
|
|
125
|
+
src_h: int = Field(gt=0)
|
|
126
|
+
scale: float | None = None
|
|
127
|
+
target_size: int | None = None
|
|
128
|
+
width: int | None = None
|
|
129
|
+
height: int | None = None
|
|
130
|
+
model: str = "RealESRGAN_x4plus"
|
|
131
|
+
device: str = "auto"
|
|
132
|
+
half: bool = False
|
|
133
|
+
tile: int | None = None
|
|
134
|
+
algorithm: str | None = None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@router.post("/api/preflight")
|
|
138
|
+
def api_preflight(body: PreflightBody) -> dict[str, Any]:
|
|
139
|
+
"""Structured sizing + resource check before enqueueing a job."""
|
|
140
|
+
import click
|
|
141
|
+
|
|
142
|
+
from upscale.config import UpscaleConfig
|
|
143
|
+
from upscale.estimates import resource_check
|
|
144
|
+
from upscale.job_prep import resolve_scale_and_targets
|
|
145
|
+
from upscale.models import DEFAULT_WEIGHTS_DIR, MODELS, all_models, model_status, registry_scale
|
|
146
|
+
from upscale.system import gather_system_info
|
|
147
|
+
|
|
148
|
+
cfg = UpscaleConfig(
|
|
149
|
+
scale=body.scale,
|
|
150
|
+
target_size=body.target_size,
|
|
151
|
+
width=body.width,
|
|
152
|
+
height=body.height,
|
|
153
|
+
)
|
|
154
|
+
if cfg.scale is None and cfg.target_size is None and (
|
|
155
|
+
cfg.width is None or cfg.height is None
|
|
156
|
+
):
|
|
157
|
+
cfg.scale = 4.0
|
|
158
|
+
try:
|
|
159
|
+
scale, tw, th = resolve_scale_and_targets(cfg, body.src_w, body.src_h)
|
|
160
|
+
except click.UsageError as exc:
|
|
161
|
+
raise HTTPException(400, str(exc)) from exc
|
|
162
|
+
|
|
163
|
+
name = body.model
|
|
164
|
+
ready = model_status(name) == "installed" or body.algorithm is not None
|
|
165
|
+
meta = all_models().get(name) or MODELS.get(name) or {}
|
|
166
|
+
model_bytes = meta.get("size_bytes")
|
|
167
|
+
if model_bytes is None and ready and body.algorithm is None:
|
|
168
|
+
url_path = (meta.get("url") or "").split("?")[0]
|
|
169
|
+
ext = Path(url_path).suffix or ".pth"
|
|
170
|
+
dest = DEFAULT_WEIGHTS_DIR / f"{name}{ext}"
|
|
171
|
+
if dest.is_file():
|
|
172
|
+
model_bytes = dest.stat().st_size
|
|
173
|
+
sys_info = gather_system_info(device=body.device, fp16=body.half)
|
|
174
|
+
tile = int(body.tile or sys_info.auto_tile or 512)
|
|
175
|
+
check = resource_check(
|
|
176
|
+
out_w=tw,
|
|
177
|
+
out_h=th,
|
|
178
|
+
tile=tile,
|
|
179
|
+
fp16=body.half,
|
|
180
|
+
model_bytes=None if body.algorithm else model_bytes,
|
|
181
|
+
vram_free_mb=sys_info.vram_free_mb,
|
|
182
|
+
ram_available_mb=sys_info.ram_available_mb,
|
|
183
|
+
disk_free_mb=sys_info.disk_free_mb,
|
|
184
|
+
model_ready=bool(ready),
|
|
185
|
+
)
|
|
186
|
+
return {
|
|
187
|
+
"ok": not check.blocked,
|
|
188
|
+
"blocked": check.blocked,
|
|
189
|
+
"scale": scale,
|
|
190
|
+
"target_w": tw,
|
|
191
|
+
"target_h": th,
|
|
192
|
+
"tile": tile,
|
|
193
|
+
"model_scale": int(meta.get("scale") or registry_scale(name) or 4),
|
|
194
|
+
"checks": [
|
|
195
|
+
{
|
|
196
|
+
"name": r.name,
|
|
197
|
+
"status": r.status.value if hasattr(r.status, "value") else str(r.status),
|
|
198
|
+
"detail": r.detail,
|
|
199
|
+
"advice": getattr(r, "advice", "") or "",
|
|
200
|
+
}
|
|
201
|
+
for r in check.rows
|
|
202
|
+
],
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
@router.post("/api/decode-preview")
|
|
207
|
+
async def decode_preview(file: UploadFile = File(...)) -> Response:
|
|
208
|
+
"""Decode any supported input format to a browser-safe PNG preview."""
|
|
209
|
+
import io
|
|
210
|
+
import tempfile
|
|
211
|
+
|
|
212
|
+
import numpy as np
|
|
213
|
+
from PIL import Image
|
|
214
|
+
|
|
215
|
+
from upscale.io_utils import is_vector_input, load_rgba, require_raster_suffix
|
|
216
|
+
|
|
217
|
+
try:
|
|
218
|
+
suffix = require_raster_suffix(file.filename)
|
|
219
|
+
except ValueError as exc:
|
|
220
|
+
raise HTTPException(400, str(exc)) from exc
|
|
221
|
+
if file.content_type and is_vector_input(file.filename, file.content_type):
|
|
222
|
+
raise HTTPException(
|
|
223
|
+
400,
|
|
224
|
+
"Vector images are not supported. "
|
|
225
|
+
"Rasterize to PNG, TIFF, or another supported bitmap format first.",
|
|
226
|
+
)
|
|
227
|
+
content = await file.read()
|
|
228
|
+
if len(content) > D.MAX_UPLOAD_BYTES:
|
|
229
|
+
raise HTTPException(413, f"Upload exceeds limit of {D.MAX_UPLOAD_BYTES} bytes")
|
|
230
|
+
with tempfile.TemporaryDirectory(prefix="upscale-decode-") as td:
|
|
231
|
+
src = Path(td) / f"input{suffix}"
|
|
232
|
+
src.write_bytes(content)
|
|
233
|
+
try:
|
|
234
|
+
rgb, alpha, _mode = load_rgba(src)
|
|
235
|
+
except Exception as exc: # noqa: BLE001
|
|
236
|
+
raise HTTPException(400, f"Could not decode image: {exc}") from exc
|
|
237
|
+
|
|
238
|
+
if alpha is not None:
|
|
239
|
+
im = Image.fromarray(np.dstack([rgb, alpha]), mode="RGBA")
|
|
240
|
+
else:
|
|
241
|
+
im = Image.fromarray(rgb, mode="RGB")
|
|
242
|
+
h, w = rgb.shape[:2]
|
|
243
|
+
edge = 4096
|
|
244
|
+
if max(im.size) > edge:
|
|
245
|
+
im = im.copy()
|
|
246
|
+
im.thumbnail((edge, edge), Image.Resampling.LANCZOS)
|
|
247
|
+
buf = io.BytesIO()
|
|
248
|
+
im.save(buf, format="PNG", optimize=False)
|
|
249
|
+
data = buf.getvalue()
|
|
250
|
+
headers = {
|
|
251
|
+
"X-Image-Width": str(w),
|
|
252
|
+
"X-Image-Height": str(h),
|
|
253
|
+
"X-Has-Alpha": "1" if alpha is not None else "0",
|
|
254
|
+
"X-Source-Name": Path(file.filename or "image").name,
|
|
255
|
+
"Cache-Control": "no-store",
|
|
256
|
+
}
|
|
257
|
+
return Response(content=data, media_type="image/png", headers=headers)
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""API routes split from server.py."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
|
|
9
|
+
|
|
10
|
+
from upscale.api import deps as D
|
|
11
|
+
from upscale.models import (
|
|
12
|
+
DEFAULT_WEIGHTS_DIR,
|
|
13
|
+
add_external_model,
|
|
14
|
+
ensure_model,
|
|
15
|
+
model_status,
|
|
16
|
+
validate_model_name,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
router = APIRouter()
|
|
20
|
+
|
|
21
|
+
@router.get("/api/models")
|
|
22
|
+
def api_models_list() -> list[dict[str, Any]]:
|
|
23
|
+
return [m.model_dump() for m in D._model_info_list()]
|
|
24
|
+
|
|
25
|
+
@router.post("/api/models")
|
|
26
|
+
def api_models_add(body: D.ExternalModelBody) -> dict[str, Any]:
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
validate_model_name(body.name)
|
|
30
|
+
entry = add_external_model(
|
|
31
|
+
body.name,
|
|
32
|
+
url=body.url,
|
|
33
|
+
path=body.path,
|
|
34
|
+
scale=body.scale,
|
|
35
|
+
sha256=body.sha256,
|
|
36
|
+
description=body.description,
|
|
37
|
+
)
|
|
38
|
+
except ValueError as exc:
|
|
39
|
+
raise HTTPException(400, str(exc)) from exc
|
|
40
|
+
except FileNotFoundError as exc:
|
|
41
|
+
raise HTTPException(400, str(exc)) from exc
|
|
42
|
+
return {"name": body.name, "entry": entry, "status": model_status(body.name)}
|
|
43
|
+
|
|
44
|
+
@router.post("/api/models/upload")
|
|
45
|
+
async def api_models_upload(
|
|
46
|
+
file: UploadFile = File(...),
|
|
47
|
+
name: str = Form(""),
|
|
48
|
+
scale: int = Form(4),
|
|
49
|
+
description: str = Form(""),
|
|
50
|
+
) -> dict[str, Any]:
|
|
51
|
+
"""Accept weights upload into the models directory and register it."""
|
|
52
|
+
|
|
53
|
+
import hashlib
|
|
54
|
+
|
|
55
|
+
from upscale.models import MODELS
|
|
56
|
+
|
|
57
|
+
raw_name = (name or Path(file.filename or "model").stem).strip()
|
|
58
|
+
try:
|
|
59
|
+
validate_model_name(raw_name)
|
|
60
|
+
except ValueError as exc:
|
|
61
|
+
raise HTTPException(400, str(exc)) from exc
|
|
62
|
+
if raw_name in MODELS:
|
|
63
|
+
raise HTTPException(400, f"Refusing to shadow built-in model {raw_name!r}")
|
|
64
|
+
suffix = Path(file.filename or "model.pth").suffix.lower() or ".pth"
|
|
65
|
+
if suffix not in (".pth", ".pt", ".safetensors", ".onnx"):
|
|
66
|
+
raise HTTPException(400, f"Unsupported weights extension: {suffix}")
|
|
67
|
+
content = await file.read()
|
|
68
|
+
if len(content) > D.MAX_UPLOAD_BYTES:
|
|
69
|
+
raise HTTPException(413, f"Upload exceeds limit of {D.MAX_UPLOAD_BYTES} bytes")
|
|
70
|
+
digest = hashlib.sha256(content).hexdigest()
|
|
71
|
+
DEFAULT_WEIGHTS_DIR.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
dest = DEFAULT_WEIGHTS_DIR / f"{raw_name}{suffix}"
|
|
73
|
+
dest.write_bytes(content)
|
|
74
|
+
try:
|
|
75
|
+
entry = add_external_model(
|
|
76
|
+
raw_name,
|
|
77
|
+
path=str(dest),
|
|
78
|
+
scale=int(scale) if 1 <= int(scale) <= 8 else 4,
|
|
79
|
+
sha256=digest,
|
|
80
|
+
description=description or f"Uploaded {file.filename}",
|
|
81
|
+
)
|
|
82
|
+
except (ValueError, FileNotFoundError) as exc:
|
|
83
|
+
dest.unlink(missing_ok=True)
|
|
84
|
+
raise HTTPException(400, str(exc)) from exc
|
|
85
|
+
return {
|
|
86
|
+
"name": raw_name,
|
|
87
|
+
"path": str(dest),
|
|
88
|
+
"entry": entry,
|
|
89
|
+
"status": model_status(raw_name),
|
|
90
|
+
"sha256": digest,
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
@router.post("/api/models/{name}/download")
|
|
94
|
+
def api_models_download(name: str) -> dict[str, Any]:
|
|
95
|
+
"""Ensure weights are on disk (download + hash verify)."""
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
validate_model_name(name)
|
|
99
|
+
except ValueError as exc:
|
|
100
|
+
raise HTTPException(400, str(exc)) from exc
|
|
101
|
+
try:
|
|
102
|
+
path = ensure_model(name)
|
|
103
|
+
except KeyError as exc:
|
|
104
|
+
raise HTTPException(404, f"Unknown model: {name}") from exc
|
|
105
|
+
except Exception as exc: # noqa: BLE001 — surface download errors to UI
|
|
106
|
+
raise HTTPException(400, str(exc)) from exc
|
|
107
|
+
return {"name": name, "path": str(path), "status": model_status(name)}
|
|
@@ -0,0 +1,210 @@
|
|
|
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.io_utils import is_vector_input, require_raster_suffix
|
|
141
|
+
from upscale.suggest import suggest_model
|
|
142
|
+
|
|
143
|
+
job_dir = Path(tempfile.mkdtemp(prefix="upscale-suggest-"))
|
|
144
|
+
try:
|
|
145
|
+
try:
|
|
146
|
+
suffix = require_raster_suffix(file.filename)
|
|
147
|
+
except ValueError as exc:
|
|
148
|
+
raise HTTPException(400, str(exc)) from exc
|
|
149
|
+
if is_vector_input(file.filename, file.content_type):
|
|
150
|
+
raise HTTPException(
|
|
151
|
+
400,
|
|
152
|
+
"Vector images are not supported. "
|
|
153
|
+
"Rasterize to PNG, TIFF, or another supported bitmap format first.",
|
|
154
|
+
)
|
|
155
|
+
dest = job_dir / f"input{suffix}"
|
|
156
|
+
content = await file.read()
|
|
157
|
+
if len(content) > D.MAX_UPLOAD_BYTES:
|
|
158
|
+
raise HTTPException(
|
|
159
|
+
413, f"Upload exceeds limit of {D.MAX_UPLOAD_BYTES} bytes"
|
|
160
|
+
)
|
|
161
|
+
dest.write_bytes(content)
|
|
162
|
+
return suggest_model(dest, fast=fast)
|
|
163
|
+
finally:
|
|
164
|
+
shutil.rmtree(job_dir, ignore_errors=True)
|
|
165
|
+
|
|
166
|
+
class BenchmarkBody(BaseModel):
|
|
167
|
+
path: str
|
|
168
|
+
model: str = "RealESRGAN_x4plus"
|
|
169
|
+
device: str = "cpu"
|
|
170
|
+
crop_size: int = 64
|
|
171
|
+
scale: float = 2.0
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@router.post("/api/benchmark")
|
|
175
|
+
def api_benchmark(body: BenchmarkBody) -> dict[str, Any]:
|
|
176
|
+
from upscale.benchmark import run_benchmark
|
|
177
|
+
|
|
178
|
+
p = Path(body.path).resolve()
|
|
179
|
+
if not p.is_file():
|
|
180
|
+
raise HTTPException(400, "path must be a readable local file")
|
|
181
|
+
# Sandbox: only allow files under D.JOBS_ROOT (or system temp upscale-jobs).
|
|
182
|
+
jobs_root = D.JOBS_ROOT.resolve()
|
|
183
|
+
if not p.is_relative_to(jobs_root):
|
|
184
|
+
raise HTTPException(
|
|
185
|
+
400,
|
|
186
|
+
"benchmark path must be under the jobs temp directory "
|
|
187
|
+
f"({jobs_root})",
|
|
188
|
+
)
|
|
189
|
+
with D._execute_lock:
|
|
190
|
+
return run_benchmark(
|
|
191
|
+
p,
|
|
192
|
+
model=body.model,
|
|
193
|
+
device=body.device,
|
|
194
|
+
crop_size=body.crop_size,
|
|
195
|
+
scale=body.scale,
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
@router.get("/api/locales/{code}")
|
|
199
|
+
def api_locale(code: str) -> JSONResponse:
|
|
200
|
+
if not re.fullmatch(r"[A-Za-z0-9_-]+", code or ""):
|
|
201
|
+
raise HTTPException(404, "Locale not found")
|
|
202
|
+
locales = D.LOCALES_DIR.resolve()
|
|
203
|
+
path = (locales / f"{code}.json").resolve()
|
|
204
|
+
if not path.is_relative_to(locales):
|
|
205
|
+
raise HTTPException(404, "Locale not found")
|
|
206
|
+
if not path.is_file():
|
|
207
|
+
path = (locales / "en.json").resolve()
|
|
208
|
+
if not path.is_file() or not path.is_relative_to(locales):
|
|
209
|
+
raise HTTPException(404, "Locale not found")
|
|
210
|
+
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"]
|