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