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
@@ -0,0 +1,140 @@
1
+ """Alpha-channel upsampling policy shared by Torch and ONNX backends.
2
+
3
+ Default is Lanczos (classical). Neural SR of alpha is optional, Torch-only,
4
+ and expensive: the alpha plane is expanded to 3ch, run through the same
5
+ tiled SR path as RGB, then averaged back to a single channel.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ import numpy as np
13
+
14
+ from .io_utils import lanczos_resize
15
+
16
+
17
+ def upsample_alpha_lanczos(
18
+ alpha: np.ndarray,
19
+ *,
20
+ target_w: int,
21
+ target_h: int,
22
+ ) -> np.ndarray:
23
+ """Classical Lanczos resize of a single-channel alpha plane."""
24
+ a = np.asarray(alpha)
25
+ if a.ndim == 3:
26
+ a = a[:, :, 0]
27
+ a = np.ascontiguousarray(a, dtype=np.uint8)
28
+ if a.shape[1] == target_w and a.shape[0] == target_h:
29
+ return a
30
+ return lanczos_resize(a, target_w, target_h)
31
+
32
+
33
+ def upsample_alpha_sr(
34
+ alpha: np.ndarray,
35
+ *,
36
+ scale: float,
37
+ descriptor: Any,
38
+ device: Any,
39
+ fp16: bool,
40
+ tile: int,
41
+ overlap: int,
42
+ show_progress: bool = False,
43
+ model_scale: int | None = None,
44
+ disk_intermediate_threshold: int | None = None,
45
+ cancel_event: Any = None,
46
+ pause_event: Any = None,
47
+ target_w: int | None = None,
48
+ target_h: int | None = None,
49
+ infer_fn: Any = None,
50
+ ) -> np.ndarray:
51
+ """Neural SR of alpha via grayscale→RGB stack then channel mean.
52
+
53
+ Prefer :func:`upsample_alpha_lanczos` for soft/semi-transparent edges;
54
+ this path is for hard mattes where SR edge detail matters and the user
55
+ opted in with ``--sr-alpha``.
56
+ """
57
+ from .pipeline import DEFAULT_DISK_INTERMEDIATE_THRESHOLD, run
58
+
59
+ a = np.asarray(alpha)
60
+ if a.ndim == 3:
61
+ a = a[:, :, 0]
62
+ a = np.ascontiguousarray(a, dtype=np.uint8)
63
+ rgb = np.stack([a, a, a], axis=-1)
64
+ thr = (
65
+ DEFAULT_DISK_INTERMEDIATE_THRESHOLD
66
+ if disk_intermediate_threshold is None
67
+ else disk_intermediate_threshold
68
+ )
69
+ out = run(
70
+ rgb,
71
+ scale=scale,
72
+ descriptor=descriptor,
73
+ device=device,
74
+ fp16=fp16,
75
+ tile=tile,
76
+ overlap=overlap,
77
+ show_progress=show_progress,
78
+ model_scale=model_scale,
79
+ disk_intermediate_threshold=thr,
80
+ cancel_event=cancel_event,
81
+ pause_event=pause_event,
82
+ strength=1.0,
83
+ target_w=target_w,
84
+ target_h=target_h,
85
+ infer_fn=infer_fn,
86
+ )
87
+ return out.mean(axis=-1).round().astype(np.uint8)
88
+
89
+
90
+ def upsample_alpha(
91
+ alpha: np.ndarray,
92
+ *,
93
+ scale: float,
94
+ target_w: int,
95
+ target_h: int,
96
+ sr_alpha: bool = False,
97
+ descriptor: Any = None,
98
+ device: Any = None,
99
+ fp16: bool = False,
100
+ tile: int = 256,
101
+ overlap: int = 32,
102
+ show_progress: bool = False,
103
+ model_scale: int | None = None,
104
+ disk_intermediate_threshold: int | None = None,
105
+ cancel_event: Any = None,
106
+ pause_event: Any = None,
107
+ infer_fn: Any = None,
108
+ allow_sr: bool = True,
109
+ ) -> np.ndarray:
110
+ """Resolve alpha to ``target_w×target_h``.
111
+
112
+ When ``sr_alpha`` is False, or SR is disallowed / unavailable, uses Lanczos
113
+ to the target size. When ``sr_alpha`` and ``allow_sr`` and a descriptor or
114
+ ``infer_fn`` is present, runs neural SR (may produce a padded canvas that
115
+ finalize unwraps).
116
+ """
117
+ if (
118
+ sr_alpha
119
+ and allow_sr
120
+ and scale > 1.0
121
+ and (descriptor is not None or infer_fn is not None)
122
+ ):
123
+ return upsample_alpha_sr(
124
+ alpha,
125
+ scale=scale,
126
+ descriptor=descriptor,
127
+ device=device,
128
+ fp16=fp16,
129
+ tile=tile,
130
+ overlap=overlap,
131
+ show_progress=show_progress,
132
+ model_scale=model_scale,
133
+ disk_intermediate_threshold=disk_intermediate_threshold,
134
+ cancel_event=cancel_event,
135
+ pause_event=pause_event,
136
+ target_w=target_w,
137
+ target_h=target_h,
138
+ infer_fn=infer_fn,
139
+ )
140
+ return upsample_alpha_lanczos(alpha, target_w=target_w, target_h=target_h)
@@ -0,0 +1,19 @@
1
+ """FastAPI route modules (included from server.app)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import FastAPI
6
+
7
+
8
+ def include_routers(app: FastAPI) -> None:
9
+ from .compare_routes import router as compare_router
10
+ from .jobs import router as jobs_router
11
+ from .media_routes import router as media_router
12
+ from .models_routes import router as models_router
13
+ from .system_routes import router as system_router
14
+
15
+ app.include_router(jobs_router)
16
+ app.include_router(compare_router)
17
+ app.include_router(models_router)
18
+ app.include_router(system_router)
19
+ app.include_router(media_router)
@@ -0,0 +1,256 @@
1
+ """API routes split from server.py."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import shutil
7
+ import threading
8
+ import uuid
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from fastapi import APIRouter, File, Form, HTTPException, UploadFile
14
+ from fastapi.responses import FileResponse, Response
15
+ from pydantic import BaseModel, Field
16
+
17
+ from upscale.api import deps as D
18
+ from upscale.tiling import JobCancelled
19
+
20
+ router = APIRouter()
21
+
22
+ class ZipBody(BaseModel):
23
+ job_ids: list[str]
24
+
25
+
26
+ @router.post("/api/zip")
27
+ def api_zip(body: ZipBody) -> Response:
28
+ """Zip completed job result files for batch download."""
29
+ import io
30
+ import zipfile
31
+
32
+ if not body.job_ids:
33
+ raise HTTPException(400, "job_ids required")
34
+ if len(body.job_ids) > 64:
35
+ raise HTTPException(400, "too many jobs")
36
+ buf = io.BytesIO()
37
+ added = 0
38
+ with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
39
+ for jid in body.job_ids:
40
+ result: Path | None = None
41
+ with D._jobs_lock:
42
+ job = D._jobs.get(jid)
43
+ if job is not None and job.output_path is not None and job.output_path.is_file():
44
+ result = job.output_path
45
+ else:
46
+ try:
47
+ result = D._find_result_file(D._safe_job_dir(jid))
48
+ except HTTPException:
49
+ continue
50
+ if result is None or not result.is_file():
51
+ continue
52
+ arc = f"{jid}_{result.name}"
53
+ zf.write(result, arcname=arc)
54
+ added += 1
55
+ if added == 0:
56
+ raise HTTPException(404, "No completed results to zip")
57
+ return Response(
58
+ content=buf.getvalue(),
59
+ media_type="application/zip",
60
+ headers={"Content-Disposition": 'attachment; filename="upscale-batch.zip"'},
61
+ )
62
+
63
+ class CompareBody(BaseModel):
64
+ models: list[str] = Field(default_factory=list)
65
+ algorithms: list[str] = Field(default_factory=list)
66
+ filters: list[str] = Field(default_factory=list)
67
+ filter_amounts: dict[str, float] = Field(default_factory=dict)
68
+ base_model: str = "RealESRGAN_x4plus"
69
+ base_algorithm: str | None = None
70
+ crop: dict[str, int]
71
+ scale: float = 4.0
72
+ device: str = "auto"
73
+ half: bool = False
74
+
75
+
76
+ @dataclass
77
+ class CompareRun:
78
+ id: str
79
+ dir: Path
80
+ cancel_event: threading.Event = field(default_factory=threading.Event)
81
+ state: str = "running" # running | done | cancelled | error
82
+ results: list[dict[str, Any]] = field(default_factory=list)
83
+ error: str | None = None
84
+ message: str = ""
85
+ created_at: float = field(default_factory=lambda: __import__("time").time())
86
+
87
+
88
+
89
+
90
+ def _compare_worker(
91
+ run: CompareRun,
92
+ input_path: Path,
93
+ variants: list[dict[str, Any]],
94
+ crop: Any,
95
+ scale: float,
96
+ device: str,
97
+ half: bool,
98
+ ) -> None:
99
+ from upscale.compare import compare_variants
100
+
101
+ try:
102
+ # Share the process-wide execute lock so compare never overlaps a job.
103
+ with D._execute_lock:
104
+ results = compare_variants(
105
+ input_path,
106
+ run.dir,
107
+ variants=variants,
108
+ crop=crop,
109
+ scale=scale,
110
+ device=device,
111
+ half=half,
112
+ cancel_event=run.cancel_event,
113
+ progress=lambda msg, _frac: setattr(run, "message", msg),
114
+ )
115
+ run.results = results
116
+ # Persist results for status after in-memory eviction
117
+ try:
118
+ (run.dir / "compare_results.json").write_text(
119
+ json.dumps(results), encoding="utf-8"
120
+ )
121
+ except OSError:
122
+ pass
123
+ if run.cancel_event.is_set():
124
+ run.state = "cancelled"
125
+ run.message = "cancelled"
126
+ else:
127
+ run.state = "done"
128
+ run.message = ""
129
+ except JobCancelled:
130
+ run.state = "cancelled"
131
+ run.message = "cancelled"
132
+ except Exception as exc: # noqa: BLE001 — surface to status poller
133
+ run.state = "error"
134
+ run.error = str(exc)
135
+ run.message = str(exc)
136
+
137
+
138
+ @router.post("/api/compare")
139
+ async def api_compare(
140
+ file: UploadFile = File(...),
141
+ body: str = Form("{}"),
142
+ ) -> dict[str, Any]:
143
+ """Start a crop compare; poll ``GET /api/compare/{id}/status`` until done."""
144
+ from upscale.compare import build_variants
145
+ from upscale.schema import CropRect
146
+
147
+ try:
148
+ raw = json.loads(body) if body.strip() else {}
149
+ cb = CompareBody.model_validate(raw)
150
+ except (json.JSONDecodeError, ValueError) as exc:
151
+ raise HTTPException(400, f"Invalid compare body: {exc}") from exc
152
+ variants = build_variants(
153
+ models=cb.models,
154
+ algorithms=cb.algorithms,
155
+ filters=cb.filters,
156
+ filter_amounts=cb.filter_amounts,
157
+ base_model=cb.base_model,
158
+ base_algorithm=cb.base_algorithm,
159
+ )
160
+ if not variants:
161
+ raise HTTPException(
162
+ 400, "Select at least one model, classical algorithm, or filter"
163
+ )
164
+
165
+ run_id = uuid.uuid4().hex
166
+ run_dir = D.JOBS_ROOT / f"compare-{run_id}"
167
+ run_dir.mkdir(parents=True, exist_ok=True)
168
+ from upscale.io_utils import is_vector_input, require_raster_suffix
169
+
170
+ try:
171
+ suffix = require_raster_suffix(file.filename)
172
+ except ValueError as exc:
173
+ shutil.rmtree(run_dir, ignore_errors=True)
174
+ raise HTTPException(400, str(exc)) from exc
175
+ if is_vector_input(file.filename, file.content_type):
176
+ shutil.rmtree(run_dir, ignore_errors=True)
177
+ raise HTTPException(
178
+ 400,
179
+ "Vector images are not supported. "
180
+ "Rasterize to PNG, TIFF, or another supported bitmap format first.",
181
+ )
182
+ input_path = run_dir / f"input{suffix}"
183
+ content = await file.read()
184
+ if len(content) > D.MAX_UPLOAD_BYTES:
185
+ shutil.rmtree(run_dir, ignore_errors=True)
186
+ raise HTTPException(413, f"Upload exceeds limit of {D.MAX_UPLOAD_BYTES} bytes")
187
+ input_path.write_bytes(content)
188
+ crop = CropRect(
189
+ x=int(cb.crop.get("x", 0)),
190
+ y=int(cb.crop.get("y", 0)),
191
+ w=int(cb.crop.get("w", 64)),
192
+ h=int(cb.crop.get("h", 64)),
193
+ )
194
+ run = CompareRun(id=run_id, dir=run_dir, message="starting")
195
+ with D._compare_lock:
196
+ D._compare_jobs[run_id] = run
197
+ D._compare_runs[run_id] = run_dir
198
+ threading.Thread(
199
+ target=_compare_worker,
200
+ args=(run, input_path, variants, crop, cb.scale, cb.device, cb.half),
201
+ name=f"compare-{run_id[:8]}",
202
+ daemon=True,
203
+ ).start()
204
+ return {"id": run_id, "state": "running"}
205
+
206
+ @router.get("/api/compare/{run_id}/status")
207
+ def api_compare_status(run_id: str) -> dict[str, Any]:
208
+ with D._compare_lock:
209
+ run = D._compare_jobs.get(run_id)
210
+ if run is None:
211
+ run_dir = D._compare_runs.get(run_id) or (D.JOBS_ROOT / f"compare-{run_id}")
212
+ run_dir = Path(run_dir)
213
+ if not run_dir.is_dir():
214
+ raise HTTPException(404, "Compare run not found")
215
+ results: list[dict[str, Any]] = []
216
+ meta = run_dir / "compare_results.json"
217
+ if meta.is_file():
218
+ try:
219
+ results = json.loads(meta.read_text(encoding="utf-8"))
220
+ except (OSError, json.JSONDecodeError):
221
+ results = []
222
+ return {
223
+ "id": run_id,
224
+ "state": "done" if results else "error",
225
+ "results": results,
226
+ "message": "" if results else "Compare results unavailable after restart",
227
+ "error": None if results else "results missing",
228
+ }
229
+ return {
230
+ "id": run.id,
231
+ "state": run.state,
232
+ "results": run.results,
233
+ "error": run.error,
234
+ "message": run.message,
235
+ }
236
+
237
+ @router.post("/api/compare/{run_id}/cancel")
238
+ def api_compare_cancel(run_id: str) -> dict[str, str]:
239
+ with D._compare_lock:
240
+ run = D._compare_jobs.get(run_id)
241
+ if run is None:
242
+ raise HTTPException(404, "Compare run not found")
243
+ run.cancel_event.set()
244
+ run.message = "cancelling"
245
+ return {"status": "cancelling"}
246
+
247
+ @router.get("/api/compare/{run_id}/{model:path}")
248
+ def api_compare_result(run_id: str, model: str) -> FileResponse:
249
+ run_dir = D._compare_runs.get(run_id)
250
+ if run_dir is None:
251
+ run_dir = D.JOBS_ROOT / f"compare-{run_id}"
252
+ safe = "".join(c if c.isalnum() or c in "-_" else "_" for c in model)
253
+ path = run_dir / f"compare_{safe}.png"
254
+ if not path.is_file():
255
+ raise HTTPException(404, "Compare result not found")
256
+ return FileResponse(path, media_type="image/png")
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