-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1201 lines (1000 loc) · 45.1 KB
/
main.py
File metadata and controls
1201 lines (1000 loc) · 45.1 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
"""
S T A R R Y N O T E · Cybernetic Knowledge Architecture v2.1
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Transforms raw academic materials into structured study guides
using Gemma 3 on Apple Silicon via MLX.
Terminal UI: Animated neon cyberpunk interface with:
- Matrix digital rain during loading
- Holographic shimmer hero banner
- Radar sweep file discovery
- Multi-panel live synthesis dashboard
- Orbital particle completion sequence
Entry point: python main.py
"""
from __future__ import annotations
import math
import os
import sys
import time
import random
import threading
import logging
from datetime import datetime
from typing import Dict, FrozenSet, List, Optional, Tuple
from rich.console import Console, Group
from rich.panel import Panel
from rich.progress import (
Progress,
SpinnerColumn,
TextColumn,
BarColumn,
TimeElapsedColumn,
)
from rich.table import Table
from rich.align import Align
from rich.rule import Rule
from rich.live import Live
from rich.layout import Layout
from rich.text import Text
from rich.columns import Columns
from rich import box
from src.model_engine import StarryEngine, MAX_TOKENS
from src.scanner import StarryScanner, UniversalResource
from src.formatter import StarryFormatter
# ═══════════════════════════════════════════════════════════════════════════
# Design System — Cyberpunk Neon Palette
# ═══════════════════════════════════════════════════════════════════════════
PURPLE: str = "#bc13fe"
CYAN: str = "#00f3ff"
GREEN: str = "#39ff14"
AMBER: str = "#ffbf00"
RED: str = "#ff0040"
DIM: str = "#555555"
DARK_BG: str = "#0a0a0a"
WHITE: str = "#e0e0e0"
PINK: str = "#ff6ec7"
BLUE: str = "#0080ff"
# Neon color cycle for pulsating effects
NEON_CYCLE: Tuple[str, ...] = (PURPLE, CYAN, PINK, GREEN, BLUE)
# ═══════════════════════════════════════════════════════════════════════════
# Console
# ═══════════════════════════════════════════════════════════════════════════
console = Console()
# ═══════════════════════════════════════════════════════════════════════════
# ASCII Art
# ═══════════════════════════════════════════════════════════════════════════
HERO_LINES: List[str] = [
" ███████╗████████╗ █████╗ ██████╗ ██████╗ ██╗ ██╗",
" ██╔════╝╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗╚██╗ ██╔╝",
" ███████╗ ██║ ███████║██████╔╝██████╔╝ ╚████╔╝ ",
" ╚════██║ ██║ ██╔══██║██╔══██╗██╔══██╗ ╚██╔╝ ",
" ███████║ ██║ ██║ ██║██║ ██║██║ ██║ ██║ ",
" ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ",
]
SUBTITLE: str = "N O T E"
VERSION_TAG: str = "╌╌╌ Cybernetic Knowledge Architecture v2.1 ╌╌╌"
STAR_CHARS: str = "·.·.·.˚˚✧✦✦★"
CONSTELLATION_WIDTH: int = 70
CONSTELLATION_HEIGHT: int = 3
# ═══════════════════════════════════════════════════════════════════════════
# Animation Primitives
# ═══════════════════════════════════════════════════════════════════════════
def _neon_pulse(t: float) -> str:
"""
Return a pulsating neon color from the cycle based on time.
Uses sine-wave oscillation to smoothly transition between
colors in the NEON_CYCLE palette. Each call with a different
time value produces a different color.
Args:
t: Time value (typically time.time()).
Returns:
A hex color string from the NEON_CYCLE.
"""
idx = int((math.sin(t * 2) + 1) / 2 * len(NEON_CYCLE)) % len(NEON_CYCLE)
return NEON_CYCLE[idx]
def _generate_starfield(
width: int = CONSTELLATION_WIDTH,
height: int = CONSTELLATION_HEIGHT,
density: float = 0.15,
) -> str:
"""
Generate a single frame of an animated starfield.
Creates a sparse field of randomized star characters on a dark
background. Each call produces a unique frame.
Args:
width: Character width of the field.
height: Number of lines in the field.
density: Probability of a star at each position (0.0–1.0).
Returns:
Multi-line string with Rich color markup.
"""
lines: List[str] = []
for _ in range(height):
row: List[str] = []
for _ in range(width):
if random.random() < density:
char = random.choice(STAR_CHARS)
roll = random.random()
if roll < 0.45:
color = DIM
elif roll < 0.65:
color = PURPLE
elif roll < 0.82:
color = CYAN
elif roll < 0.93:
color = PINK
else:
color = GREEN
row.append(f"[{color}]{char}[/{color}]")
else:
row.append(" ")
lines.append("".join(row))
return "\n".join(lines)
def _glitch_line(line: str, intensity: float = 0.05) -> str:
"""
Apply a cyberpunk glitch effect to a text line.
Randomly replaces characters with glitch symbols (░▒▓█)
to simulate digital corruption.
Args:
line: The source text line.
intensity: Probability of each character being glitched (0.0–1.0).
Returns:
Glitched version of the line.
"""
glitch_chars = "░▒▓█▀▄▌▐"
result: List[str] = []
for ch in line:
if random.random() < intensity and ch not in " \n":
result.append(random.choice(glitch_chars))
else:
result.append(ch)
return "".join(result)
def _matrix_rain(width: int = 60, height: int = 6) -> str:
"""
Generate a single frame of Matrix-style digital rain.
Creates falling columns of random characters in green tones,
simulating the iconic Matrix code rain effect. Each column has
a bright head character and dimming tail.
Args:
width: Character width of the rain field.
height: Number of lines.
Returns:
Multi-line string with Rich markup.
"""
matrix_chars = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン01"
lines: List[str] = []
for row in range(height):
chars: List[str] = []
for col in range(width):
if random.random() < 0.12:
ch = random.choice(matrix_chars)
# Brightest at top rows, dimmer at bottom
brightness = random.random()
if brightness < 0.3:
chars.append(f"[bold {GREEN}]{ch}[/bold {GREEN}]")
elif brightness < 0.6:
chars.append(f"[{GREEN}]{ch}[/{GREEN}]")
else:
chars.append(f"[{DIM}]{ch}[/{DIM}]")
else:
chars.append(" ")
lines.append("".join(chars))
return "\n".join(lines)
def _waveform(width: int = 50, t: float = 0.0, amplitude: float = 1.0) -> str:
"""
Generate a single frame of an animated sine waveform.
Creates an ASCII waveform using block characters that
oscillates smoothly based on the time parameter.
Args:
width: Character width of the waveform.
t: Time offset for animation.
amplitude: Wave height multiplier.
Returns:
Single-line string with Rich color markup.
"""
wave_chars = "▁▂▃▄▅▆▇█▇▆▅▄▃▂▁"
result: List[str] = []
for x in range(width):
# Composite wave: main + harmonic for visual interest
val = math.sin(x * 0.3 + t * 3) * 0.5 + math.sin(x * 0.15 + t * 1.5) * 0.5
val = (val + 1) / 2 # Normalize to 0–1
idx = int(val * (len(wave_chars) - 1))
ch = wave_chars[idx]
# Color based on height
if val > 0.7:
color = CYAN
elif val > 0.4:
color = PURPLE
else:
color = DIM
result.append(f"[{color}]{ch}[/{color}]")
return "".join(result)
def _orbital_particles(t: float, count: int = 12, radius: int = 8) -> str:
"""
Generate a frame of orbiting particles around a center point.
Creates multiple particles that orbit in circles at different
speeds and radii, producing a dynamic planetary effect.
Args:
t: Time offset for animation.
count: Number of orbiting particles.
radius: Radius of the orbit field in characters.
Returns:
Multi-line string of the orbital field.
"""
field_h = radius * 2 + 1
field_w = radius * 4 + 2 # Wider because terminal chars are taller than wide
grid: List[List[str]] = [[" "] * field_w for _ in range(field_h)]
# Place a center marker
cy, cx = radius, radius * 2
grid[cy][cx] = "✦"
for i in range(count):
# Each particle has a different speed and radius offset
angle = t * (1.0 + i * 0.3) + (i * 2 * math.pi / count)
r = radius * (0.5 + 0.5 * math.sin(t * 0.5 + i))
py = int(cy + math.sin(angle) * r * 0.5)
px = int(cx + math.cos(angle) * r)
if 0 <= py < field_h and 0 <= px < field_w:
particle_chars = "·✧✦★⬡◈"
grid[py][px] = random.choice(particle_chars)
lines = []
for row in grid:
line_chars = []
for ch in row:
if ch == " ":
line_chars.append(" ")
elif ch == "✦":
line_chars.append(f"[bold {CYAN}]✦[/bold {CYAN}]")
else:
color = random.choice([PURPLE, CYAN, PINK, GREEN])
line_chars.append(f"[{color}]{ch}[/{color}]")
lines.append("".join(line_chars))
return "\n".join(lines)
def _typing_effect(text: str, color: str = CYAN) -> str:
"""
Create a typewriter-style text revealing effect.
Returns the text with a blinking cursor at the end,
used in combination with progressive reveal in animations.
Args:
text: The text to display.
color: Rich color for the text.
Returns:
Text with cursor markup.
"""
cursor = (
f"[blink][bold {color}]▊[/bold {cyan}][/blink]"
if random.random() > 0.3
else f"[bold {color}]▊[/bold {color}]"
)
return f"[bold {color}]{text}[/bold {color}]{cursor}"
def _progress_bar_fancy(pct: float, width: int = 30) -> str:
"""
Generate a neon gradient progress bar.
Uses block characters with color transitions:
purple → cyan → green as progress increases.
Args:
pct: Progress percentage (0–100).
width: Character width of the bar.
Returns:
Rich-markup progress bar string.
"""
filled = int(width * pct / 100)
empty = width - filled
bar_parts: List[str] = []
for i in range(filled):
# Gradient: purple → cyan → green
ratio = i / max(width - 1, 1)
if ratio < 0.33:
color = PURPLE
elif ratio < 0.66:
color = CYAN
else:
color = GREEN
bar_parts.append(f"[{color}]█[/{color}]")
bar_parts.append(f"[{DIM}]{'░' * empty}[/{DIM}]")
return "".join(bar_parts)
# ═══════════════════════════════════════════════════════════════════════════
# Boot Sequence — System initialization with hardware checks
# ═══════════════════════════════════════════════════════════════════════════
def _boot_sequence() -> None:
"""
Display a futuristic system boot sequence.
Simulates hardware detection and system initialization with
sequential check animations, giving the feel of booting into
a cybernetic operating system.
"""
checks = [
("MEMORY", "Unified Memory Subsystem", "ALLOCATED"),
("GPU", "Apple Metal Compute Engine", "ONLINE"),
("NEURAL", "Gemma 3 Neural Pathways", "LOADED"),
("VISION", "Multimodal Vision Pipeline", "READY"),
("ARCHIVE", "Knowledge Archive System", "MOUNTED"),
("MERMAID", "Diagram Synthesis Engine", "ACTIVE"),
("CRYPTO", "Cyberpunk Style Injector", "ENGAGED"),
]
with Live(console=console, refresh_per_second=15, transient=True) as live:
completed: List[str] = []
for system, desc, status in checks:
# Scanning animation for current check
for frame in range(6):
scan_chars = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
spinner = scan_chars[frame % len(scan_chars)]
wave = _waveform(width=40, t=time.time(), amplitude=0.5)
lines = list(completed)
lines.append(
f" [{CYAN}]{spinner}[/{CYAN}] "
f"[{AMBER}]{system:8s}[/{AMBER}] "
f"[dim]{desc}[/dim] "
f"[{DIM}]scanning…[/{DIM}]"
)
lines.append(f"\n {wave}")
live.update(Text.from_markup("\n".join(lines)))
time.sleep(0.05)
# Mark as complete
completed.append(
f" [{GREEN}]✦[/{GREEN}] "
f"[{AMBER}]{system:8s}[/{AMBER}] "
f"[dim]{desc}[/dim] "
f"[bold {GREEN}]{status}[/bold {GREEN}]"
)
# Print final boot status
for line in completed:
console.print(Text.from_markup(line))
# ═══════════════════════════════════════════════════════════════════════════
# Animated Hero Banner — Holographic shimmer reveal
# ═══════════════════════════════════════════════════════════════════════════
def _animated_hero_banner(duration: float = 2.5) -> None:
"""
Display the StarryNote hero banner with holographic shimmer.
Animation sequence:
1. Matrix rain fades in behind the banner
2. Hero text materializes with glitch decay
3. Color shimmer sweeps across the text
4. Banner stabilizes with starfield surround
5. Subtitle and version tag type in
"""
frames = int(duration * 12)
with Live(console=console, refresh_per_second=14, transient=True) as live:
for frame in range(frames):
progress = frame / max(frames - 1, 1)
t = time.time()
# Background: matrix rain → starfield transition
if progress < 0.4:
bg = _matrix_rain(width=55, height=2)
elif progress < 0.7:
mix_density = 0.15 + 0.1 * (1 - progress)
bg = _generate_starfield(width=55, height=2, density=mix_density)
else:
bg = _generate_starfield(width=55, height=2, density=0.12)
# Hero text: glitch → shimmer → stable
glitch_intensity = max(0.0, 0.4 * (1 - progress * 2))
banner_lines: List[str] = []
for line_idx, line in enumerate(HERO_LINES):
if progress < 0.3:
# Glitch phase: heavy corruption
glitched = _glitch_line(line, glitch_intensity)
banner_lines.append(f"[bold {PURPLE}]{glitched}[/bold {PURPLE}]")
elif progress < 0.7:
# Shimmer phase: color sweep across text
shimmer_pos = int((progress - 0.3) / 0.4 * len(line))
parts: List[str] = []
for i, ch in enumerate(line):
dist = abs(i - shimmer_pos)
if dist < 3:
parts.append(f"[bold {CYAN}]{ch}[/bold {CYAN}]")
elif dist < 6:
parts.append(f"[bold {PINK}]{ch}[/bold {PINK}]")
else:
parts.append(f"[bold {PURPLE}]{ch}[/bold {PURPLE}]")
banner_lines.append("".join(parts))
else:
# Stable phase: settled
banner_lines.append(f"[bold {PURPLE}]{line}[/bold {PURPLE}]")
# Subtitle: typewriter reveal
if progress > 0.5:
reveal_len = int((progress - 0.5) / 0.3 * len(SUBTITLE))
revealed = SUBTITLE[: min(reveal_len, len(SUBTITLE))]
padding = " " * 18
if reveal_len < len(SUBTITLE):
banner_lines.append(
f"[bold {CYAN}]{padding}{revealed}[/bold {CYAN}]"
f"[blink {CYAN}]▊[/blink {CYAN}]"
)
else:
banner_lines.append(
f"[bold {CYAN}]{padding}{SUBTITLE}[/bold {CYAN}]"
)
else:
banner_lines.append("")
# Version tag: fade in
if progress > 0.8:
banner_lines.append(f"[dim] {VERSION_TAG}[/dim]")
else:
banner_lines.append("")
content = "\n".join(banner_lines)
# Waveform at bottom
wave = _waveform(width=55, t=t)
live.update(
Panel(
Align.center(f"{bg}\n\n{content}\n\n{wave}"),
border_style=_neon_pulse(t),
padding=(0, 2),
)
)
time.sleep(0.07)
# Final static banner with pulsing border would be replaced by static
final_lines = [f"[bold {PURPLE}]{line}[/bold {PURPLE}]" for line in HERO_LINES]
final_lines.append(f"[bold {CYAN}] {SUBTITLE}[/bold {CYAN}]")
final_lines.append(f"[dim] {VERSION_TAG}[/dim]")
stars = _generate_starfield(width=55, height=1, density=0.12)
console.print(
Panel(
Align.center(f"{stars}\n\n" + "\n".join(final_lines) + f"\n\n{stars}"),
border_style=PURPLE,
padding=(1, 4),
)
)
# ═══════════════════════════════════════════════════════════════════════════
# Directory & MIME Configuration
# ═══════════════════════════════════════════════════════════════════════════
SKIP: FrozenSet[str] = frozenset(
{
"Instructions",
".venv",
"__pycache__",
".git",
".DS_Store",
".idea",
".pytest_cache",
"node_modules",
".github",
}
)
MIME_ICONS: Dict[str, str] = {
"image": "🖼 ",
"pdf": "📄",
"python": "🐍",
"javascript": "⚡",
"markdown": "📘",
"json": "🔧",
"csv": "📊",
"html": "🌐",
"css": "🎨",
"xml": "📋",
"text": "📝",
}
# ═══════════════════════════════════════════════════════════════════════════
# Utility Functions
# ═══════════════════════════════════════════════════════════════════════════
def _icon(mime: str) -> str:
"""Map MIME type to emoji icon. Fallback: 📦."""
for keyword, emoji in MIME_ICONS.items():
if keyword in mime:
return emoji
return "📦"
def _sz(n: int) -> str:
"""Format byte count as human-readable size."""
for unit in ("B", "KB", "MB", "GB"):
if n < 1024:
return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
n /= 1024
return f"{n:.1f} TB"
def _density(input_bytes: int, output_len: int) -> str:
"""Generate star rating for knowledge amplification density."""
ratio = output_len / max(input_bytes, 1)
stars = min(5, max(1, int(ratio) + 1))
colors = [DIM, AMBER, CYAN, PURPLE, GREEN]
color = colors[min(stars - 1, len(colors) - 1)]
return f"[{color}]{'✦' * stars}[/{color}]"
def _should_skip(path: str) -> bool:
"""Check if a file path should be excluded from processing."""
return any(pattern in path for pattern in SKIP)
def _elapsed_str(seconds: float) -> str:
"""Format elapsed seconds as human-readable duration."""
if seconds < 60:
return f"{seconds:.1f}s"
mins = int(seconds // 60)
secs = seconds % 60
return f"{mins}m {secs:.0f}s"
# ═══════════════════════════════════════════════════════════════════════════
# Phase Headers — Animated phase transitions
# ═══════════════════════════════════════════════════════════════════════════
def _phase(n: int, title: str, glyph: str) -> None:
"""Print animated phase header with sweep + waveform."""
sweep_chars = "▏▎▍▌▋▊▉█"
with Live(console=console, refresh_per_second=20, transient=True) as live:
for i, ch in enumerate(sweep_chars):
bar = f"[{CYAN}]{ch * (i + 2)}[/{CYAN}]"
wave = _waveform(width=40, t=time.time())
live.update(
Text.from_markup(
f"\n{bar} [bold {CYAN}]PHASE {n} · {title}[/bold {CYAN}]\n{wave}"
)
)
time.sleep(0.04)
console.print(f"\n[bold {CYAN}]{glyph} PHASE {n} · {title}[/bold {CYAN}]")
console.print(Rule(style=PURPLE))
# ═══════════════════════════════════════════════════════════════════════════
# Animated Scanning — Radar sweep with live file counter
# ═══════════════════════════════════════════════════════════════════════════
def _animated_scan(scanner: StarryScanner, cwd: str) -> List[UniversalResource]:
"""
Run directory scan with radar sweep animation and live file counter.
Uses a background thread for the actual scan while rendering
a rotating radar display in the foreground.
"""
result_holder: List[Optional[List[UniversalResource]]] = [None]
scan_done = threading.Event()
def _scan_worker():
raw = scanner.scan_directory(cwd)
result_holder[0] = [r for r in raw if not _should_skip(r.file_path)]
scan_done.set()
thread = threading.Thread(target=_scan_worker, daemon=True)
thread.start()
# Radar animation messages
scan_msgs = [
"Mapping directory tree",
"Classifying MIME types",
"Analyzing binary headers",
"Building resource index",
"Cataloging file formats",
"Scanning nested paths",
]
# Radar sweep characters (rotating)
radar = "◜◝◞◟"
with Live(console=console, refresh_per_second=10, transient=True) as live:
frame = 0
while not scan_done.is_set():
t = time.time()
msg = scan_msgs[frame % len(scan_msgs)]
sweep = radar[frame % len(radar)]
wave = _waveform(width=45, t=t)
stars = _generate_starfield(width=50, height=1, density=0.15)
display = (
f"\n [{CYAN}]{sweep}[/{CYAN}] "
f"[bold {CYAN}]{msg}…[/bold {CYAN}]\n\n"
f" {wave}\n"
f" {stars}"
)
live.update(
Panel(
Text.from_markup(display),
border_style=_neon_pulse(t),
title=f"[bold {PURPLE}]⬡ DEEP SCAN[/bold {PURPLE}]",
)
)
frame += 1
time.sleep(0.1)
thread.join()
return result_holder[0] or []
# ═══════════════════════════════════════════════════════════════════════════
# Live Synthesis Dashboard — Multi-panel real-time display
# ═══════════════════════════════════════════════════════════════════════════
def _build_dashboard(
current_file: str,
file_idx: int,
total_files: int,
tokens_generated: int,
elapsed_file: float,
completed_files: List[Tuple[str, float]],
errors: List[Tuple[str, str]],
) -> Layout:
"""
Build a multi-panel live synthesis dashboard.
Layout:
┌─────────────────────┬──────────────────┐
│ Status Panel │ Stats Panel │
│ (current file, │ (speed, queue │
│ progress bar) │ elapsed) │
├─────────────────────┴──────────────────┤
│ Activity Feed (completed files) │
└────────────────────────────────────────┘
"""
t = time.time()
pct = min(100, int((tokens_generated / max(MAX_TOKENS, 1)) * 100))
tps = tokens_generated / max(elapsed_file, 0.01)
# ── Status panel (left) ───────────────────────────────────────
bar = _progress_bar_fancy(pct, width=28)
wave = _waveform(width=30, t=t)
status_text = (
f" [bold {WHITE}]📂 {current_file}[/bold {WHITE}]\n\n"
f" {bar} [{CYAN}]{pct:3d}%[/{CYAN}]\n\n"
f" [dim]Tokens:[/dim] [{GREEN}]{tokens_generated:,}[/{GREEN}]"
f" [dim]/ {MAX_TOKENS:,}[/dim]\n\n"
f" {wave}"
)
status_panel = Panel(
Text.from_markup(status_text),
title=f"[bold {CYAN}]⚡ Active[/bold {CYAN}]",
border_style=_neon_pulse(t),
padding=(1, 1),
)
# ── Stats panel (right) ───────────────────────────────────────
stats = Table(show_header=False, box=None, padding=(0, 1))
stats.add_column(style=f"bold {CYAN}", width=10)
stats.add_column(style=WHITE)
stats.add_row("🚀 Speed", f"[bold {GREEN}]{tps:.0f}[/bold {GREEN}] tok/s")
stats.add_row("📁 Queue", f"[bold]{file_idx}[/bold] / {total_files}")
stats.add_row("⏱ Time", f"[bold]{_elapsed_str(elapsed_file)}[/bold]")
stats.add_row(
"Status",
(
f"[bold {RED}]{len(errors)} errors[/bold {RED}]"
if errors
else f"[bold {GREEN}]Nominal[/bold {GREEN}]"
),
)
# Mini orbital display
stars = _generate_starfield(width=20, height=2, density=0.2)
stats_panel = Panel(
Group(stats, Text.from_markup(f"\n{stars}")),
title=f"[bold {PURPLE}]📊 Metrics[/bold {PURPLE}]",
border_style=PURPLE,
padding=(1, 1),
)
# ── Activity feed (bottom) ────────────────────────────────────
if completed_files:
feed_items = []
for name, dt in completed_files[-4:]:
feed_items.append(
f" [{GREEN}]✦[/{GREEN}] "
f"[dim]{name}[/dim] "
f"[{CYAN}]{dt:.1f}s[/{CYAN}]"
)
feed_text = "\n".join(feed_items)
else:
feed_text = f" [{DIM}]Waiting for first file…[/{DIM}]"
feed_panel = Panel(
Text.from_markup(feed_text),
title=f"[bold {GREEN}]✓ Completed[/bold {GREEN}]",
border_style=DIM,
padding=(0, 1),
)
# ── Assemble layout ──────────────────────────────────────────
layout = Layout()
layout.split_column(
Layout(name="top", size=10),
Layout(name="bottom", size=5),
)
layout["top"].split_row(
Layout(status_panel, ratio=3),
Layout(stats_panel, ratio=2),
)
layout["bottom"].update(feed_panel)
return layout
# ═══════════════════════════════════════════════════════════════════════════
# Completion Animation — Orbital particle celebration
# ═══════════════════════════════════════════════════════════════════════════
def _completion_animation(file_count: int, session_time: float) -> None:
"""
Display a cinematic orbital particle completion sequence.
Shows orbiting particles that converge into a constellation,
with expanding starfield and pulsating success message.
"""
with Live(console=console, refresh_per_second=12, transient=True) as live:
for frame in range(24):
t = time.time()
progress = frame / 23
# Phase 1: Orbital particles (frames 0-12)
if frame < 12:
orbitals = _orbital_particles(t, count=8 + frame, radius=6)
msg = f"[bold {_neon_pulse(t)}]Synthesizing constellation…[/bold {_neon_pulse(t)}]"
live.update(
Panel(
Align.center(Text.from_markup(f"\n{orbitals}\n\n{msg}\n")),
border_style=_neon_pulse(t),
padding=(0, 2),
)
)
# Phase 2: Stars resolve (frames 12-24)
else:
star_count = min(file_count, frame - 11)
stars_str = " ".join(
f"[bold {NEON_CYCLE[i % len(NEON_CYCLE)]}]✦[/bold {NEON_CYCLE[i % len(NEON_CYCLE)]}]"
for i in range(star_count)
)
field = _generate_starfield(
width=55, height=2, density=0.15 * (1 - (frame - 12) / 12 * 0.5)
)
status = (
f"[bold {GREEN}]{len([_ for _ in range(file_count)])} files synthesized[/bold {GREEN}]"
if progress > 0.8
else ""
)
live.update(
Align.center(
Text.from_markup(
f"\n{field}\n\n"
f" {stars_str}\n\n"
f"{field}\n\n"
f"{status}\n"
)
)
)
time.sleep(0.1)
# Final static display
stars_str = " ".join(
f"[bold {NEON_CYCLE[i % len(NEON_CYCLE)]}]✦[/bold {NEON_CYCLE[i % len(NEON_CYCLE)]}]"
for i in range(file_count)
)
wave = _waveform(width=55, t=time.time())
field = _generate_starfield(width=55, height=2, density=0.1)
console.print(
Align.center(
Text.from_markup(
f"\n{field}\n\n"
f" {stars_str}\n\n"
f" {wave}\n\n"
f"{field}\n\n"
f"[bold {CYAN}]Knowledge Archived · Stars Aligned[/bold {CYAN}]\n"
)
)
)
# ═══════════════════════════════════════════════════════════════════════════
# Main Pipeline — 4-Phase Animated Knowledge Synthesis
# ═══════════════════════════════════════════════════════════════════════════
def run() -> None:
"""
Execute the full StarryNote pipeline with premium animated TUI.
4-Phase Flow:
Phase 1: Neural Initialization — Boot sequence + model loading
Phase 2: Deep Scan — Radar sweep file discovery
Phase 3: Knowledge Synthesis — Multi-panel dashboard
Phase 4: Mission Report — Orbital completion + results
"""
t0 = time.time()
console.clear()
# ── Animated Hero Banner ──────────────────────────────────────
_animated_hero_banner(duration=2.5)
timestamp = datetime.now().strftime("%Y-%m-%d · %H:%M:%S")
console.print(
Align.center(f"[dim]Session {timestamp} · Apple Silicon · Gemma 3[/dim]\n")
)
# ── PHASE 1: NEURAL INITIALIZATION ────────────────────────────
_phase(1, "NEURAL INITIALIZATION", "⚡")
# Boot sequence animation
_boot_sequence()
# Actual model loading
with Live(console=console, refresh_per_second=8, transient=True) as live:
load_done = threading.Event()
engine_holder: List[Optional[StarryEngine]] = [None]
error_holder: List[Optional[str]] = [None]
def _load_worker():
try:
engine_holder[0] = StarryEngine()
except Exception as exc:
error_holder[0] = str(exc)
load_done.set()
load_thread = threading.Thread(target=_load_worker, daemon=True)
load_thread.start()
frame = 0
while not load_done.is_set():
t = time.time()
rain = _matrix_rain(width=50, height=3)
wave = _waveform(width=50, t=t)
spinner = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"[frame % 10]
live.update(
Panel(
Align.center(
Text.from_markup(
f"{rain}\n\n"
f" [{CYAN}]{spinner}[/{CYAN}] "
f"[bold {CYAN}]Loading Gemma 3 into Unified Memory…[/bold {CYAN}]\n\n"
f" {wave}"
)
),
border_style=_neon_pulse(t),
title=f"[bold {PURPLE}]⬡ NEURAL CORE[/bold {PURPLE}]",
)
)
frame += 1
time.sleep(0.1)
load_thread.join()
if error_holder[0]:
console.print(
Panel(
f"[bold {RED}]Engine initialization failed:[/bold {RED}]\n\n"
f"{error_holder[0]}",
border_style=RED,
title="⚠ Fatal Error",
)
)
sys.exit(1)
engine = engine_holder[0]
console.print(
f" [{GREEN}]✦[/{GREEN}] [bold]Gemma 3 neural core is fully operational[/bold]"
)
scanner = StarryScanner()
console.print(f" [{GREEN}]✦[/{GREEN}] MIME scanner initialized")
cwd = os.getcwd()
try:
formatter = StarryFormatter(cwd)
except OSError as exc:
console.print(
Panel(
f"[bold {RED}]Cannot create output directory:[/bold {RED}]\n\n{exc}",
border_style=RED,
title="⚠ Fatal Error",
)
)
sys.exit(1)
console.print(f" [{GREEN}]✦[/{GREEN}] Output → [dim]{formatter.output_dir}[/dim]")
# ── PHASE 2: DEEP SCAN ────────────────────────────────────────
_phase(2, "DEEP SCAN", "🔍")
resources = _animated_scan(scanner, cwd)