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/api/deps.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Shared server state accessors for APIRouter modules.
|
|
2
|
+
|
|
3
|
+
Routers import ``D`` and read attributes; values always come from the live
|
|
4
|
+
``upscale.server`` module so test monkeypatches keep working.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def __getattr__(name: str) -> Any:
|
|
13
|
+
import upscale.server as server
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
return getattr(server, name)
|
|
17
|
+
except AttributeError as exc:
|
|
18
|
+
raise AttributeError(name) from exc
|
upscale/api/jobs.py
ADDED
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
"""API routes split from server.py."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import queue
|
|
8
|
+
import shutil
|
|
9
|
+
import threading
|
|
10
|
+
import uuid
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
|
|
15
|
+
from fastapi.responses import FileResponse, StreamingResponse
|
|
16
|
+
|
|
17
|
+
from upscale.api import deps as D
|
|
18
|
+
from upscale.schema import JobSettings
|
|
19
|
+
|
|
20
|
+
router = APIRouter()
|
|
21
|
+
|
|
22
|
+
@router.post("/api/jobs")
|
|
23
|
+
async def create_job(
|
|
24
|
+
file: UploadFile = File(...),
|
|
25
|
+
settings: str = Form("{}"),
|
|
26
|
+
) -> dict[str, str]:
|
|
27
|
+
D._purge_expired_jobs()
|
|
28
|
+
try:
|
|
29
|
+
raw = json.loads(settings) if settings.strip() else {}
|
|
30
|
+
js = JobSettings.model_validate(raw)
|
|
31
|
+
except (json.JSONDecodeError, ValueError) as exc:
|
|
32
|
+
raise HTTPException(400, f"Invalid settings JSON: {exc}") from exc
|
|
33
|
+
|
|
34
|
+
if js.scale is None and js.target_size is None and (js.width is None or js.height is None):
|
|
35
|
+
js = js.model_copy(update={"scale": 4.0})
|
|
36
|
+
if (js.width is None) ^ (js.height is None):
|
|
37
|
+
raise HTTPException(400, "Specify both width and height, or neither.")
|
|
38
|
+
# Soft output pixel budget (matches job_prep.MAX_OUTPUT_PIXELS intent).
|
|
39
|
+
if js.width is not None and js.height is not None and js.width * js.height > 200_000_000:
|
|
40
|
+
raise HTTPException(400, "Output dimensions exceed the pixel budget.")
|
|
41
|
+
if js.scale is not None and js.scale > 64:
|
|
42
|
+
raise HTTPException(400, "Scale exceeds the allowed maximum (64).")
|
|
43
|
+
|
|
44
|
+
with D._jobs_lock:
|
|
45
|
+
queued = sum(
|
|
46
|
+
1
|
|
47
|
+
for j in D._jobs.values()
|
|
48
|
+
if j.state in (D.JobState.queued, D.JobState.running, D.JobState.paused)
|
|
49
|
+
)
|
|
50
|
+
if queued >= D.MAX_QUEUE:
|
|
51
|
+
raise HTTPException(429, f"Job queue full (max {D.MAX_QUEUE})")
|
|
52
|
+
|
|
53
|
+
job_id = uuid.uuid4().hex
|
|
54
|
+
job_dir = D.JOBS_ROOT / job_id
|
|
55
|
+
job_dir.mkdir(parents=True, exist_ok=True)
|
|
56
|
+
|
|
57
|
+
from upscale.io_utils import is_vector_input, require_raster_suffix
|
|
58
|
+
|
|
59
|
+
try:
|
|
60
|
+
suffix = require_raster_suffix(file.filename)
|
|
61
|
+
except ValueError as exc:
|
|
62
|
+
shutil.rmtree(job_dir, ignore_errors=True)
|
|
63
|
+
raise HTTPException(400, str(exc)) from exc
|
|
64
|
+
if is_vector_input(file.filename, file.content_type):
|
|
65
|
+
shutil.rmtree(job_dir, ignore_errors=True)
|
|
66
|
+
raise HTTPException(
|
|
67
|
+
400,
|
|
68
|
+
"Vector images are not supported. "
|
|
69
|
+
"Rasterize to PNG, TIFF, or another supported bitmap format first.",
|
|
70
|
+
)
|
|
71
|
+
input_path = job_dir / f"input{suffix}"
|
|
72
|
+
content = await file.read()
|
|
73
|
+
if len(content) > D.MAX_UPLOAD_BYTES:
|
|
74
|
+
shutil.rmtree(job_dir, ignore_errors=True)
|
|
75
|
+
raise HTTPException(
|
|
76
|
+
413, f"Upload exceeds limit of {D.MAX_UPLOAD_BYTES} bytes"
|
|
77
|
+
)
|
|
78
|
+
input_path.write_bytes(content)
|
|
79
|
+
try:
|
|
80
|
+
D._make_preview(input_path, job_dir / "preview.png")
|
|
81
|
+
except Exception: # noqa: BLE001
|
|
82
|
+
try:
|
|
83
|
+
shutil.copy(input_path, job_dir / "preview.png")
|
|
84
|
+
except Exception: # noqa: BLE001
|
|
85
|
+
shutil.rmtree(job_dir, ignore_errors=True)
|
|
86
|
+
raise HTTPException(400, "Could not read uploaded image") from None
|
|
87
|
+
|
|
88
|
+
job = D.JobRecord(id=job_id, job_dir=job_dir, input_path=input_path, settings=js)
|
|
89
|
+
(job_dir / "settings.json").write_text(
|
|
90
|
+
js.model_dump_json(exclude_none=True), encoding="utf-8"
|
|
91
|
+
)
|
|
92
|
+
with D._jobs_lock:
|
|
93
|
+
D._jobs[job_id] = job
|
|
94
|
+
D._ensure_worker()
|
|
95
|
+
D._job_queue.put(job_id)
|
|
96
|
+
D._push_event(job, {"type": "queued", "pct": 0, "message": "queued", "id": job_id})
|
|
97
|
+
return {"id": job_id, "input": str(input_path)}
|
|
98
|
+
|
|
99
|
+
@router.get("/api/jobs/interrupted")
|
|
100
|
+
def list_interrupted_jobs() -> dict[str, Any]:
|
|
101
|
+
"""Jobs that still have a strip checkpoint (cancelled/error mid-pass).
|
|
102
|
+
|
|
103
|
+
Registered before ``/api/jobs/{job_id}`` so ``interrupted`` is not captured as an id.
|
|
104
|
+
Skips active and completed jobs; clears leftover checkpoints on done jobs and
|
|
105
|
+
disk dirs that already have a result. Skips unreadable inputs.
|
|
106
|
+
"""
|
|
107
|
+
D._purge_expired_jobs()
|
|
108
|
+
items: list[dict[str, Any]] = []
|
|
109
|
+
with D._jobs_lock:
|
|
110
|
+
jobs = list(D._jobs.values())
|
|
111
|
+
known: set[str] = set()
|
|
112
|
+
for job in jobs:
|
|
113
|
+
known.add(job.id)
|
|
114
|
+
if job.state in (D.JobState.queued, D.JobState.running, D.JobState.paused):
|
|
115
|
+
continue
|
|
116
|
+
strip_path = job.job_dir / "checkpoints" / "strip.json"
|
|
117
|
+
ck = D._strip_checkpoint_info(job)
|
|
118
|
+
if ck is None:
|
|
119
|
+
# Unusable leftover strip.json must not surface as "resume".
|
|
120
|
+
if strip_path.is_file():
|
|
121
|
+
D._discard_bad_checkpoint(job.job_dir)
|
|
122
|
+
continue
|
|
123
|
+
# Finished jobs must not offer "resume" — clear stale strip markers.
|
|
124
|
+
if job.state == D.JobState.done:
|
|
125
|
+
D._discard_bad_checkpoint(job.job_dir)
|
|
126
|
+
continue
|
|
127
|
+
if job.state not in (D.JobState.cancelled, D.JobState.error):
|
|
128
|
+
continue
|
|
129
|
+
if not job.input_path.is_file() or not D._png_readable(job.input_path):
|
|
130
|
+
D._discard_bad_checkpoint(job.job_dir)
|
|
131
|
+
continue
|
|
132
|
+
items.append(
|
|
133
|
+
{
|
|
134
|
+
"id": job.id,
|
|
135
|
+
"state": job.state.value,
|
|
136
|
+
"checkpoint": ck,
|
|
137
|
+
"settings": job.settings.model_dump(mode="json", exclude_none=True),
|
|
138
|
+
"input": job.input_path.name,
|
|
139
|
+
"mtime": job.job_dir.stat().st_mtime if job.job_dir.is_dir() else 0,
|
|
140
|
+
}
|
|
141
|
+
)
|
|
142
|
+
if D.JOBS_ROOT.is_dir():
|
|
143
|
+
for d in D.JOBS_ROOT.iterdir():
|
|
144
|
+
if not d.is_dir() or d.name in known or d.name.startswith("compare-"):
|
|
145
|
+
continue
|
|
146
|
+
strip = d / "checkpoints" / "strip.json"
|
|
147
|
+
if not strip.is_file():
|
|
148
|
+
continue
|
|
149
|
+
# Already finished on disk — not interrupted.
|
|
150
|
+
if D._find_result_file(d) is not None:
|
|
151
|
+
D._discard_bad_checkpoint(d)
|
|
152
|
+
continue
|
|
153
|
+
# Same validation resume-checkpoint uses (rejects incomplete carry, etc.).
|
|
154
|
+
ck = D._strip_checkpoint_info_from_dir(d)
|
|
155
|
+
if ck is None:
|
|
156
|
+
D._discard_bad_checkpoint(d)
|
|
157
|
+
continue
|
|
158
|
+
inputs = sorted(d.glob("input.*"))
|
|
159
|
+
if not inputs or not D._png_readable(inputs[0]):
|
|
160
|
+
D._discard_bad_checkpoint(d)
|
|
161
|
+
continue
|
|
162
|
+
settings = None
|
|
163
|
+
sp = d / "settings.json"
|
|
164
|
+
if sp.is_file():
|
|
165
|
+
try:
|
|
166
|
+
settings = json.loads(sp.read_text(encoding="utf-8"))
|
|
167
|
+
except (OSError, json.JSONDecodeError):
|
|
168
|
+
settings = None
|
|
169
|
+
items.append(
|
|
170
|
+
{
|
|
171
|
+
"id": d.name,
|
|
172
|
+
"state": "orphaned",
|
|
173
|
+
"checkpoint": ck,
|
|
174
|
+
"settings": settings,
|
|
175
|
+
"input": inputs[0].name,
|
|
176
|
+
"mtime": d.stat().st_mtime,
|
|
177
|
+
}
|
|
178
|
+
)
|
|
179
|
+
items.sort(key=lambda j: float(j.get("mtime") or 0), reverse=True)
|
|
180
|
+
for j in items:
|
|
181
|
+
j.pop("mtime", None)
|
|
182
|
+
return {"jobs": items}
|
|
183
|
+
|
|
184
|
+
@router.get("/api/jobs/{job_id}")
|
|
185
|
+
def job_status(job_id: str) -> dict[str, Any]:
|
|
186
|
+
with D._jobs_lock:
|
|
187
|
+
job = D._jobs.get(job_id)
|
|
188
|
+
if job is not None:
|
|
189
|
+
return {
|
|
190
|
+
"id": job.id,
|
|
191
|
+
"state": job.state.value,
|
|
192
|
+
"pct": job.last_pct,
|
|
193
|
+
"error": job.error,
|
|
194
|
+
"cli": job.cli_hint,
|
|
195
|
+
"output": str(job.output_path) if job.output_path else None,
|
|
196
|
+
"input": str(job.input_path),
|
|
197
|
+
"created_at": job.created_at,
|
|
198
|
+
}
|
|
199
|
+
# Server restart: still report done if artifacts remain on disk
|
|
200
|
+
job_dir = D._safe_job_dir(job_id)
|
|
201
|
+
display = job_dir / "display.png"
|
|
202
|
+
result = D._find_result_file(job_dir)
|
|
203
|
+
if display.is_file() or (result is not None and result.is_file()):
|
|
204
|
+
return {
|
|
205
|
+
"id": job_id,
|
|
206
|
+
"state": D.JobState.done.value,
|
|
207
|
+
"pct": 1.0,
|
|
208
|
+
"error": None,
|
|
209
|
+
"cli": "",
|
|
210
|
+
"output": str(result) if result is not None else None,
|
|
211
|
+
"created_at": job_dir.stat().st_mtime,
|
|
212
|
+
}
|
|
213
|
+
raise HTTPException(404, "Job not found")
|
|
214
|
+
|
|
215
|
+
@router.get("/api/jobs/{job_id}/events")
|
|
216
|
+
async def job_events(job_id: str) -> StreamingResponse:
|
|
217
|
+
job = D._get_job(job_id)
|
|
218
|
+
|
|
219
|
+
async def stream() -> Any:
|
|
220
|
+
while True:
|
|
221
|
+
try:
|
|
222
|
+
ev = await asyncio.to_thread(job.events.get, True, 30.0)
|
|
223
|
+
except queue.Empty:
|
|
224
|
+
yield ": keepalive\n\n"
|
|
225
|
+
continue
|
|
226
|
+
payload = json.dumps(ev)
|
|
227
|
+
yield f"data: {payload}\n\n"
|
|
228
|
+
if ev.get("type") in ("done", "error", "cancelled"):
|
|
229
|
+
break
|
|
230
|
+
|
|
231
|
+
return StreamingResponse(stream(), media_type="text/event-stream")
|
|
232
|
+
|
|
233
|
+
@router.post("/api/jobs/{job_id}/cancel")
|
|
234
|
+
def job_cancel(job_id: str) -> dict[str, str]:
|
|
235
|
+
import time
|
|
236
|
+
|
|
237
|
+
with D._jobs_lock:
|
|
238
|
+
job = D._jobs.get(job_id)
|
|
239
|
+
if job is None:
|
|
240
|
+
raise HTTPException(404, "Job not found")
|
|
241
|
+
job.cancel_event.set()
|
|
242
|
+
# Queued jobs never reach the worker's cancel check until dequeued —
|
|
243
|
+
# mark cancelled now so MAX_QUEUE slots free immediately.
|
|
244
|
+
if job.state == D.JobState.queued:
|
|
245
|
+
job.state = D.JobState.cancelled
|
|
246
|
+
D._push_event(
|
|
247
|
+
job, {"type": "cancelled", "pct": job.last_pct, "message": "cancelled"}
|
|
248
|
+
)
|
|
249
|
+
return {"status": "cancelled"}
|
|
250
|
+
if job.state == D.JobState.paused:
|
|
251
|
+
# Wake the pause wait so cancel is noticed between tiles.
|
|
252
|
+
job.pause_event.clear()
|
|
253
|
+
if job.pause_started_at is not None:
|
|
254
|
+
job.paused_seconds += max(0.0, time.time() - job.pause_started_at)
|
|
255
|
+
job.pause_started_at = None
|
|
256
|
+
return {"status": "cancelling"}
|
|
257
|
+
|
|
258
|
+
@router.post("/api/jobs/{job_id}/pause")
|
|
259
|
+
def job_pause(job_id: str) -> dict[str, str]:
|
|
260
|
+
import time
|
|
261
|
+
|
|
262
|
+
with D._jobs_lock:
|
|
263
|
+
job = D._jobs.get(job_id)
|
|
264
|
+
if job is None:
|
|
265
|
+
raise HTTPException(404, "Job not found")
|
|
266
|
+
if job.state not in (D.JobState.queued, D.JobState.running):
|
|
267
|
+
raise HTTPException(
|
|
268
|
+
409, f"Cannot pause job in state {job.state.value}"
|
|
269
|
+
)
|
|
270
|
+
job.pause_event.set()
|
|
271
|
+
job.state = D.JobState.paused
|
|
272
|
+
job.pause_started_at = time.time()
|
|
273
|
+
D._push_event(job, {"type": "paused", "pct": job.last_pct, "message": "paused"})
|
|
274
|
+
return {"status": "paused"}
|
|
275
|
+
|
|
276
|
+
@router.post("/api/jobs/{job_id}/resume")
|
|
277
|
+
def job_resume(job_id: str) -> dict[str, str]:
|
|
278
|
+
import time
|
|
279
|
+
|
|
280
|
+
with D._jobs_lock:
|
|
281
|
+
job = D._jobs.get(job_id)
|
|
282
|
+
if job is None:
|
|
283
|
+
raise HTTPException(404, "Job not found")
|
|
284
|
+
if job.state != D.JobState.paused:
|
|
285
|
+
raise HTTPException(
|
|
286
|
+
409, f"Cannot resume job in state {job.state.value}"
|
|
287
|
+
)
|
|
288
|
+
job.pause_event.clear()
|
|
289
|
+
if job.pause_started_at is not None:
|
|
290
|
+
job.paused_seconds += max(0.0, time.time() - job.pause_started_at)
|
|
291
|
+
job.pause_started_at = None
|
|
292
|
+
job.state = D.JobState.running
|
|
293
|
+
D._push_event(job, {"type": "resumed", "pct": job.last_pct, "message": "resumed"})
|
|
294
|
+
return {"status": "running"}
|
|
295
|
+
|
|
296
|
+
@router.post("/api/jobs/{job_id}/resume-checkpoint")
|
|
297
|
+
def job_resume_checkpoint(job_id: str) -> dict[str, str]:
|
|
298
|
+
"""Re-queue a cancelled/errored job so strip tiling continues from flush_row."""
|
|
299
|
+
with D._jobs_lock:
|
|
300
|
+
job = D._jobs.get(job_id)
|
|
301
|
+
if job is None:
|
|
302
|
+
# Rehydrate outside would race; do it then re-enter.
|
|
303
|
+
pass
|
|
304
|
+
if job is None:
|
|
305
|
+
job = D._rehydrate_job_from_disk(job_id)
|
|
306
|
+
ck = D._strip_checkpoint_info(job)
|
|
307
|
+
if ck is None:
|
|
308
|
+
D._discard_bad_checkpoint(job.job_dir)
|
|
309
|
+
raise HTTPException(400, "No strip checkpoint to resume")
|
|
310
|
+
if not job.input_path.is_file():
|
|
311
|
+
D._discard_bad_checkpoint(job.job_dir)
|
|
312
|
+
raise HTTPException(400, "Input file missing for this job")
|
|
313
|
+
if not D._png_readable(job.input_path):
|
|
314
|
+
D._discard_bad_checkpoint(job.job_dir)
|
|
315
|
+
raise HTTPException(
|
|
316
|
+
400,
|
|
317
|
+
"Input image is corrupt or unreadable; checkpoint cleared. "
|
|
318
|
+
"Start a new upscale instead.",
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
with D._jobs_lock:
|
|
322
|
+
live = D._jobs.get(job_id) or job
|
|
323
|
+
D._jobs[job_id] = live
|
|
324
|
+
if live.state in (D.JobState.queued, D.JobState.running, D.JobState.paused):
|
|
325
|
+
raise HTTPException(409, "Job is already active")
|
|
326
|
+
if live.state not in (D.JobState.cancelled, D.JobState.error):
|
|
327
|
+
raise HTTPException(
|
|
328
|
+
409, f"Cannot resume-checkpoint from state {live.state.value}"
|
|
329
|
+
)
|
|
330
|
+
queued = sum(
|
|
331
|
+
1
|
|
332
|
+
for j in D._jobs.values()
|
|
333
|
+
if j.state in (D.JobState.queued, D.JobState.running, D.JobState.paused)
|
|
334
|
+
)
|
|
335
|
+
if queued >= D.MAX_QUEUE:
|
|
336
|
+
raise HTTPException(429, f"Job queue full (max {D.MAX_QUEUE})")
|
|
337
|
+
live.cancel_event = threading.Event()
|
|
338
|
+
live.pause_event = threading.Event()
|
|
339
|
+
live.error = None
|
|
340
|
+
live.output_path = None
|
|
341
|
+
live.state = D.JobState.queued
|
|
342
|
+
live.resume_from_checkpoint = True
|
|
343
|
+
live.last_pct = float(ck.get("pct_approx") or 0)
|
|
344
|
+
try:
|
|
345
|
+
while True:
|
|
346
|
+
live.events.get_nowait()
|
|
347
|
+
except queue.Empty:
|
|
348
|
+
pass
|
|
349
|
+
job = live
|
|
350
|
+
# Outside the lock — _ensure_worker also takes _jobs_lock (non-reentrant).
|
|
351
|
+
D._ensure_worker()
|
|
352
|
+
D._job_queue.put(job_id)
|
|
353
|
+
D._push_event(
|
|
354
|
+
job,
|
|
355
|
+
{
|
|
356
|
+
"type": "queued",
|
|
357
|
+
"pct": job.last_pct,
|
|
358
|
+
"message": "resuming from checkpoint",
|
|
359
|
+
"id": job_id,
|
|
360
|
+
},
|
|
361
|
+
)
|
|
362
|
+
return {"status": "queued", "id": job_id}
|
|
363
|
+
|
|
364
|
+
@router.get("/api/jobs/{job_id}/quality")
|
|
365
|
+
def job_quality(job_id: str, mode: str = "seam") -> dict[str, Any]:
|
|
366
|
+
"""Seam score, or Lanczos-baseline diff metrics, for a finished job.
|
|
367
|
+
|
|
368
|
+
``seam`` measures a vertical join on the result alone.
|
|
369
|
+
``diff`` compares the result with a Lanczos resize of the input
|
|
370
|
+
(both capped so the check stays small) and writes ``quality_diff.png``.
|
|
371
|
+
"""
|
|
372
|
+
mode_key = (mode or "seam").strip().lower()
|
|
373
|
+
if mode_key not in ("seam", "diff"):
|
|
374
|
+
raise HTTPException(400, "mode must be seam or diff")
|
|
375
|
+
|
|
376
|
+
with D._jobs_lock:
|
|
377
|
+
job = D._jobs.get(job_id)
|
|
378
|
+
job_dir = job.job_dir if job is not None else D._safe_job_dir(job_id)
|
|
379
|
+
result: Path | None = None
|
|
380
|
+
input_path: Path | None = None
|
|
381
|
+
if job is not None:
|
|
382
|
+
input_path = job.input_path if job.input_path.is_file() else None
|
|
383
|
+
if job.output_path is not None and job.output_path.is_file():
|
|
384
|
+
result = job.output_path
|
|
385
|
+
if result is None:
|
|
386
|
+
result = D._find_result_file(job_dir)
|
|
387
|
+
if input_path is None:
|
|
388
|
+
inputs = sorted(job_dir.glob("input.*")) if job_dir.is_dir() else []
|
|
389
|
+
input_path = inputs[0] if inputs else None
|
|
390
|
+
if result is None or not result.is_file():
|
|
391
|
+
raise HTTPException(404, "Result not ready")
|
|
392
|
+
|
|
393
|
+
import numpy as np
|
|
394
|
+
from PIL import Image
|
|
395
|
+
|
|
396
|
+
from upscale.io_utils import lanczos_resize, load_rgba
|
|
397
|
+
from upscale.quality import diff_metrics, strip_seam_score
|
|
398
|
+
|
|
399
|
+
out_rgb, _, _ = load_rgba(result)
|
|
400
|
+
if mode_key == "seam":
|
|
401
|
+
height, width = out_rgb.shape[:2]
|
|
402
|
+
if max(height, width) > 1024:
|
|
403
|
+
scale = 1024 / max(height, width)
|
|
404
|
+
out_rgb = lanczos_resize(
|
|
405
|
+
out_rgb,
|
|
406
|
+
max(2, round(width * scale)),
|
|
407
|
+
max(2, round(height * scale)),
|
|
408
|
+
)
|
|
409
|
+
height, width = out_rgb.shape[:2]
|
|
410
|
+
mid = width // 2
|
|
411
|
+
if mid < 1 or width - mid < 1:
|
|
412
|
+
score = 0.0
|
|
413
|
+
else:
|
|
414
|
+
score = strip_seam_score(out_rgb[:, :mid], out_rgb[:, mid:], overlap=1)
|
|
415
|
+
return {
|
|
416
|
+
"mode": "seam",
|
|
417
|
+
"seam_score": score,
|
|
418
|
+
"width": int(width),
|
|
419
|
+
"height": int(height),
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
if input_path is None or not input_path.is_file():
|
|
423
|
+
raise HTTPException(404, "Input not found")
|
|
424
|
+
in_rgb, _, _ = load_rgba(input_path)
|
|
425
|
+
out_h, out_w = out_rgb.shape[:2]
|
|
426
|
+
cap = 512
|
|
427
|
+
if max(out_h, out_w) > cap:
|
|
428
|
+
scale = cap / max(out_h, out_w)
|
|
429
|
+
tw, th = max(1, round(out_w * scale)), max(1, round(out_h * scale))
|
|
430
|
+
compared = lanczos_resize(out_rgb, tw, th)
|
|
431
|
+
preview = True
|
|
432
|
+
else:
|
|
433
|
+
tw, th = out_w, out_h
|
|
434
|
+
compared = out_rgb
|
|
435
|
+
preview = False
|
|
436
|
+
baseline = lanczos_resize(in_rgb, tw, th)
|
|
437
|
+
metrics = diff_metrics(compared, baseline)
|
|
438
|
+
delta = np.abs(compared.astype(np.int16) - baseline.astype(np.int16))
|
|
439
|
+
vis = np.clip(delta * 4, 0, 255).astype(np.uint8)
|
|
440
|
+
png_path = job_dir / "quality_diff.png"
|
|
441
|
+
Image.fromarray(vis, mode="RGB").save(png_path)
|
|
442
|
+
return {
|
|
443
|
+
"mode": "diff",
|
|
444
|
+
"metrics": metrics,
|
|
445
|
+
"preview": preview,
|
|
446
|
+
"width": int(tw),
|
|
447
|
+
"height": int(th),
|
|
448
|
+
"png": png_path.name,
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
@router.get("/api/jobs/{job_id}/result")
|
|
452
|
+
def job_result(job_id: str) -> FileResponse:
|
|
453
|
+
with D._jobs_lock:
|
|
454
|
+
job = D._jobs.get(job_id)
|
|
455
|
+
if job is not None and job.output_path is not None and job.output_path.is_file():
|
|
456
|
+
return FileResponse(job.output_path, filename=job.output_path.name)
|
|
457
|
+
result = D._find_result_file(D._safe_job_dir(job_id))
|
|
458
|
+
if result is not None and result.is_file():
|
|
459
|
+
return FileResponse(result, filename=result.name)
|
|
460
|
+
raise HTTPException(404, "Result not ready")
|
|
461
|
+
|
|
462
|
+
@router.get("/api/jobs/{job_id}/preview")
|
|
463
|
+
def job_preview(job_id: str) -> FileResponse:
|
|
464
|
+
"""Small input thumbnail (≤512 px)."""
|
|
465
|
+
with D._jobs_lock:
|
|
466
|
+
job = D._jobs.get(job_id)
|
|
467
|
+
preview = (job.job_dir if job is not None else D._safe_job_dir(job_id)) / "preview.png"
|
|
468
|
+
if not preview.is_file():
|
|
469
|
+
# Fall back to input.*
|
|
470
|
+
job_dir = preview.parent
|
|
471
|
+
inputs = sorted(job_dir.glob("input.*"))
|
|
472
|
+
if inputs:
|
|
473
|
+
try:
|
|
474
|
+
D._make_preview(inputs[0], preview, max_edge=512)
|
|
475
|
+
except Exception: # noqa: BLE001
|
|
476
|
+
pass
|
|
477
|
+
if not preview.is_file():
|
|
478
|
+
raise HTTPException(404, "Preview not found")
|
|
479
|
+
return FileResponse(preview, media_type="image/png")
|
|
480
|
+
|
|
481
|
+
@router.get("/api/jobs/{job_id}/display")
|
|
482
|
+
def job_display(job_id: str) -> FileResponse:
|
|
483
|
+
"""Browser-safe result preview (long edge ≤4096). Full file is /result.
|
|
484
|
+
|
|
485
|
+
Serves from disk even after process restart (job no longer in memory).
|
|
486
|
+
"""
|
|
487
|
+
job_dir = D._safe_job_dir(job_id)
|
|
488
|
+
display = job_dir / "display.png"
|
|
489
|
+
if display.is_file():
|
|
490
|
+
return FileResponse(display, media_type="image/png")
|
|
491
|
+
|
|
492
|
+
with D._jobs_lock:
|
|
493
|
+
job = D._jobs.get(job_id)
|
|
494
|
+
result: Path | None = None
|
|
495
|
+
if job is not None and job.output_path is not None and job.output_path.is_file():
|
|
496
|
+
result = job.output_path
|
|
497
|
+
else:
|
|
498
|
+
result = D._find_result_file(job_dir)
|
|
499
|
+
|
|
500
|
+
if result is not None and result.is_file():
|
|
501
|
+
try:
|
|
502
|
+
D._make_preview(result, display, max_edge=4096)
|
|
503
|
+
if display.is_file():
|
|
504
|
+
return FileResponse(display, media_type="image/png")
|
|
505
|
+
except Exception: # noqa: BLE001
|
|
506
|
+
pass
|
|
507
|
+
return FileResponse(result, filename=result.name)
|
|
508
|
+
raise HTTPException(404, "Display preview not ready")
|
|
509
|
+
|
|
510
|
+
@router.get("/api/jobs/{job_id}/passes/{pass_n:int}")
|
|
511
|
+
def job_pass(job_id: str, pass_n: int) -> FileResponse:
|
|
512
|
+
job_dir = D._safe_job_dir(job_id)
|
|
513
|
+
art = job_dir / f"pass_{pass_n}.png"
|
|
514
|
+
if not art.is_file():
|
|
515
|
+
raise HTTPException(404, "Pass preview not found")
|
|
516
|
+
return FileResponse(art, media_type="image/png")
|
|
@@ -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)}
|