saliacoel commited on
Commit
2532fd1
·
verified ·
1 Parent(s): 2a31d24

Upload salia_detailer_lora.py

Browse files
Files changed (1) hide show
  1. salia_detailer_lora.py +70 -38
salia_detailer_lora.py CHANGED
@@ -57,7 +57,7 @@ def _find_plugin_root() -> Path:
57
 
58
 
59
  PLUGIN_ROOT = _find_plugin_root()
60
- LORA_REPO_BASE = "https://huggingface.co/saliacoel/x/resolve/main"
61
 
62
 
63
  # -------------------------------------------------------------------------------------
@@ -265,7 +265,7 @@ def _ensure_lora_available(lora_name: str) -> str:
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)
@@ -285,59 +285,86 @@ def _load_lora_cached(lora_path: str):
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)
@@ -388,7 +415,7 @@ def _download_url_to_file(url: str, dst: Path, timeout: int = 180) -> None:
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
 
@@ -738,7 +765,6 @@ class Salia_Detailer_Lora:
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
@@ -782,7 +808,14 @@ class Salia_Detailer_Lora:
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}),
@@ -855,6 +888,7 @@ class Salia_Detailer_Lora:
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, :]
@@ -867,10 +901,8 @@ class Salia_Detailer_Lora:
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)
@@ -938,7 +970,7 @@ class Salia_Detailer_Lora:
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}"
@@ -981,5 +1013,5 @@ NODE_CLASS_MAPPINGS = {
981
  }
982
 
983
  NODE_DISPLAY_NAME_MAPPINGS = {
984
- "Salia_Detailer_Lora": "Salia_Detailer_Lora",
985
  }
 
57
 
58
 
59
  PLUGIN_ROOT = _find_plugin_root()
60
+ HF_REPO_BASE = "https://huggingface.co/saliacoel/x/resolve/main"
61
 
62
 
63
  # -------------------------------------------------------------------------------------
 
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)
 
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)
 
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
 
 
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
 
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}),
 
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, :]
 
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)
 
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}"
 
1013
  }
1014
 
1015
  NODE_DISPLAY_NAME_MAPPINGS = {
1016
+ "Salia_Detailer_Lora": "Salia_Detailer_Lora (1 Lora)",
1017
  }