-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathmain.py
More file actions
1347 lines (1181 loc) · 53.8 KB
/
Copy pathmain.py
File metadata and controls
1347 lines (1181 loc) · 53.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import argparse
import json
import os
import shutil
import subprocess
import time
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from threading import Event, Lock, Thread
from urllib.parse import parse_qs, urlparse
ROOT = Path(__file__).resolve().parent
WEB_ROOT = ROOT / "web"
VERSION_FILE = WEB_ROOT / "version.json"
YOLO26_DETECTION_MODELS = ("yolo26n.pt", "yolo26s.pt", "yolo26m.pt", "yolo26l.pt", "yolo26x.pt")
YOLO26_SEGMENTATION_MODELS = ("yolo26n-seg.pt", "yolo26s-seg.pt", "yolo26m-seg.pt", "yolo26l-seg.pt", "yolo26x-seg.pt")
YOLO26_CLASSIFICATION_MODELS = ("yolo26n-cls.pt", "yolo26s-cls.pt", "yolo26m-cls.pt", "yolo26l-cls.pt", "yolo26x-cls.pt")
YOLO26_MODELS = (*YOLO26_DETECTION_MODELS, *YOLO26_SEGMENTATION_MODELS, *YOLO26_CLASSIFICATION_MODELS)
YOLO26_MODEL_SET = set(YOLO26_MODELS)
RFDETR_DETECTION_MODELS = ("rfdetr-nano", "rfdetr-small", "rfdetr-medium", "rfdetr-large")
RFDETR_SEGMENTATION_MODELS = ("rfdetr-seg-nano", "rfdetr-seg-small", "rfdetr-seg-medium", "rfdetr-seg-large")
RFDETR_MODEL_CLASSES = {
"rfdetr-nano": "RFDETRNano",
"rfdetr-small": "RFDETRSmall",
"rfdetr-medium": "RFDETRMedium",
"rfdetr-large": "RFDETRLarge",
"rfdetr-seg-nano": "RFDETRSegNano",
"rfdetr-seg-small": "RFDETRSegSmall",
"rfdetr-seg-medium": "RFDETRSegMedium",
"rfdetr-seg-large": "RFDETRSegLarge",
}
RFDETR_MODEL_SET = set(RFDETR_MODEL_CLASSES)
SAM3_MODELS = ("facebook/sam3",)
INPUT_NODE_ID = "input"
LEGACY_CAMERA_NODE_ID = "camera"
INFERENCE_NODE_IDS = ("detector", "segmenter", "classifier")
IMAGE_EXTENSIONS = {".bmp", ".dib", ".jpg", ".jpeg", ".jpe", ".jp2", ".png", ".webp", ".pbm", ".pgm", ".ppm", ".pxm", ".pnm", ".tif", ".tiff"}
MAX_EVENTS = 32
MAX_TERMINAL_LINES = 500
_model_cache = {}
_model_lock = Lock()
def load_version_info() -> dict:
try:
with VERSION_FILE.open("r", encoding="utf-8") as version_file:
payload = json.load(version_file)
except (OSError, json.JSONDecodeError):
payload = {}
app = str(payload.get("app") or "VisoNode")
version = str(payload.get("version") or "0.0.0")
return {"app": app, "version": version}
VERSION_INFO = load_version_info()
APP_VERSION = VERSION_INFO["version"]
def git_version_info() -> dict:
try:
commit_result = subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
cwd=ROOT,
check=True,
capture_output=True,
text=True,
timeout=2,
)
dirty_result = subprocess.run(
["git", "diff", "--quiet"],
cwd=ROOT,
capture_output=True,
text=True,
timeout=2,
)
except (OSError, subprocess.SubprocessError):
return {"commit": None, "dirty": None}
return {
"commit": commit_result.stdout.strip() or None,
"dirty": dirty_result.returncode != 0,
}
class TerminalBuffer:
def __init__(self, max_lines: int = MAX_TERMINAL_LINES) -> None:
self._lock = Lock()
self._lines: list[dict] = []
self._seq = 0
self._max = max_lines
def append(self, text: str) -> None:
with self._lock:
self._seq += 1
self._lines.append({
"seq": self._seq,
"time": time.strftime("%H:%M:%S"),
"text": text,
})
overflow = len(self._lines) - self._max
if overflow > 0:
del self._lines[:overflow]
def since(self, cursor: int) -> dict:
with self._lock:
new_lines = [line for line in self._lines if line["seq"] > cursor]
return {"cursor": self._seq, "lines": new_lines}
terminal = TerminalBuffer()
def terminal_log(text: str) -> None:
print(text, flush=True)
terminal.append(text)
def json_response(handler: SimpleHTTPRequestHandler, status: int, payload: dict) -> None:
body = json.dumps(payload).encode("utf-8")
handler.send_response(status)
handler.send_header("Content-Type", "application/json")
handler.send_header("Content-Length", str(len(body)))
handler.send_header("Cache-Control", "no-store")
handler.end_headers()
handler.wfile.write(body)
def read_json_body(handler: SimpleHTTPRequestHandler) -> dict:
content_length = int(handler.headers.get("Content-Length", "0"))
if content_length <= 0:
raise ValueError("Missing request body.")
return json.loads(handler.rfile.read(content_length).decode("utf-8"))
def open_external_terminal() -> str:
if os.name == "nt":
creationflags = getattr(subprocess, "CREATE_NEW_CONSOLE", 0)
windows_terminal = shutil.which("wt.exe") or shutil.which("wt")
if windows_terminal:
subprocess.Popen(
[windows_terminal, "-d", str(ROOT)],
cwd=str(ROOT),
creationflags=creationflags,
)
return "Opened Windows Terminal"
shell_path = shutil.which("pwsh.exe") or shutil.which("powershell.exe")
if shell_path:
subprocess.Popen(
[shell_path, "-NoExit", "-Command", "Set-Location -LiteralPath $PWD"],
cwd=str(ROOT),
creationflags=creationflags,
)
return f"Opened {Path(shell_path).name}"
subprocess.Popen(["cmd.exe", "/K"], cwd=str(ROOT), creationflags=creationflags)
return "Opened Command Prompt"
candidates = (
("x-terminal-emulator", []),
("gnome-terminal", ["--working-directory", str(ROOT)]),
("konsole", ["--workdir", str(ROOT)]),
("xfce4-terminal", ["--working-directory", str(ROOT)]),
("xterm", ["-e", f"cd {ROOT} && exec sh"]),
)
for executable, args in candidates:
path = shutil.which(executable)
if path:
subprocess.Popen([path, *args], cwd=str(ROOT), start_new_session=True)
return f"Opened {executable}"
raise RuntimeError("No supported external terminal application was found.")
def open_file_dialog(kind: str = "vision") -> str | None:
checkpoint_mode = kind == "checkpoint"
if os.name == "nt":
powershell = shutil.which("powershell.exe") or shutil.which("powershell")
if not powershell:
raise RuntimeError("PowerShell is required to open the Windows file picker.")
if checkpoint_mode:
title = "Select RF-DETR checkpoint"
filter_spec = "RF-DETR checkpoints (*.pth;*.pt;*.ckpt)|*.pth;*.pt;*.ckpt|All files (*.*)|*.*"
else:
title = "Select input file"
filter_spec = (
"Vision files (*.bmp;*.dib;*.jpg;*.jpeg;*.jpe;*.jp2;*.png;*.webp;*.pbm;*.pgm;*.ppm;*.pxm;*.pnm;*.tif;*.tiff;*.mp4;*.avi;*.mov;*.mkv;*.webm;*.m4v;*.wmv)"
"|*.bmp;*.dib;*.jpg;*.jpeg;*.jpe;*.jp2;*.png;*.webp;*.pbm;*.pgm;*.ppm;*.pxm;*.pnm;*.tif;*.tiff;*.mp4;*.avi;*.mov;*.mkv;*.webm;*.m4v;*.wmv"
"|Image files (*.bmp;*.jpg;*.jpeg;*.png;*.webp;*.tif;*.tiff)|*.bmp;*.jpg;*.jpeg;*.png;*.webp;*.tif;*.tiff"
"|Video files (*.mp4;*.avi;*.mov;*.mkv;*.webm;*.m4v;*.wmv)|*.mp4;*.avi;*.mov;*.mkv;*.webm;*.m4v;*.wmv"
"|All files (*.*)|*.*"
)
script = f"""
Add-Type -AssemblyName System.Windows.Forms
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$dialog = New-Object System.Windows.Forms.OpenFileDialog
$dialog.Title = '{title}'
$dialog.Filter = @'
{filter_spec}
'@
$dialog.Multiselect = $false
$result = $dialog.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {{
Write-Output $dialog.FileName
}}
"""
result = subprocess.run(
[powershell, "-NoProfile", "-STA", "-ExecutionPolicy", "Bypass", "-Command", script],
capture_output=True,
text=True,
cwd=str(ROOT),
check=False,
)
if result.returncode != 0:
detail = (result.stderr or result.stdout or "Windows file picker failed.").strip()
raise RuntimeError(detail)
selected = result.stdout.strip()
return str(Path(selected).resolve()) if selected else None
try:
import tkinter as tk
from tkinter import filedialog
except ImportError as exc:
raise RuntimeError("Tkinter is not available in this Python installation.") from exc
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
root.update()
try:
if checkpoint_mode:
title = "Select RF-DETR checkpoint"
filetypes = [
("RF-DETR checkpoints", "*.pth *.pt *.ckpt"),
("All files", "*.*"),
]
else:
title = "Select input file"
filetypes = [
("Vision files", "*.bmp *.dib *.jpg *.jpeg *.jpe *.jp2 *.png *.webp *.pbm *.pgm *.ppm *.pxm *.pnm *.tif *.tiff *.mp4 *.avi *.mov *.mkv *.webm *.m4v *.wmv"),
("Image files", "*.bmp *.dib *.jpg *.jpeg *.jpe *.jp2 *.png *.webp *.pbm *.pgm *.ppm *.pxm *.pnm *.tif *.tiff"),
("Video files", "*.mp4 *.avi *.mov *.mkv *.webm *.m4v *.wmv"),
("All files", "*.*"),
]
path = filedialog.askopenfilename(
title=title,
filetypes=filetypes,
)
return str(Path(path).resolve()) if path else None
finally:
root.destroy()
def runtime_devices() -> dict:
payload = {
"torchInstalled": False,
"torchVersion": None,
"cudaAvailable": False,
"cudaVersion": None,
"nvidiaSmi": bool(shutil.which("nvidia-smi")),
"nvidiaGpus": [],
"devices": [],
"recommendation": "Use CPU, or run scripts\\install-gpu.ps1 on a machine with an NVIDIA GPU.",
}
nvidia_smi = shutil.which("nvidia-smi")
if nvidia_smi:
try:
result = subprocess.run(
[
nvidia_smi,
"--query-gpu=name,memory.total,driver_version",
"--format=csv,noheader,nounits",
],
capture_output=True,
text=True,
timeout=5,
check=False,
)
if result.returncode == 0:
for line in result.stdout.splitlines():
parts = [part.strip() for part in line.split(",")]
if len(parts) >= 3:
payload["nvidiaGpus"].append({
"name": parts[0],
"memoryMb": int(float(parts[1])),
"driver": parts[2],
})
except Exception:
pass
try:
import torch
except ImportError:
return payload
payload["torchInstalled"] = True
payload["torchVersion"] = torch.__version__
payload["cudaVersion"] = torch.version.cuda
payload["cudaAvailable"] = bool(torch.cuda.is_available())
if payload["cudaAvailable"]:
for index in range(torch.cuda.device_count()):
props = torch.cuda.get_device_properties(index)
payload["devices"].append({
"id": f"cuda:{index}",
"index": index,
"name": torch.cuda.get_device_name(index),
"memoryMb": round(props.total_memory / (1024 * 1024)),
})
payload["recommendation"] = "CUDA is available. Select Auto or a CUDA device in Object Detection."
elif payload["nvidiaGpus"]:
payload["recommendation"] = "NVIDIA GPU detected, but PyTorch CUDA is unavailable. Run scripts\\install-gpu.ps1."
return payload
def resolve_inference_device(config: dict) -> tuple[str, str]:
requested = str(config.get("device", "auto") or "auto").strip().lower()
if requested in ("", "auto"):
try:
import torch
except ImportError:
return "cpu", "CPU"
if torch.cuda.is_available():
return "cuda:0", f"CUDA 0 - {torch.cuda.get_device_name(0)}"
return "cpu", "CPU"
if requested == "cpu":
return "cpu", "CPU"
if requested.isdigit():
requested = f"cuda:{requested}"
if requested.startswith("cuda"):
try:
import torch
except ImportError as exc:
raise RuntimeError("GPU was selected, but PyTorch is not installed. Run scripts\\install-gpu.ps1.") from exc
if not torch.cuda.is_available():
raise RuntimeError("GPU was selected, but PyTorch CUDA is not available. Run scripts\\check-gpu.ps1.")
try:
index = int(requested.split(":", 1)[1]) if ":" in requested else 0
except ValueError as exc:
raise RuntimeError(f"Invalid CUDA device '{requested}'.") from exc
if index < 0 or index >= torch.cuda.device_count():
raise RuntimeError(f"CUDA device {index} is not available.")
return f"cuda:{index}", f"CUDA {index} - {torch.cuda.get_device_name(index)}"
raise RuntimeError(f"Unsupported inference device '{requested}'.")
def load_yolo_model(model_name: str, device: str = "cpu"):
if model_name not in YOLO26_MODEL_SET:
raise ValueError(f"Unsupported YOLO26 model '{model_name}'.")
cache_key = (model_name, device)
with _model_lock:
if cache_key in _model_cache:
return _model_cache[cache_key]
try:
from ultralytics import YOLO
except ImportError as exc:
raise RuntimeError(
"Ultralytics is not installed. Run '.\\.venv\\Scripts\\python.exe -m pip install -r requirements.txt'."
) from exc
model = YOLO(model_name)
model.to(device)
_model_cache[cache_key] = model
return model
def default_rfdetr_model(source_node_id: str) -> str:
return "rfdetr-seg-nano" if source_node_id == "segmenter" else "rfdetr-nano"
def inference_model_name(inference_node: dict) -> str:
config = inference_node.get("config", {})
engine = config.get("engine", "yolo26")
if engine == "sam3":
return str(sam3_checkpoint_path(config) or "facebook/sam3")
if engine == "rfdetr":
model_name = config.get("rfdetrModel") or default_rfdetr_model(inference_node.get("id", "detector"))
checkpoint_path = rfdetr_checkpoint_path(config)
return f"{model_name} ({checkpoint_path})" if checkpoint_path else model_name
return config.get("yoloModel") or "yolo26n.pt"
def rfdetr_checkpoint_path(config: dict) -> Path | None:
raw_value = str(config.get("rfdetrCheckpoint") or "").strip().strip('"')
if not raw_value:
return None
checkpoint_path = resolve_model_file(raw_value)
if not checkpoint_path.exists() or not checkpoint_path.is_file():
raise RuntimeError(f"RF-DETR checkpoint was not found at {checkpoint_path}.")
return checkpoint_path
def load_rfdetr_model(model_name: str, device: str = "cpu", checkpoint_path: Path | None = None):
if model_name not in RFDETR_MODEL_SET:
raise ValueError(f"Unsupported RF-DETR model '{model_name}'.")
cache_key = ("rfdetr", model_name, str(checkpoint_path or ""), device)
with _model_lock:
if cache_key in _model_cache:
return _model_cache[cache_key]
try:
import rfdetr
except ImportError as exc:
raise RuntimeError(
"RF-DETR is not installed. Run '.\\.venv\\Scripts\\python.exe -m pip install -r requirements.txt'."
) from exc
class_name = RFDETR_MODEL_CLASSES[model_name]
model_class = getattr(rfdetr, class_name, None)
if model_class is None:
raise RuntimeError(
f"The installed RF-DETR package does not provide {class_name}. Update with '.\\.venv\\Scripts\\python.exe -m pip install -r requirements.txt'."
)
model_kwargs = {"device": device}
if checkpoint_path is not None:
model_kwargs["pretrain_weights"] = str(checkpoint_path)
try:
model = model_class(**model_kwargs)
except TypeError:
model_kwargs.pop("device", None)
model = model_class(**model_kwargs)
_model_cache[cache_key] = model
return model
def resolve_model_file(value: str, default_name: str = "") -> Path:
model_path = Path(str(value or default_name).strip().strip('"') or default_name).expanduser()
if not model_path.is_absolute():
model_path = ROOT / model_path
return model_path.resolve()
def sam3_concepts(config: dict) -> list[str]:
concepts = [
item.strip()
for item in str(config.get("concepts") or "person").split(",")
if item.strip()
]
if not concepts:
raise RuntimeError("SAM 3 concept prompts are empty. Add one or more noun phrases, for example 'person, car'.")
return concepts
def sam3_checkpoint_path(config: dict) -> Path | None:
raw_value = str(config.get("samCheckpoint") or "").strip().strip('"')
if not raw_value:
return None
checkpoint_path = resolve_model_file(raw_value)
if not checkpoint_path.exists():
raise RuntimeError(f"SAM 3 checkpoint was not found at {checkpoint_path}.")
return checkpoint_path
def load_sam3_processor(config: dict, device: str = "cpu"):
checkpoint_path = sam3_checkpoint_path(config)
threshold = float(config.get("threshold", 0.25))
imgsz = int(config.get("imgsz", 640))
cache_key = ("official-sam3", str(checkpoint_path or "hf"), device, threshold, imgsz)
with _model_lock:
if cache_key in _model_cache:
return _model_cache[cache_key]
try:
from sam3.model.sam3_image_processor import Sam3Processor
from sam3.model_builder import build_sam3_image_model
except ImportError as exc:
if getattr(exc, "name", "") == "triton":
raise RuntimeError(
"Meta's official SAM 3 package requires Triton and the official CUDA/Linux stack. Use WSL/Linux with CUDA 12.6+ and PyTorch 2.7+, or install a compatible Triton build for this environment."
) from exc
raise RuntimeError(
"Meta's official SAM 3 package is not installed. Run '.\\.venv\\Scripts\\python.exe -m pip install -r requirements.txt'."
) from exc
try:
builder_device = "cuda" if device.startswith("cuda") else device
model = build_sam3_image_model(
checkpoint_path=str(checkpoint_path) if checkpoint_path else None,
device=builder_device,
load_from_HF=checkpoint_path is None,
)
model.to(device)
except Exception as exc:
raise RuntimeError(
"Unable to load Meta SAM 3. If you are using Hugging Face download, request access to facebook/sam3 and run 'hf auth login'."
) from exc
processor = Sam3Processor(model, resolution=imgsz, device=device, confidence_threshold=threshold)
_model_cache[cache_key] = processor
return processor
def enabled_node(workflow: dict, node_id: str) -> dict | None:
node = node_by_id(workflow, node_id)
return node if node and node.get("enabled", True) else None
def node_by_id(workflow: dict, node_id: str) -> dict | None:
return next((node for node in workflow.get("nodes", []) if node.get("id") == node_id), None)
def normalize_workflow(workflow: dict) -> dict:
for node in workflow.get("nodes", []):
if node.get("type") == LEGACY_CAMERA_NODE_ID:
node["type"] = INPUT_NODE_ID
if node.get("id") == LEGACY_CAMERA_NODE_ID and not node_by_id(workflow, INPUT_NODE_ID):
node["id"] = INPUT_NODE_ID
if node.get("type") == INPUT_NODE_ID:
config = node.setdefault("config", {})
config.setdefault("sourceType", "camera")
if "source" not in config:
config["source"] = config.get("cameraIndex", config.get("deviceId", 0))
if node.get("type") == "detector":
config = node.setdefault("config", {})
if config.get("engine") not in ("yolo26", "rfdetr"):
config["engine"] = "yolo26"
config.setdefault("rfdetrModel", "rfdetr-nano")
config.setdefault("rfdetrCheckpoint", "")
if node.get("type") == "segmenter":
config = node.setdefault("config", {})
if config.get("engine") not in ("yolo26", "sam3", "rfdetr"):
config["engine"] = "yolo26"
config.setdefault("rfdetrModel", "rfdetr-seg-nano")
config.setdefault("rfdetrCheckpoint", "")
if node.get("type") == "classifier":
config = node.setdefault("config", {})
config["engine"] = "yolo26"
for edge in workflow.get("edges", []):
if len(edge) < 2:
continue
if edge[0] == LEGACY_CAMERA_NODE_ID:
edge[0] = INPUT_NODE_ID
if edge[1] == LEGACY_CAMERA_NODE_ID:
edge[1] = INPUT_NODE_ID
return workflow
def source_node_id(workflow: dict) -> str:
if node_by_id(workflow, INPUT_NODE_ID):
return INPUT_NODE_ID
return LEGACY_CAMERA_NODE_ID
def active_input_node(workflow: dict) -> dict | None:
return enabled_node(workflow, source_node_id(workflow))
def has_active_path(workflow: dict, from_id: str, to_id: str) -> bool:
if not enabled_node(workflow, from_id) or not enabled_node(workflow, to_id):
return False
if from_id == to_id:
return True
visited = set()
queue = [from_id]
edges = workflow.get("edges", [])
while queue:
current_id = queue.pop(0)
if current_id == to_id:
return True
if current_id in visited:
continue
visited.add(current_id)
for edge_from_id, edge_to_id in edges:
if edge_from_id == current_id and edge_to_id not in visited and enabled_node(workflow, edge_to_id):
queue.append(edge_to_id)
return False
def active_detector_node(workflow: dict) -> dict | None:
detector = enabled_node(workflow, "detector")
input_id = source_node_id(workflow)
if detector and has_active_path(workflow, input_id, "detector"):
return detector
return None
def active_segmenter_node(workflow: dict) -> dict | None:
segmenter = enabled_node(workflow, "segmenter")
input_id = source_node_id(workflow)
if segmenter and has_active_path(workflow, input_id, "segmenter"):
return segmenter
return None
def active_classifier_node(workflow: dict) -> dict | None:
classifier = enabled_node(workflow, "classifier")
input_id = source_node_id(workflow)
if classifier and has_active_path(workflow, input_id, "classifier"):
return classifier
return None
def active_inference_nodes(workflow: dict) -> list[dict]:
nodes = []
input_id = source_node_id(workflow)
for node_id in INFERENCE_NODE_IDS:
node = enabled_node(workflow, node_id)
if node and has_active_path(workflow, input_id, node_id):
nodes.append(node)
return nodes
def active_filter_node(workflow: dict) -> dict | None:
filter_node = enabled_node(workflow, "filter")
if filter_node and any(
has_active_path(workflow, node.get("id"), "filter")
for node in active_inference_nodes(workflow)
):
return filter_node
return None
def inference_results_for_node(workflow: dict, node_id: str, detections: list[dict]) -> list[dict]:
return [
detection for detection in detections
if has_active_path(workflow, detection.get("sourceNodeId", "detector"), node_id)
]
def detections_for_node(workflow: dict, node_id: str, detections: list[dict], filtered: list[dict]) -> list[dict]:
node = enabled_node(workflow, node_id)
input_id = source_node_id(workflow)
if not node or not has_active_path(workflow, input_id, node_id):
return []
if node_id == "preview" and not bool(node.get("config", {}).get("useFilter", False)):
direct_detections = inference_results_for_node(workflow, node_id, detections)
if direct_detections:
return direct_detections
if active_filter_node(workflow) and has_active_path(workflow, "filter", node_id):
return filtered
return inference_results_for_node(workflow, node_id, detections)
def normalize_camera_source(value) -> int | str:
if value is None or value == "":
return 0
if isinstance(value, int):
return value
text = str(value).strip()
return int(text) if text.isdigit() else text
def resolve_file_input_path(value) -> Path:
text = str(value or "").strip().strip('"')
if not text:
raise RuntimeError("File input path is empty.")
path = Path(text).expanduser()
if not path.is_absolute():
path = ROOT / path
path = path.resolve()
if not path.exists() or not path.is_file():
raise RuntimeError(f"File input does not exist: {path}")
return path
class OpenCVInputSource:
def __init__(self, cv2_module, config: dict) -> None:
self.cv2 = cv2_module
self.config = config
self.capture = None
self.image = None
self.loop = bool(config.get("loop", True))
self.label = "input"
def open(self) -> tuple[str, int, int]:
source_type = str(self.config.get("sourceType", "camera") or "camera").lower()
if source_type == "file":
path = resolve_file_input_path(self.config.get("filePath"))
self.label = str(path)
if path.suffix.lower() in IMAGE_EXTENSIONS:
self.image = self.cv2.imread(str(path))
if self.image is None:
raise RuntimeError(f"Unable to read image file: {path}")
height, width = self.image.shape[:2]
return f"image file {path}", width, height
self.capture = self.cv2.VideoCapture(str(path))
if not self.capture.isOpened():
raise RuntimeError(f"Unable to open video file: {path}")
return f"video file {path}", self.width, self.height
source = normalize_camera_source(
self.config.get("source", self.config.get("cameraIndex", self.config.get("deviceId", 0)))
)
self.label = repr(source)
self.capture = self.cv2.VideoCapture(source)
self.capture.set(self.cv2.CAP_PROP_BUFFERSIZE, 1)
width = int(self.config.get("width", 0) or 0)
height = int(self.config.get("height", 0) or 0)
if width > 0:
self.capture.set(self.cv2.CAP_PROP_FRAME_WIDTH, width)
if height > 0:
self.capture.set(self.cv2.CAP_PROP_FRAME_HEIGHT, height)
if not self.capture.isOpened():
raise RuntimeError(f"Unable to open camera source {source!r}.")
return f"camera source {source!r}", self.width, self.height
@property
def width(self) -> int:
if self.image is not None:
return int(self.image.shape[1])
return int(self.capture.get(self.cv2.CAP_PROP_FRAME_WIDTH) or 0) if self.capture is not None else 0
@property
def height(self) -> int:
if self.image is not None:
return int(self.image.shape[0])
return int(self.capture.get(self.cv2.CAP_PROP_FRAME_HEIGHT) or 0) if self.capture is not None else 0
@property
def is_static(self) -> bool:
return self.image is not None
def read(self):
if self.image is not None:
return True, self.image.copy()
ok, frame = self.capture.read()
if ok or not self.loop:
return ok, frame
self.capture.set(self.cv2.CAP_PROP_POS_FRAMES, 0)
return self.capture.read()
def release(self) -> None:
if self.capture is not None:
self.capture.release()
def run_yolo26_frame(frame, inference_node: dict) -> list[dict]:
config = inference_node.get("config", {})
source_node_id = inference_node.get("id", "detector")
is_classifier = source_node_id == "classifier"
model_name = config.get("yoloModel") or "yolo26n.pt"
threshold = float(config.get("threshold", 0.55))
imgsz = int(config.get("imgsz", 640))
device, _ = resolve_inference_device(config)
model = load_yolo_model(model_name, device)
predict_args = {
"imgsz": imgsz,
"device": device,
"verbose": False,
}
if not is_classifier:
predict_args["conf"] = threshold
if not is_classifier and "end2end" in config:
predict_args["end2end"] = bool(config.get("end2end"))
try:
results = model.predict(frame, **predict_args)
except TypeError:
predict_args.pop("end2end", None)
results = model.predict(frame, **predict_args)
detections = []
for result in results:
names = result.names or {}
probs = getattr(result, "probs", None)
if is_classifier and probs is not None:
class_id = int(probs.top1)
confidence = probs.top1conf
if hasattr(confidence, "cpu"):
confidence = confidence.cpu().item()
detections.append({
"class": names.get(class_id, str(class_id)),
"score": float(confidence),
"sourceNodeId": source_node_id,
"kind": "classification",
})
continue
if result.boxes is None:
continue
boxes = result.boxes.xyxy.cpu().tolist()
scores = result.boxes.conf.cpu().tolist()
classes = result.boxes.cls.cpu().tolist()
masks = []
if getattr(result, "masks", None) is not None and result.masks is not None:
masks = getattr(result.masks, "xy", None)
if masks is None:
masks = []
for index, (box, score, class_id) in enumerate(zip(boxes, scores, classes)):
x1, y1, x2, y2 = box
detection = {
"class": names.get(int(class_id), str(int(class_id))),
"score": float(score),
"bbox": [float(x1), float(y1), float(x2 - x1), float(y2 - y1)],
"sourceNodeId": source_node_id,
"kind": "segmentation" if source_node_id == "segmenter" else "detection",
}
if index < len(masks):
polygon = masks[index]
if len(polygon):
detection["mask"] = [[float(point[0]), float(point[1])] for point in polygon]
detections.append(detection)
return detections
def _rfdetr_class_name(model, detections, index: int, class_id) -> str:
data = getattr(detections, "data", {}) or {}
for key in ("class_name", "class_names", "label", "labels"):
labels = data.get(key)
if labels is not None and index < len(labels):
return str(labels[index])
class_names = getattr(model, "class_names", {}) or {}
try:
class_key = int(class_id)
except (TypeError, ValueError):
return "object"
return str(class_names.get(class_key, str(class_key)))
def run_rfdetr_frame(frame, inference_node: dict) -> list[dict]:
import cv2
import numpy as np
config = inference_node.get("config", {})
source_node_id = inference_node.get("id", "detector")
model_name = config.get("rfdetrModel") or default_rfdetr_model(source_node_id)
if source_node_id == "segmenter" and model_name not in RFDETR_SEGMENTATION_MODELS:
raise RuntimeError(f"RF-DETR model '{model_name}' is not an instance segmentation model.")
if source_node_id == "detector" and model_name not in RFDETR_DETECTION_MODELS:
raise RuntimeError(f"RF-DETR model '{model_name}' is not an object detection model.")
threshold = float(config.get("threshold", 0.55))
device, _ = resolve_inference_device(config)
model = load_rfdetr_model(model_name, device, rfdetr_checkpoint_path(config))
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = model.predict(rgb_frame, threshold=threshold)
if isinstance(results, list):
results = results[0] if results else None
if results is None:
return []
xyxy = getattr(results, "xyxy", None)
if xyxy is None:
return []
boxes = np.asarray(xyxy).tolist()
confidences = getattr(results, "confidence", None)
scores = np.asarray(confidences).tolist() if confidences is not None else [1.0] * len(boxes)
class_ids_raw = getattr(results, "class_id", None)
class_ids = np.asarray(class_ids_raw).tolist() if class_ids_raw is not None else [None] * len(boxes)
masks = getattr(results, "mask", None)
detections = []
for index, box in enumerate(boxes):
if len(box) < 4:
continue
x1, y1, x2, y2 = [float(value) for value in box[:4]]
class_id = class_ids[index] if index < len(class_ids) else None
score = scores[index] if index < len(scores) else 1.0
detection = {
"class": _rfdetr_class_name(model, results, index, class_id),
"score": float(score),
"bbox": [x1, y1, x2 - x1, y2 - y1],
"sourceNodeId": source_node_id,
"kind": "segmentation" if source_node_id == "segmenter" else "detection",
}
if masks is not None and index < len(masks):
mask = np.squeeze(np.asarray(masks[index]))
if mask.ndim == 2:
mask = (mask > 0).astype(np.uint8) * 255
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
contour = max(contours, key=cv2.contourArea).reshape(-1, 2)
if len(contour) >= 3:
detection["mask"] = [[float(point[0]), float(point[1])] for point in contour]
detections.append(detection)
return detections
def run_sam3_frame(frame, inference_node: dict) -> list[dict]:
from contextlib import nullcontext
import cv2
import numpy as np
import torch
from PIL import Image
config = inference_node.get("config", {})
source_node_id = inference_node.get("id", "segmenter")
device, _ = resolve_inference_device(config)
processor = load_sam3_processor(config, device)
concepts = sam3_concepts(config)
image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
def sam3_autocast():
if device.startswith("cuda"):
return torch.autocast(device_type="cuda", dtype=torch.bfloat16)
return nullcontext()
with sam3_autocast():
image_state = processor.set_image(image)
detections = []
for concept in concepts:
prompt_state = dict(image_state)
prompt_state["backbone_out"] = dict(image_state["backbone_out"])
with sam3_autocast():
output = processor.set_text_prompt(state=prompt_state, prompt=concept)
masks = output.get("masks")
boxes = output.get("boxes")
scores = output.get("scores")
if masks is None or boxes is None or scores is None:
continue
boxes = boxes.detach().cpu().tolist()
scores = scores.detach().cpu().tolist()
masks = masks.detach().cpu().numpy()
for index, (box, score) in enumerate(zip(boxes, scores)):
x1, y1, x2, y2 = [float(value) for value in box]
detection = {
"class": concept,
"score": float(score),
"bbox": [float(x1), float(y1), float(x2 - x1), float(y2 - y1)],
"sourceNodeId": source_node_id,
"kind": "segmentation",
}
if index < len(masks):
mask = np.squeeze(masks[index]).astype(np.uint8)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
contour = max(contours, key=cv2.contourArea).reshape(-1, 2)
if len(contour) >= 3:
detection["mask"] = [[float(point[0]), float(point[1])] for point in contour]
detections.append(detection)
return detections
def filter_detections(workflow: dict, detections: list[dict]) -> list[dict]:
filter_node = active_filter_node(workflow)
if not filter_node:
return detections
config = filter_node.get("config", {})
classes = {
item.strip().lower()
for item in str(config.get("classes", "")).split(",")
if item.strip()
}
filtered = [
item for item in detections
if not classes or item.get("class", "").lower() in classes
]
return filtered if len(filtered) >= int(config.get("minCount", 1)) else []
def detection_color(label: str) -> tuple[int, int, int]:
palette = (
(41, 211, 145),
(56, 189, 248),
(168, 85, 247),
(245, 158, 11),
(239, 68, 68),
(99, 102, 241),
)
index = sum(label.encode("utf-8")) % len(palette)
return palette[index]
def draw_detections(frame, detections: list[dict], preview: dict) -> None:
import cv2
import numpy as np
config = preview.get("config", {})
show_boxes = bool(config.get("showBoxes", True))
show_labels = bool(config.get("showLabels", True))
show_masks = bool(config.get("showMasks", True))
mask_opacity = min(0.85, max(0.05, float(config.get("maskOpacity", 0.35))))
classification_y = 12
for detection in detections:
label_text = detection.get("class", "object")
color = detection_color(label_text)
label = f"{label_text} {round(float(detection.get('score', 0)) * 100)}%"
if detection.get("kind") == "classification":
if show_labels:
text_size, _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.65, 2)
x = 12
y = classification_y
cv2.rectangle(frame, (x, y), (x + text_size[0] + 14, y + text_size[1] + 12), (8, 18, 27), -1)
cv2.rectangle(frame, (x, y), (x + text_size[0] + 14, y + text_size[1] + 12), color, 2)
cv2.putText(frame, label, (x + 7, y + text_size[1] + 5), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 2)
classification_y += text_size[1] + 18
continue
x, y, width, height = [int(round(value)) for value in detection.get("bbox", [0, 0, 0, 0])]
mask = detection.get("mask")
if show_masks and mask:
points = np.array(mask, dtype=np.int32).reshape((-1, 1, 2))
overlay = frame.copy()
cv2.fillPoly(overlay, [points], color)
cv2.addWeighted(overlay, mask_opacity, frame, 1 - mask_opacity, 0, dst=frame)
cv2.polylines(frame, [points], True, color, 2)
if show_boxes:
cv2.rectangle(frame, (x, y), (x + width, y + height), color, 2)
if show_labels:
text_size, _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.55, 2)
label_y = max(0, y - text_size[1] - 8)