saliacoel commited on
Commit
760b0a6
·
verified ·
1 Parent(s): 5420348

Upload salia_bbox_detector_provider_with_square.py

Browse files
salia_bbox_detector_provider_with_square.py ADDED
@@ -0,0 +1,1176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import os
5
+ import logging
6
+ import pickle
7
+ import shutil
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from datetime import datetime
12
+ from contextlib import contextmanager
13
+ from collections import namedtuple
14
+
15
+ import folder_paths
16
+
17
+ from PIL import Image
18
+ import numpy as np
19
+ import torch
20
+
21
+ try:
22
+ import cv2 # opencv-python or opencv-python-headless
23
+ except Exception:
24
+ cv2 = None
25
+
26
+
27
+ HF_REPO_BASE = "https://huggingface.co/saliacoel/x/resolve/main"
28
+
29
+
30
+ # ---------------------------
31
+ # Model folders (BBox ONLY)
32
+ # ---------------------------
33
+
34
+ _SUPPORTED_PT_EXTS = getattr(
35
+ folder_paths,
36
+ "supported_pt_extensions",
37
+ [".pt", ".pth", ".ckpt", ".safetensors"],
38
+ )
39
+
40
+
41
+ def _ordered_supported_exts() -> list[str]:
42
+ preferred = [".pt", ".pth", ".ckpt", ".safetensors"]
43
+ existing = list(_SUPPORTED_PT_EXTS)
44
+
45
+ out: list[str] = []
46
+ for ext in preferred + existing:
47
+ if ext not in out:
48
+ out.append(ext)
49
+ return out
50
+
51
+
52
+ def _add_folder_path_and_extensions(folder_name: str, paths: list[str], extensions: list[str] | tuple[str, ...]):
53
+ """Add/merge a folder_paths entry without depending on Impact-Pack helpers."""
54
+ if folder_name in folder_paths.folder_names_and_paths:
55
+ existing_paths, existing_exts = folder_paths.folder_names_and_paths[folder_name]
56
+ merged_paths = list(existing_paths)
57
+ for p in paths:
58
+ if p not in merged_paths:
59
+ merged_paths.append(p)
60
+
61
+ merged_exts = list(existing_exts)
62
+ for ext in extensions:
63
+ if ext not in merged_exts:
64
+ merged_exts.append(ext)
65
+
66
+ folder_paths.folder_names_and_paths[folder_name] = (merged_paths, tuple(merged_exts))
67
+ else:
68
+ folder_paths.folder_names_and_paths[folder_name] = (list(paths), tuple(extensions))
69
+
70
+
71
+ def _update_model_paths(base_path: str):
72
+ """
73
+ Register standard locations.
74
+ BBox models are expected at:
75
+ <base>/ultralytics/bbox/*.pt
76
+ """
77
+ _add_folder_path_and_extensions(
78
+ "ultralytics_bbox",
79
+ [os.path.join(base_path, "ultralytics", "bbox")],
80
+ _SUPPORTED_PT_EXTS,
81
+ )
82
+
83
+ # Keep the generic ultralytics root registered as a fallback/search location.
84
+ _add_folder_path_and_extensions(
85
+ "ultralytics",
86
+ [os.path.join(base_path, "ultralytics")],
87
+ _SUPPORTED_PT_EXTS,
88
+ )
89
+
90
+
91
+ # Register common folders (models_dir + ComfyUI-Manager download_model_base)
92
+ _update_model_paths(folder_paths.models_dir)
93
+ if "download_model_base" in folder_paths.folder_names_and_paths:
94
+ try:
95
+ _update_model_paths(folder_paths.get_folder_paths("download_model_base")[0])
96
+ except Exception:
97
+ pass
98
+
99
+ # Also register local folder(s) inside THIS custom-node extension, so you can keep
100
+ # models next to your Salia_*.py files if you want.
101
+ _THIS_DIR = os.path.dirname(os.path.abspath(__file__))
102
+ for local_dir in [
103
+ os.path.join(_THIS_DIR, "nodes"),
104
+ os.path.join(_THIS_DIR, "models"),
105
+ _THIS_DIR,
106
+ ]:
107
+ if os.path.isdir(local_dir):
108
+ _add_folder_path_and_extensions("ultralytics_bbox", [local_dir], _SUPPORTED_PT_EXTS)
109
+ _add_folder_path_and_extensions("ultralytics", [local_dir], _SUPPORTED_PT_EXTS)
110
+
111
+
112
+ # ---------------------------
113
+ # Download helpers
114
+ # ---------------------------
115
+
116
+
117
+ def _preferred_bbox_dir() -> str:
118
+ models_dir = getattr(folder_paths, "models_dir", None)
119
+ if models_dir:
120
+ return os.path.join(models_dir, "ultralytics", "bbox")
121
+
122
+ try:
123
+ bbox_dirs = list(folder_paths.get_folder_paths("ultralytics_bbox"))
124
+ except Exception:
125
+ bbox_dirs = []
126
+
127
+ if bbox_dirs:
128
+ return bbox_dirs[0]
129
+
130
+ raise RuntimeError("[Salia Ultralytics] No 'ultralytics_bbox' model folder is configured.")
131
+
132
+
133
+ def _download_file(url: str, target_path: str) -> None:
134
+ os.makedirs(os.path.dirname(target_path), exist_ok=True)
135
+ tmp_path = target_path + ".download"
136
+
137
+ if os.path.exists(tmp_path):
138
+ os.remove(tmp_path)
139
+
140
+ try:
141
+ request = urllib.request.Request(
142
+ url,
143
+ headers={"User-Agent": "ComfyUI-Salia-Ultralytics/1.0"},
144
+ )
145
+ with urllib.request.urlopen(request) as response, open(tmp_path, "wb") as out_file:
146
+ shutil.copyfileobj(response, out_file)
147
+
148
+ os.replace(tmp_path, target_path)
149
+ except Exception:
150
+ if os.path.exists(tmp_path):
151
+ os.remove(tmp_path)
152
+ raise
153
+
154
+
155
+ def _normalize_model_name(model_name: str) -> str:
156
+ """
157
+ Accept values like:
158
+ - 'face.pt'
159
+ - 'face' -> will later try common checkpoint extensions, preferring .pt
160
+ - 'bbox/face.pt'
161
+ - 'segm/face.pt' -> treated as 'face.pt' for best-effort compatibility
162
+ """
163
+ s = (model_name or "").strip().replace("\\", "/")
164
+ if s.startswith("bbox/"):
165
+ s = s[5:]
166
+ elif s.startswith("segm/"):
167
+ s = s[5:]
168
+
169
+ s = os.path.basename(s)
170
+ if not s:
171
+ raise ValueError("[Salia Ultralytics] model_name cannot be empty.")
172
+
173
+ return s
174
+
175
+
176
+ def _candidate_model_names(model_name: str) -> list[str]:
177
+ normalized = _normalize_model_name(model_name)
178
+ root, ext = os.path.splitext(normalized)
179
+
180
+ if ext:
181
+ return [normalized]
182
+
183
+ return [f"{root}{ext_name}" for ext_name in _ordered_supported_exts()]
184
+
185
+
186
+ # ---------------------------
187
+ # Optional safe-load fallback (PyTorch >= 2.6)
188
+ # ---------------------------
189
+
190
+ _ORIG_TORCH_LOAD = torch.load
191
+
192
+
193
+ def _get_whitelist_file() -> str | None:
194
+ """Create/return the whitelist file path under ComfyUI's user directory."""
195
+ try:
196
+ user_dir = folder_paths.get_user_directory()
197
+ except Exception:
198
+ user_dir = None
199
+
200
+ if not user_dir or not os.path.isdir(user_dir):
201
+ return None
202
+
203
+ wl_dir = os.path.join(user_dir, "default", "ComfyUI-Salia-Ultralytics")
204
+ wl_file = os.path.join(wl_dir, "model-whitelist.txt")
205
+ try:
206
+ os.makedirs(wl_dir, exist_ok=True)
207
+ if not os.path.exists(wl_file):
208
+ with open(wl_file, "w", encoding="utf-8") as f:
209
+ f.write("# Add base filenames of trusted legacy models here (one per line).\n")
210
+ f.write("# Example: face.pt\n")
211
+ f.write("# These will be allowed to load with weights_only=False if safe loading fails.\n")
212
+ f.write("# WARNING: Only add models you trust.\n")
213
+ except Exception:
214
+ return None
215
+
216
+ return wl_file
217
+
218
+
219
+ _WHITELIST_PATH = _get_whitelist_file()
220
+
221
+
222
+ # ---------------------------
223
+ # Model path logging
224
+ # ---------------------------
225
+
226
+ def _get_model_load_log_file() -> str:
227
+ """
228
+ Log file path used to record which ultralytics model file was actually loaded.
229
+ Prefer the same ComfyUI user dir used for the whitelist (if available).
230
+ """
231
+ if _WHITELIST_PATH:
232
+ base_dir = os.path.dirname(_WHITELIST_PATH)
233
+ return os.path.join(base_dir, "model-load-log.txt")
234
+
235
+ try:
236
+ user_dir = folder_paths.get_user_directory()
237
+ except Exception:
238
+ user_dir = None
239
+
240
+ if user_dir and os.path.isdir(user_dir):
241
+ base_dir = os.path.join(user_dir, "default", "ComfyUI-Salia-Ultralytics")
242
+ try:
243
+ os.makedirs(base_dir, exist_ok=True)
244
+ except Exception:
245
+ pass
246
+ return os.path.join(base_dir, "model-load-log.txt")
247
+
248
+ return os.path.join(_THIS_DIR, "model-load-log.txt")
249
+
250
+
251
+ _MODEL_LOAD_LOG_PATH = _get_model_load_log_file()
252
+
253
+
254
+ def _find_all_model_paths(model_file: str) -> list[str]:
255
+ """
256
+ Find all possible on-disk matches across the registered ultralytics folders.
257
+ Useful if the same filename exists in multiple locations.
258
+ """
259
+ matches: list[str] = []
260
+
261
+ bbox_roots: list[str] = []
262
+ ultra_roots: list[str] = []
263
+ try:
264
+ bbox_roots = list(folder_paths.get_folder_paths("ultralytics_bbox"))
265
+ except Exception:
266
+ pass
267
+ try:
268
+ ultra_roots = list(folder_paths.get_folder_paths("ultralytics"))
269
+ except Exception:
270
+ pass
271
+
272
+ def add_if_exists(root: str, rel: str):
273
+ p = os.path.join(root, rel)
274
+ if os.path.exists(p):
275
+ matches.append(os.path.abspath(p))
276
+
277
+ # Primary: bbox roots
278
+ for r in bbox_roots:
279
+ add_if_exists(r, model_file)
280
+
281
+ # Secondary: ultralytics roots (try both direct and bbox/ subfolder)
282
+ for r in ultra_roots:
283
+ add_if_exists(r, model_file)
284
+ add_if_exists(r, f"bbox/{model_file}")
285
+
286
+ # De-dupe preserving order
287
+ out: list[str] = []
288
+ seen = set()
289
+ for p in matches:
290
+ if p not in seen:
291
+ seen.add(p)
292
+ out.append(p)
293
+ return out
294
+
295
+
296
+ def _log_selected_model(model_name: str, model_path: str, matches: list[str] | None = None):
297
+ """
298
+ Prints the resolved model path to console AND appends it to a log file.
299
+ """
300
+ print(f"[Salia Ultralytics] Selected model_name: {model_name}")
301
+ print(f"[Salia Ultralytics] Resolved model_path: {model_path}")
302
+ if matches and len(matches) > 1:
303
+ print("[Salia Ultralytics] Multiple matches found (first one is used):")
304
+ for p in matches:
305
+ print(f" - {p}")
306
+ print(f"[Salia Ultralytics] Model load log file: {_MODEL_LOAD_LOG_PATH}")
307
+
308
+ logging.info("[Salia Ultralytics] Selected model_name: %s", model_name)
309
+ logging.info("[Salia Ultralytics] Resolved model_path: %s", model_path)
310
+ if matches and len(matches) > 1:
311
+ logging.warning("[Salia Ultralytics] Multiple matches found (first one is used):")
312
+ for p in matches:
313
+ logging.warning(" - %s", p)
314
+ logging.info("[Salia Ultralytics] Model load log file: %s", _MODEL_LOAD_LOG_PATH)
315
+
316
+ try:
317
+ ts = datetime.now().isoformat(timespec="seconds")
318
+ exists = os.path.isfile(model_path)
319
+ size = os.path.getsize(model_path) if exists else -1
320
+
321
+ log_dir = os.path.dirname(_MODEL_LOAD_LOG_PATH)
322
+ if log_dir:
323
+ os.makedirs(log_dir, exist_ok=True)
324
+
325
+ with open(_MODEL_LOAD_LOG_PATH, "a", encoding="utf-8") as f:
326
+ f.write(f"{ts}\t{model_name}\t{model_path}\texists={exists}\tsize={size}\n")
327
+ if matches and len(matches) > 1:
328
+ for p in matches:
329
+ f.write(f"{ts}\tmatch\t{p}\n")
330
+ except Exception as e:
331
+ logging.warning("[Salia Ultralytics] Failed to write model-load log to %s: %s", _MODEL_LOAD_LOG_PATH, e)
332
+
333
+
334
+
335
+ def _load_whitelist(filepath: str | None) -> set[str]:
336
+ if not filepath:
337
+ return set()
338
+ try:
339
+ approved: set[str] = set()
340
+ with open(filepath, "r", encoding="utf-8") as f:
341
+ for line in f:
342
+ line = line.strip()
343
+ if line and not line.startswith("#"):
344
+ approved.add(os.path.basename(line))
345
+ return approved
346
+ except Exception:
347
+ return set()
348
+
349
+
350
+ _MODEL_WHITELIST = _load_whitelist(_WHITELIST_PATH)
351
+
352
+
353
+ def _torch_load_wrapper(*args, **kwargs):
354
+ """Try safe load first; if it fails due to weights-only restrictions, allow fallback if whitelisted."""
355
+ filename = None
356
+ if args and isinstance(args[0], str):
357
+ filename = os.path.basename(args[0])
358
+ elif isinstance(kwargs.get("f"), str):
359
+ filename = os.path.basename(kwargs["f"])
360
+
361
+ try:
362
+ return _ORIG_TORCH_LOAD(*args, **kwargs)
363
+ except pickle.UnpicklingError as e:
364
+ msg = str(e)
365
+ maybe_weights_only_error = (
366
+ "Weights only load failed" in msg
367
+ or "Unsupported global" in msg
368
+ or "disallowed" in msg
369
+ or "not allowed" in msg
370
+ or "getattr" in msg
371
+ )
372
+
373
+ if not maybe_weights_only_error:
374
+ raise
375
+
376
+ global _MODEL_WHITELIST
377
+ _MODEL_WHITELIST = _load_whitelist(_WHITELIST_PATH)
378
+
379
+ if filename and filename in _MODEL_WHITELIST:
380
+ logging.warning(
381
+ "[Salia Ultralytics] Safe torch.load failed for '%s'. Retrying with weights_only=False because it's whitelisted (%s).",
382
+ filename,
383
+ _WHITELIST_PATH,
384
+ )
385
+ retry_kwargs = dict(kwargs)
386
+ retry_kwargs["weights_only"] = False
387
+ return _ORIG_TORCH_LOAD(*args, **retry_kwargs)
388
+
389
+ logging.error(
390
+ "[Salia Ultralytics] Blocked unsafe model load for '%s'.\n"
391
+ "Safe loading failed and the file is not whitelisted.\n"
392
+ "If you TRUST this model, add its base name to: %s",
393
+ filename or "[unknown]",
394
+ _WHITELIST_PATH or "[whitelist path unavailable]",
395
+ )
396
+ raise
397
+
398
+
399
+ @contextmanager
400
+ def _patched_torch_load_for_ultralytics():
401
+ """Patch torch.load only while ultralytics loads a checkpoint."""
402
+ if not hasattr(torch.serialization, "safe_globals"):
403
+ yield
404
+ return
405
+
406
+ prev = torch.load
407
+ torch.load = _torch_load_wrapper
408
+ try:
409
+ yield
410
+ finally:
411
+ torch.load = prev
412
+
413
+
414
+ def _load_yolo(model_path: str):
415
+ """Load an Ultralytics YOLO model (with optional safe-load fallback)."""
416
+ try:
417
+ from ultralytics import YOLO # lazy import
418
+ except Exception as e:
419
+ raise ImportError(
420
+ "[Salia Ultralytics] ultralytics is not installed. Install it in your ComfyUI env, e.g.:\n"
421
+ "pip install ultralytics"
422
+ ) from e
423
+
424
+ with _patched_torch_load_for_ultralytics():
425
+ return YOLO(model_path)
426
+
427
+
428
+ # ---------------------------
429
+ # Repo-backed model resolution
430
+ # ---------------------------
431
+
432
+
433
+ def _resolve_existing_model_path(model_name: str):
434
+ for candidate in _candidate_model_names(model_name):
435
+ model_path = folder_paths.get_full_path("ultralytics_bbox", candidate)
436
+
437
+ if model_path is None:
438
+ model_path = folder_paths.get_full_path("ultralytics", f"bbox/{candidate}")
439
+
440
+ if model_path is None:
441
+ model_path = folder_paths.get_full_path("ultralytics", candidate)
442
+
443
+ if model_path is not None:
444
+ matches = _find_all_model_paths(candidate)
445
+ return candidate, os.path.abspath(model_path), matches
446
+
447
+ return None, None, []
448
+
449
+
450
+ def _ensure_model_available(model_name: str):
451
+ resolved_name, model_path, matches = _resolve_existing_model_path(model_name)
452
+ if model_path is not None:
453
+ return resolved_name, model_path, matches
454
+
455
+ download_dir = _preferred_bbox_dir()
456
+ attempted_urls: list[str] = []
457
+
458
+ for candidate in _candidate_model_names(model_name):
459
+ target_path = os.path.join(download_dir, candidate)
460
+ url = f"{HF_REPO_BASE}/{urllib.parse.quote(candidate)}"
461
+ attempted_urls.append(url)
462
+
463
+ logging.info("[Salia Ultralytics] Downloading missing bbox model: %s", url)
464
+ try:
465
+ _download_file(url, target_path)
466
+ except urllib.error.HTTPError as e:
467
+ if e.code == 404:
468
+ logging.info("[Salia Ultralytics] Model not found in repo: %s", url)
469
+ continue
470
+ raise RuntimeError(
471
+ f"[Salia Ultralytics] Failed to download '{candidate}' from {url}: {e}"
472
+ ) from e
473
+ except Exception as e:
474
+ raise RuntimeError(
475
+ f"[Salia Ultralytics] Failed to download '{candidate}' from {url}: {e}"
476
+ ) from e
477
+
478
+ resolved_name, model_path, matches = _resolve_existing_model_path(candidate)
479
+ if model_path is None:
480
+ if os.path.isfile(target_path):
481
+ model_path = os.path.abspath(target_path)
482
+ matches = _find_all_model_paths(candidate)
483
+ resolved_name = candidate
484
+ else:
485
+ raise RuntimeError(
486
+ f"[Salia Ultralytics] Downloaded '{candidate}' but could not resolve the saved file."
487
+ )
488
+
489
+ return resolved_name, model_path, matches
490
+
491
+ tried = "\n - ".join(attempted_urls) if attempted_urls else "[no download URLs attempted]"
492
+ raise ValueError(
493
+ f"[Salia Ultralytics] model file '{model_name}' was not found locally and could not be downloaded from the repo.\n"
494
+ f"Tried:\n - {tried}\n"
495
+ f"Expected local folder: {download_dir}"
496
+ )
497
+
498
+
499
+ # ---------------------------
500
+ # Minimal Impact-compatible utilities (self-contained)
501
+ # ---------------------------
502
+
503
+ def _tensor2np_rgb(image: torch.Tensor) -> np.ndarray:
504
+ """Convert a ComfyUI IMAGE tensor to a uint8 RGB numpy image."""
505
+ if not isinstance(image, torch.Tensor):
506
+ raise TypeError(f"Expected torch.Tensor, got {type(image)}")
507
+
508
+ if image.dim() == 4:
509
+ img = image[0]
510
+ else:
511
+ img = image
512
+
513
+ img = img.detach()
514
+ if img.is_cuda:
515
+ img = img.cpu()
516
+
517
+ img = img.clamp(0, 1).numpy()
518
+ if img.shape[-1] == 1:
519
+ img = np.repeat(img, 3, axis=-1)
520
+
521
+ img_u8 = (img * 255.0).round().astype(np.uint8)
522
+ return img_u8
523
+
524
+
525
+ def tensor2pil(image: torch.Tensor) -> Image.Image:
526
+ return Image.fromarray(_tensor2np_rgb(image))
527
+
528
+
529
+ def make_crop_region(w: int, h: int, bbox_xyxy, crop_factor: float, crop_min_size: int | None = None):
530
+ x1, y1, x2, y2 = [float(v) for v in bbox_xyxy]
531
+ bbox_w = max(1.0, x2 - x1)
532
+ bbox_h = max(1.0, y2 - y1)
533
+
534
+ crop_w = bbox_w * float(crop_factor)
535
+ crop_h = bbox_h * float(crop_factor)
536
+
537
+ if crop_min_size is not None:
538
+ crop_w = max(crop_w, float(crop_min_size))
539
+ crop_h = max(crop_h, float(crop_min_size))
540
+
541
+ cx = (x1 + x2) / 2.0
542
+ cy = (y1 + y2) / 2.0
543
+
544
+ rx1 = int(round(cx - crop_w / 2.0))
545
+ ry1 = int(round(cy - crop_h / 2.0))
546
+ rx2 = int(round(cx + crop_w / 2.0))
547
+ ry2 = int(round(cy + crop_h / 2.0))
548
+
549
+ rx1 = max(0, min(w - 1, rx1))
550
+ ry1 = max(0, min(h - 1, ry1))
551
+ rx2 = max(rx1 + 1, min(w, rx2))
552
+ ry2 = max(ry1 + 1, min(h, ry2))
553
+
554
+ return (rx1, ry1, rx2, ry2)
555
+
556
+
557
+ def crop_image(image: torch.Tensor, crop_region):
558
+ x1, y1, x2, y2 = crop_region
559
+ x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
560
+ if image.dim() == 4:
561
+ return image[:, y1:y2, x1:x2, :]
562
+ if image.dim() == 3:
563
+ return image[y1:y2, x1:x2, :]
564
+ raise ValueError(f"Unexpected image tensor shape: {tuple(image.shape)}")
565
+
566
+
567
+ def crop_ndarray2(arr: np.ndarray, crop_region):
568
+ x1, y1, x2, y2 = crop_region
569
+ x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
570
+ return arr[y1:y2, x1:x2]
571
+
572
+
573
+ def dilate_masks(masks, dilation: int):
574
+ if dilation <= 0:
575
+ return masks
576
+ if cv2 is None:
577
+ raise ImportError(
578
+ "[Salia Ultralytics] opencv-python is required for mask dilation but cv2 could not be imported.\n"
579
+ "Install: pip install opencv-python-headless"
580
+ )
581
+
582
+ k = int(dilation)
583
+ ksize = k * 2 + 1
584
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ksize, ksize))
585
+
586
+ out = []
587
+ for bbox, mask, conf in masks:
588
+ m = (mask > 0.5).astype(np.uint8) * 255
589
+ m = cv2.dilate(m, kernel, iterations=1)
590
+ out.append((bbox, (m > 0).astype(np.float32), conf))
591
+ return out
592
+
593
+
594
+ def combine_masks(masks, out_shape_hw: tuple[int, int] | None = None) -> torch.Tensor:
595
+ if not masks:
596
+ if out_shape_hw is None:
597
+ return torch.zeros((1, 1, 1), dtype=torch.float32)
598
+ h, w = out_shape_hw
599
+ return torch.zeros((1, h, w), dtype=torch.float32)
600
+
601
+ base = masks[0][1]
602
+ combined = np.zeros_like(base, dtype=np.float32)
603
+ for _, m, _ in masks:
604
+ combined = np.maximum(combined, m.astype(np.float32))
605
+ return torch.from_numpy(combined).unsqueeze(0)
606
+
607
+
608
+ # ---------------------------
609
+ # Impact-compatible detector wrapper objects
610
+ # ---------------------------
611
+
612
+ SEG = namedtuple(
613
+ "SEG",
614
+ [
615
+ "cropped_image",
616
+ "cropped_mask",
617
+ "confidence",
618
+ "crop_region",
619
+ "bbox",
620
+ "label",
621
+ "control_net_wrapper",
622
+ ],
623
+ defaults=[None],
624
+ )
625
+
626
+
627
+ class NO_BBOX_DETECTOR:
628
+ pass
629
+
630
+
631
+ def _create_masks(results):
632
+ # results = [labels, bboxes_xyxy, masks, confs]
633
+ bboxes = results[1]
634
+ masks = results[2]
635
+ confs = results[3]
636
+
637
+ out = []
638
+ for i in range(len(masks)):
639
+ out.append((bboxes[i], masks[i].astype(np.float32), confs[i]))
640
+ return out
641
+
642
+
643
+ def _inference_bbox(model, image_pil: Image.Image, confidence: float = 0.3, device: str = ""):
644
+ pred = model(image_pil, conf=confidence, device=device)
645
+
646
+ bboxes = pred[0].boxes.xyxy.cpu().numpy() # xyxy
647
+ if bboxes.shape[0] == 0:
648
+ return [[], [], [], []]
649
+
650
+ # Make simple rectangle masks for each bbox
651
+ np_img = np.array(image_pil)
652
+ if np_img.ndim == 2:
653
+ h, w = np_img.shape
654
+ else:
655
+ h, w = np_img.shape[0], np_img.shape[1]
656
+
657
+ masks = []
658
+ for x0, y0, x1, y1 in bboxes:
659
+ m = np.zeros((h, w), dtype=np.uint8)
660
+ x0i, y0i, x1i, y1i = int(x0), int(y0), int(x1), int(y1)
661
+ x0i = max(0, min(w - 1, x0i))
662
+ x1i = max(0, min(w, x1i))
663
+ y0i = max(0, min(h - 1, y0i))
664
+ y1i = max(0, min(h, y1i))
665
+ if cv2 is not None:
666
+ cv2.rectangle(m, (x0i, y0i), (x1i, y1i), 255, -1)
667
+ else:
668
+ m[y0i:y1i, x0i:x1i] = 255
669
+ masks.append((m > 0))
670
+
671
+ labels = []
672
+ confs = []
673
+ for i in range(len(bboxes)):
674
+ labels.append(pred[0].names[int(pred[0].boxes[i].cls.item())])
675
+ confs.append(pred[0].boxes[i].conf.detach().cpu().numpy())
676
+
677
+ return [labels, list(bboxes), masks, confs]
678
+
679
+
680
+ class SaliaUltraBBoxDetector:
681
+ def __init__(self, model):
682
+ self.model = model
683
+
684
+ def detect(self, image, threshold, dilation, crop_factor, drop_size=1, detailer_hook=None):
685
+ drop_size = max(int(drop_size), 1)
686
+ detected = _inference_bbox(self.model, tensor2pil(image), confidence=float(threshold))
687
+ masks = _create_masks(detected)
688
+
689
+ if int(dilation) > 0:
690
+ masks = dilate_masks(masks, int(dilation))
691
+
692
+ items = []
693
+ h = image.shape[1]
694
+ w = image.shape[2]
695
+
696
+ for (bbox, mask, conf), label in zip(masks, detected[0]):
697
+ x1, y1, x2, y2 = bbox
698
+ if (x2 - x1) > drop_size and (y2 - y1) > drop_size:
699
+ crop_region = make_crop_region(w, h, bbox, float(crop_factor))
700
+
701
+ if detailer_hook is not None and hasattr(detailer_hook, "post_crop_region"):
702
+ crop_region = detailer_hook.post_crop_region(w, h, bbox, crop_region)
703
+
704
+ cropped_image = crop_image(image, crop_region)
705
+ cropped_mask = crop_ndarray2(mask, crop_region)
706
+
707
+ items.append(SEG(cropped_image, cropped_mask, conf, crop_region, bbox, label, None))
708
+
709
+ segs = (image.shape[1], image.shape[2]), items
710
+
711
+ if detailer_hook is not None and hasattr(detailer_hook, "post_detection"):
712
+ segs = detailer_hook.post_detection(segs)
713
+
714
+ return segs
715
+
716
+ def detect_combined(self, image, threshold, dilation):
717
+ detected = _inference_bbox(self.model, tensor2pil(image), confidence=float(threshold))
718
+ masks = _create_masks(detected)
719
+ if int(dilation) > 0:
720
+ masks = dilate_masks(masks, int(dilation))
721
+ return combine_masks(masks, out_shape_hw=(image.shape[1], image.shape[2]))
722
+
723
+ def setAux(self, x):
724
+ pass
725
+
726
+
727
+ # ---------------------------
728
+ # The actual ComfyUI Node (BBox ONLY)
729
+ # ---------------------------
730
+
731
+ class Salia_BBox_DetectorProvider:
732
+ """Load an Ultralytics model from local disk or the saliacoel/x repo and provide an Impact-compatible BBOX detector (BBox only)."""
733
+
734
+ @classmethod
735
+ def INPUT_TYPES(cls):
736
+ return {
737
+ "required": {
738
+ "model_name": (
739
+ "STRING",
740
+ {
741
+ "default": "",
742
+ "multiline": False,
743
+ "placeholder": "face.pt",
744
+ "tooltip": "Ultralytics bbox model filename. You can enter 'face.pt', 'face', or legacy values like 'bbox/face.pt'.",
745
+ },
746
+ )
747
+ }
748
+ }
749
+
750
+ RETURN_TYPES = ("BBOX_DETECTOR",)
751
+ FUNCTION = "doit"
752
+ CATEGORY = "Salia/Detectors"
753
+
754
+ def doit(self, model_name: str):
755
+ resolved_name, model_path, matches = _ensure_model_available(model_name)
756
+ _log_selected_model(resolved_name, os.path.abspath(model_path), matches)
757
+
758
+ model = _load_yolo(model_path)
759
+ return (SaliaUltraBBoxDetector(model),)
760
+
761
+
762
+
763
+ def _round_half_up(value: float) -> int:
764
+ return int(math.floor(float(value) + 0.5))
765
+
766
+
767
+ def _get_image_size_hw(image: torch.Tensor) -> tuple[int, int]:
768
+ if not isinstance(image, torch.Tensor):
769
+ raise TypeError(f"Expected IMAGE to be a torch.Tensor, got {type(image)}")
770
+
771
+ if image.dim() < 3:
772
+ raise ValueError(f"Unexpected IMAGE tensor shape: {tuple(image.shape)}")
773
+
774
+ return int(image.shape[1]), int(image.shape[2])
775
+
776
+
777
+ def _normalize_bbox_xyxy(bbox, image_w: int, image_h: int) -> tuple[int, int, int, int] | None:
778
+ try:
779
+ x1f, y1f, x2f, y2f = [float(v) for v in bbox]
780
+ except Exception:
781
+ return None
782
+
783
+ left = int(math.floor(min(x1f, x2f)))
784
+ top = int(math.floor(min(y1f, y2f)))
785
+ right = int(math.ceil(max(x1f, x2f)))
786
+ bottom = int(math.ceil(max(y1f, y2f)))
787
+
788
+ left = max(0, min(image_w, left))
789
+ top = max(0, min(image_h, top))
790
+ right = max(0, min(image_w, right))
791
+ bottom = max(0, min(image_h, bottom))
792
+
793
+ if right <= left or bottom <= top:
794
+ return None
795
+
796
+ return (left, top, right, bottom)
797
+
798
+
799
+ def _floor_to_multiple(value: int, multiple: int) -> int:
800
+ value = int(value)
801
+ multiple = int(multiple)
802
+ if multiple <= 0:
803
+ return value
804
+ return value - (value % multiple)
805
+
806
+
807
+ def _ceil_to_multiple(value: int, multiple: int) -> int:
808
+ value = int(math.ceil(float(value)))
809
+ multiple = int(multiple)
810
+ if multiple <= 0:
811
+ return value
812
+ remainder = value % multiple
813
+ return value if remainder == 0 else value + (multiple - remainder)
814
+
815
+
816
+ def _choose_divisible_square_size(target_size: int, max_size: int, multiple: int = 8) -> int | None:
817
+ target_size = int(math.ceil(float(target_size)))
818
+ max_size = int(math.floor(float(max_size)))
819
+
820
+ if target_size <= 0 or max_size <= 0:
821
+ return None
822
+
823
+ grow = _ceil_to_multiple(target_size, multiple)
824
+ if grow <= max_size:
825
+ return grow
826
+
827
+ shrink = _floor_to_multiple(max_size, multiple)
828
+ if shrink > 0:
829
+ return shrink
830
+
831
+ return None
832
+
833
+
834
+ def _place_square_from_center(center_x: float, center_y: float, size: int, image_w: int, image_h: int):
835
+ size = int(size)
836
+ if size <= 0 or size > image_w or size > image_h:
837
+ return None
838
+
839
+ x = _round_half_up(float(center_x) - (size / 2.0))
840
+ y = _round_half_up(float(center_y) - (size / 2.0))
841
+
842
+ max_x = image_w - size
843
+ max_y = image_h - size
844
+
845
+ x = max(0, min(max_x, x))
846
+ y = max(0, min(max_y, y))
847
+
848
+ return (int(x), int(y), int(size))
849
+
850
+
851
+ def _move_square_within_bounds(x: int, y: int, size: int, dx: int, dy: int, image_w: int, image_h: int):
852
+ size = int(size)
853
+ if size <= 0 or size > image_w or size > image_h:
854
+ return None
855
+
856
+ max_x = image_w - size
857
+ max_y = image_h - size
858
+
859
+ moved_x = max(0, min(max_x, int(x) + int(dx)))
860
+ moved_y = max(0, min(max_y, int(y) + int(dy)))
861
+
862
+ return (int(moved_x), int(moved_y), int(size))
863
+
864
+
865
+ def _square_center(x: int, y: int, size: int) -> tuple[float, float]:
866
+ return (float(x) + (float(size) / 2.0), float(y) + (float(size) / 2.0))
867
+
868
+
869
+ def _max_centered_square_size(center_x: float, center_y: float, image_w: int, image_h: int) -> int:
870
+ max_half = min(
871
+ float(center_x),
872
+ float(image_w) - float(center_x),
873
+ float(center_y),
874
+ float(image_h) - float(center_y),
875
+ )
876
+ if max_half <= 0:
877
+ return 0
878
+ return int(math.floor(max_half * 2.0))
879
+
880
+
881
+ def _extract_bbox_and_confidence(item):
882
+ bbox = getattr(item, "bbox", None)
883
+ confidence = getattr(item, "confidence", None)
884
+
885
+ if bbox is None and isinstance(item, (tuple, list)) and len(item) >= 5:
886
+ bbox = item[4]
887
+ confidence = item[2] if len(item) >= 3 else confidence
888
+
889
+ if bbox is None:
890
+ return None
891
+
892
+ try:
893
+ conf_value = float(confidence)
894
+ except Exception:
895
+ conf_value = float("-inf")
896
+
897
+ return bbox, conf_value
898
+
899
+
900
+ def _get_most_confident_bbox(bbox_detector, image, threshold: float = 0.3):
901
+ if bbox_detector is None or not hasattr(bbox_detector, "detect"):
902
+ return None
903
+
904
+ try:
905
+ segs = bbox_detector.detect(image, threshold, 0, 1.0, 1)
906
+ except TypeError:
907
+ try:
908
+ segs = bbox_detector.detect(image, threshold, 0, 1.0)
909
+ except Exception as e:
910
+ logging.warning("[Salia BBox To Square] Detector execution failed: %s", e)
911
+ return None
912
+ except Exception as e:
913
+ logging.warning("[Salia BBox To Square] Detector execution failed: %s", e)
914
+ return None
915
+
916
+ if not isinstance(segs, tuple) or len(segs) < 2:
917
+ return None
918
+
919
+ items = segs[1]
920
+ if not isinstance(items, (list, tuple)) or len(items) == 0:
921
+ return None
922
+
923
+ parsed = []
924
+ for item in items:
925
+ extracted = _extract_bbox_and_confidence(item)
926
+ if extracted is not None:
927
+ parsed.append(extracted)
928
+
929
+ if not parsed:
930
+ return None
931
+
932
+ parsed.sort(key=lambda x: x[1], reverse=True)
933
+ return parsed[0][0]
934
+
935
+
936
+ class Salia_BBox_To_Square_Coords:
937
+ """
938
+ Takes a BBOX_DETECTOR and an IMAGE, grabs the most confident bbox,
939
+ converts it to an in-bounds square divisible by 8, applies move and
940
+ resize offsets, and returns top-left x/y plus square size.
941
+
942
+ If no bbox is found or the computed square is invalid, fallback values
943
+ are returned unchanged.
944
+ """
945
+
946
+ CATEGORY = "Salia/Detectors"
947
+ FUNCTION = "doit"
948
+ RETURN_TYPES = ("INT", "INT", "INT")
949
+ RETURN_NAMES = ("x_coord", "y_coord", "square_size")
950
+ DESCRIPTION = (
951
+ "Uses the most confident bbox from a BBOX_DETECTOR, converts it to a "
952
+ "square divisible by 8, applies move and size adjustments, and returns "
953
+ "top-left x/y plus square size. Falls back when detection fails."
954
+ )
955
+ OUTPUT_TOOLTIPS = (
956
+ "Top-left X coordinate of the final square.",
957
+ "Top-left Y coordinate of the final square.",
958
+ "Final square side length in pixels.",
959
+ )
960
+ SEARCH_ALIASES = [
961
+ "bbox to square",
962
+ "bbox square coords",
963
+ "square crop coords",
964
+ "first bbox coords",
965
+ ]
966
+
967
+ @classmethod
968
+ def INPUT_TYPES(cls):
969
+ return {
970
+ "required": {
971
+ "bbox_detector": ("BBOX_DETECTOR",),
972
+ "image": ("IMAGE",),
973
+ "fallback_x": (
974
+ "INT",
975
+ {
976
+ "default": 0,
977
+ "min": -1048576,
978
+ "max": 1048576,
979
+ "step": 1,
980
+ },
981
+ ),
982
+ "fallback_y": (
983
+ "INT",
984
+ {
985
+ "default": 0,
986
+ "min": -1048576,
987
+ "max": 1048576,
988
+ "step": 1,
989
+ },
990
+ ),
991
+ "fallback_square_size": (
992
+ "INT",
993
+ {
994
+ "default": 512,
995
+ "min": 0,
996
+ "max": 1048576,
997
+ "step": 1,
998
+ },
999
+ ),
1000
+ "move_up": (
1001
+ "INT",
1002
+ {
1003
+ "default": 0,
1004
+ "min": 0,
1005
+ "max": 1048576,
1006
+ "step": 1,
1007
+ },
1008
+ ),
1009
+ "move_down": (
1010
+ "INT",
1011
+ {
1012
+ "default": 0,
1013
+ "min": 0,
1014
+ "max": 1048576,
1015
+ "step": 1,
1016
+ },
1017
+ ),
1018
+ "move_left": (
1019
+ "INT",
1020
+ {
1021
+ "default": 0,
1022
+ "min": 0,
1023
+ "max": 1048576,
1024
+ "step": 1,
1025
+ },
1026
+ ),
1027
+ "move_right": (
1028
+ "INT",
1029
+ {
1030
+ "default": 0,
1031
+ "min": 0,
1032
+ "max": 1048576,
1033
+ "step": 1,
1034
+ },
1035
+ ),
1036
+ "enlarge": (
1037
+ "INT",
1038
+ {
1039
+ "default": 0,
1040
+ "min": 0,
1041
+ "max": 1048576,
1042
+ "step": 1,
1043
+ },
1044
+ ),
1045
+ "shrink": (
1046
+ "INT",
1047
+ {
1048
+ "default": 0,
1049
+ "min": 0,
1050
+ "max": 1048576,
1051
+ "step": 1,
1052
+ },
1053
+ ),
1054
+ }
1055
+ }
1056
+
1057
+ @staticmethod
1058
+ def _fallback(fallback_x: int, fallback_y: int, fallback_square_size: int):
1059
+ return (int(fallback_x), int(fallback_y), int(fallback_square_size))
1060
+
1061
+ def doit(
1062
+ self,
1063
+ bbox_detector,
1064
+ image,
1065
+ fallback_x,
1066
+ fallback_y,
1067
+ fallback_square_size,
1068
+ move_up,
1069
+ move_down,
1070
+ move_left,
1071
+ move_right,
1072
+ enlarge,
1073
+ shrink,
1074
+ ):
1075
+ fallback = self._fallback(fallback_x, fallback_y, fallback_square_size)
1076
+
1077
+ try:
1078
+ image_h, image_w = _get_image_size_hw(image)
1079
+ except Exception as e:
1080
+ logging.warning("[Salia BBox To Square] Invalid IMAGE input, using fallback: %s", e)
1081
+ return fallback
1082
+
1083
+ bbox = _get_most_confident_bbox(bbox_detector, image, threshold=0.3)
1084
+ if bbox is None:
1085
+ logging.info("[Salia BBox To Square] No bbox found, using fallback values.")
1086
+ return fallback
1087
+
1088
+ bbox_xyxy = _normalize_bbox_xyxy(bbox, image_w, image_h)
1089
+ if bbox_xyxy is None:
1090
+ logging.warning("[Salia BBox To Square] Invalid bbox from detector, using fallback values.")
1091
+ return fallback
1092
+
1093
+ x1, y1, x2, y2 = bbox_xyxy
1094
+ bbox_w = x2 - x1
1095
+ bbox_h = y2 - y1
1096
+
1097
+ if bbox_w <= 0 or bbox_h <= 0:
1098
+ logging.warning("[Salia BBox To Square] Degenerate bbox, using fallback values.")
1099
+ return fallback
1100
+
1101
+ base_size = max(bbox_w, bbox_h)
1102
+ max_image_square = min(image_w, image_h)
1103
+ square_size = _choose_divisible_square_size(base_size, max_image_square, multiple=8)
1104
+
1105
+ if square_size is None or square_size <= 0:
1106
+ logging.warning("[Salia BBox To Square] Could not derive a valid divisible-by-8 square, using fallback.")
1107
+ return fallback
1108
+
1109
+ center_x = (x1 + x2) / 2.0
1110
+ center_y = (y1 + y2) / 2.0
1111
+
1112
+ square = _place_square_from_center(center_x, center_y, square_size, image_w, image_h)
1113
+ if square is None:
1114
+ logging.warning("[Salia BBox To Square] Initial square placement failed, using fallback.")
1115
+ return fallback
1116
+
1117
+ x, y, square_size = square
1118
+
1119
+ dx = int(move_right) - int(move_left)
1120
+ dy = int(move_down) - int(move_up)
1121
+
1122
+ moved = _move_square_within_bounds(x, y, square_size, dx, dy, image_w, image_h)
1123
+ if moved is None:
1124
+ logging.warning("[Salia BBox To Square] Move step failed, using fallback.")
1125
+ return fallback
1126
+
1127
+ x, y, square_size = moved
1128
+ moved_center_x, moved_center_y = _square_center(x, y, square_size)
1129
+
1130
+ requested_size = int(square_size) + int(enlarge) - int(shrink)
1131
+ if requested_size <= 0:
1132
+ logging.warning("[Salia BBox To Square] Requested size is non-positive, using fallback.")
1133
+ return fallback
1134
+
1135
+ max_resizable_size = _max_centered_square_size(moved_center_x, moved_center_y, image_w, image_h)
1136
+ final_square_size = _choose_divisible_square_size(requested_size, max_resizable_size, multiple=8)
1137
+
1138
+ if final_square_size is None or final_square_size <= 0:
1139
+ logging.warning("[Salia BBox To Square] Final square size could not be resolved, using fallback.")
1140
+ return fallback
1141
+
1142
+ final_square = _place_square_from_center(
1143
+ moved_center_x,
1144
+ moved_center_y,
1145
+ final_square_size,
1146
+ image_w,
1147
+ image_h,
1148
+ )
1149
+ if final_square is None:
1150
+ logging.warning("[Salia BBox To Square] Final square placement failed, using fallback.")
1151
+ return fallback
1152
+
1153
+ final_x, final_y, final_square_size = final_square
1154
+
1155
+ if (
1156
+ final_square_size <= 0
1157
+ or final_x < 0
1158
+ or final_y < 0
1159
+ or final_x + final_square_size > image_w
1160
+ or final_y + final_square_size > image_h
1161
+ ):
1162
+ logging.warning("[Salia BBox To Square] Final square is out of bounds, using fallback.")
1163
+ return fallback
1164
+
1165
+ return (int(final_x), int(final_y), int(final_square_size))
1166
+
1167
+
1168
+ NODE_CLASS_MAPPINGS = {
1169
+ "Salia_BBox_DetectorProvider": Salia_BBox_DetectorProvider,
1170
+ "Salia_BBox_To_Square_Coords": Salia_BBox_To_Square_Coords,
1171
+ }
1172
+
1173
+ NODE_DISPLAY_NAME_MAPPINGS = {
1174
+ "Salia_BBox_DetectorProvider": "Salia_BBox_DetectorProvider",
1175
+ "Salia_BBox_To_Square_Coords": "Salia BBox To Square Coords",
1176
+ }