saliacoel commited on
Commit
2a31d24
·
verified ·
1 Parent(s): 17df7f9

Upload salia_detailer_lora.py

Browse files
Files changed (1) hide show
  1. salia_detailer_lora.py +985 -0
salia_detailer_lora.py ADDED
@@ -0,0 +1,985 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import logging
3
+ import shutil
4
+ import threading
5
+ import urllib.parse
6
+ import urllib.request
7
+ from pathlib import Path
8
+ from typing import Any, Dict, Tuple, Optional
9
+
10
+ import numpy as np
11
+ import torch
12
+ from PIL import Image, ImageOps
13
+
14
+ import comfy.sd
15
+ import comfy.utils
16
+ import folder_paths
17
+ import comfy.model_management as model_management
18
+
19
+
20
+ # transformers is required for depth-estimation pipeline
21
+ try:
22
+ from transformers import pipeline
23
+ except Exception as e:
24
+ pipeline = None
25
+ _TRANSFORMERS_IMPORT_ERROR = e
26
+
27
+
28
+ # -------------------------------------------------------------------------------------
29
+ # Global caches (checkpoint + controlnet + lora) so using the node multiple times
30
+ # won't reload the same files repeatedly
31
+ # -------------------------------------------------------------------------------------
32
+
33
+ _CKPT_CACHE: Dict[str, Tuple[Any, Any, Any]] = {}
34
+ _CN_CACHE: Dict[str, Any] = {}
35
+ _LORA_CACHE: Dict[str, Any] = {}
36
+
37
+ _CKPT_LOCK = threading.Lock()
38
+ _CN_LOCK = threading.Lock()
39
+ _LORA_LOCK = threading.Lock()
40
+
41
+
42
+ # -------------------------------------------------------------------------------------
43
+ # Plugin root detection (works whether file is in plugin root or nodes/)
44
+ # -------------------------------------------------------------------------------------
45
+
46
+ def _find_plugin_root() -> Path:
47
+ """
48
+ Walk upwards from this file until we find an 'assets' folder.
49
+ Robust against hyphen/underscore package naming and different file placement.
50
+ """
51
+ here = Path(__file__).resolve()
52
+ for parent in [here.parent] + list(here.parents)[:12]:
53
+ if (parent / "assets").is_dir():
54
+ return parent
55
+ # fallback: typical nodes/<file>.py
56
+ return here.parent.parent
57
+
58
+
59
+ PLUGIN_ROOT = _find_plugin_root()
60
+ LORA_REPO_BASE = "https://huggingface.co/saliacoel/x/resolve/main"
61
+
62
+
63
+ # -------------------------------------------------------------------------------------
64
+ # PIL helpers (Lanczos resize for IMAGE and MASK)
65
+ # -------------------------------------------------------------------------------------
66
+
67
+ def _pil_lanczos():
68
+ if hasattr(Image, "Resampling"):
69
+ return Image.Resampling.LANCZOS
70
+ return Image.LANCZOS
71
+
72
+
73
+ def _image_tensor_to_pil(img: torch.Tensor) -> Image.Image:
74
+ """
75
+ Comfy IMAGE: [B,H,W,C] or [H,W,C], float [0..1] -> PIL RGB/RGBA
76
+ """
77
+ if img.ndim == 4:
78
+ img = img[0]
79
+ img = img.detach().cpu().float().clamp(0, 1)
80
+ arr = (img.numpy() * 255.0).round().astype(np.uint8)
81
+ if arr.shape[-1] == 4:
82
+ return Image.fromarray(arr, mode="RGBA")
83
+ return Image.fromarray(arr, mode="RGB")
84
+
85
+
86
+ def _pil_to_image_tensor(pil: Image.Image) -> torch.Tensor:
87
+ """
88
+ PIL RGB/RGBA -> Comfy IMAGE [1,H,W,C], float [0..1]
89
+ """
90
+ if pil.mode not in ("RGB", "RGBA"):
91
+ pil = pil.convert("RGBA") if "A" in pil.getbands() else pil.convert("RGB")
92
+ arr = np.array(pil).astype(np.float32) / 255.0
93
+ t = torch.from_numpy(arr) # [H,W,C]
94
+ return t.unsqueeze(0)
95
+
96
+
97
+ def _mask_tensor_to_pil(mask: torch.Tensor) -> Image.Image:
98
+ """
99
+ Comfy MASK: [B,H,W] or [H,W], float [0..1] -> PIL L
100
+ """
101
+ if mask.ndim == 3:
102
+ mask = mask[0]
103
+ mask = mask.detach().cpu().float().clamp(0, 1)
104
+ arr = (mask.numpy() * 255.0).round().astype(np.uint8)
105
+ return Image.fromarray(arr, mode="L")
106
+
107
+
108
+ def _pil_to_mask_tensor(pil_l: Image.Image) -> torch.Tensor:
109
+ """
110
+ PIL L -> Comfy MASK [1,H,W], float [0..1]
111
+ """
112
+ if pil_l.mode != "L":
113
+ pil_l = pil_l.convert("L")
114
+ arr = np.array(pil_l).astype(np.float32) / 255.0
115
+ t = torch.from_numpy(arr) # [H,W]
116
+ return t.unsqueeze(0)
117
+
118
+
119
+ def _resize_image_lanczos(img: torch.Tensor, w: int, h: int) -> torch.Tensor:
120
+ """
121
+ Resize Comfy IMAGE [B,H,W,C] with Lanczos via PIL.
122
+ """
123
+ if img.ndim != 4:
124
+ raise ValueError("Expected IMAGE tensor with shape [B,H,W,C].")
125
+ outs = []
126
+ for i in range(img.shape[0]):
127
+ pil = _image_tensor_to_pil(img[i].unsqueeze(0))
128
+ pil = pil.resize((int(w), int(h)), resample=_pil_lanczos())
129
+ outs.append(_pil_to_image_tensor(pil))
130
+ return torch.cat(outs, dim=0)
131
+
132
+
133
+ def _resize_mask_lanczos(mask: torch.Tensor, w: int, h: int) -> torch.Tensor:
134
+ """
135
+ Resize Comfy MASK [B,H,W] with Lanczos via PIL.
136
+ """
137
+ if mask.ndim != 3:
138
+ raise ValueError("Expected MASK tensor with shape [B,H,W].")
139
+ outs = []
140
+ for i in range(mask.shape[0]):
141
+ pil = _mask_tensor_to_pil(mask[i].unsqueeze(0))
142
+ pil = pil.resize((int(w), int(h)), resample=_pil_lanczos())
143
+ outs.append(_pil_to_mask_tensor(pil))
144
+ return torch.cat(outs, dim=0)
145
+
146
+
147
+ # -------------------------------------------------------------------------------------
148
+ # ✅ ComfyUI 0.5.1 FIX: Manual JoinImageWithAlpha equivalent
149
+ # -------------------------------------------------------------------------------------
150
+
151
+ def _rgb_to_rgba_with_comfy_mask(rgb: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
152
+ """
153
+ Make RGBA from:
154
+ rgb: IMAGE [B,H,W,3] float [0..1]
155
+ mask: MASK [B,H,W] float [0..1] (Comfy convention: 1=masked/transparent)
156
+ Output:
157
+ rgba: IMAGE [B,H,W,4] where alpha = 1 - mask (1=opaque, 0=transparent)
158
+ """
159
+ if rgb.ndim == 3:
160
+ rgb = rgb.unsqueeze(0)
161
+ if mask.ndim == 2:
162
+ mask = mask.unsqueeze(0)
163
+
164
+ if rgb.ndim != 4 or rgb.shape[-1] != 3:
165
+ raise ValueError(f"rgb must be [B,H,W,3], got {tuple(rgb.shape)}")
166
+ if mask.ndim != 3:
167
+ raise ValueError(f"mask must be [B,H,W], got {tuple(mask.shape)}")
168
+
169
+ # Batch match
170
+ if mask.shape[0] != rgb.shape[0]:
171
+ if mask.shape[0] == 1 and rgb.shape[0] > 1:
172
+ mask = mask.expand(rgb.shape[0], -1, -1)
173
+ else:
174
+ raise ValueError("Batch mismatch between rgb and mask.")
175
+
176
+ # Size match
177
+ if mask.shape[1] != rgb.shape[1] or mask.shape[2] != rgb.shape[2]:
178
+ raise ValueError(
179
+ f"Mask size mismatch. rgb={rgb.shape[2]}x{rgb.shape[1]} mask={mask.shape[2]}x{mask.shape[1]}"
180
+ )
181
+
182
+ mask = mask.to(device=rgb.device, dtype=rgb.dtype).clamp(0, 1)
183
+ alpha = (1.0 - mask).unsqueeze(-1).clamp(0, 1) # [B,H,W,1]
184
+
185
+ rgba = torch.cat([rgb.clamp(0, 1), alpha], dim=-1) # [B,H,W,4]
186
+ return rgba
187
+
188
+
189
+ # -------------------------------------------------------------------------------------
190
+ # Core lazy loaders (checkpoint + controlnet), cached globally
191
+ # -------------------------------------------------------------------------------------
192
+
193
+ def _load_checkpoint_cached(ckpt_name: str):
194
+ """
195
+ Mirrors comfy-core CheckpointLoaderSimple, but cached to avoid double-loads.
196
+ Returns: (model, clip, vae)
197
+ """
198
+ with _CKPT_LOCK:
199
+ if ckpt_name in _CKPT_CACHE:
200
+ return _CKPT_CACHE[ckpt_name]
201
+
202
+ import nodes
203
+ loader = nodes.CheckpointLoaderSimple()
204
+ fn = getattr(loader, loader.FUNCTION)
205
+ model, clip, vae = fn(ckpt_name=ckpt_name)
206
+
207
+ _CKPT_CACHE[ckpt_name] = (model, clip, vae)
208
+ return model, clip, vae
209
+
210
+
211
+ def _load_controlnet_cached(control_net_name: str):
212
+ """
213
+ Mirrors comfy-core ControlNetLoader, but cached to avoid double-loads.
214
+ Returns: controlnet
215
+ """
216
+ with _CN_LOCK:
217
+ if control_net_name in _CN_CACHE:
218
+ return _CN_CACHE[control_net_name]
219
+
220
+ import nodes
221
+ loader = nodes.ControlNetLoader()
222
+ fn = getattr(loader, loader.FUNCTION)
223
+ (cn,) = fn(control_net_name=control_net_name)
224
+
225
+ _CN_CACHE[control_net_name] = cn
226
+ return cn
227
+
228
+
229
+ # -------------------------------------------------------------------------------------
230
+ # Single LoRA helpers (download if missing, cache loaded state dict)
231
+ # -------------------------------------------------------------------------------------
232
+
233
+ def _normalize_lora_name(name: str) -> str:
234
+ """
235
+ Accepts:
236
+ - MyLora
237
+ - MyLora.safetensors
238
+ - accidental path input
239
+ Returns:
240
+ - MyLora.safetensors
241
+ Empty input returns "" so the caller can skip LoRA entirely.
242
+ """
243
+ base = str(name or "").strip().replace("\\", "/").split("/")[-1]
244
+ if not base:
245
+ return ""
246
+
247
+ if base.lower().endswith(".safetensors"):
248
+ base = base[:-len(".safetensors")]
249
+
250
+ base = base.strip()
251
+ if not base:
252
+ return ""
253
+
254
+ return f"{base}.safetensors"
255
+
256
+
257
+ def _ensure_lora_available(lora_name: str) -> str:
258
+ existing_path = folder_paths.get_full_path("loras", lora_name)
259
+ if existing_path is not None:
260
+ return existing_path
261
+
262
+ lora_dirs = folder_paths.get_folder_paths("loras")
263
+ if not lora_dirs:
264
+ raise RuntimeError("No ComfyUI 'loras' folder is configured.")
265
+
266
+ target_dir = Path(lora_dirs[0])
267
+ target_path = target_dir / lora_name
268
+ url = f"{LORA_REPO_BASE}/{urllib.parse.quote(lora_name)}"
269
+
270
+ logging.info("[Salia_OneNode_WorkflowSquare] Downloading missing LoRA: %s", url)
271
+ _download_url_to_file(url, target_path)
272
+
273
+ resolved_path = folder_paths.get_full_path("loras", lora_name)
274
+ return resolved_path if resolved_path is not None else str(target_path)
275
+
276
+
277
+ def _load_lora_cached(lora_path: str):
278
+ with _LORA_LOCK:
279
+ if lora_path in _LORA_CACHE:
280
+ return _LORA_CACHE[lora_path]
281
+
282
+ lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
283
+ _LORA_CACHE[lora_path] = lora
284
+ return lora
285
+
286
+
287
+ # -------------------------------------------------------------------------------------
288
+ # Assets/images dropdown + loader (inlined; no LoadImage_SaliaOnline_Assets dependency)
289
+ # -------------------------------------------------------------------------------------
290
+
291
+ def _assets_images_dir() -> Path:
292
+ return PLUGIN_ROOT / "assets" / "images"
293
+
294
+
295
+ def _list_asset_pngs() -> list:
296
+ img_dir = _assets_images_dir()
297
+ if not img_dir.is_dir():
298
+ return []
299
+ files = []
300
+ for p in img_dir.rglob("*"):
301
+ if p.is_file() and p.suffix.lower() == ".png":
302
+ files.append(p.relative_to(img_dir).as_posix())
303
+ files.sort()
304
+ return files
305
+
306
+
307
+ def _safe_asset_path(asset_rel_path: str) -> Path:
308
+ img_dir = _assets_images_dir()
309
+ if not img_dir.is_dir():
310
+ raise FileNotFoundError(f"assets/images folder not found: {img_dir}")
311
+
312
+ base = img_dir.resolve()
313
+ rel = Path(asset_rel_path)
314
+
315
+ if rel.is_absolute():
316
+ raise ValueError("Absolute paths are not allowed for asset_image.")
317
+
318
+ full = (base / rel).resolve()
319
+
320
+ # path traversal protection
321
+ if base != full and base not in full.parents:
322
+ raise ValueError(f"Invalid asset path (path traversal blocked): {asset_rel_path}")
323
+
324
+ if not full.is_file():
325
+ raise FileNotFoundError(f"Asset PNG not found in assets/images: {asset_rel_path}")
326
+ if full.suffix.lower() != ".png":
327
+ raise ValueError(f"Asset is not a PNG: {asset_rel_path}")
328
+
329
+ return full
330
+
331
+
332
+ def _load_asset_image_and_mask(asset_rel_path: str) -> Tuple[torch.Tensor, torch.Tensor]:
333
+ """
334
+ Returns (IMAGE, MASK) in ComfyUI formats.
335
+
336
+ Mask semantics: match ComfyUI core LoadImage:
337
+ - alpha is RGBA alpha channel normalized to [0..1]
338
+ - mask = 1 - alpha
339
+ """
340
+ p = _safe_asset_path(asset_rel_path)
341
+
342
+ im = Image.open(p)
343
+ im = ImageOps.exif_transpose(im)
344
+
345
+ rgba = im.convert("RGBA")
346
+ rgb = rgba.convert("RGB")
347
+
348
+ rgb_arr = np.array(rgb).astype(np.float32) / 255.0 # [H,W,3]
349
+ img_t = torch.from_numpy(rgb_arr)[None, ...]
350
+
351
+ alpha = np.array(rgba.getchannel("A")).astype(np.float32) / 255.0 # [H,W]
352
+ mask = 1.0 - alpha # Comfy MASK convention
353
+
354
+ mask_t = torch.from_numpy(mask)[None, ...]
355
+ return img_t, mask_t
356
+
357
+
358
+ # -------------------------------------------------------------------------------------
359
+ # Salia_Depth (INLINED, no imports from other files)
360
+ # -------------------------------------------------------------------------------------
361
+
362
+ MODEL_DIR = PLUGIN_ROOT / "assets" / "depth"
363
+ MODEL_DIR.mkdir(parents=True, exist_ok=True)
364
+
365
+ REQUIRED_FILES = {
366
+ "config.json": "https://huggingface.co/saliacoel/depth/resolve/main/config.json",
367
+ "model.safetensors": "https://huggingface.co/saliacoel/depth/resolve/main/model.safetensors",
368
+ "preprocessor_config.json": "https://huggingface.co/saliacoel/depth/resolve/main/preprocessor_config.json",
369
+ }
370
+
371
+ ZOE_FALLBACK_REPO_ID = "Intel/zoedepth-nyu-kitti"
372
+
373
+ _PIPE_CACHE: Dict[Tuple[str, str], Any] = {} # (model_source, device_str) -> pipeline
374
+ _PIPE_LOCK = threading.Lock()
375
+
376
+
377
+ def _have_required_files() -> bool:
378
+ return all((MODEL_DIR / name).exists() for name in REQUIRED_FILES.keys())
379
+
380
+
381
+ def _download_url_to_file(url: str, dst: Path, timeout: int = 180) -> None:
382
+ dst.parent.mkdir(parents=True, exist_ok=True)
383
+ tmp = dst.with_suffix(dst.suffix + ".tmp")
384
+
385
+ if tmp.exists():
386
+ try:
387
+ tmp.unlink()
388
+ except Exception:
389
+ pass
390
+
391
+ req = urllib.request.Request(url, headers={"User-Agent": "ComfyUI-Salia/1.2"})
392
+ with urllib.request.urlopen(req, timeout=timeout) as r, open(tmp, "wb") as f:
393
+ shutil.copyfileobj(r, f)
394
+
395
+ tmp.replace(dst)
396
+
397
+
398
+ def ensure_local_model_files() -> bool:
399
+ if _have_required_files():
400
+ return True
401
+ try:
402
+ for fname, url in REQUIRED_FILES.items():
403
+ fpath = MODEL_DIR / fname
404
+ if fpath.exists():
405
+ continue
406
+ _download_url_to_file(url, fpath)
407
+ return _have_required_files()
408
+ except Exception:
409
+ return False
410
+
411
+
412
+ def HWC3(x: np.ndarray) -> np.ndarray:
413
+ assert x.dtype == np.uint8
414
+ if x.ndim == 2:
415
+ x = x[:, :, None]
416
+ assert x.ndim == 3
417
+ H, W, C = x.shape
418
+ assert C == 1 or C == 3 or C == 4
419
+ if C == 3:
420
+ return x
421
+ if C == 1:
422
+ return np.concatenate([x, x, x], axis=2)
423
+ # C == 4
424
+ color = x[:, :, 0:3].astype(np.float32)
425
+ alpha = x[:, :, 3:4].astype(np.float32) / 255.0
426
+ y = color * alpha + 255.0 * (1.0 - alpha) # white background
427
+ y = y.clip(0, 255).astype(np.uint8)
428
+ return y
429
+
430
+
431
+ def pad64(x: int) -> int:
432
+ return int(np.ceil(float(x) / 64.0) * 64 - x)
433
+
434
+
435
+ def safer_memory(x: np.ndarray) -> np.ndarray:
436
+ return np.ascontiguousarray(x.copy()).copy()
437
+
438
+
439
+ def resize_image_with_pad_min_side(
440
+ input_image: np.ndarray,
441
+ resolution: int,
442
+ upscale_method: str = "INTER_CUBIC",
443
+ skip_hwc3: bool = False,
444
+ mode: str = "edge",
445
+ ) -> Tuple[np.ndarray, Any]:
446
+ cv2 = None
447
+ try:
448
+ import cv2 as _cv2
449
+ cv2 = _cv2
450
+ except Exception:
451
+ cv2 = None
452
+
453
+ img = input_image if skip_hwc3 else HWC3(input_image)
454
+
455
+ H_raw, W_raw, _ = img.shape
456
+ if resolution <= 0:
457
+ return img, (lambda x: x)
458
+
459
+ k = float(resolution) / float(min(H_raw, W_raw))
460
+ H_target = int(np.round(float(H_raw) * k))
461
+ W_target = int(np.round(float(W_raw) * k))
462
+
463
+ if cv2 is not None:
464
+ upscale_methods = {
465
+ "INTER_NEAREST": cv2.INTER_NEAREST,
466
+ "INTER_LINEAR": cv2.INTER_LINEAR,
467
+ "INTER_AREA": cv2.INTER_AREA,
468
+ "INTER_CUBIC": cv2.INTER_CUBIC,
469
+ "INTER_LANCZOS4": cv2.INTER_LANCZOS4,
470
+ }
471
+ method = upscale_methods.get(upscale_method, cv2.INTER_CUBIC)
472
+ img = cv2.resize(img, (W_target, H_target), interpolation=method if k > 1 else cv2.INTER_AREA)
473
+ else:
474
+ pil = Image.fromarray(img)
475
+ resample = Image.BICUBIC if k > 1 else Image.LANCZOS
476
+ pil = pil.resize((W_target, H_target), resample=resample)
477
+ img = np.array(pil, dtype=np.uint8)
478
+
479
+ H_pad, W_pad = pad64(H_target), pad64(W_target)
480
+ img_padded = np.pad(img, [[0, H_pad], [0, W_pad], [0, 0]], mode=mode)
481
+
482
+ def remove_pad(x: np.ndarray) -> np.ndarray:
483
+ return safer_memory(x[:H_target, :W_target, ...])
484
+
485
+ return safer_memory(img_padded), remove_pad
486
+
487
+
488
+ def pad_only_to_64(img_u8: np.ndarray, mode: str = "edge") -> Tuple[np.ndarray, Any]:
489
+ img = HWC3(img_u8)
490
+ H_raw, W_raw, _ = img.shape
491
+ H_pad, W_pad = pad64(H_raw), pad64(W_raw)
492
+ img_padded = np.pad(img, [[0, H_pad], [0, W_pad], [0, 0]], mode=mode)
493
+
494
+ def remove_pad(x: np.ndarray) -> np.ndarray:
495
+ return safer_memory(x[:H_raw, :W_raw, ...])
496
+
497
+ return safer_memory(img_padded), remove_pad
498
+
499
+
500
+ def composite_rgba_over_white_keep_alpha(inp_u8: np.ndarray) -> Tuple[np.ndarray, Optional[np.ndarray]]:
501
+ if inp_u8.ndim == 3 and inp_u8.shape[2] == 4:
502
+ rgba = inp_u8.astype(np.uint8)
503
+ rgb = rgba[:, :, 0:3].astype(np.float32)
504
+ a = (rgba[:, :, 3:4].astype(np.float32) / 255.0)
505
+ rgb_white = (rgb * a + 255.0 * (1.0 - a)).clip(0, 255).astype(np.uint8)
506
+ alpha_u8 = rgba[:, :, 3].copy()
507
+ return rgb_white, alpha_u8
508
+ return HWC3(inp_u8), None
509
+
510
+
511
+ def apply_alpha_then_black_background(depth_rgb_u8: np.ndarray, alpha_u8: np.ndarray) -> np.ndarray:
512
+ depth_rgb_u8 = HWC3(depth_rgb_u8)
513
+ a = (alpha_u8.astype(np.float32) / 255.0)[:, :, None]
514
+ out = (depth_rgb_u8.astype(np.float32) * a).clip(0, 255).astype(np.uint8)
515
+ return out
516
+
517
+
518
+ def comfy_tensor_to_u8(img: torch.Tensor) -> np.ndarray:
519
+ if img.ndim == 4:
520
+ img = img[0]
521
+ arr = img.detach().cpu().float().clamp(0, 1).numpy()
522
+ u8 = (arr * 255.0).round().astype(np.uint8)
523
+ return u8
524
+
525
+
526
+ def u8_to_comfy_tensor(img_u8: np.ndarray) -> torch.Tensor:
527
+ img_u8 = HWC3(img_u8)
528
+ t = torch.from_numpy(img_u8.astype(np.float32) / 255.0)
529
+ return t.unsqueeze(0) # [1,H,W,C]
530
+
531
+
532
+ def _try_load_pipeline(model_source: str, device: torch.device):
533
+ if pipeline is None:
534
+ raise RuntimeError(f"transformers import failed: {_TRANSFORMERS_IMPORT_ERROR}")
535
+
536
+ key = (model_source, str(device))
537
+ with _PIPE_LOCK:
538
+ if key in _PIPE_CACHE:
539
+ return _PIPE_CACHE[key]
540
+
541
+ p = pipeline(task="depth-estimation", model=model_source)
542
+ try:
543
+ p.model = p.model.to(device)
544
+ p.device = device
545
+ except Exception:
546
+ pass
547
+
548
+ _PIPE_CACHE[key] = p
549
+ return p
550
+
551
+
552
+ def get_depth_pipeline(device: torch.device):
553
+ if ensure_local_model_files():
554
+ try:
555
+ return _try_load_pipeline(str(MODEL_DIR), device)
556
+ except Exception:
557
+ pass
558
+ try:
559
+ return _try_load_pipeline(ZOE_FALLBACK_REPO_ID, device)
560
+ except Exception:
561
+ return None
562
+
563
+
564
+ def depth_estimate_zoe_style(
565
+ pipe,
566
+ input_rgb_u8: np.ndarray,
567
+ detect_resolution: int,
568
+ upscale_method: str = "INTER_CUBIC",
569
+ ) -> np.ndarray:
570
+ if detect_resolution == -1:
571
+ work_img, remove_pad = pad_only_to_64(input_rgb_u8, mode="edge")
572
+ else:
573
+ work_img, remove_pad = resize_image_with_pad_min_side(
574
+ input_rgb_u8,
575
+ int(detect_resolution),
576
+ upscale_method=upscale_method,
577
+ skip_hwc3=False,
578
+ mode="edge",
579
+ )
580
+
581
+ pil_image = Image.fromarray(work_img)
582
+
583
+ with torch.no_grad():
584
+ result = pipe(pil_image)
585
+ depth = result["depth"]
586
+
587
+ if isinstance(depth, Image.Image):
588
+ depth_array = np.array(depth, dtype=np.float32)
589
+ else:
590
+ depth_array = np.array(depth, dtype=np.float32)
591
+
592
+ vmin = float(np.percentile(depth_array, 2))
593
+ vmax = float(np.percentile(depth_array, 85))
594
+
595
+ depth_array = depth_array - vmin
596
+ denom = (vmax - vmin)
597
+ if abs(denom) < 1e-12:
598
+ denom = 1e-6
599
+ depth_array = depth_array / denom
600
+
601
+ depth_array = 1.0 - depth_array
602
+ depth_image = (depth_array * 255.0).clip(0, 255).astype(np.uint8)
603
+
604
+ detected_map = remove_pad(HWC3(depth_image))
605
+ return detected_map
606
+
607
+
608
+ def resize_to_original(depth_rgb_u8: np.ndarray, w0: int, h0: int) -> np.ndarray:
609
+ try:
610
+ import cv2
611
+ out = cv2.resize(depth_rgb_u8, (w0, h0), interpolation=cv2.INTER_LINEAR)
612
+ return out.astype(np.uint8)
613
+ except Exception:
614
+ pil = Image.fromarray(depth_rgb_u8)
615
+ pil = pil.resize((w0, h0), resample=Image.BILINEAR)
616
+ return np.array(pil, dtype=np.uint8)
617
+
618
+
619
+ def _salia_depth_execute(image: torch.Tensor, resolution: int = -1) -> torch.Tensor:
620
+ """
621
+ Internal callable version of Salia_Depth:
622
+ input: IMAGE [B,H,W,3 or 4]
623
+ output: IMAGE [B,H,W,3]
624
+ """
625
+ try:
626
+ device = model_management.get_torch_device()
627
+ except Exception:
628
+ device = torch.device("cpu")
629
+
630
+ pipe_obj = None
631
+ try:
632
+ pipe_obj = get_depth_pipeline(device)
633
+ except Exception:
634
+ pipe_obj = None
635
+
636
+ if pipe_obj is None:
637
+ return image
638
+
639
+ if image.ndim == 3:
640
+ image = image.unsqueeze(0)
641
+
642
+ outs = []
643
+ for i in range(image.shape[0]):
644
+ try:
645
+ h0 = int(image[i].shape[0])
646
+ w0 = int(image[i].shape[1])
647
+
648
+ inp_u8 = comfy_tensor_to_u8(image[i])
649
+
650
+ rgb_for_depth, alpha_u8 = composite_rgba_over_white_keep_alpha(inp_u8)
651
+ had_rgba = alpha_u8 is not None
652
+
653
+ depth_rgb = depth_estimate_zoe_style(
654
+ pipe=pipe_obj,
655
+ input_rgb_u8=rgb_for_depth,
656
+ detect_resolution=int(resolution),
657
+ upscale_method="INTER_CUBIC",
658
+ )
659
+
660
+ depth_rgb = resize_to_original(depth_rgb, w0=w0, h0=h0)
661
+
662
+ if had_rgba:
663
+ if alpha_u8.shape[0] != h0 or alpha_u8.shape[1] != w0:
664
+ try:
665
+ import cv2
666
+ alpha_u8 = cv2.resize(alpha_u8, (w0, h0), interpolation=cv2.INTER_LINEAR).astype(np.uint8)
667
+ except Exception:
668
+ pil_a = Image.fromarray(alpha_u8)
669
+ pil_a = pil_a.resize((w0, h0), resample=Image.BILINEAR)
670
+ alpha_u8 = np.array(pil_a, dtype=np.uint8)
671
+
672
+ depth_rgb = apply_alpha_then_black_background(depth_rgb, alpha_u8)
673
+
674
+ outs.append(u8_to_comfy_tensor(depth_rgb))
675
+ except Exception:
676
+ outs.append(image[i].unsqueeze(0))
677
+
678
+ return torch.cat(outs, dim=0)
679
+
680
+
681
+ # -------------------------------------------------------------------------------------
682
+ # Alpha-over paste (RGBA square onto base at X,Y)
683
+ # -------------------------------------------------------------------------------------
684
+
685
+ def _alpha_over_region(base: torch.Tensor, overlay_rgba: torch.Tensor, x: int, y: int) -> torch.Tensor:
686
+ """
687
+ base: [B,H,W,C] where C is 3 or 4, float [0..1]
688
+ overlay_rgba: [B,s,s,4] float [0..1]
689
+ """
690
+ if base.ndim != 4 or overlay_rgba.ndim != 4:
691
+ raise ValueError("base and overlay must be [B,H,W,C].")
692
+
693
+ B, H, W, C = base.shape
694
+ b2, sH, sW, c2 = overlay_rgba.shape
695
+ if c2 != 4:
696
+ raise ValueError("overlay_rgba must have 4 channels (RGBA).")
697
+ if sH != sW:
698
+ raise ValueError("overlay must be square.")
699
+ s = sH
700
+
701
+ if x < 0 or y < 0 or x + s > W or y + s > H:
702
+ raise ValueError(f"Square paste out of bounds. base={W}x{H}, paste at ({x},{y}) size={s}")
703
+
704
+ if b2 != B:
705
+ if b2 == 1 and B > 1:
706
+ overlay_rgba = overlay_rgba.expand(B, -1, -1, -1)
707
+ else:
708
+ raise ValueError("Batch mismatch between base and overlay.")
709
+
710
+ out = base.clone()
711
+
712
+ overlay_rgb = overlay_rgba[..., 0:3].clamp(0, 1)
713
+ overlay_a = overlay_rgba[..., 3:4].clamp(0, 1)
714
+
715
+ base_rgb = out[:, y:y + s, x:x + s, 0:3]
716
+ comp_rgb = overlay_rgb * overlay_a + base_rgb * (1.0 - overlay_a)
717
+ out[:, y:y + s, x:x + s, 0:3] = comp_rgb
718
+
719
+ if C == 4:
720
+ base_a = out[:, y:y + s, x:x + s, 3:4].clamp(0, 1)
721
+ comp_a = overlay_a + base_a * (1.0 - overlay_a)
722
+ out[:, y:y + s, x:x + s, 3:4] = comp_a
723
+
724
+ return out.clamp(0, 1)
725
+
726
+
727
+ # -------------------------------------------------------------------------------------
728
+ # The One-Node Workflow
729
+ # -------------------------------------------------------------------------------------
730
+
731
+ class Salia_Detailer_Lora:
732
+ CATEGORY = "image/salia"
733
+ RETURN_TYPES = ("IMAGE",)
734
+ RETURN_NAMES = ("image",)
735
+ FUNCTION = "run"
736
+
737
+ @classmethod
738
+ def INPUT_TYPES(cls):
739
+ ckpts = folder_paths.get_filename_list("checkpoints") or ["<no checkpoints found>"]
740
+ cns = folder_paths.get_filename_list("controlnet") or ["<no controlnets found>"]
741
+ assets = _list_asset_pngs() or ["<no pngs found>"]
742
+
743
+ try:
744
+ import comfy.samplers
745
+ sampler_names = comfy.samplers.KSampler.SAMPLERS
746
+ scheduler_names = comfy.samplers.KSampler.SCHEDULERS
747
+ except Exception:
748
+ sampler_names = ["euler"]
749
+ scheduler_names = ["karras"]
750
+
751
+ upscale_choices = ["1", "2", "4", "6", "8", "10", "12", "14", "16"]
752
+
753
+ return {
754
+ "required": {
755
+ "image": ("IMAGE",),
756
+
757
+ "X_coord": ("INT", {"default": 0, "min": 0, "max": 16384, "step": 1}),
758
+ "Y_coord": ("INT", {"default": 0, "min": 0, "max": 16384, "step": 1}),
759
+ "square_size": ("INT", {"default": 384, "min": 8, "max": 8192, "step": 1}),
760
+
761
+ "positive_prompt": ("STRING", {"default": "", "multiline": True}),
762
+ "negative_prompt": ("STRING", {"default": "", "multiline": True}),
763
+
764
+ "upscale_factor": (upscale_choices, {"default": "4"}),
765
+
766
+ "ckpt_name": (ckpts, {}),
767
+ "control_net_name": (cns, {}),
768
+ "lora_name": (
769
+ "STRING",
770
+ {
771
+ "default": "",
772
+ "multiline": False,
773
+ "placeholder": "Fade_to_Black",
774
+ },
775
+ ),
776
+ "lora_strength": (
777
+ "FLOAT",
778
+ {
779
+ "default": 1.0,
780
+ "min": -100.0,
781
+ "max": 100.0,
782
+ "step": 0.01,
783
+ },
784
+ ),
785
+ "asset_image": (assets, {}),
786
+
787
+ "controlnet_strength": ("FLOAT", {"default": 0.33, "min": 0.00, "max": 10.00, "step": 0.01}),
788
+ "controlnet_start_percent": ("FLOAT", {"default": 0.00, "min": 0.00, "max": 1.00, "step": 0.01}),
789
+ "controlnet_end_percent": ("FLOAT", {"default": 1.00, "min": 0.00, "max": 1.00, "step": 0.01}),
790
+
791
+ "steps": ("INT", {"default": 30, "min": 1, "max": 200, "step": 1}),
792
+ "cfg": ("FLOAT", {"default": 2.6, "min": 0.00, "max": 10.00, "step": 0.05}),
793
+ "sampler_name": (sampler_names, {"default": "euler"} if "euler" in sampler_names else {}),
794
+ "scheduler": (scheduler_names, {"default": "karras"} if "karras" in scheduler_names else {}),
795
+ "denoise": ("FLOAT", {"default": 0.35, "min": 0.00, "max": 1.00, "step": 0.01}),
796
+ }
797
+ }
798
+
799
+ def run(
800
+ self,
801
+ image: torch.Tensor,
802
+ X_coord: int,
803
+ Y_coord: int,
804
+ square_size: int,
805
+ positive_prompt: str,
806
+ negative_prompt: str,
807
+ upscale_factor: str,
808
+ ckpt_name: str,
809
+ control_net_name: str,
810
+ lora_name: str,
811
+ lora_strength: float,
812
+ asset_image: str,
813
+ controlnet_strength: float,
814
+ controlnet_start_percent: float,
815
+ controlnet_end_percent: float,
816
+ steps: int,
817
+ cfg: float,
818
+ sampler_name: str,
819
+ scheduler: str,
820
+ denoise: float,
821
+ ):
822
+ # Normalize input to [B,H,W,C]
823
+ if image.ndim == 3:
824
+ image = image.unsqueeze(0)
825
+ if image.ndim != 4:
826
+ raise ValueError("Input image must be [B,H,W,C].")
827
+
828
+ B, H, W, C = image.shape
829
+ if C not in (3, 4):
830
+ raise ValueError("Input image must have 3 (RGB) or 4 (RGBA) channels.")
831
+
832
+ x = int(X_coord)
833
+ y = int(Y_coord)
834
+ s = int(square_size)
835
+
836
+ up = int(upscale_factor)
837
+ if up not in (1, 2, 4, 6, 8, 10, 12, 14, 16):
838
+ raise ValueError("upscale_factor must be one of: 1,2,4,6,8,10,12,14,16")
839
+
840
+ if s <= 0:
841
+ raise ValueError("square_size must be > 0")
842
+ if x < 0 or y < 0 or x + s > W or y + s > H:
843
+ raise ValueError(f"Crop out of bounds. image={W}x{H}, crop at ({x},{y}) size={s}")
844
+
845
+ up_w = s * up
846
+ up_h = s * up
847
+
848
+ # VAE/UNet path likes multiples of 8
849
+ if (up_w % 8) != 0 or (up_h % 8) != 0:
850
+ raise ValueError("square_size * upscale_factor must be divisible by 8 (required by VAE pipeline).")
851
+
852
+ start_p = float(max(0.0, min(1.0, controlnet_start_percent)))
853
+ end_p = float(max(0.0, min(1.0, controlnet_end_percent)))
854
+ if end_p < start_p:
855
+ start_p, end_p = end_p, start_p
856
+
857
+ normalized_lora_name = _normalize_lora_name(lora_name)
858
+
859
+ # 1) Crop square
860
+ crop = image[:, y:y + s, x:x + s, :]
861
+ crop_rgb = crop[:, :, :, 0:3].contiguous()
862
+
863
+ # 2) Depth (inline Salia_Depth) then upscale with Lanczos
864
+ depth_small = _salia_depth_execute(crop_rgb, resolution=s)
865
+ depth_up = _resize_image_lanczos(depth_small, up_w, up_h)
866
+
867
+ # 3) Upscale crop for VAE encode
868
+ crop_up = _resize_image_lanczos(crop_rgb, up_w, up_h)
869
+
870
+ # 4) Load asset mask and resize
871
+ if asset_image == "<no pngs found>":
872
+ raise FileNotFoundError("No PNGs found in assets/images for this plugin.")
873
+ _asset_img_unused, asset_mask = _load_asset_image_and_mask(asset_image)
874
+
875
+ if asset_mask.ndim == 2:
876
+ asset_mask = asset_mask.unsqueeze(0)
877
+ if asset_mask.ndim != 3:
878
+ raise ValueError("Asset mask must be [B,H,W].")
879
+
880
+ if asset_mask.shape[0] != B:
881
+ if asset_mask.shape[0] == 1 and B > 1:
882
+ asset_mask = asset_mask.expand(B, -1, -1)
883
+ else:
884
+ raise ValueError("Batch mismatch for asset mask.")
885
+
886
+ asset_mask_up = _resize_mask_lanczos(asset_mask, up_w, up_h)
887
+
888
+ # 5) Load checkpoint, then optional LoRA, then controlnet
889
+ if ckpt_name == "<no checkpoints found>":
890
+ raise FileNotFoundError("No checkpoints found in models/checkpoints.")
891
+ if control_net_name == "<no controlnets found>":
892
+ raise FileNotFoundError("No controlnets found in models/controlnet.")
893
+
894
+ model, clip, vae = _load_checkpoint_cached(ckpt_name)
895
+
896
+ if normalized_lora_name:
897
+ lora_path = _ensure_lora_available(normalized_lora_name)
898
+ lora = _load_lora_cached(lora_path)
899
+ if float(lora_strength) != 0.0:
900
+ model, _ = comfy.sd.load_lora_for_models(
901
+ model,
902
+ None,
903
+ lora,
904
+ float(lora_strength),
905
+ 0,
906
+ )
907
+
908
+ controlnet = _load_controlnet_cached(control_net_name)
909
+
910
+ import nodes
911
+
912
+ # 6) CLIP encodes
913
+ pos_enc = nodes.CLIPTextEncode()
914
+ neg_enc = nodes.CLIPTextEncode()
915
+ pos_fn = getattr(pos_enc, pos_enc.FUNCTION)
916
+ neg_fn = getattr(neg_enc, neg_enc.FUNCTION)
917
+ (pos_cond,) = pos_fn(text=str(positive_prompt), clip=clip)
918
+ (neg_cond,) = neg_fn(text=str(negative_prompt), clip=clip)
919
+
920
+ # 7) Apply ControlNet
921
+ cn_apply = nodes.ControlNetApplyAdvanced()
922
+ cn_fn = getattr(cn_apply, cn_apply.FUNCTION)
923
+ pos_cn, neg_cn = cn_fn(
924
+ strength=float(controlnet_strength),
925
+ start_percent=float(start_p),
926
+ end_percent=float(end_p),
927
+ positive=pos_cond,
928
+ negative=neg_cond,
929
+ control_net=controlnet,
930
+ image=depth_up,
931
+ vae=vae,
932
+ )
933
+
934
+ # 8) VAE Encode
935
+ vae_enc = nodes.VAEEncode()
936
+ vae_enc_fn = getattr(vae_enc, vae_enc.FUNCTION)
937
+ (latent,) = vae_enc_fn(pixels=crop_up, vae=vae)
938
+
939
+ # 9) KSampler (deterministic seed derived from inputs)
940
+ seed_material = (
941
+ f"{ckpt_name}|{control_net_name}|{normalized_lora_name}|{lora_strength}|{asset_image}|{x}|{y}|{s}|{up}|"
942
+ f"{steps}|{cfg}|{sampler_name}|{scheduler}|{denoise}|"
943
+ f"{controlnet_strength}|{start_p}|{end_p}|"
944
+ f"{positive_prompt}|{negative_prompt}"
945
+ ).encode("utf-8", errors="ignore")
946
+ seed64 = int(hashlib.sha256(seed_material).hexdigest()[:16], 16)
947
+
948
+ ksampler = nodes.KSampler()
949
+ k_fn = getattr(ksampler, ksampler.FUNCTION)
950
+ (sampled_latent,) = k_fn(
951
+ seed=seed64,
952
+ steps=int(steps),
953
+ cfg=float(cfg),
954
+ sampler_name=str(sampler_name),
955
+ scheduler=str(scheduler),
956
+ denoise=float(denoise),
957
+ model=model,
958
+ positive=pos_cn,
959
+ negative=neg_cn,
960
+ latent_image=latent,
961
+ )
962
+
963
+ # 10) VAE Decode -> RGB
964
+ vae_dec = nodes.VAEDecode()
965
+ vae_dec_fn = getattr(vae_dec, vae_dec.FUNCTION)
966
+ (decoded_rgb,) = vae_dec_fn(samples=sampled_latent, vae=vae)
967
+
968
+ # 11) ✅ Manual "JoinImageWithAlpha"
969
+ rgba_up = _rgb_to_rgba_with_comfy_mask(decoded_rgb, asset_mask_up)
970
+
971
+ # 12) Downscale RGBA back to crop size
972
+ rgba_square = _resize_image_lanczos(rgba_up, s, s)
973
+
974
+ # 13) Paste back onto original at X,Y (alpha-over)
975
+ out = _alpha_over_region(image, rgba_square, x=x, y=y)
976
+ return (out,)
977
+
978
+
979
+ NODE_CLASS_MAPPINGS = {
980
+ "Salia_Detailer_Lora": Salia_Detailer_Lora,
981
+ }
982
+
983
+ NODE_DISPLAY_NAME_MAPPINGS = {
984
+ "Salia_Detailer_Lora": "Salia_Detailer_Lora",
985
+ }