saliacoel commited on
Commit
2b9980e
·
verified ·
1 Parent(s): 71620b0

Upload salia_bbox_detect_and_more_2.py

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