forked from Kazuhito00/Image-Processing-Node-Editor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_system_sizing.py
More file actions
860 lines (730 loc) · 31.7 KB
/
Copy pathnode_system_sizing.py
File metadata and controls
860 lines (730 loc) · 31.7 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
SystemSizing Node (System category)
Aide au dimensionnement des ressources hardware pour un pipeline CV_Studio.
L'utilisateur renseigne :
• Résolution des flux (size)
• Runtime cible (DeepStream / OpenVINO / OpenCV-ONNXRuntime)
• Type de board cible (Custom ou carte embarquée prédéfinie)
• GPU cible (sélectionné dans le catalogue — détermine automatiquement la VRAM)
• CPU disponibles (cores logiques)
• RAM disponible (GB, par créneaux de 8 GB)
• FPS cible
Le bouton "Scan Editeur" détecte automatiquement :
• Modèles AI actifs (noeuds VisionModel / AudioModel présents dans l'éditeur)
• Nombre de flux entrants (noeuds Input présents dans l'éditeur)
• Noeuds VisionProcess et AudioProcess (overhead de traitement)
La sortie est un graphique matplotlib rendu en texture DPG :
• Barres vertes → ressource suffisante
• Barres rouges → ressource insuffisante
"""
import threading
from collections import Counter
import math
import numpy as np
import dearpygui.dearpygui as dpg
from node_editor.util import dpg_get_value, dpg_set_value
from node.node_abc import DpgNodeABC
from node.basenode import Node
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.backends.backend_agg import FigureCanvasAgg
# Baseline FPS used for per-inference CPU cost normalisation.
_BASELINE_FPS = 30.0
# ---------------------------------------------------------------------------
# Catalogue GPU (VRAM réelle, par créneaux constructeur)
# ---------------------------------------------------------------------------
_GPU_CATALOG = {
# tflops: FP32 shader performance (TFLOPS) – indicatif pour l'inférence
"RTX 5090": {"vram_gb": 32, "tflops": 209.0},
"RTX 5080": {"vram_gb": 16, "tflops": 137.0},
"RTX 5070 Ti": {"vram_gb": 16, "tflops": 103.0},
"RTX 5070": {"vram_gb": 12, "tflops": 77.0},
"RTX 5060 Ti": {"vram_gb": 16, "tflops": 55.0},
"RTX 5060": {"vram_gb": 8, "tflops": 42.0},
"RTX 4090": {"vram_gb": 24, "tflops": 82.6},
"RTX 4080 Super": {"vram_gb": 16, "tflops": 52.2},
"RTX 4080": {"vram_gb": 16, "tflops": 48.7},
"RTX 4070 Ti Super": {"vram_gb": 16, "tflops": 44.1},
"RTX 4070 Ti": {"vram_gb": 12, "tflops": 40.1},
"RTX 4070 Super": {"vram_gb": 12, "tflops": 35.5},
"RTX 4070": {"vram_gb": 12, "tflops": 29.1},
"RTX 4060 Ti": {"vram_gb": 16, "tflops": 22.1},
"RTX 4060": {"vram_gb": 8, "tflops": 15.1},
"RTX 3090 Ti": {"vram_gb": 24, "tflops": 40.0},
"RTX 3090": {"vram_gb": 24, "tflops": 35.6},
"RTX 3080 Ti": {"vram_gb": 12, "tflops": 34.1},
"RTX 3080": {"vram_gb": 10, "tflops": 29.8},
"RTX 3070 Ti": {"vram_gb": 8, "tflops": 21.7},
"RTX 3070": {"vram_gb": 8, "tflops": 20.3},
"RTX 3060 Ti": {"vram_gb": 8, "tflops": 16.2},
"RTX 3060": {"vram_gb": 12, "tflops": 12.7},
# Embedded / Jetson (memoire unifiee – vram_gb partage avec RAM systeme)
"Jetson Orin AGX": {"vram_gb": 0, "tflops": 5.3},
"Jetson Orin NX": {"vram_gb": 0, "tflops": 3.5},
"Jetson Orin Nano": {"vram_gb": 0, "tflops": 1.5},
"Jetson Xavier NX": {"vram_gb": 0, "tflops": 2.1},
"Jetson TX2": {"vram_gb": 0, "tflops": 1.3},
"Jetson Nano (Maxwell)": {"vram_gb": 0, "tflops": 0.5},
"CPU only": {"vram_gb": 0, "tflops": 0.0},
}
_GPU_NAMES = list(_GPU_CATALOG.keys())
# ---------------------------------------------------------------------------
# Catalogue des boards embarquees
# None -> champs editables (mode Custom)
# cpu_cores : nombre de coeurs CPU
# ram_gb : RAM systeme totale (GB)
# gpu : cle dans _GPU_CATALOG
# ---------------------------------------------------------------------------
_BOARD_CATALOG = {
"Custom": None,
"Jetson Orin AGX 64GB": {"cpu_cores": 12, "ram_gb": 64, "gpu": "Jetson Orin AGX"},
"Jetson Orin AGX 32GB": {"cpu_cores": 12, "ram_gb": 32, "gpu": "Jetson Orin AGX"},
"Jetson Orin NX 16GB": {"cpu_cores": 8, "ram_gb": 16, "gpu": "Jetson Orin NX"},
"Jetson Orin NX 8GB": {"cpu_cores": 8, "ram_gb": 8, "gpu": "Jetson Orin NX"},
"Jetson Orin Nano 8GB": {"cpu_cores": 6, "ram_gb": 8, "gpu": "Jetson Orin Nano"},
"Jetson Orin Nano 4GB": {"cpu_cores": 6, "ram_gb": 4, "gpu": "Jetson Orin Nano"},
"Jetson Xavier NX 16GB": {"cpu_cores": 6, "ram_gb": 16, "gpu": "Jetson Xavier NX"},
"Jetson Xavier NX 8GB": {"cpu_cores": 6, "ram_gb": 8, "gpu": "Jetson Xavier NX"},
"Jetson TX2": {"cpu_cores": 6, "ram_gb": 8, "gpu": "Jetson TX2"},
"Jetson Nano (Maxwell) 4GB": {"cpu_cores": 4, "ram_gb": 4, "gpu": "Jetson Nano (Maxwell)"},
}
_BOARD_NAMES = list(_BOARD_CATALOG.keys())
# ---------------------------------------------------------------------------
# Couts par type de noeud AI detecte dans l'editeur
#
# vram_gb : VRAM pour charger les poids (une fois par noeud)
# ram_gb : RAM hote pour les poids + overhead framework
# cpu_per_inf : coeurs logiques consommes par inference a _BASELINE_FPS
# ---------------------------------------------------------------------------
_NODE_AI_COSTS = {
# VisionModel nodes
"ObjectDetection": {"vram_gb": 0.50, "ram_gb": 0.60, "cpu_per_inf": 1.5},
"Classification": {"vram_gb": 0.30, "ram_gb": 0.40, "cpu_per_inf": 1.0},
"FaceDetection": {"vram_gb": 0.25, "ram_gb": 0.35, "cpu_per_inf": 0.8},
"PoseEstimation": {"vram_gb": 0.50, "ram_gb": 0.70, "cpu_per_inf": 1.5},
"SemanticSegmentation": {"vram_gb": 1.00, "ram_gb": 1.50, "cpu_per_inf": 2.5},
"MonocularDepthEstimation": {"vram_gb": 0.80, "ram_gb": 1.00, "cpu_per_inf": 2.0},
"LLIE": {"vram_gb": 0.50, "ram_gb": 0.60, "cpu_per_inf": 1.2},
"OnlineTraining": {"vram_gb": 1.50, "ram_gb": 2.00, "cpu_per_inf": 4.0},
# AudioModel nodes
"AudioClassification": {"vram_gb": 0.10, "ram_gb": 0.18, "cpu_per_inf": 0.4},
}
# Node tags that represent video/audio input flux
_INPUT_NODE_TAGS = frozenset({
"Video", "Webcam", "RTSP", "HLS", "YouTube", "WebRTC", "Api", "Microphone",
})
# Node tags in the VisionProcess category (ProcessNode folder)
_VISION_PROCESS_TAGS = frozenset({
"AdaptiveThreshold", "ApplyColorMap", "BilateralFilter", "Blur", "Brightness",
"CLAHE", "Canny", "ColorSpace", "Contrast", "Crop", "CropMonitor",
"EqualizeHist", "Flip", "GammaCorrection", "Grayscale", "IlluminationCorrect",
"ImageAlphaBlend", "KernelSharpen", "Morphology", "NLMDenoise",
"OmnidirectionalViewer", "Resize", "SimpleFilter", "Threshold",
"UnsharpMask", "Zoom",
})
# Node tags in the AudioProcess category (AudioProcessNode folder)
_AUDIO_PROCESS_TAGS = frozenset({
"BandPassFilter", "Compressor", "Decibel", "Equalizer",
"NoiseGate", "Normalize", "Resample", "Spectrogram",
})
# Resource overhead added per VisionProcess / AudioProcess node present
_VISION_PROC_CPU = 0.10 # CPU cores per vision process node
_VISION_PROC_RAM = 0.05 # GB RAM per vision process node
_AUDIO_PROC_CPU = 0.05 # CPU cores per audio process node
_AUDIO_PROC_RAM = 0.03 # GB RAM per audio process node
# ---------------------------------------------------------------------------
# Catalogue de modèles (ressources estimées par inférence)
# (conservé pour compatibilité avec les fichiers sauvegardés existants)
# ---------------------------------------------------------------------------
_MODEL_DB = {
"YOLOv8n": {"vram_gb": 0.20, "ram_gb": 0.30, "cpu_per_inf": 0.8},
"YOLOv8s": {"vram_gb": 0.40, "ram_gb": 0.55, "cpu_per_inf": 1.2},
"YOLOv8m": {"vram_gb": 0.80, "ram_gb": 1.00, "cpu_per_inf": 2.0},
"YOLOv8l": {"vram_gb": 1.50, "ram_gb": 2.00, "cpu_per_inf": 3.5},
"YOLOv8x": {"vram_gb": 3.00, "ram_gb": 4.00, "cpu_per_inf": 5.5},
"YOLOv5n": {"vram_gb": 0.18, "ram_gb": 0.28, "cpu_per_inf": 0.8},
"YOLOv5s": {"vram_gb": 0.35, "ram_gb": 0.50, "cpu_per_inf": 1.2},
"YOLOv5m": {"vram_gb": 0.75, "ram_gb": 0.95, "cpu_per_inf": 2.0},
"YOLOv5l": {"vram_gb": 1.40, "ram_gb": 1.90, "cpu_per_inf": 3.2},
"YOLOv5x": {"vram_gb": 2.80, "ram_gb": 3.80, "cpu_per_inf": 5.0},
"NanoDet": {"vram_gb": 0.15, "ram_gb": 0.20, "cpu_per_inf": 0.6},
"YAMNet": {"vram_gb": 0.10, "ram_gb": 0.18, "cpu_per_inf": 0.4},
"Custom-S": {"vram_gb": 0.30, "ram_gb": 0.40, "cpu_per_inf": 1.5},
"Custom-M": {"vram_gb": 0.80, "ram_gb": 1.00, "cpu_per_inf": 3.0},
"Custom-L": {"vram_gb": 2.00, "ram_gb": 2.50, "cpu_per_inf": 5.0},
}
_MODEL_NAMES = list(_MODEL_DB.keys())
# GFLOPs estimés par inférence pour chaque type de nœud AI détecté dans l'éditeur
# (valeurs indicatives à résolution standard)
_NODE_AI_GFLOPS = {
"ObjectDetection": 80.0,
"Classification": 4.0,
"FaceDetection": 2.0,
"PoseEstimation": 80.0,
"SemanticSegmentation": 150.0,
"MonocularDepthEstimation": 100.0,
"LLIE": 50.0,
"OnlineTraining": 80.0,
"AudioClassification": 1.0,
}
# Runtime multipliers applied on top of the base model costs.
_RUNTIME_MULT = {
"DeepStream": {"cpu": 0.40, "ram": 1.30, "vram": 1.00},
"OpenVINO": {"cpu": 1.20, "ram": 1.20, "vram": 0.05},
"OpenCV-ONNXRuntime": {"cpu": 2.00, "ram": 1.00, "vram": 0.05},
}
_RUNTIMES = list(_RUNTIME_MULT.keys())
_RESOLUTIONS = [
"AI (300×300)",
"AI (416×416)",
"SD (640×480)",
"HD (1280×720)",
"FHD (1920×1080)",
"4K (3840×2160)",
]
_RESOLUTION_DEFAULT = "HD (1280×720)"
# RAM slots disponibles (inclut 4 GB pour boards embarquees)
_RAM_SLOTS = [f"{n} GB" for n in [4, 8, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512]]
_RAM_DEFAULT = "32 GB"
# Overhead reseau / capture par flux (RAM GB, CPU cores a 30 fps)
_STREAM_RAM_OVERHEAD = 0.12 # GB / flux
_STREAM_CPU_OVERHEAD = 0.40 # cores / flux @ 30 fps
_STREAM_VRAM_OVERHEAD = 0.04 # GB / flux (pipeline GPU)
# Overhead fixe du framework (OS + runtime)
_FIXED_RAM_OVERHEAD = 1.0 # GB
_FIXED_CPU_OVERHEAD = 0.5 # cores
# Chart dimensions (pixels)
_CHART_W = 420
_CHART_H = 280
# ---------------------------------------------------------------------------
# Editor introspection helpers
# ---------------------------------------------------------------------------
def _get_node_editor():
"""Retrieve the DpgNodeEditor singleton from the main module."""
import sys
main_module = sys.modules.get("__main__") or sys.modules.get("main")
if main_module and hasattr(main_module, "_node_editor_ref"):
return main_module._node_editor_ref
return None
def _scan_editor_nodes():
"""
Scan the live editor and return a summary dict:
{
"ai_nodes": [(node_id_name, node_tag), ...], # AI model nodes
"n_streams": int, # input flux count
"n_vision_proc": int, # VisionProcess count
"n_audio_proc": int, # AudioProcess count
}
"""
editor = _get_node_editor()
result = {
"ai_nodes": [],
"n_streams": 0,
"n_vision_proc": 0,
"n_audio_proc": 0,
}
if editor is None:
return result
for node_id_name in editor._node_list:
if ":" not in node_id_name:
continue
_, node_tag = node_id_name.split(":", 1)
if node_tag in _NODE_AI_COSTS:
result["ai_nodes"].append((node_id_name, node_tag))
elif node_tag in _INPUT_NODE_TAGS:
result["n_streams"] += 1
elif node_tag in _VISION_PROCESS_TAGS:
result["n_vision_proc"] += 1
elif node_tag in _AUDIO_PROCESS_TAGS:
result["n_audio_proc"] += 1
return result
def _ram_slot_to_gb(slot_str: str) -> float:
"""Convert a RAM slot string like '32 GB' to a float."""
try:
return float(slot_str.replace("GB", "").strip())
except ValueError:
return 32.0
def _ceil8(value: float) -> int:
"""Round value up to the nearest multiple of 8."""
return int(math.ceil(value / 8.0)) * 8
def _compute_needs(runtime, n_streams, fps, ai_node_tags,
n_vision_proc=0, n_audio_proc=0):
"""
Retourne un dict {"cpu": float, "ram_gb": float, "vram_gb": float}
indiquant les ressources nécessaires.
ai_node_tags : list of node_tag strings (e.g. ["ObjectDetection", "AudioClassification"])
"""
mult = _RUNTIME_MULT[runtime]
fps_scale = max(fps, 1) / _BASELINE_FPS
# Overheads fixes
need_cpu = _FIXED_CPU_OVERHEAD
need_ram = _FIXED_RAM_OVERHEAD
need_vram = 0.0
# Coût par flux (capture / decode)
need_cpu += n_streams * _STREAM_CPU_OVERHEAD * fps_scale
need_ram += n_streams * _STREAM_RAM_OVERHEAD
need_vram += n_streams * _STREAM_VRAM_OVERHEAD
# Overhead VisionProcess et AudioProcess
need_cpu += n_vision_proc * _VISION_PROC_CPU * fps_scale
need_ram += n_vision_proc * _VISION_PROC_RAM
need_cpu += n_audio_proc * _AUDIO_PROC_CPU
need_ram += n_audio_proc * _AUDIO_PROC_RAM
# Coût des modèles AI (poids chargés 1 fois + inférence sur chaque flux)
for tag in ai_node_tags:
m = _NODE_AI_COSTS.get(tag)
if m is None:
continue
need_ram += m["ram_gb"] * mult["ram"]
need_vram += m["vram_gb"] * mult["vram"]
need_cpu += m["cpu_per_inf"] * mult["cpu"] * n_streams * fps_scale
return {
"cpu": round(need_cpu, 2),
"ram_gb": round(need_ram, 2),
"vram_gb": round(need_vram, 2),
}
def _render_chart(avail_cpu, avail_ram, avail_vram, need_cpu, need_ram, need_vram,
chart_w=_CHART_W, chart_h=_CHART_H):
"""
Génère un graphique matplotlib sous forme de ndarray BGR (uint8).
Barres vertes = OK, rouges = insuffisant.
"""
fig, ax = plt.subplots(figsize=(chart_w / 100, chart_h / 100), dpi=100)
fig.patch.set_facecolor('#1e1e2e')
ax.set_facecolor('#1e1e2e')
resources = ["CPU\n(cores)", "RAM\n(GB)", "VRAM\n(GB)"]
avail = [avail_cpu, avail_ram, avail_vram]
needed = [need_cpu, need_ram, need_vram]
x = np.arange(len(resources))
bar_w = 0.35
# Couleurs selon suffisance
colors_need = []
for a, n in zip(avail, needed):
colors_need.append('#2ecc71' if n <= a else '#e74c3c')
bars_avail = ax.bar(x - bar_w / 2, avail, bar_w,
label='Disponible', color='#3498db', alpha=0.85,
edgecolor='white', linewidth=0.5)
bars_need = ax.bar(x + bar_w / 2, needed, bar_w,
label='Nécessaire', color=colors_need,
edgecolor='white', linewidth=0.5)
# Valeurs au-dessus des barres
for bar in bars_avail:
h = bar.get_height()
ax.text(bar.get_x() + bar.get_width() / 2, h + 0.02 * max(avail + needed + [1]),
f'{h:.1f}', ha='center', va='bottom', color='white', fontsize=7)
for bar, c in zip(bars_need, colors_need):
h = bar.get_height()
ax.text(bar.get_x() + bar.get_width() / 2, h + 0.02 * max(avail + needed + [1]),
f'{h:.1f}', ha='center', va='bottom', color='white', fontsize=7)
ax.set_xticks(x)
ax.set_xticklabels(resources, color='white', fontsize=9)
ax.tick_params(axis='y', colors='white', labelsize=8)
ax.spines['bottom'].set_color('#555')
ax.spines['left'].set_color('#555')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.yaxis.grid(True, color='#333', linestyle='--', linewidth=0.5)
ax.set_axisbelow(True)
ax.set_title('Dimensionnement des ressources', color='white', fontsize=10, pad=8)
green_patch = mpatches.Patch(color='#2ecc71', label='Nécessaire (OK)')
red_patch = mpatches.Patch(color='#e74c3c', label='Nécessaire (insuffisant)')
blue_patch = mpatches.Patch(color='#3498db', label='Disponible')
ax.legend(handles=[blue_patch, green_patch, red_patch],
facecolor='#2a2a3e', edgecolor='#555', labelcolor='white',
fontsize=7, loc='upper right')
fig.tight_layout(pad=0.5)
canvas = FigureCanvasAgg(fig)
canvas.draw()
buf = canvas.buffer_rgba()
img_rgba = np.frombuffer(buf, dtype=np.uint8).reshape(chart_h, chart_w, 4)
img_bgr = img_rgba[:, :, :3][:, :, ::-1].copy()
plt.close(fig)
return img_bgr
class FactoryNode:
node_label = 'SystemSizing'
node_tag = 'SystemSizing'
def __init__(self):
pass
def add_node(
self,
parent,
node_id,
pos=[0, 0],
opencv_setting_dict=None,
callback=None,
):
node = _Node()
node.tag_node_name = str(node_id) + ':' + node.node_tag
node._opencv_setting_dict = opencv_setting_dict or {}
tag = node.tag_node_name
# Pre-render blank chart
blank = np.zeros((_CHART_H, _CHART_W, 3), dtype=np.uint8)
blank_tex = node.convert_cv_to_dpg(blank, _CHART_W, _CHART_H)
node.tag_chart_texture = tag + ':ChartTexture'
with dpg.texture_registry(show=False):
dpg.add_raw_texture(
_CHART_W, _CHART_H, blank_tex,
tag=node.tag_chart_texture,
format=dpg.mvFormat_Float_rgb,
)
with dpg.node(
tag=tag,
parent=parent,
label=node.node_label,
pos=pos,
):
# ---- Configuration ----
with dpg.node_attribute(
tag=tag + ':Static',
attribute_type=dpg.mvNode_Attr_Static,
):
dpg.add_spacer(height=2)
# Resolution
dpg.add_combo(
tag=tag + ':Resolution',
label='Resolution',
items=_RESOLUTIONS,
default_value=_RESOLUTION_DEFAULT, # HD
width=220,
)
# Runtime
dpg.add_combo(
tag=tag + ':Runtime',
label='Runtime',
items=_RUNTIMES,
default_value=_RUNTIMES[0],
width=220,
)
# Board type (Custom = mode libre, sinon verrouille CPU/RAM/GPU)
dpg.add_combo(
tag=tag + ':Board',
label='Board type',
items=_BOARD_NAMES,
default_value=_BOARD_NAMES[0],
width=220,
callback=_callback_board_change,
user_data=tag,
)
dpg.add_spacer(height=4)
# Input streams (read-only – updated by Scan)
dpg.add_text(
tag=tag + ':StreamsDisplay',
default_value='Flux entrants : – (scan requis)',
color=(160, 220, 255),
)
# Target FPS
dpg.add_input_int(
tag=tag + ':FPS',
label='FPS cible',
default_value=30,
min_value=1,
max_value=120,
width=100,
)
dpg.add_spacer(height=4)
dpg.add_text('-- Ressources disponibles --', color=(200, 200, 200))
# CPU
dpg.add_input_int(
tag=tag + ':AvailCPU',
label='CPU cores',
default_value=8,
min_value=1,
max_value=256,
width=100,
)
# RAM
dpg.add_combo(
tag=tag + ':AvailRAM',
label='RAM',
items=_RAM_SLOTS,
default_value=_RAM_DEFAULT,
width=130,
)
dpg.add_spacer(height=4)
dpg.add_text('-- GPU cible --', color=(200, 200, 200))
# GPU model selector -> auto-sets VRAM
dpg.add_combo(
tag=tag + ':GPU',
label='Modele GPU',
items=_GPU_NAMES,
default_value=_GPU_NAMES[0],
width=220,
callback=_callback_gpu_change,
user_data=tag,
)
# VRAM (read-only display, driven by GPU picker)
dpg.add_text(
tag=tag + ':VRAMLabel',
default_value=(
f"VRAM : {_GPU_CATALOG[_GPU_NAMES[0]]['vram_gb']} GB"
f" | FP32 : {_GPU_CATALOG[_GPU_NAMES[0]].get('tflops', 0):.1f} TFLOPS"
),
color=(160, 220, 255),
)
dpg.add_spacer(height=4)
dpg.add_text('-- Modeles AI actifs --', color=(200, 200, 200))
# Read-only display of editor-scanned AI nodes
dpg.add_text(
tag=tag + ':AINodesList',
default_value='(cliquer Scan & Calculer)',
color=(180, 180, 180),
wrap=220,
)
dpg.add_spacer(height=4)
# Combined Scan + Compute button
dpg.add_button(
tag=tag + ':BtnScanCompute',
label=' Scan & Calculer ',
width=220,
callback=_callback_scan_and_compute,
user_data=node,
)
dpg.add_spacer(height=4)
# Status / summary text
dpg.add_text(
tag=tag + ':Status',
default_value='Cliquer Scan & Calculer pour analyser.',
color=(180, 180, 180),
wrap=220,
)
dpg.add_spacer(height=6)
dpg.add_text('-- GFLOPs total (estime) --', color=(200, 200, 200))
dpg.add_text(
tag=tag + ':GFLOPsTotal',
default_value='(scan requis)',
color=(170, 210, 170),
wrap=220,
)
dpg.add_spacer(height=4)
# ---- Chart image output ----
with dpg.node_attribute(
tag=tag + ':ChartAttr',
attribute_type=dpg.mvNode_Attr_Static,
):
dpg.add_image(node.tag_chart_texture)
return node
# ---------------------------------------------------------------------------
# Callbacks
# ---------------------------------------------------------------------------
def _callback_gpu_change(sender, app_data, user_data):
"""Update the VRAM/TFLOPS label when the GPU combo changes."""
tag = user_data
gpu_name = app_data or _GPU_NAMES[0]
info = _GPU_CATALOG.get(gpu_name, {})
vram = info.get("vram_gb", 0)
tflops = info.get("tflops", 0.0)
label = (
f"VRAM : {vram} GB | FP32 : {tflops:.1f} TFLOPS"
if tflops > 0 else
f"VRAM : {vram} GB (CPU only)"
)
try:
dpg.set_value(tag + ':VRAMLabel', label)
except Exception:
pass
def _callback_board_change(sender, app_data, user_data):
"""Lock/unlock CPU, RAM, GPU fields based on selected board."""
tag = user_data
board_name = app_data or _BOARD_NAMES[0]
spec = _BOARD_CATALOG.get(board_name)
is_custom = spec is None
try:
dpg.configure_item(tag + ':AvailCPU', enabled=is_custom)
dpg.configure_item(tag + ':AvailRAM', enabled=is_custom)
dpg.configure_item(tag + ':GPU', enabled=is_custom)
if not is_custom:
dpg.set_value(tag + ':AvailCPU', spec["cpu_cores"])
ram_str = f"{spec['ram_gb']} GB"
if ram_str not in _RAM_SLOTS:
ram_str = _RAM_SLOTS[0]
dpg.set_value(tag + ':AvailRAM', ram_str)
gpu_key = spec["gpu"]
if gpu_key in _GPU_CATALOG:
dpg.set_value(tag + ':GPU', gpu_key)
_callback_gpu_change(None, gpu_key, tag)
except Exception:
pass
def _callback_scan_and_compute(sender, data, user_data):
node = user_data
threading.Thread(target=_do_scan_and_compute, args=(node,), daemon=True).start()
def _do_scan_and_compute(node):
tag = node.tag_node_name
try:
# ---- Scan ----
scan = _scan_editor_nodes()
ai_tags = [t for _, t in scan["ai_nodes"]]
n_streams = scan["n_streams"]
n_vp = scan["n_vision_proc"]
n_ap = scan["n_audio_proc"]
# Update streams read-only display
dpg_set_value(
tag + ':StreamsDisplay',
f'Flux entrants : {n_streams}',
)
# Build AI nodes display
counts = Counter(ai_tags)
if ai_tags:
lines = [f" • {t} ×{cnt}" for t, cnt in counts.items()]
summary = "\n".join(lines)
else:
summary = "(aucun modèle AI détecté)"
extra = []
if n_vp:
extra.append(f"VisionProcess : {n_vp} nœuds")
if n_ap:
extra.append(f"AudioProcess : {n_ap} nœuds")
if extra:
summary += "\n" + "\n".join(extra)
dpg_set_value(tag + ':AINodesList', summary)
# ---- Compute GFLOPs total ----
total_gflops = sum(
_NODE_AI_GFLOPS.get(t, 0.0) * cnt
for t, cnt in counts.items()
)
if total_gflops > 0:
gflops_str = f"{total_gflops:.1f} GFLOPs ({len(ai_tags)} nœud(s) AI)"
else:
gflops_str = "0 GFLOPs (aucun nœud AI)"
dpg_set_value(tag + ':GFLOPsTotal', gflops_str)
# ---- Compute ----
runtime = dpg_get_value(tag + ':Runtime') or _RUNTIMES[0]
fps = max(1, int(dpg_get_value(tag + ':FPS') or 30))
avail_cpu = max(1.0, float(dpg_get_value(tag + ':AvailCPU') or 8))
avail_ram = _ram_slot_to_gb(dpg_get_value(tag + ':AvailRAM') or _RAM_DEFAULT)
gpu_name = dpg_get_value(tag + ':GPU') or _GPU_NAMES[0]
avail_vram = float(_GPU_CATALOG.get(gpu_name, {}).get("vram_gb", 0))
needs = _compute_needs(
runtime, n_streams, fps, ai_tags,
n_vision_proc=n_vp,
n_audio_proc=n_ap,
)
need_cpu = needs["cpu"]
need_ram = needs["ram_gb"]
need_vram = needs["vram_gb"]
rec_ram_slot = _ceil8(need_ram)
rec_vram_slot = _ceil8(need_vram)
chart_img = _render_chart(
avail_cpu, avail_ram, avail_vram,
need_cpu, need_ram, need_vram,
)
tex_data = node.convert_cv_to_dpg(chart_img, _CHART_W, _CHART_H)
try:
dpg.set_value(node.tag_chart_texture, tex_data)
except Exception:
pass
warnings = []
if need_cpu > avail_cpu:
warnings.append(f"⚠ CPU : besoin {need_cpu:.1f} cores > {avail_cpu:.0f}")
if need_ram > avail_ram:
warnings.append(
f"⚠ RAM : besoin ≥{rec_ram_slot} GB (calculé {need_ram:.1f} GB) "
f"> disponible {avail_ram:.0f} GB"
)
if need_vram > avail_vram:
if avail_vram == 0:
warnings.append(f"⚠ VRAM : besoin ≥{rec_vram_slot} GB mais CPU only")
else:
warnings.append(
f"⚠ VRAM : besoin ≥{rec_vram_slot} GB (calculé {need_vram:.1f} GB) "
f"> {gpu_name} ({avail_vram:.0f} GB)"
)
if warnings:
status = "MANQUE DE RESSOURCES :\n" + "\n".join(warnings)
else:
status = (
f"✓ OK CPU:{need_cpu:.1f}/{avail_cpu:.0f} "
f"RAM:{rec_ram_slot}/{avail_ram:.0f}GB "
f"VRAM:{rec_vram_slot}/{avail_vram:.0f}GB ({gpu_name})"
)
dpg_set_value(tag + ':Status', status)
except Exception as exc:
try:
dpg_set_value(tag + ':Status', f'Erreur: {exc}')
except Exception:
pass
# ---------------------------------------------------------------------------
# Node class
# ---------------------------------------------------------------------------
class _Node(Node):
_ver = '0.0.3'
node_label = 'SystemSizing'
node_tag = 'SystemSizing'
_opencv_setting_dict = None
tag_chart_texture = ''
def __init__(self):
pass
def update(
self,
node_id,
connection_list,
node_image_dict,
node_result_dict,
node_audio_dict,
):
# SystemSizing is a purely interactive node – no per-frame computation needed.
return {"image": None, "json": None, "audio": None}
def close(self, node_id):
pass
def get_setting_dict(self, node_id):
tag = str(node_id) + ':' + self.node_tag
pos = dpg.get_item_pos(tag)
return {
"ver": self._ver,
"pos": pos,
"resolution": dpg_get_value(tag + ':Resolution') or _RESOLUTION_DEFAULT,
"runtime": dpg_get_value(tag + ':Runtime') or _RUNTIMES[0],
"board": dpg_get_value(tag + ':Board') or _BOARD_NAMES[0],
"fps": int(dpg_get_value(tag + ':FPS') or 30),
"avail_cpu": int(dpg_get_value(tag + ':AvailCPU') or 8),
"avail_ram": dpg_get_value(tag + ':AvailRAM') or _RAM_DEFAULT,
"gpu": dpg_get_value(tag + ':GPU') or _GPU_NAMES[0],
}
def set_setting_dict(self, node_id, setting_dict):
tag = str(node_id) + ':' + self.node_tag
pos = setting_dict.get("pos", [0, 0])
dpg.set_item_pos(tag, pos)
try:
res_val = setting_dict.get("resolution", _RESOLUTION_DEFAULT)
if res_val not in _RESOLUTIONS:
res_val = _RESOLUTION_DEFAULT
dpg.set_value(tag + ':Resolution', res_val)
dpg.set_value(tag + ':Runtime',
setting_dict.get("runtime", _RUNTIMES[0]))
# Board type
board_val = setting_dict.get("board", _BOARD_NAMES[0])
if board_val not in _BOARD_CATALOG:
board_val = _BOARD_NAMES[0]
dpg.set_value(tag + ':Board', board_val)
_callback_board_change(None, board_val, tag)
# Only restore CPU/RAM/GPU when board is Custom (not locked)
if _BOARD_CATALOG.get(board_val) is None:
dpg.set_value(tag + ':FPS', setting_dict.get("fps", 30))
dpg.set_value(tag + ':AvailCPU', setting_dict.get("avail_cpu", 8))
# RAM slot – migrate old float value to nearest slot string
ram_val = setting_dict.get("avail_ram", _RAM_DEFAULT)
if isinstance(ram_val, (int, float)):
ram_val = f"{_ceil8(float(ram_val))} GB"
if ram_val not in _RAM_SLOTS:
ram_val = _RAM_DEFAULT
dpg.set_value(tag + ':AvailRAM', ram_val)
# GPU model
gpu_val = setting_dict.get("gpu", _GPU_NAMES[0])
if gpu_val not in _GPU_CATALOG:
gpu_val = _GPU_NAMES[0]
dpg.set_value(tag + ':GPU', gpu_val)
info = _GPU_CATALOG[gpu_val]
vram = info["vram_gb"]
tflops = info.get("tflops", 0.0)
label = (
f"VRAM : {vram} GB | FP32 : {tflops:.1f} TFLOPS"
if tflops > 0 else
f"VRAM : {vram} GB (CPU only)"
)
dpg.set_value(tag + ':VRAMLabel', label)
else:
dpg.set_value(tag + ':FPS', setting_dict.get("fps", 30))
except Exception:
pass