saliacoel commited on
Commit
326edb9
·
verified ·
1 Parent(s): 4c62e9e

Upload salia_detailer_lora.py

Browse files
Files changed (1) hide show
  1. salia_detailer_lora.py +1017 -0
salia_detailer_lora.py ADDED
@@ -0,0 +1,1017 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ HF_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"{HF_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
+ # Asset PNG helpers (string input, local-first, repo fallback)
289
+ # -------------------------------------------------------------------------------------
290
+
291
+ def _assets_images_dir() -> Path:
292
+ return PLUGIN_ROOT / "assets" / "images"
293
+
294
+
295
+ def _normalize_asset_png_name(name: str) -> str:
296
+ """
297
+ Accepts:
298
+ - car
299
+ - car.png
300
+ - accidental path input
301
+ Returns:
302
+ - car.png
303
+ """
304
+ base = str(name or "").strip().replace("\\", "/").split("/")[-1]
305
+ if not base:
306
+ raise ValueError("asset_image cannot be empty.")
307
+
308
+ if not base.lower().endswith(".png"):
309
+ base = f"{base}.png"
310
+
311
+ return base
312
+
313
+
314
+ def _find_existing_asset_png(asset_name: str) -> Optional[Path]:
315
+ img_dir = _assets_images_dir()
316
+ if not img_dir.is_dir():
317
+ return None
318
+
319
+ target_lower = asset_name.lower()
320
+
321
+ direct = img_dir / asset_name
322
+ if direct.is_file():
323
+ return direct.resolve()
324
+
325
+ for p in img_dir.rglob("*"):
326
+ if p.is_file() and p.name.lower() == target_lower:
327
+ return p.resolve()
328
+
329
+ return None
330
+
331
+
332
+ def _ensure_asset_png_available(asset_name: str) -> Path:
333
+ normalized_name = _normalize_asset_png_name(asset_name)
334
+
335
+ existing = _find_existing_asset_png(normalized_name)
336
+ if existing is not None:
337
+ return existing
338
+
339
+ img_dir = _assets_images_dir()
340
+ img_dir.mkdir(parents=True, exist_ok=True)
341
+
342
+ target_path = img_dir / normalized_name
343
+ url = f"{HF_REPO_BASE}/{urllib.parse.quote(normalized_name)}"
344
+
345
+ logging.info("[Salia_OneNode_WorkflowSquare] Downloading missing asset PNG: %s", url)
346
+ _download_url_to_file(url, target_path)
347
+
348
+ if not target_path.is_file():
349
+ raise FileNotFoundError(f"Failed to download asset PNG: {normalized_name}")
350
+
351
+ return target_path.resolve()
352
+
353
+
354
+ def _load_asset_image_and_mask(asset_name: str) -> Tuple[torch.Tensor, torch.Tensor]:
355
+ """
356
+ Returns (IMAGE, MASK) in ComfyUI formats.
357
+
358
+ Asset behavior:
359
+ - normalize to *.png
360
+ - use existing file from assets/images if present
361
+ - otherwise download from HF repo into assets/images
362
+
363
+ Mask semantics: match ComfyUI core LoadImage:
364
+ - alpha is RGBA alpha channel normalized to [0..1]
365
+ - mask = 1 - alpha
366
+ """
367
+ p = _ensure_asset_png_available(asset_name)
368
+
369
+ im = Image.open(p)
370
+ im = ImageOps.exif_transpose(im)
371
+
372
+ rgba = im.convert("RGBA")
373
+ rgb = rgba.convert("RGB")
374
+
375
+ rgb_arr = np.array(rgb).astype(np.float32) / 255.0 # [H,W,3]
376
+ img_t = torch.from_numpy(rgb_arr)[None, ...]
377
+
378
+ alpha = np.array(rgba.getchannel("A")).astype(np.float32) / 255.0 # [H,W]
379
+ mask = 1.0 - alpha # Comfy MASK convention
380
+
381
+ mask_t = torch.from_numpy(mask)[None, ...]
382
+ return img_t, mask_t
383
+
384
+
385
+ # -------------------------------------------------------------------------------------
386
+ # Salia_Depth (INLINED, no imports from other files)
387
+ # -------------------------------------------------------------------------------------
388
+
389
+ MODEL_DIR = PLUGIN_ROOT / "assets" / "depth"
390
+ MODEL_DIR.mkdir(parents=True, exist_ok=True)
391
+
392
+ REQUIRED_FILES = {
393
+ "config.json": "https://huggingface.co/saliacoel/depth/resolve/main/config.json",
394
+ "model.safetensors": "https://huggingface.co/saliacoel/depth/resolve/main/model.safetensors",
395
+ "preprocessor_config.json": "https://huggingface.co/saliacoel/depth/resolve/main/preprocessor_config.json",
396
+ }
397
+
398
+ ZOE_FALLBACK_REPO_ID = "Intel/zoedepth-nyu-kitti"
399
+
400
+ _PIPE_CACHE: Dict[Tuple[str, str], Any] = {} # (model_source, device_str) -> pipeline
401
+ _PIPE_LOCK = threading.Lock()
402
+
403
+
404
+ def _have_required_files() -> bool:
405
+ return all((MODEL_DIR / name).exists() for name in REQUIRED_FILES.keys())
406
+
407
+
408
+ def _download_url_to_file(url: str, dst: Path, timeout: int = 180) -> None:
409
+ dst.parent.mkdir(parents=True, exist_ok=True)
410
+ tmp = dst.with_suffix(dst.suffix + ".tmp")
411
+
412
+ if tmp.exists():
413
+ try:
414
+ tmp.unlink()
415
+ except Exception:
416
+ pass
417
+
418
+ req = urllib.request.Request(url, headers={"User-Agent": "ComfyUI-Salia/1.3"})
419
+ with urllib.request.urlopen(req, timeout=timeout) as r, open(tmp, "wb") as f:
420
+ shutil.copyfileobj(r, f)
421
+
422
+ tmp.replace(dst)
423
+
424
+
425
+ def ensure_local_model_files() -> bool:
426
+ if _have_required_files():
427
+ return True
428
+ try:
429
+ for fname, url in REQUIRED_FILES.items():
430
+ fpath = MODEL_DIR / fname
431
+ if fpath.exists():
432
+ continue
433
+ _download_url_to_file(url, fpath)
434
+ return _have_required_files()
435
+ except Exception:
436
+ return False
437
+
438
+
439
+ def HWC3(x: np.ndarray) -> np.ndarray:
440
+ assert x.dtype == np.uint8
441
+ if x.ndim == 2:
442
+ x = x[:, :, None]
443
+ assert x.ndim == 3
444
+ H, W, C = x.shape
445
+ assert C == 1 or C == 3 or C == 4
446
+ if C == 3:
447
+ return x
448
+ if C == 1:
449
+ return np.concatenate([x, x, x], axis=2)
450
+ # C == 4
451
+ color = x[:, :, 0:3].astype(np.float32)
452
+ alpha = x[:, :, 3:4].astype(np.float32) / 255.0
453
+ y = color * alpha + 255.0 * (1.0 - alpha) # white background
454
+ y = y.clip(0, 255).astype(np.uint8)
455
+ return y
456
+
457
+
458
+ def pad64(x: int) -> int:
459
+ return int(np.ceil(float(x) / 64.0) * 64 - x)
460
+
461
+
462
+ def safer_memory(x: np.ndarray) -> np.ndarray:
463
+ return np.ascontiguousarray(x.copy()).copy()
464
+
465
+
466
+ def resize_image_with_pad_min_side(
467
+ input_image: np.ndarray,
468
+ resolution: int,
469
+ upscale_method: str = "INTER_CUBIC",
470
+ skip_hwc3: bool = False,
471
+ mode: str = "edge",
472
+ ) -> Tuple[np.ndarray, Any]:
473
+ cv2 = None
474
+ try:
475
+ import cv2 as _cv2
476
+ cv2 = _cv2
477
+ except Exception:
478
+ cv2 = None
479
+
480
+ img = input_image if skip_hwc3 else HWC3(input_image)
481
+
482
+ H_raw, W_raw, _ = img.shape
483
+ if resolution <= 0:
484
+ return img, (lambda x: x)
485
+
486
+ k = float(resolution) / float(min(H_raw, W_raw))
487
+ H_target = int(np.round(float(H_raw) * k))
488
+ W_target = int(np.round(float(W_raw) * k))
489
+
490
+ if cv2 is not None:
491
+ upscale_methods = {
492
+ "INTER_NEAREST": cv2.INTER_NEAREST,
493
+ "INTER_LINEAR": cv2.INTER_LINEAR,
494
+ "INTER_AREA": cv2.INTER_AREA,
495
+ "INTER_CUBIC": cv2.INTER_CUBIC,
496
+ "INTER_LANCZOS4": cv2.INTER_LANCZOS4,
497
+ }
498
+ method = upscale_methods.get(upscale_method, cv2.INTER_CUBIC)
499
+ img = cv2.resize(img, (W_target, H_target), interpolation=method if k > 1 else cv2.INTER_AREA)
500
+ else:
501
+ pil = Image.fromarray(img)
502
+ resample = Image.BICUBIC if k > 1 else Image.LANCZOS
503
+ pil = pil.resize((W_target, H_target), resample=resample)
504
+ img = np.array(pil, dtype=np.uint8)
505
+
506
+ H_pad, W_pad = pad64(H_target), pad64(W_target)
507
+ img_padded = np.pad(img, [[0, H_pad], [0, W_pad], [0, 0]], mode=mode)
508
+
509
+ def remove_pad(x: np.ndarray) -> np.ndarray:
510
+ return safer_memory(x[:H_target, :W_target, ...])
511
+
512
+ return safer_memory(img_padded), remove_pad
513
+
514
+
515
+ def pad_only_to_64(img_u8: np.ndarray, mode: str = "edge") -> Tuple[np.ndarray, Any]:
516
+ img = HWC3(img_u8)
517
+ H_raw, W_raw, _ = img.shape
518
+ H_pad, W_pad = pad64(H_raw), pad64(W_raw)
519
+ img_padded = np.pad(img, [[0, H_pad], [0, W_pad], [0, 0]], mode=mode)
520
+
521
+ def remove_pad(x: np.ndarray) -> np.ndarray:
522
+ return safer_memory(x[:H_raw, :W_raw, ...])
523
+
524
+ return safer_memory(img_padded), remove_pad
525
+
526
+
527
+ def composite_rgba_over_white_keep_alpha(inp_u8: np.ndarray) -> Tuple[np.ndarray, Optional[np.ndarray]]:
528
+ if inp_u8.ndim == 3 and inp_u8.shape[2] == 4:
529
+ rgba = inp_u8.astype(np.uint8)
530
+ rgb = rgba[:, :, 0:3].astype(np.float32)
531
+ a = (rgba[:, :, 3:4].astype(np.float32) / 255.0)
532
+ rgb_white = (rgb * a + 255.0 * (1.0 - a)).clip(0, 255).astype(np.uint8)
533
+ alpha_u8 = rgba[:, :, 3].copy()
534
+ return rgb_white, alpha_u8
535
+ return HWC3(inp_u8), None
536
+
537
+
538
+ def apply_alpha_then_black_background(depth_rgb_u8: np.ndarray, alpha_u8: np.ndarray) -> np.ndarray:
539
+ depth_rgb_u8 = HWC3(depth_rgb_u8)
540
+ a = (alpha_u8.astype(np.float32) / 255.0)[:, :, None]
541
+ out = (depth_rgb_u8.astype(np.float32) * a).clip(0, 255).astype(np.uint8)
542
+ return out
543
+
544
+
545
+ def comfy_tensor_to_u8(img: torch.Tensor) -> np.ndarray:
546
+ if img.ndim == 4:
547
+ img = img[0]
548
+ arr = img.detach().cpu().float().clamp(0, 1).numpy()
549
+ u8 = (arr * 255.0).round().astype(np.uint8)
550
+ return u8
551
+
552
+
553
+ def u8_to_comfy_tensor(img_u8: np.ndarray) -> torch.Tensor:
554
+ img_u8 = HWC3(img_u8)
555
+ t = torch.from_numpy(img_u8.astype(np.float32) / 255.0)
556
+ return t.unsqueeze(0) # [1,H,W,C]
557
+
558
+
559
+ def _try_load_pipeline(model_source: str, device: torch.device):
560
+ if pipeline is None:
561
+ raise RuntimeError(f"transformers import failed: {_TRANSFORMERS_IMPORT_ERROR}")
562
+
563
+ key = (model_source, str(device))
564
+ with _PIPE_LOCK:
565
+ if key in _PIPE_CACHE:
566
+ return _PIPE_CACHE[key]
567
+
568
+ p = pipeline(task="depth-estimation", model=model_source)
569
+ try:
570
+ p.model = p.model.to(device)
571
+ p.device = device
572
+ except Exception:
573
+ pass
574
+
575
+ _PIPE_CACHE[key] = p
576
+ return p
577
+
578
+
579
+ def get_depth_pipeline(device: torch.device):
580
+ if ensure_local_model_files():
581
+ try:
582
+ return _try_load_pipeline(str(MODEL_DIR), device)
583
+ except Exception:
584
+ pass
585
+ try:
586
+ return _try_load_pipeline(ZOE_FALLBACK_REPO_ID, device)
587
+ except Exception:
588
+ return None
589
+
590
+
591
+ def depth_estimate_zoe_style(
592
+ pipe,
593
+ input_rgb_u8: np.ndarray,
594
+ detect_resolution: int,
595
+ upscale_method: str = "INTER_CUBIC",
596
+ ) -> np.ndarray:
597
+ if detect_resolution == -1:
598
+ work_img, remove_pad = pad_only_to_64(input_rgb_u8, mode="edge")
599
+ else:
600
+ work_img, remove_pad = resize_image_with_pad_min_side(
601
+ input_rgb_u8,
602
+ int(detect_resolution),
603
+ upscale_method=upscale_method,
604
+ skip_hwc3=False,
605
+ mode="edge",
606
+ )
607
+
608
+ pil_image = Image.fromarray(work_img)
609
+
610
+ with torch.no_grad():
611
+ result = pipe(pil_image)
612
+ depth = result["depth"]
613
+
614
+ if isinstance(depth, Image.Image):
615
+ depth_array = np.array(depth, dtype=np.float32)
616
+ else:
617
+ depth_array = np.array(depth, dtype=np.float32)
618
+
619
+ vmin = float(np.percentile(depth_array, 2))
620
+ vmax = float(np.percentile(depth_array, 85))
621
+
622
+ depth_array = depth_array - vmin
623
+ denom = (vmax - vmin)
624
+ if abs(denom) < 1e-12:
625
+ denom = 1e-6
626
+ depth_array = depth_array / denom
627
+
628
+ depth_array = 1.0 - depth_array
629
+ depth_image = (depth_array * 255.0).clip(0, 255).astype(np.uint8)
630
+
631
+ detected_map = remove_pad(HWC3(depth_image))
632
+ return detected_map
633
+
634
+
635
+ def resize_to_original(depth_rgb_u8: np.ndarray, w0: int, h0: int) -> np.ndarray:
636
+ try:
637
+ import cv2
638
+ out = cv2.resize(depth_rgb_u8, (w0, h0), interpolation=cv2.INTER_LINEAR)
639
+ return out.astype(np.uint8)
640
+ except Exception:
641
+ pil = Image.fromarray(depth_rgb_u8)
642
+ pil = pil.resize((w0, h0), resample=Image.BILINEAR)
643
+ return np.array(pil, dtype=np.uint8)
644
+
645
+
646
+ def _salia_depth_execute(image: torch.Tensor, resolution: int = -1) -> torch.Tensor:
647
+ """
648
+ Internal callable version of Salia_Depth:
649
+ input: IMAGE [B,H,W,3 or 4]
650
+ output: IMAGE [B,H,W,3]
651
+ """
652
+ try:
653
+ device = model_management.get_torch_device()
654
+ except Exception:
655
+ device = torch.device("cpu")
656
+
657
+ pipe_obj = None
658
+ try:
659
+ pipe_obj = get_depth_pipeline(device)
660
+ except Exception:
661
+ pipe_obj = None
662
+
663
+ if pipe_obj is None:
664
+ return image
665
+
666
+ if image.ndim == 3:
667
+ image = image.unsqueeze(0)
668
+
669
+ outs = []
670
+ for i in range(image.shape[0]):
671
+ try:
672
+ h0 = int(image[i].shape[0])
673
+ w0 = int(image[i].shape[1])
674
+
675
+ inp_u8 = comfy_tensor_to_u8(image[i])
676
+
677
+ rgb_for_depth, alpha_u8 = composite_rgba_over_white_keep_alpha(inp_u8)
678
+ had_rgba = alpha_u8 is not None
679
+
680
+ depth_rgb = depth_estimate_zoe_style(
681
+ pipe=pipe_obj,
682
+ input_rgb_u8=rgb_for_depth,
683
+ detect_resolution=int(resolution),
684
+ upscale_method="INTER_CUBIC",
685
+ )
686
+
687
+ depth_rgb = resize_to_original(depth_rgb, w0=w0, h0=h0)
688
+
689
+ if had_rgba:
690
+ if alpha_u8.shape[0] != h0 or alpha_u8.shape[1] != w0:
691
+ try:
692
+ import cv2
693
+ alpha_u8 = cv2.resize(alpha_u8, (w0, h0), interpolation=cv2.INTER_LINEAR).astype(np.uint8)
694
+ except Exception:
695
+ pil_a = Image.fromarray(alpha_u8)
696
+ pil_a = pil_a.resize((w0, h0), resample=Image.BILINEAR)
697
+ alpha_u8 = np.array(pil_a, dtype=np.uint8)
698
+
699
+ depth_rgb = apply_alpha_then_black_background(depth_rgb, alpha_u8)
700
+
701
+ outs.append(u8_to_comfy_tensor(depth_rgb))
702
+ except Exception:
703
+ outs.append(image[i].unsqueeze(0))
704
+
705
+ return torch.cat(outs, dim=0)
706
+
707
+
708
+ # -------------------------------------------------------------------------------------
709
+ # Alpha-over paste (RGBA square onto base at X,Y)
710
+ # -------------------------------------------------------------------------------------
711
+
712
+ def _alpha_over_region(base: torch.Tensor, overlay_rgba: torch.Tensor, x: int, y: int) -> torch.Tensor:
713
+ """
714
+ base: [B,H,W,C] where C is 3 or 4, float [0..1]
715
+ overlay_rgba: [B,s,s,4] float [0..1]
716
+ """
717
+ if base.ndim != 4 or overlay_rgba.ndim != 4:
718
+ raise ValueError("base and overlay must be [B,H,W,C].")
719
+
720
+ B, H, W, C = base.shape
721
+ b2, sH, sW, c2 = overlay_rgba.shape
722
+ if c2 != 4:
723
+ raise ValueError("overlay_rgba must have 4 channels (RGBA).")
724
+ if sH != sW:
725
+ raise ValueError("overlay must be square.")
726
+ s = sH
727
+
728
+ if x < 0 or y < 0 or x + s > W or y + s > H:
729
+ raise ValueError(f"Square paste out of bounds. base={W}x{H}, paste at ({x},{y}) size={s}")
730
+
731
+ if b2 != B:
732
+ if b2 == 1 and B > 1:
733
+ overlay_rgba = overlay_rgba.expand(B, -1, -1, -1)
734
+ else:
735
+ raise ValueError("Batch mismatch between base and overlay.")
736
+
737
+ out = base.clone()
738
+
739
+ overlay_rgb = overlay_rgba[..., 0:3].clamp(0, 1)
740
+ overlay_a = overlay_rgba[..., 3:4].clamp(0, 1)
741
+
742
+ base_rgb = out[:, y:y + s, x:x + s, 0:3]
743
+ comp_rgb = overlay_rgb * overlay_a + base_rgb * (1.0 - overlay_a)
744
+ out[:, y:y + s, x:x + s, 0:3] = comp_rgb
745
+
746
+ if C == 4:
747
+ base_a = out[:, y:y + s, x:x + s, 3:4].clamp(0, 1)
748
+ comp_a = overlay_a + base_a * (1.0 - overlay_a)
749
+ out[:, y:y + s, x:x + s, 3:4] = comp_a
750
+
751
+ return out.clamp(0, 1)
752
+
753
+
754
+ # -------------------------------------------------------------------------------------
755
+ # The One-Node Workflow
756
+ # -------------------------------------------------------------------------------------
757
+
758
+ class Salia_Detailer_Lora:
759
+ CATEGORY = "image/salia"
760
+ RETURN_TYPES = ("IMAGE",)
761
+ RETURN_NAMES = ("image",)
762
+ FUNCTION = "run"
763
+
764
+ @classmethod
765
+ def INPUT_TYPES(cls):
766
+ ckpts = folder_paths.get_filename_list("checkpoints") or ["<no checkpoints found>"]
767
+ cns = folder_paths.get_filename_list("controlnet") or ["<no controlnets found>"]
768
+
769
+ try:
770
+ import comfy.samplers
771
+ sampler_names = comfy.samplers.KSampler.SAMPLERS
772
+ scheduler_names = comfy.samplers.KSampler.SCHEDULERS
773
+ except Exception:
774
+ sampler_names = ["euler"]
775
+ scheduler_names = ["karras"]
776
+
777
+ upscale_choices = ["1", "2", "4", "6", "8", "10", "12", "14", "16"]
778
+
779
+ return {
780
+ "required": {
781
+ "image": ("IMAGE",),
782
+
783
+ "X_coord": ("INT", {"default": 0, "min": 0, "max": 16384, "step": 1}),
784
+ "Y_coord": ("INT", {"default": 0, "min": 0, "max": 16384, "step": 1}),
785
+ "square_size": ("INT", {"default": 384, "min": 8, "max": 8192, "step": 1}),
786
+
787
+ "positive_prompt": ("STRING", {"default": "", "multiline": True}),
788
+ "negative_prompt": ("STRING", {"default": "", "multiline": True}),
789
+
790
+ "upscale_factor": (upscale_choices, {"default": "4"}),
791
+
792
+ "ckpt_name": (ckpts, {}),
793
+ "control_net_name": (cns, {}),
794
+ "lora_name": (
795
+ "STRING",
796
+ {
797
+ "default": "",
798
+ "multiline": False,
799
+ "placeholder": "Fade_to_Black",
800
+ },
801
+ ),
802
+ "lora_strength": (
803
+ "FLOAT",
804
+ {
805
+ "default": 1.0,
806
+ "min": -100.0,
807
+ "max": 100.0,
808
+ "step": 0.01,
809
+ },
810
+ ),
811
+ "asset_image": (
812
+ "STRING",
813
+ {
814
+ "default": "",
815
+ "multiline": False,
816
+ "placeholder": "car or car.png",
817
+ },
818
+ ),
819
+
820
+ "controlnet_strength": ("FLOAT", {"default": 0.33, "min": 0.00, "max": 10.00, "step": 0.01}),
821
+ "controlnet_start_percent": ("FLOAT", {"default": 0.00, "min": 0.00, "max": 1.00, "step": 0.01}),
822
+ "controlnet_end_percent": ("FLOAT", {"default": 1.00, "min": 0.00, "max": 1.00, "step": 0.01}),
823
+
824
+ "steps": ("INT", {"default": 30, "min": 1, "max": 200, "step": 1}),
825
+ "cfg": ("FLOAT", {"default": 2.6, "min": 0.00, "max": 10.00, "step": 0.05}),
826
+ "sampler_name": (sampler_names, {"default": "euler"} if "euler" in sampler_names else {}),
827
+ "scheduler": (scheduler_names, {"default": "karras"} if "karras" in scheduler_names else {}),
828
+ "denoise": ("FLOAT", {"default": 0.35, "min": 0.00, "max": 1.00, "step": 0.01}),
829
+ }
830
+ }
831
+
832
+ def run(
833
+ self,
834
+ image: torch.Tensor,
835
+ X_coord: int,
836
+ Y_coord: int,
837
+ square_size: int,
838
+ positive_prompt: str,
839
+ negative_prompt: str,
840
+ upscale_factor: str,
841
+ ckpt_name: str,
842
+ control_net_name: str,
843
+ lora_name: str,
844
+ lora_strength: float,
845
+ asset_image: str,
846
+ controlnet_strength: float,
847
+ controlnet_start_percent: float,
848
+ controlnet_end_percent: float,
849
+ steps: int,
850
+ cfg: float,
851
+ sampler_name: str,
852
+ scheduler: str,
853
+ denoise: float,
854
+ ):
855
+ # Normalize input to [B,H,W,C]
856
+ if image.ndim == 3:
857
+ image = image.unsqueeze(0)
858
+ if image.ndim != 4:
859
+ raise ValueError("Input image must be [B,H,W,C].")
860
+
861
+ B, H, W, C = image.shape
862
+ if C not in (3, 4):
863
+ raise ValueError("Input image must have 3 (RGB) or 4 (RGBA) channels.")
864
+
865
+ x = int(X_coord)
866
+ y = int(Y_coord)
867
+ s = int(square_size)
868
+
869
+ up = int(upscale_factor)
870
+ if up not in (1, 2, 4, 6, 8, 10, 12, 14, 16):
871
+ raise ValueError("upscale_factor must be one of: 1,2,4,6,8,10,12,14,16")
872
+
873
+ if s <= 0:
874
+ raise ValueError("square_size must be > 0")
875
+ if x < 0 or y < 0 or x + s > W or y + s > H:
876
+ raise ValueError(f"Crop out of bounds. image={W}x{H}, crop at ({x},{y}) size={s}")
877
+
878
+ up_w = s * up
879
+ up_h = s * up
880
+
881
+ # VAE/UNet path likes multiples of 8
882
+ if (up_w % 8) != 0 or (up_h % 8) != 0:
883
+ raise ValueError("square_size * upscale_factor must be divisible by 8 (required by VAE pipeline).")
884
+
885
+ start_p = float(max(0.0, min(1.0, controlnet_start_percent)))
886
+ end_p = float(max(0.0, min(1.0, controlnet_end_percent)))
887
+ if end_p < start_p:
888
+ start_p, end_p = end_p, start_p
889
+
890
+ normalized_lora_name = _normalize_lora_name(lora_name)
891
+ normalized_asset_name = _normalize_asset_png_name(asset_image)
892
+
893
+ # 1) Crop square
894
+ crop = image[:, y:y + s, x:x + s, :]
895
+ crop_rgb = crop[:, :, :, 0:3].contiguous()
896
+
897
+ # 2) Depth (inline Salia_Depth) then upscale with Lanczos
898
+ depth_small = _salia_depth_execute(crop_rgb, resolution=s)
899
+ depth_up = _resize_image_lanczos(depth_small, up_w, up_h)
900
+
901
+ # 3) Upscale crop for VAE encode
902
+ crop_up = _resize_image_lanczos(crop_rgb, up_w, up_h)
903
+
904
+ # 4) Load asset mask and resize (local first, download if missing)
905
+ _asset_img_unused, asset_mask = _load_asset_image_and_mask(normalized_asset_name)
906
+
907
+ if asset_mask.ndim == 2:
908
+ asset_mask = asset_mask.unsqueeze(0)
909
+ if asset_mask.ndim != 3:
910
+ raise ValueError("Asset mask must be [B,H,W].")
911
+
912
+ if asset_mask.shape[0] != B:
913
+ if asset_mask.shape[0] == 1 and B > 1:
914
+ asset_mask = asset_mask.expand(B, -1, -1)
915
+ else:
916
+ raise ValueError("Batch mismatch for asset mask.")
917
+
918
+ asset_mask_up = _resize_mask_lanczos(asset_mask, up_w, up_h)
919
+
920
+ # 5) Load checkpoint, then optional LoRA, then controlnet
921
+ if ckpt_name == "<no checkpoints found>":
922
+ raise FileNotFoundError("No checkpoints found in models/checkpoints.")
923
+ if control_net_name == "<no controlnets found>":
924
+ raise FileNotFoundError("No controlnets found in models/controlnet.")
925
+
926
+ model, clip, vae = _load_checkpoint_cached(ckpt_name)
927
+
928
+ if normalized_lora_name:
929
+ lora_path = _ensure_lora_available(normalized_lora_name)
930
+ lora = _load_lora_cached(lora_path)
931
+ if float(lora_strength) != 0.0:
932
+ model, _ = comfy.sd.load_lora_for_models(
933
+ model,
934
+ None,
935
+ lora,
936
+ float(lora_strength),
937
+ 0,
938
+ )
939
+
940
+ controlnet = _load_controlnet_cached(control_net_name)
941
+
942
+ import nodes
943
+
944
+ # 6) CLIP encodes
945
+ pos_enc = nodes.CLIPTextEncode()
946
+ neg_enc = nodes.CLIPTextEncode()
947
+ pos_fn = getattr(pos_enc, pos_enc.FUNCTION)
948
+ neg_fn = getattr(neg_enc, neg_enc.FUNCTION)
949
+ (pos_cond,) = pos_fn(text=str(positive_prompt), clip=clip)
950
+ (neg_cond,) = neg_fn(text=str(negative_prompt), clip=clip)
951
+
952
+ # 7) Apply ControlNet
953
+ cn_apply = nodes.ControlNetApplyAdvanced()
954
+ cn_fn = getattr(cn_apply, cn_apply.FUNCTION)
955
+ pos_cn, neg_cn = cn_fn(
956
+ strength=float(controlnet_strength),
957
+ start_percent=float(start_p),
958
+ end_percent=float(end_p),
959
+ positive=pos_cond,
960
+ negative=neg_cond,
961
+ control_net=controlnet,
962
+ image=depth_up,
963
+ vae=vae,
964
+ )
965
+
966
+ # 8) VAE Encode
967
+ vae_enc = nodes.VAEEncode()
968
+ vae_enc_fn = getattr(vae_enc, vae_enc.FUNCTION)
969
+ (latent,) = vae_enc_fn(pixels=crop_up, vae=vae)
970
+
971
+ # 9) KSampler (deterministic seed derived from inputs)
972
+ seed_material = (
973
+ f"{ckpt_name}|{control_net_name}|{normalized_lora_name}|{lora_strength}|{normalized_asset_name}|{x}|{y}|{s}|{up}|"
974
+ f"{steps}|{cfg}|{sampler_name}|{scheduler}|{denoise}|"
975
+ f"{controlnet_strength}|{start_p}|{end_p}|"
976
+ f"{positive_prompt}|{negative_prompt}"
977
+ ).encode("utf-8", errors="ignore")
978
+ seed64 = int(hashlib.sha256(seed_material).hexdigest()[:16], 16)
979
+
980
+ ksampler = nodes.KSampler()
981
+ k_fn = getattr(ksampler, ksampler.FUNCTION)
982
+ (sampled_latent,) = k_fn(
983
+ seed=seed64,
984
+ steps=int(steps),
985
+ cfg=float(cfg),
986
+ sampler_name=str(sampler_name),
987
+ scheduler=str(scheduler),
988
+ denoise=float(denoise),
989
+ model=model,
990
+ positive=pos_cn,
991
+ negative=neg_cn,
992
+ latent_image=latent,
993
+ )
994
+
995
+ # 10) VAE Decode -> RGB
996
+ vae_dec = nodes.VAEDecode()
997
+ vae_dec_fn = getattr(vae_dec, vae_dec.FUNCTION)
998
+ (decoded_rgb,) = vae_dec_fn(samples=sampled_latent, vae=vae)
999
+
1000
+ # 11) ✅ Manual "JoinImageWithAlpha"
1001
+ rgba_up = _rgb_to_rgba_with_comfy_mask(decoded_rgb, asset_mask_up)
1002
+
1003
+ # 12) Downscale RGBA back to crop size
1004
+ rgba_square = _resize_image_lanczos(rgba_up, s, s)
1005
+
1006
+ # 13) Paste back onto original at X,Y (alpha-over)
1007
+ out = _alpha_over_region(image, rgba_square, x=x, y=y)
1008
+ return (out,)
1009
+
1010
+
1011
+ NODE_CLASS_MAPPINGS = {
1012
+ "Salia_Detailer_Lora": Salia_Detailer_Lora,
1013
+ }
1014
+
1015
+ NODE_DISPLAY_NAME_MAPPINGS = {
1016
+ "Salia_Detailer_Lora": "Salia_Detailer_Lora (1 Lora)",
1017
+ }