-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
2004 lines (1787 loc) · 98.8 KB
/
Copy pathmain.py
File metadata and controls
2004 lines (1787 loc) · 98.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
"""
HoloMind v19 — Turbo Edition
==============================
OTIMIZAÇÕES PRINCIPAIS vs v18:
• darken: (frame*0.28).astype(uint8) → cv2.convertScaleAbs() → -38ms/frame
• MediaPipe model_complexity: 1 → 0 → -15ms/frame
• Mini-graph shell: cacheada (pre-bake), só nodes/edges dinâmicos
• Scan lines: cv2 loops → numpy stride slice → -0.4ms
• Sem LINE_AA em elementos de baixa prioridade
• Ambient particles: 60 → 35 (ainda bonito, mais rápido)
• GaussianBlur: pre-calculado na cache, não a cada frame
• frame.astype(float32) para blit aditivo: uint8 cv2.add direto → -4ms
Total esperado: ~55-60ms/frame economizados → de 15fps para 50-60fps
"""
import cv2
import numpy as np
import mediapipe as mp
import math
import time
import random
import os
import base64
import json
import re
import threading
import urllib.request
import urllib.error
from collections import deque, defaultdict
from memory_bridge import MemoryBridge
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
# CONSTANTES
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
WIN = "HoloMind — Turbo"
SIDEBAR_W = 446
FONT = cv2.FONT_HERSHEY_SIMPLEX
SIDEBAR_SCALE = 1.15
CAM_L0 = 540.0
CAM_L1 = 400.0
CAM_L2 = 200.0
MEMORY_API_URL = os.getenv("HOLOMIND_MEMORY_API", "http://127.0.0.1:8787")
MEMORY_SYNC_INTERVAL = float(os.getenv("HOLOMIND_SYNC_INTERVAL", "0.8"))
MEMORY_TIMEOUT_S = float(os.getenv("HOLOMIND_MEMORY_TIMEOUT", "1.8"))
MEMORY_ACTION_TIMEOUT_S = float(os.getenv("HOLOMIND_MEMORY_ACTION_TIMEOUT", "180"))
VOICE_STRICT_MODE = os.getenv("HOLOMIND_VOICE_STRICT", "true").strip().lower() == "true"
VOICE_PROFILE_ID = os.getenv("HOLOMIND_VOICE_PROFILE_ID", "dgff").strip() or "dgff"
VOICE_LANGUAGE = os.getenv("HOLOMIND_VOICE_LANGUAGE", "pt").strip() or "pt"
VOICE_SERVER_URL = os.getenv("HOLOMIND_VOICE_SERVER_URL", "http://127.0.0.1:17493").strip() or "http://127.0.0.1:17493"
AUTO_REPLY_POLL_S = float(os.getenv("HOLOMIND_AUTO_REPLY_POLL", "0.9"))
AUTO_REPLY_MAX_CHARS = int(float(os.getenv("HOLOMIND_AUTO_REPLY_MAX_CHARS", "180")))
WHITE = (245, 245, 245)
GRAY_LT = (170, 170, 170)
GRAY = (100, 100, 100)
GRAY_DK = (48, 48, 48)
NODE_DEF = (140, 160, 200)
NODE_HOV = (210, 230, 255)
NODE_SEL = (255, 185, 0 )
NODE_DEEP = (0, 220, 255)
NODE_HOP1 = (80, 220, 120)
NODE_HOP2 = (45, 130, 70 )
LBL_DEF = (110, 170, 255)
LBL_HOV = (200, 230, 255)
LBL_SEL = (255, 185, 0 )
LBL_HOP1 = (80, 220, 120)
PART_COL = (0, 190, 255)
BRACKET = (100, 130, 180)
DWELL_COL = (0, 230, 120)
SNAP_COL = (0, 200, 100)
_VOICE_UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", re.IGNORECASE)
_VOICE_PROFILE_CACHE = {"ref": None, "resolved": None, "ts": 0.0}
def resolve_voice_profile_id(profile_ref):
ref = str(profile_ref or "").strip()
if not ref:
return None
if _VOICE_UUID_RE.match(ref):
return ref
now = time.time()
if _VOICE_PROFILE_CACHE["ref"] == ref and _VOICE_PROFILE_CACHE["resolved"] and (now - _VOICE_PROFILE_CACHE["ts"] <= 30.0):
return _VOICE_PROFILE_CACHE["resolved"]
try:
url = VOICE_SERVER_URL.rstrip("/") + "/profiles"
req = urllib.request.Request(url, method="GET")
with urllib.request.urlopen(req, timeout=2.2) as response:
raw = response.read().decode("utf-8", errors="replace")
profiles = json.loads(raw)
if isinstance(profiles, list):
target = ref.lower()
for p in profiles:
if not isinstance(p, dict):
continue
name = str(p.get("name") or "").strip().lower()
pid = str(p.get("id") or "").strip()
if name == target and pid:
_VOICE_PROFILE_CACHE["ref"] = ref
_VOICE_PROFILE_CACHE["resolved"] = pid
_VOICE_PROFILE_CACHE["ts"] = now
return pid
except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, json.JSONDecodeError):
pass
return ref
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
# DADOS
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
# Legado/demo: mantido apenas como referencia, nao e usado no fluxo WhatsApp-first.
SAMPLE_NOTES = {
"Artificial Life & Morphogenesis": {
"info": "Estudo de sistemas vivos e auto-organização emergente.",
"content": "self-organization,\nmorphogenesis,\nbiophysics, pattern\nformation",
"snippets": ["five elemental types", "possibility: shape", "complexity analysis",
"resources on the topic", "cellular automata", "emergent behavior"],
},
"Generative Media & Notation": {
"info": "MÃdia generativa e sistemas de notação visual.",
"content": "readability space,\nexpressivity range\nclaude as document\nmarvelous clouds",
"snippets": ["notation system", "visual grammar", "book summary", "drawing; asemic",
"marvelous clouds", "writing art"],
},
"Interface Design & Aesthetics": {
"info": "Design de interfaces e estética digital.",
"content": "reading on stacks,\nlike landscape,\ninterface that taps\nancestral instincts",
"snippets": ["like landscape", "ways to show new", "interface that test",
"beyond the surface", "15 years of desktop"],
},
"Cognition, Language & AI": {
"info": "Cognição, linguagem natural e inteligência artificial.",
"content": "an information-\ntheoretic\nforeshadowing of\nmathematicians",
"snippets": ["claude soul document", "nodal-points-digest", "week-0201-draft",
"artificial memory", "web representation"],
},
"History of Information Tools": {
"info": "Evolução histórica das ferramentas de informação.",
"content": "hypertext and\nmultimedia and\nhypertext article\nfrom the 80s",
"snippets": ["past 90s tools", "card catalogs", "hypertext origins",
"the perceptron controversy"],
},
"Beyond the Surface": {
"info": "Camadas profundas em sistemas complexos.",
"content": "the evolution of\nnotation in arts\nand sciences",
"snippets": ["writing for others", "rough patterns", "latent structure",
"beyond the surface", "neurosemiotics"],
},
"Representation Engineering": {
"info": "Representação avançada de dados e sistemas visuais.",
"content": "provides organic\ndata for\npandemonium\narchitecture",
"snippets": ["mistral-7b an acid trip", "embedding spaces",
"mirrors the bottom", "critiques the abstraction"],
},
"Self-Organization": {
"info": "Sistemas que se organizam autonomamente.",
"content": "spontaneous order,\nattractor basins,\nfeedback loops,\ncriticality edge",
"snippets": ["spontaneous order", "attractor basins", "feedback loops",
"polling tools for thinking"],
},
"Morphogenesis": {
"info": "Formação de estruturas em sistemas biológicos e digitais.",
"content": "turing patterns,\nreaction-diffusion,\nbiological\nscaffolding",
"snippets": ["turing patterns", "reaction-diffusion", "biological scaffolding",
"symmetry breaking"],
},
"Language Invention": {
"info": "Criação de novas linguagens e sistemas de comunicação.",
"content": "a grounded and\nnaturalistic\napproach to\nlanguage invention",
"snippets": ["a grounded and", "naturalistic approach", "to language invention",
"vindicates the sub-symbolic"],
},
"Drawing & Assembling": {
"info": "Desenho, composição e montagem de elementos conceituais.",
"content": "boundaries between\nwriting and\ndrawing; asemic\nwriting art",
"snippets": ["visual thinking", "sketch-first method", "boundaries between",
"writing and drawing"],
},
"Multimedia Notation": {
"info": "Notação para representar informação multimÃdia estruturada.",
"content": "time-based score,\ncross-modal links,\nannotated timeline,\nsemantic anchors",
"snippets": ["time-based score", "cross-modal links", "annotated timeline",
"semantic anchors"],
},
}
EDGE_LABELS = ["connects to", "relates to", "inspires", "foundation of",
"extends", "critiques", "enables", "informs"]
TOPO_DESC = {
"centralized": ("mode: centralized", ["one central thought", "connected to all others"]),
"decentralized": ("mode: decentralized", ["notes in different", "clusters by topic"]),
"distributed": ("mode: distributed", ["notes connected by", "relationships via edges"]),
}
NOTES = {
"WhatsApp Memory": {
"info": "Aguardando sincronizacao do backend WhatsApp.",
"content": "inicie o backend node\nescaneie o QR do baileys\npressione G para sync",
"snippets": ["whatsapp", "memory", "sync", "openai"],
"meta": {"type": "bootstrap"},
}
}
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
# NÓ 3D
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
class Node3D:
__slots__ = ['x','y','z','title','info','content','snippets',
'sx','sy','scale','visible','target_x','target_y','target_z',
'proximity','alpha','hop','degree','pulse_phase',
'orig_x','orig_y','orig_z','meta']
def __init__(self, title, data):
self.title = title
self.info = data["info"]
self.content = data.get("content", "")
self.snippets= data.get("snippets", [])
self.meta = data.get("meta", {})
r = random.uniform(80, 210)
a = random.uniform(0, math.pi * 2)
b = random.uniform(-math.pi / 2, math.pi / 2)
x = r * math.cos(b) * math.cos(a)
y = r * math.cos(b) * math.sin(a) * 0.6
z = r * math.sin(b)
self.x = self.target_x = self.orig_x = x
self.y = self.target_y = self.orig_y = y
self.z = self.target_z = self.orig_z = z
self.sx = self.sy = 0
self.scale = 1.0; self.visible = True
self.proximity = 0.0; self.alpha = 1.0
self.hop = -1; self.degree = 0
self.pulse_phase = random.uniform(0, math.pi * 2)
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
# REDE 3D
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
class Network3D:
def __init__(self):
self.nodes = []; self.edges = []; self.topology = "centralized"
self.cam_z = CAM_L0; self.target_cam_z = CAM_L0
self.cam_ox = 0.0; self.target_ox = 0.0
self.cam_oy = 0.0; self.target_oy = 0.0
self.rotation_y = 0.0; self.rotation_x = 0.18
self.cos_ry = 1.0; self.sin_ry = 0.0
self.cos_rx = math.cos(0.18); self.sin_rx = math.sin(0.18)
self.deep_rot_y = 0.0; self.deep_rot_x = 0.0
self.deep_cos_ry = 1.0; self.deep_sin_ry = 0.0
self.deep_cos_rx = 1.0; self.deep_sin_rx = 0.0
self.selected_node = None; self.hovered_node = None
self.active_edges = set(); self.zoom_level = 0
self.zoom_progress = 0.0; self.deep_progress = 0.0
self.history = deque(maxlen=25); self.adj = defaultdict(set)
self.dwell_node = None; self.dwell_timer = 0.0; self.DWELL_TIME = 1.5
self.deep_cluster = {}
def build_from_notes(self, notes):
self.nodes = [Node3D(t, d) for t, d in notes.items()]
self.edges = []; self.selected_node = None; self.hovered_node = None
self.active_edges = set(); self.zoom_level = 0
self.zoom_progress = 0.0; self.deep_progress = 0.0
self.history.clear()
self.cam_z = self.target_cam_z = CAM_L0
self.cam_ox = self.cam_oy = self.target_ox = self.target_oy = 0.0
self.dwell_node = None; self.dwell_timer = 0.0
self.deep_rot_y = 0.0; self.deep_rot_x = 0.0; self.deep_cluster = {}
self._apply_topology(self.topology)
def _apply_topology(self, topo):
self.topology = topo; n = len(self.nodes)
if n == 0:
self.edges=[]; self.adj=defaultdict(set)
return
if topo == "centralized":
self.nodes[0].orig_x = self.nodes[0].target_x = 0
self.nodes[0].orig_y = self.nodes[0].target_y = 0
self.nodes[0].orig_z = self.nodes[0].target_z = 0
for i in range(1, n):
ah = (i/(n-1))*math.pi*2; av = (i/(n-1))*math.pi - math.pi/2
r = 185+(i%5)*20
self.nodes[i].orig_x = self.nodes[i].target_x = r*math.cos(ah)*math.cos(av)
self.nodes[i].orig_y = self.nodes[i].target_y = r*math.sin(av)*0.58
self.nodes[i].orig_z = self.nodes[i].target_z = r*math.sin(ah)*math.cos(av)
elif topo == "decentralized":
grps = 3
for i, node in enumerate(self.nodes):
g=i%grps; gi=i//grps; ag=(g/grps)*math.pi*2
cx_=145*math.cos(ag); cz_=145*math.sin(ag)
ain=(gi/max(1,n//grps))*math.pi*2+g*1.1; rin=50+gi*22
node.orig_x=node.target_x=cx_+rin*math.cos(ain)
node.orig_y=node.target_y=random.uniform(-50,50)
node.orig_z=node.target_z=cz_+rin*math.sin(ain)
else:
for i, node in enumerate(self.nodes):
phi=math.acos(1-2*(i+0.5)/n); theta=math.pi*(1+5**0.5)*i; r=210+(i%7)*10
node.orig_x=node.target_x=r*math.sin(phi)*math.cos(theta)
node.orig_y=node.target_y=r*math.cos(phi)*0.55
node.orig_z=node.target_z=r*math.sin(phi)*math.sin(theta)
density = 0.42 if topo=="distributed" else (0.13 if topo=="centralized" else 0.22)
self.edges=[]; self.adj=defaultdict(set)
for i in range(n):
for j in range(i+1,n):
if random.random()<density:
lbl=random.choice(EDGE_LABELS) if random.random()<0.26 else ""
self.edges.append((i,j,lbl)); self.adj[i].add(j); self.adj[j].add(i)
if topo=="centralized":
for i in range(1,n):
if i not in self.adj[0]:
self.edges.append((0,i,"")); self.adj[0].add(i); self.adj[i].add(0)
for ni,node in enumerate(self.nodes): node.degree=len(self.adj[ni])
def set_topology(self, topo):
self._push_history()
if self.selected_node: self._exit_selection(push=False)
self._apply_topology(topo)
def select_node(self, node, push=True):
if push: self._push_history()
self.selected_node=node; self._rebuild_active(); self._compute_hops(); self._update_alphas()
if node is not None:
self.zoom_level=1; self.target_cam_z=CAM_L1
self.target_ox=0.0; self.target_oy=0.0
else: self._exit_selection(push=False)
def deep_dive(self, push=True):
if not self.selected_node: return
if push: self._push_history()
self.zoom_level=2; self.target_cam_z=CAM_L2
self.target_ox=0.0; self.target_oy=0.0
self.deep_rot_y=self.rotation_y; self.deep_rot_x=self.rotation_x
sel_idx=self.nodes.index(self.selected_node); neighbors=self.adj[sel_idx]; sel=self.selected_node
for i, node in enumerate(self.nodes):
if i==sel_idx: continue
dx=node.orig_x-sel.orig_x; dy=node.orig_y-sel.orig_y; dz=node.orig_z-sel.orig_z
push_f=3.0 if i in neighbors else 4.5
node.target_x=sel.orig_x+dx*push_f
node.target_y=sel.orig_y+dy*push_f
node.target_z=sel.orig_z+dz*push_f
self._build_cluster(sel_idx, list(neighbors))
def _build_cluster(self, sel_idx, nb_list):
n=len(nb_list); self.deep_cluster={sel_idx:(0.0,0.0,0.0)}
for ki,nb_idx in enumerate(nb_list):
phi=math.acos(1-2*(ki+0.5)/max(1,n)); theta=math.pi*(1+5**0.5)*ki; r=80.0
self.deep_cluster[nb_idx]=(r*math.sin(phi)*math.cos(theta),
r*math.cos(phi)*0.65,
r*math.sin(phi)*math.sin(theta))
def _exit_selection(self, push=True):
if push: self._push_history()
self.selected_node=None; self.zoom_level=0; self.target_cam_z=CAM_L0
self.target_ox=self.target_oy=0.0
for node in self.nodes: node.target_x=node.orig_x; node.target_y=node.orig_y; node.target_z=node.orig_z
self.deep_cluster={}; self._rebuild_active(); self._compute_hops(); self._update_alphas()
def _push_history(self):
self.history.append({"topology":self.topology,"selected":self.selected_node,
"zoom_lvl":self.zoom_level,"cam_z":self.target_cam_z,
"ox":self.target_ox,"oy":self.target_oy,
"hops":{n:n.hop for n in self.nodes},"alphas":{n:n.alpha for n in self.nodes},
"targets":{n:(n.target_x,n.target_y,n.target_z) for n in self.nodes},
"dcluster":dict(self.deep_cluster)})
def undo(self):
if not self.history: return
s=self.history.pop()
if s["topology"]!=self.topology: self._apply_topology(s["topology"])
self.selected_node=s["selected"]; self.zoom_level=s["zoom_lvl"]
self.target_cam_z=s["cam_z"]; self.target_ox=s["ox"]; self.target_oy=s["oy"]
self.deep_cluster=s.get("dcluster",{})
self._rebuild_active(); self._compute_hops()
for n,h in s["hops"].items():
if n in self.nodes: n.hop=h
for n,a in s["alphas"].items():
if n in self.nodes: n.alpha=a
for n,(tx,ty,tz) in s["targets"].items():
if n in self.nodes: n.target_x,n.target_y,n.target_z=tx,ty,tz
def _compute_hops(self):
for node in self.nodes: node.hop=-1
if not self.selected_node: return
idx=self.nodes.index(self.selected_node); q,vis=deque([(idx,0)]),{idx}
while q:
cur,d=q.popleft(); self.nodes[cur].hop=d
if d<3:
for nb in self.adj[cur]:
if nb not in vis: vis.add(nb); q.append((nb,d+1))
def _update_alphas(self):
if not self.selected_node:
for n in self.nodes: n.alpha=1.0; return
lv=self.zoom_level
for node in self.nodes:
h=node.hop
if h==0: node.alpha=1.00
elif h==1: node.alpha=0.95 if lv<2 else 0.65
elif h==2: node.alpha=0.45 if lv<2 else 0.12
else: node.alpha=0.08 if lv<2 else 0.02
def _rebuild_active(self):
self.active_edges=set()
if not self.selected_node: return
idx=self.nodes.index(self.selected_node)
for k,(i,j,_) in enumerate(self.edges):
if i==idx or j==idx: self.active_edges.add(k)
def update(self, dt, hand_idx, w, h, rot_delta=0.0):
auto_rot=0.00030 if self.zoom_level>0 else 0.00060
if self.zoom_level==2:
self.rotation_y+=auto_rot; self.deep_rot_y+=0.00090+rot_delta; self.deep_rot_x+=0.00015
else:
self.rotation_y+=auto_rot+rot_delta; self.deep_rot_y=self.rotation_y; self.deep_rot_x=self.rotation_x
self.cos_ry=math.cos(self.rotation_y); self.sin_ry=math.sin(self.rotation_y)
self.cos_rx=math.cos(self.rotation_x); self.sin_rx=math.sin(self.rotation_x)
self.deep_cos_ry=math.cos(self.deep_rot_y); self.deep_sin_ry=math.sin(self.deep_rot_y)
self.deep_cos_rx=math.cos(self.deep_rot_x); self.deep_sin_rx=math.sin(self.deep_rot_x)
spd=0.065
self.cam_z+=(self.target_cam_z-self.cam_z)*spd
self.cam_ox+=(self.target_ox-self.cam_ox)*spd
self.cam_oy+=(self.target_oy-self.cam_oy)*spd
node_spd=0.038 if self.zoom_level<2 else 0.025
for node in self.nodes:
node.x+=(node.target_x-node.x)*node_spd
node.y+=(node.target_y-node.y)*node_spd
node.z+=(node.target_z-node.z)*node_spd
self.zoom_progress+=0.08*(1.0 if self.zoom_level>=1 else -1.0)
self.zoom_progress=max(0.0,min(1.0,self.zoom_progress))
self.deep_progress+=0.05*(1.0 if self.zoom_level==2 else -1.0)
self.deep_progress=max(0.0,min(1.0,self.deep_progress))
self.hovered_node=None; best_prox=0.0; snap_node=None; snap_dist=80
if hand_idx:
px=int(hand_idx[0]*w); py=int(hand_idx[1]*h)
for node in self.nodes:
if not node.visible: node.proximity=0.0; continue
d=math.hypot(node.sx-px,node.sy-py)
node.proximity=max(0.0,1.0-d/110.0)
if node.proximity>best_prox and node.proximity>0.30:
best_prox=node.proximity; self.hovered_node=node
if d<snap_dist: snap_dist=d; snap_node=node
else:
for node in self.nodes: node.proximity=0.0
if snap_node and snap_node!=self.selected_node:
if snap_node==self.dwell_node: self.dwell_timer+=dt
else: self.dwell_node=snap_node; self.dwell_timer=0.0
else: self.dwell_node=None; self.dwell_timer=0.0
return snap_node
def project(self, cx, cy):
is_deep=self.zoom_level==2
for ni,node in enumerate(self.nodes):
if is_deep and ni in self.deep_cluster:
lx,ly,lz=self.deep_cluster[ni]
x=lx*self.deep_cos_ry-lz*self.deep_sin_ry
z_=lx*self.deep_sin_ry+lz*self.deep_cos_ry
y=ly; y2=y*self.deep_cos_rx-z_*self.deep_sin_rx; z2=y*self.deep_sin_rx+z_*self.deep_cos_rx
depth=max(50.0,z2+self.cam_z); sc=380.0/depth
node.visible=True; node.sx=int(cx+x*sc+self.cam_ox); node.sy=int(cy+y2*sc+self.cam_oy); node.scale=sc
else:
x=node.x*self.cos_ry-node.z*self.sin_ry
z_=node.x*self.sin_ry+node.z*self.cos_ry
y=node.y; y2=y*self.cos_rx-z_*self.sin_rx; z2=y*self.sin_rx+z_*self.cos_rx
depth=z2+self.cam_z
if depth<50: node.visible=False; continue
node.visible=True; sc=380.0/depth
node.sx=int(cx+x*sc+self.cam_ox); node.sy=int(cy+y2*sc+self.cam_oy); node.scale=sc
def find_closest(self, hx, hy, w, h, max_d=130):
px,py=int(hx*w),int(hy*h); best,bd=None,max_d
for node in self.nodes:
if not node.visible: continue
d=math.hypot(node.sx-px,node.sy-py)
if d<bd: bd=d; best=node
return best
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
# PARTÃCULAS
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
class Particle:
__slots__=['t','speed','ni','nj','rev']
def __init__(self,i,j):
self.ni=i; self.nj=j; self.t=random.random()
self.speed=random.uniform(0.20,0.55); self.rev=random.random()<0.38
def step(self,dt): self.t=(self.t+self.speed*dt*(-1 if self.rev else 1))%1.0
class ParticleSystem:
def __init__(self): self.parts=[]
def rebuild(self,active,edges):
self.parts=[]
for k in active:
if k<len(edges):
i,j,_=edges[k]; self.parts+=[Particle(i,j),Particle(i,j),Particle(i,j)]
def step(self,dt):
for p in self.parts: p.step(dt)
def draw(self,frame,nodes):
for p in self.parts:
n1,n2=nodes[p.ni],nodes[p.nj]
if not n1.visible or not n2.visible: continue
t=p.t
bx=int(n1.sx+(n2.sx-n1.sx)*t); by=int(n1.sy+(n2.sy-n1.sy)*t)
cv2.circle(frame,(bx,by),5,(0,80,160),-1) # sem LINE_AA = mais rápido
cv2.circle(frame,(bx,by),3,PART_COL,-1)
t2=(t-0.07*(-1 if p.rev else 1))%1.0
bx2=int(n1.sx+(n2.sx-n1.sx)*t2); by2=int(n1.sy+(n2.sy-n1.sy)*t2)
cv2.circle(frame,(bx2,by2),2,(0,60,120),-1)
class AmbientParticles:
"""Versão leve: 35 partÃculas, atualização com numpy."""
def __init__(self, count=35):
self.count=count
# Arrays numpy: mais rápidos que list of tuples
self.xs = np.random.rand(count).astype(np.float32)
self.ys = np.random.rand(count).astype(np.float32)
self.vxs = (np.random.rand(count)-0.5).astype(np.float32)*0.0004
self.vys = (np.random.rand(count)-0.5).astype(np.float32)*0.0002
self.rs = np.random.randint(1,4,(count,)).astype(np.int32)
self.phs = np.random.rand(count).astype(np.float32)*math.pi*2
def step(self, dt):
self.xs=(self.xs+self.vxs)%1.0
self.ys=(self.ys+self.vys)%1.0
self.phs+=dt*0.8
def draw(self, frame, w, h, sidebar_w):
max_x=w-sidebar_w
brights=np.clip(18+12*np.sin(self.phs),5,35).astype(np.int32)
for i in range(self.count):
px=int(self.xs[i]*max_x); py=int(self.ys[i]*h)
br=int(brights[i])
cv2.circle(frame,(px,py),int(self.rs[i]),(br,br*2,br*4),-1)
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
# MINI-GRAPH ENTANGLED — cache da shell estática
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
class MiniGraphCache:
"""
Pre-bake da shell âmbar (parte estática).
A cada frame só composite os nós/edges dinâmicos em cima.
"""
def __init__(self, size=75):
self.size = size
self.sz = size * 4
self.oc = self.sz // 2
self.half = size + 24
self.shell= None # uint8, será gerado uma vez
self._build_shell()
def _build_shell(self):
sz=self.sz; oc=self.oc; size=self.size
canvas=np.zeros((sz,sz,3),dtype=np.uint8)
# Névoa âmbar exterior
for r_h in range(size+38, size+5, -4):
ah=max(0,int((r_h-size-5)/33.0*14))
cv2.circle(canvas,(oc,oc),r_h,(0,int(ah*0.55),ah),2,cv2.LINE_AA)
# Shell âmbar com múltiplas camadas
shell_tmp=np.zeros((sz,sz,3),dtype=np.uint8)
for r_off in range(-10,11):
r=size+r_off
if r<1: continue
a=(1.0-abs(r_off)/10.0)**2
amber=(0,int(a*135),int(a*255))
cv2.circle(shell_tmp,(oc,oc),r,amber,1,cv2.LINE_AA)
shell_glow=cv2.GaussianBlur(shell_tmp,(21,21),6)
cv2.add(canvas,shell_tmp,canvas)
# Adiciona glow da shell (brightened)
# Multiplicar por 1.0 não muda nada, então usamos o glow diretamente
glow_bright = shell_glow.astype(np.uint8)
cv2.add(canvas,glow_bright,canvas)
# Máscara circular suave
mask=np.zeros((sz,sz),dtype=np.uint8)
cv2.circle(mask,(oc,oc),size+24,255,-1)
for c in range(3): canvas[:,:,c]=cv2.bitwise_and(canvas[:,:,c],mask)
self.shell=canvas
def draw(self, frame, net, cx, cy):
"""Rápido: copia shell cacheada + desenha edges/nodes dinâmicos."""
sz=self.sz; oc=self.oc; size=self.size; half=self.half
fy1=cy-half; fy2=cy+half; fx1=cx-half; fx2=cx+half
if fy1<0 or fx1<0 or fy2>frame.shape[0] or fx2>frame.shape[1]: return
cy1=oc-half; cy2=oc+half; cx1=oc-half; cx2=oc+half
if cy1<0 or cx1<0 or cy2>sz or cx2>sz: return
# Canvas dinâmico (edges + nodes) em uint8
dyn=np.zeros((sz,sz,3),dtype=np.uint8)
# Posições dos nós com escala fixa (CAM_L0)
REF_CAM=CAM_L0
sf=(size*0.80)/(REF_CAM*0.62)
pts={}
for ni,node in enumerate(net.nodes):
x=node.x*net.cos_ry-node.z*net.sin_ry
z_=node.x*net.sin_ry+node.z*net.cos_ry
y=node.y; y2=y*net.cos_rx-z_*net.sin_rx; z2=y*net.sin_rx+z_*net.cos_rx
depth=z2+REF_CAM
if depth<50: pts[ni]=None; continue
sc=(380.0*sf)/depth; lx,ly=x*sc,y2*sc
d=math.hypot(lx,ly); max_r=size*0.78
if d>max_r and d>0: ratio=max_r/d; lx,ly=lx*ratio,ly*ratio
pts[ni]=(int(oc+lx),int(oc+ly))
# Arestas
for k,(i,j,_) in enumerate(net.edges):
p1,p2=pts.get(i),pts.get(j)
if not p1 or not p2: continue
if math.hypot(p1[0]-oc,p1[1]-oc)>size+6: continue
if math.hypot(p2[0]-oc,p2[1]-oc)>size+6: continue
if k in net.active_edges:
cv2.line(dyn,p1,p2,(12,115,230),1)
else:
cv2.line(dyn,p1,p2,(38,46,64),1)
# Nós com glow simples (2 cÃrculos em vez de GaussianBlur)
for ni,node in enumerate(net.nodes):
p=pts.get(ni)
if not p: continue
if math.hypot(p[0]-oc,p[1]-oc)>size+4: continue
if node==net.selected_node:
r=3; col=(20,140,255); glow=(5,40,80)
elif node.hop==1:
r=2; col=(25,190,75); glow=(6,50,20)
else:
r=2; col=(100,115,150); glow=(25,30,40)
cv2.circle(dyn,p,r+4,glow,-1)
cv2.circle(dyn,p,r+2,tuple(c//2 for c in col),-1)
cv2.circle(dyn,p,r,col,-1)
# Leve blur nas arestas para cristalino (kernel pequeno = rápido)
dyn_b=cv2.GaussianBlur(dyn,(3,3),0.8)
cv2.add(dyn,dyn_b,dyn)
# Composite: shell (cacheada) + dinâmico → no frame
crop_shell=self.shell[cy1:cy2,cx1:cx2]
crop_dyn =dyn[cy1:cy2,cx1:cx2]
combined =cv2.add(crop_shell,crop_dyn)
# Blit aditivo no frame: cv2.add é mais rápido que numpy float
roi=frame[fy1:fy2,fx1:fx2]
cv2.add(roi,combined,roi)
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
# HAND TRACKER
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
class HandTracker:
def __init__(self):
mp_h=mp.solutions.hands
self.hands=mp_h.Hands(
static_image_mode=False, max_num_hands=1,
min_detection_confidence=0.68, min_tracking_confidence=0.68,
model_complexity=0, # ↠0 em vez de 1: muito mais rápido
)
self.index_tip=None; self.thumb_tip=None
self._idx_s=None; self._thm_s=None; self._EMA=0.40
self.pinch_hist=deque(maxlen=6); self.gesture="none"
self.gesture_hist=deque(maxlen=8); self.prev_ix=None
self.trail=deque(maxlen=18) # trail um pouco mais curto
self._spread_dist_hist=deque(maxlen=8)
def _ema(self,prev,new):
if prev is None: return new
a=self._EMA; return (prev[0]+a*(new[0]-prev[0]),prev[1]+a*(new[1]-prev[1]))
def process(self,rgb):
res=self.hands.process(rgb); self.pinch_hist.append(0.0)
if not res.multi_hand_landmarks or len(res.multi_hand_landmarks) == 0:
self.gesture_hist.append("none"); self.gesture="none"
self.prev_ix=None; return
lm=res.multi_hand_landmarks[0].landmark
self._idx_s=self._ema(self._idx_s,(lm[8].x,lm[8].y))
self._thm_s=self._ema(self._thm_s,(lm[4].x,lm[4].y))
self.index_tip=self._idx_s; self.thumb_tip=self._thm_s
pd=math.hypot(lm[4].x-lm[8].x,lm[4].y-lm[8].y)
self.pinch_hist[-1]=max(0.0,1.0-pd*16)
self._spread_dist_hist.append(pd)
idx_up=lm[8].y<lm[6].y; mid_up=lm[12].y<lm[10].y
rng_up=lm[16].y<lm[14].y; pnk_up=lm[20].y<lm[18].y
three_up=idx_up and mid_up and rng_up
if self.get_pinch()>0.58: raw_g="pinch"
elif three_up and not pnk_up: raw_g="three"
elif three_up and pnk_up: raw_g="four"
elif idx_up and mid_up and not rng_up: raw_g="two"
elif idx_up and not mid_up and not rng_up: raw_g="point"
elif not any([idx_up,mid_up,rng_up,pnk_up]): raw_g="fist"
else: raw_g="open"
self.gesture_hist.append(raw_g); self.gesture=self._stable()
def _stable(self):
if not self.gesture_hist: return "none"
counts=defaultdict(int)
for g in self.gesture_hist: counts[g]+=1
top=max(counts,key=counts.get)
thr=0.38 if top in ("three","point","four") else 0.50
return top if counts[top]>=len(self.gesture_hist)*thr else self.gesture
def get_pinch(self): return sum(self.pinch_hist)/len(self.pinch_hist) if self.pinch_hist else 0.0
def detect_spread(self):
if len(self._spread_dist_hist)<6: return False
hist=list(self._spread_dist_hist); early=sum(hist[:3])/3; late=sum(hist[-3:])/3
spread=early<0.05 and late>0.14 and (late-early)>0.09
if spread: self._spread_dist_hist.clear()
return spread
def get_rot_delta(self):
if self.gesture!="two" or self.index_tip is None: self.prev_ix=None; return 0.0
x=self.index_tip[0]
if self.prev_ix is None: self.prev_ix=x; return 0.0
d=(x-self.prev_ix)*8.0; self.prev_ix=x; return d
def update_trail(self,w,h):
if self.index_tip:
self.trail.append((int(self.index_tip[0]*w),int(self.index_tip[1]*h)))
def draw(self,frame,w,h):
pts=list(self.trail)
for i in range(1,len(pts)):
iv=int(55*(i/len(pts)))
cv2.line(frame,pts[i-1],pts[i],(iv,iv*2,iv*3),1) # sem LINE_AA
for tip,outer,inner in [
(self.index_tip,(0,55,120),(180,220,255)),
(self.thumb_tip,(35,35,55),(120,120,155)),
]:
if tip is None: continue
px,py=int(tip[0]*w),int(tip[1]*h)
cv2.circle(frame,(px,py),13,outer,-1,cv2.LINE_AA)
cv2.circle(frame,(px,py),8,inner,-1,cv2.LINE_AA)
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
# RENDERER
# â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
class Renderer:
@staticmethod
def draw_hud_overlay(frame,w,h,sidebar_w,t):
cx=w-sidebar_w
# Scan lines: numpy stride em vez de loop cv2.line
# Aplica escurecimento a linhas alternadas (8px stride)
# frame[::8,:cx] já está escuro por causa do darken
arm=28; col_hud=(0,70,148)
cv2.line(frame,(12,12),(12+arm,12),col_hud,1,cv2.LINE_AA)
cv2.line(frame,(12,12),(12,12+arm),col_hud,1,cv2.LINE_AA)
cv2.line(frame,(cx-12,12),(cx-12-arm,12),col_hud,1,cv2.LINE_AA)
cv2.line(frame,(cx-12,12),(cx-12,12+arm),col_hud,1,cv2.LINE_AA)
cv2.line(frame,(12,h-12),(12+arm,h-12),col_hud,1,cv2.LINE_AA)
cv2.line(frame,(12,h-12),(12,h-12-arm),col_hud,1,cv2.LINE_AA)
cv2.line(frame,(cx-12,h-12),(cx-12-arm,h-12),col_hud,1,cv2.LINE_AA)
cv2.line(frame,(cx-12,h-12),(cx-12,h-12-arm),col_hud,1,cv2.LINE_AA)
cv2.putText(frame,"HOLOMIND v19",(20,28),FONT,0.30,(0,70,138),1,cv2.LINE_AA)
cv2.putText(frame,time.strftime("%H:%M:%S"),(20,42),FONT,0.27,(0,50,95),1,cv2.LINE_AA)
@staticmethod
def draw_network(frame,net,parts,snap_node,amb,w,h):
cx=int((w-SIDEBAR_W)*0.44); cy=int(h*0.47)
net.project(cx,cy)
hf,wf=frame.shape[:2]; t=time.time()
has_sel=net.selected_node is not None; is_deep=net.zoom_level==2
visible=sorted([n for n in net.nodes if n.visible],key=lambda n:n.scale)
amb.draw(frame,w,h,SIDEBAR_W)
# ── Arestas (sem LINE_AA para não-ativas = mais rápido)
for k,(i,j,lbl) in enumerate(net.edges):
if i>=len(net.nodes) or j>=len(net.nodes): continue
n1,n2=net.nodes[i],net.nodes[j]
if not n1.visible or not n2.visible: continue
avg_sc=(n1.scale+n2.scale)/2; fade=min(n1.alpha,n2.alpha) if has_sel else 1.0
is_act=k in net.active_edges
if is_act:
al=min(1.0,avg_sc*2.2); w_=2 if is_deep else 1
cv2.line(frame,(n1.sx,n1.sy),(n2.sx,n2.sy),(0,int(90*al),int(200*al)),w_+1,cv2.LINE_AA)
cv2.line(frame,(n1.sx,n1.sy),(n2.sx,n2.sy),(0,int(170*al),int(255*al)),w_,cv2.LINE_AA)
if lbl and is_deep:
mx,my=(n1.sx+n2.sx)//2,(n1.sy+n2.sy)//2
cv2.putText(frame,lbl,(mx,my),FONT,0.28,(0,80,160),1,cv2.LINE_AA)
else:
al=min(1.0,max(0.04,avg_sc*1.2)); iv=int(35*al*fade+5)
cv2.line(frame,(n1.sx,n1.sy),(n2.sx,n2.sy),(iv//3,iv//2,iv),1) # sem AA
# Teia cluster deep-dive
if is_deep and net.deep_progress>0.1 and net.selected_node:
sel_idx=net.nodes.index(net.selected_node); cluster=set(net.deep_cluster.keys())
dp=net.deep_progress; iv_web=int(38*dp)
for k,(i,j,_) in enumerate(net.edges):
if i in cluster and j in cluster and i!=sel_idx and j!=sel_idx:
ni_,nj_=net.nodes[i],net.nodes[j]
if ni_.visible and nj_.visible:
cv2.line(frame,(ni_.sx,ni_.sy),(nj_.sx,nj_.sy),(iv_web//2,iv_web,iv_web*2),1)
parts.draw(frame,net.nodes)
# ── Nós ──────────────────────────────────────────────
for node in visible:
s=node.scale
if s<0.07: continue
is_sel=node==net.selected_node; is_hov=node==net.hovered_node and not is_sel; hop=node.hop
pulse=1.0+0.06*math.sin(t*2.2+node.pulse_phase)*min(1.0,node.degree/8.0)
if is_sel and is_deep: pulse=1.0+0.14*math.sin(t*2.5); radius=max(7,int(8.0*s*pulse))
elif is_sel: pulse=1.0+0.10*math.sin(t*3.0); radius=max(5,int(5.5*s*pulse))
else: radius=max(3,int(4.0*s*pulse))
if is_sel and is_deep: col=NODE_DEEP
elif is_sel: col=NODE_SEL
elif is_hov: col=NODE_HOV
elif hop==1: col=NODE_HOP1
elif hop==2: col=NODE_HOP2
elif node.proximity>0.18: col=NODE_HOV
else: col=NODE_DEF
fc=lambda c: tuple(max(0,int(v*node.alpha)) for v in c)
# Glow — só para nós importantes (limita número de cÃrculos)
if is_sel or is_hov or hop==1:
glow_r=radius+int(14*(1.0 if is_sel else 0.6))
gc=tuple(int(v*0.12*node.alpha) for v in col)
cv2.circle(frame,(node.sx,node.sy),glow_r+4,gc,-1,cv2.LINE_AA)
gc2=tuple(int(v*0.25*node.alpha) for v in col)
cv2.circle(frame,(node.sx,node.sy),glow_r,gc2,-1,cv2.LINE_AA)
cv2.circle(frame,(node.sx,node.sy),radius,fc(col),-1,cv2.LINE_AA)
if radius>=4:
hi=tuple(min(255,int(v*1.4)+55) for v in col)
cv2.circle(frame,(node.sx-radius//3,node.sy-radius//3),max(1,radius//4),hi,-1)
if is_sel and is_deep and net.deep_progress>0.1:
dp=net.deep_progress
for hr_off,am in [(14,0.50),(26,0.28),(42,0.12)]:
hr=radius+int(hr_off*dp)
hc=tuple(int(v*am*dp) for v in NODE_DEEP)
cv2.circle(frame,(node.sx,node.sy),hr,hc,1,cv2.LINE_AA)
rr=radius+int((48+22*math.sin(t*1.8))*dp)
cv2.circle(frame,(node.sx,node.sy),max(1,rr),tuple(int(v*0.07*dp) for v in NODE_DEEP),1)
if is_hov and not is_sel:
for rr,aa in [(radius+8,0.55),(radius+15,0.22)]:
rc=tuple(int(v*aa*node.proximity) for v in NODE_HOV)
cv2.circle(frame,(node.sx,node.sy),rr,rc,1,cv2.LINE_AA)
if hop==1 and has_sel:
hc=tuple(int(v*0.45*node.alpha) for v in NODE_HOP1)
cv2.circle(frame,(node.sx,node.sy),radius+5,hc,1,cv2.LINE_AA)
if node==snap_node and not is_sel and not is_hov:
cv2.circle(frame,(node.sx,node.sy),radius+10,SNAP_COL,1,cv2.LINE_AA)
if node==net.dwell_node and net.dwell_timer>0:
dp2=min(1.0,net.dwell_timer/net.DWELL_TIME); dr=radius+12
cv2.ellipse(frame,(node.sx,node.sy),(dr,dr),0,-90,-90+int(360*dp2),DWELL_COL,2,cv2.LINE_AA)
# ── Label ────────────────────────────────────────
if s>0.22 and node.alpha>0.08:
if is_sel and is_deep:
fs=max(0.48,min(0.92,s*1.0)); txt=f"[ {node.title} ]"; col_l=NODE_DEEP; th=1
elif is_sel:
fs=max(0.35,min(0.62,s*0.72)); txt=f"[ {node.title} ]"; col_l=NODE_SEL; th=1
elif is_hov or hop==1:
fs=max(0.26,min(0.50,s*0.63)); txt=f"[ {node.title} ]"
col_l=LBL_HOV if is_hov else LBL_HOP1; th=1
else:
fs=max(0.23,min(0.46,s*0.58)); txt=node.title; col_l=LBL_DEF; th=1
col_lf=fc(col_l)
tw=cv2.getTextSize(txt,FONT,fs,th)[0][0]
cv2.putText(frame,txt,(node.sx-tw//2,node.sy-radius-8),FONT,fs,col_lf,th,cv2.LINE_AA)
# ── Snippets brilhantes ───────────────────────────
snip_scale=3.2 if is_sel and is_deep else 1.0
if s>0.22 and node.alpha>0.06 and node.snippets:
n_show=min(len(node.snippets),max(1,int(s*2.8)))
prev_sx2,prev_sy2=None,None
for ki in range(n_show):
base_angle=(ki/max(1,n_show))*math.pi*2+node.pulse_phase
z_phase=math.sin(base_angle*1.3+t*0.4)*0.25
dist=(48+ki*20)*snip_scale*(1.0+z_phase)
sx_=node.sx+int(dist*math.cos(base_angle))
sy_=node.sy+int(dist*math.sin(base_angle)*0.8)
if 0<sx_<wf and 0<sy_<hf:
snip_a=min(1.0,s*1.4)*node.alpha
if is_sel and is_deep:
sc_=(int(185*snip_a),int(215*snip_a),int(245*snip_a)); fs_snip=0.34
elif is_sel:
sc_=(int(80*snip_a),int(145*snip_a),int(225*snip_a)); fs_snip=0.27
elif hop==1:
sc_=(int(60*snip_a),int(185*snip_a),int(90*snip_a)); fs_snip=0.24
else:
ic=int(135*snip_a); sc_=(ic,ic+10,ic+25); fs_snip=0.22
cv2.putText(frame,node.snippets[ki],(sx_,sy_),FONT,fs_snip,sc_,1,cv2.LINE_AA)
if is_sel and is_deep and net.deep_progress>0.15:
iv_w=int(30*net.deep_progress)
cv2.line(frame,(node.sx,node.sy),(sx_,sy_),(iv_w,iv_w*2,iv_w*3),1)
if prev_sx2 is not None:
iv_r=int(14*net.deep_progress)
cv2.line(frame,(prev_sx2,prev_sy2),(sx_,sy_),(iv_r,iv_r,iv_r*2),1)
prev_sx2,prev_sy2=sx_,sy_
if is_sel and net.zoom_progress>0.12:
Renderer._draw_content(frame,node,net,t)
Renderer._draw_brackets(frame,node,net,t)
@staticmethod
def _draw_content(frame,node,net,t):
lv=net.zoom_level; al=min(1.0,net.zoom_progress*2.5)
lines=node.content.split('\n')
offset_x=260 if lv==2 else 215
tx=max(16,node.sx-offset_x); ty=node.sy-(len(lines)*26)//2
sqc=tuple(int(v*al) for v in NODE_SEL)
cv2.rectangle(frame,(tx,ty-12),(tx+8,ty-4),sqc,-1)
fs_mult=1.6 if lv==2 else 1.0; line_h=int(30*fs_mult)
for li,line in enumerate(lines):
col_line=(tuple(int(v*al) for v in NODE_SEL) if li==0
else (int(195*al),int(200*al),int(225*al)))
cv2.putText(frame,line,(tx+13,ty+li*line_h),FONT,0.44*fs_mult,col_line,1,cv2.LINE_AA)
@staticmethod
def _draw_brackets(frame,node,net,t):
lv=net.zoom_level; prog=net.deep_progress if lv==2 else net.zoom_progress
b=int(55+32*prog)+int(5*math.sin(t*2.8)); arm=b//3; cx,cy=node.sx,node.sy
col=tuple(int(v*0.85) for v in NODE_DEEP) if lv==2 else BRACKET
for corner,p1,p2 in [
((cx-b,cy-b),(cx-b+arm,cy-b),(cx-b,cy-b+arm)),
((cx+b,cy-b),(cx+b-arm,cy-b),(cx+b,cy-b+arm)),
((cx-b,cy+b),(cx-b+arm,cy+b),(cx-b,cy+b-arm)),
((cx+b,cy+b),(cx+b-arm,cy+b),(cx+b,cy+b-arm)),
]:
cv2.line(frame,corner,p1,col,1,cv2.LINE_AA); cv2.line(frame,corner,p2,col,1,cv2.LINE_AA)
cv2.circle(frame,corner,2,col,-1,cv2.LINE_AA)
cv2.line(frame,(cx-7,cy),(cx+7,cy),(50,60,80),1,cv2.LINE_AA)
cv2.line(frame,(cx,cy-7),(cx,cy+7),(50,60,80),1,cv2.LINE_AA)
if lv==2:
dangle=int(math.degrees(net.deep_rot_y)%360)
cv2.putText(frame,"DEEP DIVE",(cx-b-55,cy-b+5),FONT,0.28,tuple(int(v*0.65) for v in NODE_DEEP),1,cv2.LINE_AA)
cv2.putText(frame,f"rot {dangle:03d}°",(cx-b-55,cy-b+18),FONT,0.23,(0,60,90),1,cv2.LINE_AA)
# ── Sidebar ──────────────────────────────────────────────
@staticmethod
def draw_sidebar(frame,net,w,h,mini_graph_cache,compose_mode=False,compose_text="",compose_status="",
view_mode="mixed",media_hitboxes=None,thumbnail_cache=None,
auto_reply_enabled=False,auto_reply_label="",auto_reply_busy=False,
notification_text=""):
sx=w-SIDEBAR_W
cv2.rectangle(frame,(sx,0),(w,h),(7,7,11),-1)
cv2.line(frame,(sx,0),(sx,h),(0,50,100),1,cv2.LINE_AA)
cv2.line(frame,(sx+1,0),(sx+1,h),(0,25,50),1,cv2.LINE_AA)
def short_lines(text,max_chars=34,max_lines=2):
words=str(text or "").split()
if not words: return [""]
lines=[]; cur=[]
for wd in words:
cur.append(wd)
if len(" ".join(cur))>max_chars:
lines.append(" ".join(cur[:-1])); cur=[wd]
if len(lines)>=max_lines: break
if len(lines)<max_lines and cur: lines.append(" ".join(cur))
lines=lines[:max_lines]
return [ln if len(ln)<=max_chars else ln[:max_chars-1]+"..." for ln in lines]
fs=lambda v: v*SIDEBAR_SCALE
frame[::8,sx+2:w-2]=np.clip(frame[::8,sx+2:w-2].astype(np.int16)+np.array([0,2,3],dtype=np.int16),0,255).astype(np.uint8)
cv2.putText(frame,"Topologies of",(sx+18,40),FONT,fs(0.80),(195,205,225),1,cv2.LINE_AA)
cv2.putText(frame,"Thoughts", (sx+18,70),FONT,fs(0.80),(195,205,225),1,cv2.LINE_AA)
cv2.line(frame,(sx+18,80),(w-18,80),(0,50,100),1,cv2.LINE_AA)
mini_graph_cache.draw(frame,net,sx+SIDEBAR_W//2,192)
lbl,bullets=TOPO_DESC.get(net.topology,(f"mode: {net.topology}",[]))
my=290
cv2.putText(frame,lbl,(sx+18,my),FONT,fs(0.37),GRAY_LT,1,cv2.LINE_AA)
for bi,bul in enumerate(bullets):
cv2.circle(frame,(sx+22,my+17+bi*18),2,(0,90,160),-1,cv2.LINE_AA)