upscalex 0.1.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.
upscalex/server.py ADDED
@@ -0,0 +1,241 @@
1
+ """
2
+ Model Context Protocol (MCP) server for UpscaleX Ultra-High-Resolution Image Upscaling.
3
+ Integrates directly with Claude Desktop, Antigravity, Cursor, and any MCP client.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Any, Dict, List, Optional, Union
12
+
13
+ from fastmcp import FastMCP
14
+
15
+ from .engine import RealESRGANEngine
16
+
17
+ # Initialize the FastMCP server instance
18
+ mcp = FastMCP("UpscaleX")
19
+
20
+ _engine_instance: Optional[RealESRGANEngine] = None
21
+
22
+ def get_engine() -> RealESRGANEngine:
23
+ """Lazy engine singleton resolver."""
24
+ global _engine_instance
25
+ if _engine_instance is None:
26
+ _engine_instance = RealESRGANEngine(auto_download=True)
27
+ return _engine_instance
28
+
29
+ @mcp.tool()
30
+ def upscale_image(
31
+ image_path: str,
32
+ target: str = "16k",
33
+ model: str = "realesrgan-x4plus",
34
+ output_path: Optional[str] = None,
35
+ tile_size: int = 256,
36
+ gpu_id: str = "auto",
37
+ tta: bool = False,
38
+ ) -> Dict[str, Any]:
39
+ """
40
+ Upscale an image to 8K, 16K, 4x, or custom resolution using UpscaleX.
41
+ Automatically optimizes between Vulkan GPU acceleration and multi-threaded CPU fallback.
42
+
43
+ Args:
44
+ image_path: Absolute or relative path to the source image (PNG, JPG, WEBP).
45
+ target: Target resolution preset ('16k', '8k', '4k', '4x', '2x', or 'WIDTHxHEIGHT').
46
+ Defaults to '16k' (4x upscale).
47
+ model: RealESRGAN model ID from catalog (e.g. 'realesrgan-x4plus', 'realesrgan-x4plus-anime',
48
+ '4x-ultrasharp', '4x-nmkd-superscale').
49
+ output_path: Optional path for the upscaled output. If omitted, saves next to source.
50
+ tile_size: GPU tile size in pixels (default 256, safe for 4GB-8GB VRAM).
51
+ gpu_id: Hardware device selection: 'auto' (picks discrete GPU), integer ID ('0', '1'),
52
+ or 'cpu' for CPU-only multi-threaded processing.
53
+ tta: Enable Test-Time Augmentation for higher quality at the cost of speed.
54
+
55
+ Returns:
56
+ Dictionary containing upscale metrics, output path, final resolution, acceleration mode, and duration.
57
+ """
58
+ try:
59
+ engine = get_engine()
60
+ return engine.upscale(
61
+ input_path=image_path,
62
+ output_path=output_path,
63
+ target=target,
64
+ model=model,
65
+ tile_size=tile_size,
66
+ gpu_id=gpu_id,
67
+ tta=tta,
68
+ )
69
+ except Exception as e:
70
+ return {
71
+ "success": False,
72
+ "error": str(e),
73
+ "error_type": type(e).__name__,
74
+ "image_path": image_path,
75
+ "solution": "Verify file exists, check available models via 'list_available_models', or use '--gpu-id cpu'.",
76
+ }
77
+
78
+ @mcp.tool()
79
+ def recommend_model(image_path: str, priority: str = "balanced") -> Dict[str, Any]:
80
+ """
81
+ Inspect host GPU specifications, VRAM tier, CPU threads, and image characteristics
82
+ (photos vs illustrations) to recommend the optimal model, target preset, and tile size.
83
+
84
+ Args:
85
+ image_path: Path to the image file to evaluate.
86
+ priority: Optimization priority ('balanced', 'speed', 'quality').
87
+
88
+ Returns:
89
+ Dictionary containing recommended model, target preset, tile size, reasoning, and ready CLI command.
90
+ """
91
+ try:
92
+ engine = get_engine()
93
+ return engine.recommend_model(image_path, priority=priority)
94
+ except Exception as e:
95
+ return {
96
+ "success": False,
97
+ "error": str(e),
98
+ "error_type": type(e).__name__,
99
+ "image_path": image_path,
100
+ "solution": "Ensure the path points to a readable image file.",
101
+ }
102
+
103
+ @mcp.tool()
104
+ def download_model(model_id: str) -> Dict[str, Any]:
105
+ """
106
+ Download open-weight model files on demand from upstream mirrors into the local models directory.
107
+
108
+ Args:
109
+ model_id: Identifier of the model to download (e.g. '4x-ultrasharp', '4x-nmkd-superscale',
110
+ 'realesr-general-x4v3', 'realesrgan-anime-6b').
111
+
112
+ Returns:
113
+ Status dictionary with download confirmation, file size, and target path.
114
+ """
115
+ try:
116
+ engine = get_engine()
117
+ return engine.download_model(model_id)
118
+ except Exception as e:
119
+ return {
120
+ "success": False,
121
+ "error": str(e),
122
+ "error_type": type(e).__name__,
123
+ "model_id": model_id,
124
+ "solution": "Call 'list_available_models' to inspect available models in catalog.",
125
+ }
126
+
127
+ @mcp.tool()
128
+ def get_image_metadata(image_path: str) -> Dict[str, Any]:
129
+ """
130
+ Retrieve comprehensive image metadata including resolution, megapixels,
131
+ aspect ratio, file size, color space, and print sizing at 300 DPI.
132
+
133
+ Args:
134
+ image_path: Path to the image file to inspect.
135
+
136
+ Returns:
137
+ Dictionary with image properties and print dimensions.
138
+ """
139
+ try:
140
+ engine = get_engine()
141
+ return engine.get_image_metadata(image_path)
142
+ except Exception as e:
143
+ return {
144
+ "success": False,
145
+ "error": str(e),
146
+ "error_type": type(e).__name__,
147
+ "image_path": image_path,
148
+ }
149
+
150
+ @mcp.tool()
151
+ def list_available_models() -> List[Dict[str, Any]]:
152
+ """
153
+ List all supported models in the catalog with installation status, VRAM requirements,
154
+ and ideal media targets.
155
+
156
+ Returns:
157
+ List of model dictionaries.
158
+ """
159
+ try:
160
+ engine = get_engine()
161
+ return engine.list_models()
162
+ except Exception as e:
163
+ return [{"error": str(e)}]
164
+
165
+ @mcp.tool()
166
+ def get_system_diagnostics() -> Dict[str, Any]:
167
+ """
168
+ Check cross-platform hardware profile, OS, CPU thread count, Vulkan status,
169
+ and detected GPU acceleration hardware.
170
+
171
+ Returns:
172
+ Hardware diagnostics dictionary.
173
+ """
174
+ try:
175
+ engine = get_engine()
176
+ return engine.get_system_diagnostics()
177
+ except Exception as e:
178
+ return {"error": str(e)}
179
+
180
+ @mcp.tool()
181
+ def calculate_print_dpi(
182
+ image_path: str,
183
+ print_width_inches: float,
184
+ print_height_inches: float,
185
+ ) -> Dict[str, Any]:
186
+ """
187
+ Calculate print fidelity (DPI) for a given physical print size and recommend
188
+ whether upscaling to 8K or 16K is required.
189
+
190
+ Args:
191
+ image_path: Path to the image.
192
+ print_width_inches: Desired print width in inches (e.g. 24 for 24x36 poster).
193
+ print_height_inches: Desired print height in inches (e.g. 36 for 24x36 poster).
194
+
195
+ Returns:
196
+ DPI analysis, quality rating, and recommended upscale factor.
197
+ """
198
+ try:
199
+ engine = get_engine()
200
+ meta = engine.get_image_metadata(image_path)
201
+ w, h = meta["width"], meta["height"]
202
+
203
+ dpi_x = w / print_width_inches if print_width_inches > 0 else 0
204
+ dpi_y = h / print_height_inches if print_height_inches > 0 else 0
205
+ effective_dpi = round(min(dpi_x, dpi_y), 1)
206
+
207
+ if effective_dpi >= 300:
208
+ quality = "Excellent (Gallery / Fine Art Quality: >=300 DPI)"
209
+ recommendation = "No upscaling necessary for this print size."
210
+ elif effective_dpi >= 200:
211
+ quality = "Good (Standard Commercial Print: 200-299 DPI)"
212
+ recommendation = "Upscaling to 8K or 2x recommended for fine text and sharp lines."
213
+ elif effective_dpi >= 150:
214
+ quality = "Fair (Acceptable viewing distance print: 150-199 DPI)"
215
+ recommendation = "Upscaling to 8K or 16K strongly recommended for sharp print detail."
216
+ else:
217
+ quality = "Poor (Pixelated / Low Resolution: <150 DPI)"
218
+ recommendation = "Upscaling to 16K (4x) required to avoid visible pixelation and blurring."
219
+
220
+ return {
221
+ "success": True,
222
+ "image_path": str(image_path),
223
+ "current_resolution": f"{w}x{h}",
224
+ "print_size_inches": f"{print_width_inches} x {print_height_inches}",
225
+ "effective_dpi": effective_dpi,
226
+ "quality_rating": quality,
227
+ "recommendation": recommendation,
228
+ }
229
+ except Exception as e:
230
+ return {
231
+ "success": False,
232
+ "error": str(e),
233
+ "image_path": image_path,
234
+ }
235
+
236
+ def main():
237
+ """Run MCP server via stdio transport."""
238
+ mcp.run()
239
+
240
+ if __name__ == "__main__":
241
+ main()
upscalex/utils.py ADDED
@@ -0,0 +1,198 @@
1
+ """
2
+ Utility functions for UpscaleX engine, cross-platform hardware detection, downloader, and formatters.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import platform
9
+ import re
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+ import urllib.request
15
+ import zipfile
16
+ from pathlib import Path
17
+ from typing import Any, Dict, List, Optional, Tuple
18
+
19
+ from PIL import Image
20
+
21
+ # Official Real-ESRGAN release binary URLs
22
+ RELEASE_URLS = {
23
+ "Windows": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-windows.zip",
24
+ "Linux": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-ubuntu.zip",
25
+ "Darwin": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-macos.zip",
26
+ }
27
+
28
+ def get_default_cache_dir() -> Path:
29
+ """Returns the platform-appropriate cache directory for binary storage."""
30
+ home = Path.home()
31
+ if sys.platform == "win32":
32
+ base = os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA")
33
+ if base:
34
+ return Path(base) / "realesrgan-upscaler"
35
+ return home / ".cache" / "realesrgan-upscaler"
36
+ elif sys.platform == "darwin":
37
+ return home / "Library" / "Caches" / "realesrgan-upscaler"
38
+ else:
39
+ return home / ".cache" / "realesrgan-upscaler"
40
+
41
+ def get_binary_name() -> str:
42
+ """Returns the executable name for the current OS."""
43
+ return "realesrgan-ncnn-vulkan.exe" if sys.platform == "win32" else "realesrgan-ncnn-vulkan"
44
+
45
+ def download_and_extract_engine(dest_dir: Optional[Path] = None, progress_callback = None) -> Path:
46
+ """
47
+ Downloads and extracts the official pre-compiled Real-ESRGAN binary.
48
+ Ensures POSIX execution permissions and clears macOS quarantine flags.
49
+ """
50
+ system_name = platform.system()
51
+ if system_name not in RELEASE_URLS:
52
+ raise RuntimeError(f"Unsupported operating system for precompiled binary: {system_name}")
53
+
54
+ url = RELEASE_URLS[system_name]
55
+ target_dir = dest_dir or get_default_cache_dir()
56
+ target_dir.mkdir(parents=True, exist_ok=True)
57
+
58
+ bin_name = get_binary_name()
59
+ bin_path = target_dir / bin_name
60
+
61
+ if bin_path.exists() and (target_dir / "models").exists():
62
+ return bin_path
63
+
64
+ zip_path = target_dir / "realesrgan.zip"
65
+
66
+ try:
67
+ def reporthook(block_num, block_size, total_size):
68
+ if progress_callback and total_size > 0:
69
+ progress_callback(block_num * block_size, total_size)
70
+
71
+ urllib.request.urlretrieve(url, zip_path, reporthook=reporthook)
72
+
73
+ with zipfile.ZipFile(zip_path, "r") as zf:
74
+ zf.extractall(target_dir)
75
+
76
+ # Set execution permissions on Linux/macOS
77
+ if sys.platform != "win32" and bin_path.exists():
78
+ bin_path.chmod(bin_path.stat().st_mode | 0o755)
79
+
80
+ # Remove macOS quarantine flag if on Darwin
81
+ if sys.platform == "darwin":
82
+ try:
83
+ subprocess.run(["xattr", "-cr", str(target_dir)], check=False, capture_output=True)
84
+ except Exception:
85
+ pass
86
+
87
+ return bin_path
88
+ finally:
89
+ if zip_path.exists():
90
+ try:
91
+ zip_path.unlink()
92
+ except OSError:
93
+ pass
94
+
95
+ def probe_vulkan_gpus(binary_path: Path, models_dir: Path) -> List[Dict[str, Any]]:
96
+ """
97
+ Probes available Vulkan compute devices through the native runtime.
98
+ Returns list of discovered GPU devices and indices.
99
+ """
100
+ if not binary_path.exists():
101
+ return []
102
+
103
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f_in:
104
+ Image.new("RGB", (16, 16), "black").save(f_in.name)
105
+ tmp_in = f_in.name
106
+
107
+ tmp_out = Path(tempfile.gettempdir()) / f"probe_{os.getpid()}.png"
108
+
109
+ try:
110
+ cmd = [
111
+ str(binary_path),
112
+ "-i", tmp_in,
113
+ "-o", str(tmp_out),
114
+ "-m", str(models_dir),
115
+ "-v",
116
+ ]
117
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=8)
118
+ output = proc.stdout + "\n" + proc.stderr
119
+
120
+ # Pattern matches device declarations: [0 Intel UHD], [1 NVIDIA GeForce RTX...]
121
+ pattern = re.compile(r"\[(\d+)\s+([^\]]+)\]\s+queueC")
122
+ devices = []
123
+ seen = set()
124
+
125
+ for match in pattern.finditer(output):
126
+ dev_id = int(match.group(1))
127
+ dev_name = match.group(2).strip()
128
+ if dev_id not in seen:
129
+ seen.add(dev_id)
130
+ is_discrete = any(k in dev_name.lower() for k in ["nvidia", "geforce", "rtx", "gtx", "radeon", "rx", "apple", "discrete"])
131
+ devices.append({
132
+ "id": dev_id,
133
+ "name": dev_name,
134
+ "is_discrete": is_discrete,
135
+ })
136
+
137
+ return devices
138
+ except Exception:
139
+ return []
140
+ finally:
141
+ for f in [Path(tmp_in), tmp_out]:
142
+ if f.exists():
143
+ try:
144
+ f.unlink()
145
+ except OSError:
146
+ pass
147
+
148
+ def get_system_diagnostics(binary_path: Optional[Path] = None, models_dir: Optional[Path] = None) -> Dict[str, Any]:
149
+ """
150
+ Returns complete cross-platform environment diagnostics including
151
+ OS, architecture, CPU threads, and detected GPU acceleration hardware.
152
+ """
153
+ sys_name = platform.system()
154
+ arch = platform.machine()
155
+ cpu_count = os.cpu_count() or 1
156
+
157
+ gpus = []
158
+ if binary_path and models_dir and binary_path.exists():
159
+ gpus = probe_vulkan_gpus(binary_path, models_dir)
160
+
161
+ # Determine recommended acceleration strategy
162
+ if gpus:
163
+ discrete = [g for g in gpus if g["is_discrete"]]
164
+ selected_gpu = discrete[0]["id"] if discrete else gpus[0]["id"]
165
+ accel_mode = f"Vulkan GPU (Device {selected_gpu}: {gpus[selected_gpu]['name']})"
166
+ recommended_tile = 256
167
+ else:
168
+ selected_gpu = None
169
+ accel_mode = f"CPU Multi-Threaded (Lanczos-3, {cpu_count} threads)"
170
+ recommended_tile = 256
171
+
172
+ return {
173
+ "os": sys_name,
174
+ "os_release": platform.release(),
175
+ "architecture": arch,
176
+ "python_version": platform.python_version(),
177
+ "cpu_threads": cpu_count,
178
+ "has_vulkan_gpu": len(gpus) > 0,
179
+ "detected_gpus": gpus,
180
+ "recommended_gpu_id": selected_gpu,
181
+ "acceleration_mode": accel_mode,
182
+ "recommended_tile_size": recommended_tile,
183
+ }
184
+
185
+ def format_bytes(size: int | float) -> str:
186
+ """Format bytes into a human-readable string (KB, MB, GB)."""
187
+ units = ["B", "KB", "MB", "GB", "TB"]
188
+ val = float(size)
189
+ for u in units:
190
+ if val < 1024.0 or u == "TB":
191
+ return f"{val:.2f} {u}"
192
+ val /= 1024.0
193
+ return f"{size} B"
194
+
195
+ def format_megapixels(width: int, height: int) -> str:
196
+ """Calculates megapixels and formats as string."""
197
+ mp = (width * height) / 1_000_000.0
198
+ return f"{mp:.2f} MP"