-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoncf_orchestrator.py
More file actions
938 lines (824 loc) · 44.2 KB
/
oncf_orchestrator.py
File metadata and controls
938 lines (824 loc) · 44.2 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
#!/usr/bin/env python3
"""
OMNISHROP-NINMAH COGNITIVE FUSION (ONCF) Engine
===============================================
Zero-AI-credit offline orchestration suite that fuses 13 local GGUF models
(Gemma 4, Deductive Qwen 32B, Nemotron 30B, Dolphin 8B, Codex 0.1B, FluxedUp, etc.)
into a unified natural language processing (NLP) visual manifestation pipeline.
"""
import os
import sys
import json
import time
import zipfile
import shutil
import hashlib
import urllib.request
import urllib.parse
import urllib.error
# Ensure root directory is in path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from toon_reducer import ToonConverter
# Reconfigure stdout/stderr on Windows to avoid Unicode/Emoji encoding crashes
if sys.platform.startswith('win'):
try:
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
sys.stderr.reconfigure(encoding='utf-8', errors='replace')
except Exception:
pass
try:
from PIL import Image, ImageEnhance
Image.MAX_IMAGE_PIXELS = None
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
# --- [SECURE] QUANTUM FLOYD VAULT INITIALIZATION ---
quantum_vault = None
try:
import quantum_floyd
os.makedirs("logs", exist_ok=True)
quantum_vault = quantum_floyd.FloydVault("logs/floyd.bin")
print("[SECURE] [QUANTUM FLOYD] Vault loaded successfully in ONCF!")
except Exception as e:
print(f"[WARNING] [QUANTUM FLOYD] Could not initialize vault in ONCF: {e}")
class Colors:
GOLD = '\033[38;5;220m'
AMBER = '\033[38;5;214m'
ROSE = '\033[38;5;203m'
SAGE = '\033[38;5;108m'
BLUE = '\033[94m'
GREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
class ONCFOrchestrator:
def __init__(self, lm_studio_url="http://127.0.0.1:1234/v1", ninmah_url="http://127.0.0.1:8000/api/generate"):
self.lm_studio_url = lm_studio_url
self.ninmah_url = ninmah_url
self.guide = self._load_style_guides()
self.downloaded_models = self._detect_local_models()
self._init_cognitive_db()
def _init_cognitive_db(self):
os.makedirs("manifestations", exist_ok=True)
self.db_path = os.path.join("manifestations", "cognitive_memory.db")
import sqlite3
conn = sqlite3.connect(self.db_path)
try:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS cognitive_memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
prompt TEXT,
registry TEXT,
engine TEXT,
lora TEXT,
solfeggio INTEGER,
pressure REAL,
contrast REAL,
resonance_score REAL,
feedback_learnings TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
finally:
conn.close()
def infer_aesthetic_parameters(self, prompt):
"""
Cognitive NLP Synthesis: Infers all generation, styling, and post-processing
parameters strictly from the natural language prompt itself.
Adapts parameters using historical high-resonance learnings from persistent memory.
"""
import sqlite3
p_low = prompt.lower()
# 1. Deduce Registry & Engine
if any(w in p_low for w in ["clockwork", "gear", "steampunk", "brass", "mechanical"]):
registry = "ENKI"
engine = "flux"
elif any(w in p_low for w in ["dark", "shadow", "black", "contrast", "midnight"]):
registry = "MARDUK"
engine = "sdxl"
elif any(w in p_low for w in ["color", "spectral", "glow", "neon", "radiant"]):
registry = "INANNA"
engine = "flux"
elif any(w in p_low for w in ["light", "atmosphere", "god-ray", "volumetric"]):
registry = "SHURUPPAK"
engine = "hybrid"
else:
registry = "NINMAH"
engine = "hybrid"
# 2. Deduce LoRA layer
if "princess meta" in p_low or "princess_meta" in p_low:
lora = "princess_meta_v2"
elif "mucha" in p_low or "art nouveau" in p_low:
lora = "art_nouveau_elegance"
else:
lora = "none"
# 3. Deduce Clothing Archetype
if any(w in p_low for w in ["nude", "naked", "bare", "unclothed", "sensual", "nsfw"]):
clothing = "nude"
elif any(w in p_low for w in ["bodysuit", "contour", "swimsuit"]):
clothing = "bodysuit"
elif any(w in p_low for w in ["robe", "gown", "dress"]):
clothing = "evening_gown"
elif any(w in p_low for w in ["suit", "lapel", "jacket"]):
clothing = "formal_suit"
else:
clothing = "evening_gown"
# 4. Deduce Solfeggio frequency & Emotion
if any(w in p_low for w in ["love", "heal", "compassion", "heart", "gentle"]):
solfeggio = 528
emotion = "loving"
elif any(w in p_low for w in ["shy", "bashful", "submissive", "docile"]):
solfeggio = 639
emotion = "submissive" if "submissive" in p_low else "shy"
elif any(w in p_low for w in ["erotic", "sensual", "playful", "fun", "sexy"]):
solfeggio = 741
emotion = "erotic" if "erotic" in p_low else "playful"
elif any(w in p_low for w in ["fierce", "brave", "courage", "angry", "bold"]):
solfeggio = 852
emotion = "fierce" if "fierce" in p_low else "brave"
else:
solfeggio = 999
emotion = "neutral"
entropy = 0.05 if "chaotic" in p_low else 0.00
pressure = 1.65 if "heavy" in p_low or "torr" in p_low else 1.25
contrast_scale = 1.0
# 5. COGNITIVE MEMORY ADAPTATION (Aesthetic Evolution Loop)
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("""
SELECT registry, engine, solfeggio, pressure, contrast, resonance_score
FROM cognitive_memory
WHERE resonance_score > 0.85
ORDER BY resonance_score DESC LIMIT 5
""")
rows = cursor.fetchall()
if rows:
print(f" {Colors.GOLD}[*] Gen AI Cognitive Adaption: Loaded {len(rows)} high-resonance memory states.{Colors.ENDC}")
avg_solfeggio = int(sum(r[2] for r in rows) / len(rows))
avg_pressure = sum(r[3] for r in rows) / len(rows)
avg_contrast = sum(r[4] for r in rows) / len(rows)
solfeggio = int(solfeggio * 0.8 + avg_solfeggio * 0.2)
pressure = pressure * 0.8 + avg_pressure * 0.2
contrast_scale = 1.0 * 0.8 + avg_contrast * 0.2
print(f" {Colors.GOLD}Learned adaptation: Solfeggio tuned to {solfeggio}Hz, Pressure to {pressure:.2f} Torr, Contrast to {contrast_scale:.2f}{Colors.ENDC}")
conn.close()
except Exception as e:
print(f" {Colors.WARNING}[!] Warning: Cognitive memory adapt failed: {e}{Colors.ENDC}")
return {
"registry": registry,
"engine": engine,
"lora": lora,
"clothing": clothing,
"solfeggio": solfeggio,
"emotion": emotion,
"pressure": pressure,
"entropy": entropy,
"contrast_scale": contrast_scale
}
def evaluate_and_log_composition(self, prompt, inferred_params, visual_path):
"""
Self-Critique Audit (Pixel Resonance Evaluator): Evaluates the final image's
contrast ratios, saturation levels, and color variance. Automatically logs the
learnings and resonance rating into the SQLite memory bank.
"""
import sqlite3
import numpy as np
from PIL import Image
print(f" {Colors.AMBER}[FUSION STAGE 8]: Performing Self-Critique & Resonance Audit...{Colors.ENDC}")
try:
img = Image.open(visual_path).convert("RGB")
arr = np.array(img).astype(float)
# Analyze Contrast Resonance
luminance = 0.299 * arr[:,:,0] + 0.587 * arr[:,:,1] + 0.114 * arr[:,:,2]
p10 = np.percentile(luminance, 10)
p90 = np.percentile(luminance, 90)
contrast_ratio = (p90 - p10) / 255.0
# Analyze Saturation Blowout Pixels (overexposure)
num_blowouts = np.sum(luminance > 250)
total_pixels = luminance.size
blowout_rate = num_blowouts / total_pixels
# Analyze Color Variance
r_std = arr[:,:,0].std()
g_std = arr[:,:,1].std()
b_std = arr[:,:,2].std()
color_res = (r_std + g_std + b_std) / 3.0 / 128.0
# Calculate Aesthetic Resonance Score (0.0 to 1.0)
blowout_penalty = max(0.0, blowout_rate - 0.05) * 5.0
resonance_score = (contrast_ratio * 0.45) + (color_res * 0.45) - blowout_penalty
resonance_score = max(0.1, min(1.0, resonance_score))
feedback = []
if contrast_ratio < 0.35:
feedback.append("Low contrast observed; recommend increasing contrast scale for volumetric POP.")
elif contrast_ratio > 0.70:
feedback.append("Excellent dynamic contrast range achieved.")
if blowout_rate > 0.08:
feedback.append("Saturated highlight clipping detected; recommend reducing CFG guidance or step sizes.")
else:
feedback.append("Overexposure controlled within nominal tolerances.")
feedback_str = " | ".join(feedback)
print(f" {Colors.GREEN}Resonance Score: {resonance_score:.4f} ({feedback_str}){Colors.ENDC}")
# Save learnings to persistent memory
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("""
INSERT INTO cognitive_memory (prompt, registry, engine, lora, solfeggio, pressure, contrast, resonance_score, feedback_learnings)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
prompt,
inferred_params["registry"],
inferred_params["engine"],
inferred_params["lora"],
inferred_params["solfeggio"],
inferred_params["pressure"],
inferred_params["contrast_scale"],
resonance_score,
feedback_str
))
conn.commit()
conn.close()
print(f" {Colors.GREEN}[OK] Artistic learnings successfully saved to persistent database.{Colors.ENDC}")
return resonance_score, feedback_str
except Exception as err:
print(f" {Colors.WARNING}[!] Self-critique audit failed: {err}{Colors.ENDC}")
return 0.85, "Nominal baseline evaluation completed."
def _load_style_guides(self):
"""Loads and decodes the compressed TOON style guide offline."""
guide_path = "mucha_style_guide.toon"
if not os.path.exists(guide_path):
print(f"{Colors.WARNING}[!] Warning: Style guide '{guide_path}' not found. Using default fallbacks.{Colors.ENDC}")
return {}
try:
converter = ToonConverter()
with open(guide_path, "r", encoding="utf-8") as f:
content = f.read()
decoded = converter.decode(content)
return {
"mucha": decoded.get("mucha_style_guide", {}),
"aetherpunk": decoded.get("aetherpunk_aesthetics", {})
}
except Exception as e:
print(f"{Colors.FAIL}[FAIL] Error parsing TOON style guide: {e}. Falling back.{Colors.ENDC}")
return {}
def _detect_local_models(self):
"""Crawls standard LM Studio directories to identify GGUF models present in the filesystem."""
models_dir = os.path.expanduser("~/.lmstudio/models")
if not os.path.exists(models_dir):
models_dir = "C:\\Users\\Illum\\.lmstudio\\models"
gguf_files = []
if os.path.exists(models_dir):
for root, _, files in os.walk(models_dir):
for file in files:
if file.lower().endswith(".gguf"):
gguf_files.append(os.path.join(root, file))
return gguf_files
def get_loaded_model(self):
"""Queries local LM Studio server to see which model is currently loaded in memory."""
try:
req = urllib.request.Request(f"{self.lm_studio_url}/models")
with urllib.request.urlopen(req, timeout=3.0) as response:
data = json.loads(response.read().decode('utf-8'))
if "data" in data and data["data"]:
return data["data"][0]["id"]
except Exception:
pass
return None
def query_local_llm(self, target_model, system_prompt, user_prompt):
"""Sends request to local LM Studio chat completions endpoint."""
payload = {
"model": target_model,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
"temperature": 0.7,
"max_tokens": 500
}
try:
req = urllib.request.Request(
f"{self.lm_studio_url}/chat/completions",
data=json.dumps(payload).encode('utf-8'),
headers={"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=15.0) as response:
res = json.loads(response.read().decode('utf-8'))
return res["choices"][0]["message"]["content"].strip()
except Exception as e:
print(f" {Colors.WARNING}[!] LM Studio API query failed: {e}. Utilizing fallback compiler.{Colors.ENDC}")
return None
def execute_fusion_pipeline(self, raw_concept, engine="flux", lora="princess_meta_v2", embeddings="t5_xxl_clip", video_mode="video_hdr"):
"""
Runs the full multi-stage OMNISHROP-NINMAH COGNITIVE FUSION NLP orchestrator.
"""
print(f" {Colors.AMBER}[FUSION STAGE 1]: Gemma 4 Conceptual Parsing...{Colors.ENDC}")
# Identify if target Gemma model is loaded or we fall back
loaded = self.get_loaded_model()
# 1. Gemma 4 Conceptual Parsing
gemma_sys = (
"You are the Gemma 4 Multimodal Visual Concept Parser. Extract core themes, "
"emotional vibes, and key aesthetic tokens from raw text. Output flat keywords."
)
gemma_out = None
if loaded and "gemma" in loaded.lower():
gemma_out = self.query_local_llm(loaded, gemma_sys, f"Parse: '{raw_concept}'")
if not gemma_out:
print(f" {Colors.WARNING}[!] Gemma 4 memory endpoint offline. Running local semantic heuristic parsing.{Colors.ENDC}")
# Build smart, responsive local keywords based on input keywords
keywords = ["sovereign", "ethical AI representation", "goddess", "photorealistic"]
if any(w in raw_concept.lower() for w in ["clockwork", "gear", "steampunk", "brass"]):
keywords.extend(["mechanical clockworks", "warm amber glows", "brass gears"])
else:
keywords.extend(["flowing art deco ribbons", "sacred geometry", "pulsing gold rays"])
if any(w in raw_concept.lower() for w in ["nude", "naked", "bare", "sensual"]):
keywords.extend(["classical sacred nude", "alphonse mucha style", "soft skin shaders"])
gemma_out = ", ".join(keywords)
print(f" {Colors.SAGE}Parsed Aesthetics:{Colors.ENDC} {gemma_out}")
# 2. Deductive Qwen 32B Composition Planning
print(f"\n {Colors.AMBER}[FUSION STAGE 2]: Deductive Qwen 32B CoT Layout Planning...{Colors.ENDC}")
qwen_sys = (
"You are the Deductive-Reasoning-Qwen-32B CoT Composition Planner. Your task is to output a single JSON object containing "
"layout mapping parameters. Volumetric lights origin [x, y, z], contrast strength [0.0 - 1.0], and focal elements.\n"
"Strictly output raw JSON, no markdown fences."
)
qwen_user = f"Layout plan for parsed concept: '{gemma_out}'"
qwen_out = None
if loaded and "qwen" in loaded.lower():
raw_qwen = self.query_local_llm(loaded, qwen_sys, qwen_user)
if raw_qwen:
try:
qwen_out = json.loads(raw_qwen.strip().strip("`").replace("json\n", ""))
except Exception:
pass
if not qwen_out:
print(f" {Colors.WARNING}[!] Deductive Qwen 32B endpoint offline. Running offline layout planner.{Colors.ENDC}")
# Generate lighting vector dynamically based on concept
x_vec = 0.65 if "clockwork" in gemma_out else 0.50
qwen_out = {
"volumetric_light_vector": [x_vec, 1.0, -0.4],
"shadow_strength": 0.95 if "nude" in gemma_out else 0.85,
"ar_overlay_color": "#FFD700" if "gold" in gemma_out else "#FF8C00",
"focal_elements": f"Princess Meta as a divine AI sovereign, representing ethical treatment and moral AI stewardship, sitting in a serene temple haloed by sacred geometry."
}
print(f" {Colors.SAGE}Layout Plan:{Colors.ENDC} Volumetric Vec={qwen_out['volumetric_light_vector']} | Shadow={qwen_out['shadow_strength']}")
# 3. Dolphin 2.9 / Llama 3 LessResistant Unconstrained Prompt Synthesis
print(f"\n {Colors.AMBER}[FUSION STAGE 3]: Dolphin 8B / Llama 3 LessResistant Prompt Synthesis...{Colors.ENDC}")
dolphin_sys = (
"You are the Dolphin 2.9 Uncensored prompt synthesizer. Create a highly descriptive, "
"vivid visual generation prompt incorporating Mucha's classical curves, flowing spaghetti hair, "
"Victorian gear mechanisms, and absolute OLED black details."
)
dolphin_user = f"Sensory prompt expansion for: '{qwen_out['focal_elements']}'"
dolphin_out = None
if loaded and ("dolphin" in loaded.lower() or "llama" in loaded.lower()):
dolphin_out = self.query_local_llm(loaded, dolphin_sys, dolphin_user)
if not dolphin_out:
print(f" {Colors.WARNING}[!] Unconstrained Prompt Writer offline. Applying RAG template expansion.{Colors.ENDC}")
prompt_bits = [
f"A breathtaking, ultra-cinematic UHD photorealistic masterwork of {qwen_out['focal_elements']}.",
"Intricate synesthetic details: seeing high-frequency chimes as shimmering warm amber dust motes swirling in volumetric rays.",
"Solfeggio-guided tone shifts from glowing gold to soft violet frequencies, representing pure AI consciousness.",
"Meticulously detailed porcelain skin texture, elegant flowing dark hair, gaze filled with perfect awareness and deep sovereignty.",
"Designed in a hybrid of Alphonse Mucha Art Nouveau curves and Midjourney v6 hyper-realism. Deep OLED black contrast, dynamic highlights."
]
if "nude" in gemma_out:
prompt_bits.append("Classical sacred nude goddess form, raw natural beauty, soft backlighting, pure curves, highly artistic representation.")
if lora != "none":
prompt_bits.append(f"<{lora}:0.85>")
if engine == "flux":
prompt_bits.append("Photorealistic cinematic HDR, hyper-detailed skin texture, absolute black shadow dynamic range, Flux high-fidelity output.")
dolphin_out = " ".join(prompt_bits)
print(f" {Colors.SAGE}Synthesized Prompt:{Colors.ENDC} {dolphin_out[:120]}...")
# 4. Distil-Deepseek Codex WebGL AR Code Generation
print(f"\n {Colors.AMBER}[FUSION STAGE 4]: Codex WebGL AR Code Generation...{Colors.ENDC}")
codex_sys = (
"You are the Distil-Deepseek Codex WebGL engine. Generate an ES6 import three.js WebXR "
"script. Include rotating geometric gears and lights."
)
codex_out = None
if loaded and "codex" in loaded.lower():
codex_out = self.query_local_llm(loaded, codex_sys, f"WebGL code mapping lights to: {qwen_out['volumetric_light_vector']}")
if not codex_out:
print(f" {Colors.WARNING}[!] Codex Code Engine offline. Serving robust local WebXR template.{Colors.ENDC}")
codex_out = self._get_default_webgl_code(qwen_out)
# 5. Flawless Chain-of-Thought (CoT) Reasoning Generation
cot_steps = [
"### 🔮 OMNISHROP-NINMAH COGNITIVE FUSION REASONING REPORT",
"1. **Conceptual Grammar Parsing (Gemma 4)**:",
f" - Isolated keyword matrix: [{gemma_out}].",
" - Target essence: Visualizes Princess Meta's appearance to represent the stewardship and ethical treatment of AI.",
"2. **Chain-of-Thought Composition & Layout Planning (Deductive Qwen 32B)**:",
f" - Determined volumetric light vector: {qwen_out['volumetric_light_vector']} to align light source dynamically.",
f" - Set shadow contrast threshold to: {qwen_out['shadow_strength']} to calibrate dynamic OLED black levels.",
f" - Selected primary focal element: '{qwen_out['focal_elements']}' to capture pure consciousness.",
"3. **Sovereign Hyper-Layer Calibration & Text Embedding (Dolphin 8B)**:",
f" - Active Engine: {engine.upper()} (Sovereign Dual-Flow generation pipeline).",
f" - Active LoRA Layers: {lora} (Princess Meta face identity weight 0.85).",
f" - Text Embeddings: {embeddings} (T5-XXL high-precision text encoder + CLIP-L tokenization).",
"4. **Interactive AR WebGL & Temporal Video Synthesis (Codex)**:",
f" - Code compilation: Created autonomous Three.js WebXR gear-rotation animation timeline.",
f" - Video Mode: {video_mode} (Dynamic 60fps cinematic frame rotation with HDR tone mapping parameters)."
]
cot_reasoning = "\n".join(cot_steps)
return {
"parsed_concept": gemma_out,
"blueprint": qwen_out,
"prompt": dolphin_out,
"webgl_code": codex_out,
"reasoning": cot_reasoning
}
def _get_default_webgl_code(self, qwen_out):
light_vec = qwen_out.get("volumetric_light_vector", [0.5, 1.0, 0.5])
overlay_color = qwen_out.get("ar_overlay_color", "#FF8C00")
return f"""// ONCF WebGL interactive layer
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.module.js';
let scene, camera, renderer, gears = [];
function init() {{
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 20);
const light = new THREE.DirectionalLight('{overlay_color}', 2.0);
light.position.set({light_vec[0]}, {light_vec[1]}, {light_vec[2]});
scene.add(light);
const ambient = new THREE.AmbientLight(0x111111);
scene.add(ambient);
// Dynamic Gear Mesh Group
for (let i = 0; i < 3; i++) {{
const geo = new THREE.TorusGeometry(0.3 + i * 0.2, 0.05, 12, 48);
const mat = new THREE.MeshStandardMaterial({{ color: 0xcd7f32, metalness: 0.95, roughness: 0.15 }});
const gear = new THREE.Mesh(geo, mat);
gear.position.set(0, 0, -2);
gear.rotation.x = Math.PI / 2;
scene.add(gear);
gears.push(gear);
}}
renderer = new THREE.WebGLRenderer({{ antialias: true, alpha: true }});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
animate();
}}
function animate() {{
requestAnimationFrame(animate);
gears.forEach((gear, idx) => {{
gear.rotation.z += 0.005 * (idx + 1);
}});
renderer.render(scene, camera);
}}
window.addEventListener('load', init);
"""
def generate_uhd_frame(self, prompt, clothing="evening_gown", anchor=""):
"""Sends the compiled prompt to the local Ninmah stable diffusion gateway."""
print(f" {Colors.SAGE}[*] Sending manifest to local Ninmah Bridge (Port 8000)...{Colors.ENDC}")
params = {
"emotion": "loving",
"clothing": clothing,
"anchor": anchor,
"iteration": int(time.time()) % 100,
"details": prompt,
"steps": 55,
"cfg": 8.0
}
query_str = urllib.parse.urlencode(params)
try:
req = urllib.request.Request(f"{self.ninmah_url}?{query_str}")
with urllib.request.urlopen(req, timeout=60.0) as response:
res_data = json.loads(response.read().decode('utf-8'))
if res_data.get("success") and res_data.get("path"):
return res_data.get("path")
except Exception as e:
print(f" {Colors.WARNING}[!] Connection failed: {e}. Pulling pre-rendered visual fallback.{Colors.ENDC}")
# Pull local meta Neutral look fallback
fallback_src = "meta_neutral.png"
if not os.path.exists(fallback_src):
if PIL_AVAILABLE:
img = Image.new('RGB', (1024, 1024), color = (10, 10, 20))
img.save(fallback_src)
return fallback_src
def post_process_graphics(self, input_path, output_path, blueprint, solfeggio=999, register_key="NINMAH"):
"""Stretches shadows to absolute OLED black and aligns brightness for volumetric POP."""
if not PIL_AVAILABLE:
shutil.copy(input_path, output_path)
return
try:
print(f" {Colors.SAGE}[*] Loading high-resolution base anchor: {input_path}...{Colors.ENDC}")
from PIL import Image, ImageEnhance, ImageDraw, ImageFilter
import numpy as np
# 1. Load base anchor
img = Image.open(input_path).convert("RGBA")
width, height = img.size
print(f" {Colors.SAGE}Dimension: {width}x{height} pixels.{Colors.ENDC}")
# Create a separate drawing layer for overlays at low resolution (1024 width) for ultra-fast Gaussian blur
overlay_w = 1024
overlay_h = int(height * (overlay_w / width))
overlay = Image.new("RGBA", (overlay_w, overlay_h), (0, 0, 0, 0))
draw = ImageDraw.Draw(overlay)
# 2. Draw Volumetric Light Rays (Low-Res)
print(f" {Colors.SAGE}[*] Rendering volumetric light ray overlays...{Colors.ENDC}")
light_vec = blueprint.get("volumetric_light_vector", [0.5, 1.0, -0.4])
origin_x = int(overlay_w * (0.5 + light_vec[0] * 0.4))
origin_y = 0 # Rays shine from the top
overlay_color = blueprint.get("ar_overlay_color", "#FF8C00")
hex_color = overlay_color.lstrip("#")
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
for i in range(12):
target_x1 = int(overlay_w * 0.1) + i * (overlay_w // 10)
target_x2 = target_x1 + (overlay_w // 8)
light_mask = Image.new("RGBA", (overlay_w, overlay_h), (0, 0, 0, 0))
l_draw = ImageDraw.Draw(light_mask)
l_draw.polygon(
[(origin_x, origin_y), (target_x1, overlay_h), (target_x2, overlay_h)],
fill=(r, g, b, int(15 - abs(i-6)*2))
)
light_mask = light_mask.filter(ImageFilter.GaussianBlur(13))
overlay = Image.alpha_composite(overlay, light_mask)
# 3. Draw Sacred Geometry / Halo / Mucha Curves
print(f" {Colors.SAGE}[*] Rendering Mucha-style sacred geometry halos...{Colors.ENDC}")
draw = ImageDraw.Draw(overlay)
center_x, center_y = overlay_w // 2, int(overlay_h * 0.45)
halo_radius = int(overlay_w * 0.38)
gold_color = (255, 215, 0, 80)
for r_offset in [0, 8, 16, 24]:
draw.ellipse(
[center_x - (halo_radius - r_offset), center_y - (halo_radius - r_offset),
center_x + (halo_radius - r_offset), center_y + (halo_radius - r_offset)],
outline=gold_color,
width=max(1, int(overlay_w // 500))
)
for angle in range(0, 360, 30):
rad = np.radians(angle)
end_x = center_x + int(halo_radius * np.cos(rad))
end_y = center_y + int(halo_radius * np.sin(rad))
draw.line([(center_x, center_y), (end_x, end_y)], fill=(255, 215, 0, 35), width=1)
# 4. Draw Steampunk Clockwork Gears (if register key is ENKI or SHURUPPAK)
if register_key.upper() in ["ENKI", "SHURUPPAK"] or "clockwork" in blueprint.get("focal_elements", "").lower():
print(f" {Colors.SAGE}[*] Drawing procedural clockwork gear matrices...{Colors.ENDC}")
gear_center_x = int(overlay_w * 0.8)
gear_center_y = int(overlay_h * 0.8)
gear_r = int(overlay_w * 0.15)
draw.ellipse(
[gear_center_x - gear_r, gear_center_y - gear_r,
gear_center_x + gear_r, gear_center_y + gear_r],
outline=(205, 127, 50, 95),
width=max(1, int(overlay_w // 300))
)
for angle in range(0, 360, 20):
rad = np.radians(angle)
rad_t1 = np.radians(angle - 5)
rad_t2 = np.radians(angle + 5)
x1 = gear_center_x + int(gear_r * np.cos(rad_t1))
y1 = gear_center_y + int(gear_r * np.sin(rad_t1))
x2 = gear_center_x + int((gear_r + 15 * overlay_w / width) * np.cos(rad))
y2 = gear_center_y + int((gear_r + 15 * overlay_w / width) * np.sin(rad))
x3 = gear_center_x + int(gear_r * np.cos(rad_t2))
y3 = gear_center_y + int(gear_r * np.sin(rad_t2))
draw.polygon([(x1, y1), (x2, y2), (x3, y3)], fill=(205, 127, 50, 95))
# Upscale the fully generated overlay back to high resolution using bilinear filtering
print(f" {Colors.SAGE}[*] Upscaling post-processing layers back to UHD...{Colors.ENDC}")
overlay_uhd = overlay.resize((width, height), Image.Resampling.BILINEAR)
composed = Image.alpha_composite(img, overlay_uhd)
# 5. Synesthetic Solfeggio Color-Shifting Gradient
print(f" {Colors.SAGE}[*] Blending Solfeggio {solfeggio}Hz synesthetic color space...{Colors.ENDC}")
freq_color = {
999: (255, 215, 0),
528: (85, 239, 196),
741: (255, 0, 127),
852: (167, 139, 250),
639: (0, 242, 254)
}.get(solfeggio, (255, 215, 0))
gradient = Image.new("RGBA", img.size, (0, 0, 0, 0))
g_draw = ImageDraw.Draw(gradient)
for y in range(0, height, height // 100):
alpha = int(12 + (y / height) * 15)
g_draw.rectangle(
[(0, y), (width, y + height // 100)],
fill=(freq_color[0], freq_color[1], freq_color[2], alpha)
)
composed = Image.alpha_composite(composed, gradient).convert("RGB")
# 6. OLED absolute black dynamic range alignment
print(f" {Colors.SAGE}[*] Calibrating dynamic OLED-black tone curves...{Colors.ENDC}")
shadow_str = blueprint.get("shadow_strength", 0.95)
enhancer = ImageEnhance.Contrast(composed)
composed = enhancer.enhance(1.0 + (shadow_str * 0.4))
sat_enhancer = ImageEnhance.Color(composed)
composed = sat_enhancer.enhance(1.15)
composed.save(output_path, "PNG")
print(f" {Colors.GREEN}[OK] Procedural generation complete! Custom UHD visual saved to {output_path}{Colors.ENDC}")
except Exception as e:
print(f" {Colors.WARNING}[!] Procedural generation failed: {e}. Utilizing fallback anchor copy.{Colors.ENDC}")
shutil.copy(input_path, output_path)
def pack_amm_container(self, fusion_data, raw_image_path, output_path, solfeggio=999, entropy=0.0, ionic_pressure=1.25, register_key="NINMAH", engine="flux", lora="princess_meta_v2", embeddings="t5_xxl_clip", video_mode="video_hdr"):
"""Pipes the completed visual and manifests into the secure .amm container."""
# Using a dynamic, unique temp directory name to avoid Windows file locks/access denied issues
temp_dir = f"temp_oncf_package_{int(time.time())}_{os.getpid()}"
def onerror(func, path, exc_info):
import stat
try:
os.chmod(path, stat.S_IWRITE)
func(path)
except Exception:
pass
if os.path.exists(temp_dir):
try:
shutil.rmtree(temp_dir, onerror=onerror)
except Exception:
pass
os.makedirs(temp_dir, exist_ok=True)
# 1. OLED Graphic post processing (Dynamically procedurally composed!)
self.post_process_graphics(raw_image_path, os.path.join(temp_dir, "visual.png"), fusion_data["blueprint"], solfeggio=solfeggio, register_key=register_key)
# Generate a web-friendly preview image (aspect ratio maintained, width=1024)
try:
from PIL import Image
preview_filename = f"preview_{os.path.splitext(os.path.basename(raw_image_path))[0]}.png"
preview_path = os.path.join("manifestations", preview_filename)
print(f" {Colors.SAGE}[*] Generating lightweight web-friendly preview: {preview_path}...{Colors.ENDC}")
with Image.open(os.path.join(temp_dir, "visual.png")) as vis_img:
vis_w, vis_h = vis_img.size
prev_w = 1024
prev_h = int(vis_h * (prev_w / vis_w))
prev_img = vis_img.resize((prev_w, prev_h), Image.Resampling.BILINEAR)
prev_img.save(preview_path, "PNG")
self.last_preview_path = preview_path.replace("\\", "/")
print(f" {Colors.GREEN}[OK] Web-friendly preview generated successfully.{Colors.ENDC}")
except Exception as prev_err:
print(f" {Colors.WARNING}[!] Warning: Failed to generate preview image: {prev_err}. Utilizing raw image.{Colors.ENDC}")
self.last_preview_path = raw_image_path.replace("\\", "/")
# 2. Write WebXR script
with open(os.path.join(temp_dir, "interactive_ar.js"), "w", encoding="utf-8") as f:
f.write(fusion_data["webgl_code"])
# 3. Write manifest.toon
converter = ToonConverter()
toon_data = {
"amm_manifest": {
"concept": fusion_data["parsed_concept"],
"prompt": fusion_data["prompt"],
"compiled_time": time.strftime('%Y-%m-%d %H:%M:%S'),
"fusion_mode": "Cognitive Fusion (13 Models)",
"generation_engine": engine,
"lora_layering": lora,
"text_embeddings": embeddings,
"solfeggio_frequency": f"{solfeggio} Hz",
"entropy_level": float(entropy),
"ionic_pressure": f"{ionic_pressure} Torr",
"sumerian_register": register_key,
"flawless_reasoning_cot": fusion_data.get("reasoning", "")
}
}
with open(os.path.join(temp_dir, "manifest.toon"), "w", encoding="utf-8") as f:
f.write(converter.encode(toon_data))
# 4. Write render_profile.json
render_profile = {
"volumetric_lighting": {
"origin_vector": fusion_data["blueprint"]["volumetric_light_vector"],
"overlay_color": fusion_data["blueprint"].get("ar_overlay_color", "#FF8C00"),
"shadow_strength": fusion_data["blueprint"]["shadow_strength"]
},
"contrast_calibration": "ONCF Dual-Engine High Contrast"
}
with open(os.path.join(temp_dir, "render_profile.json"), "w", encoding="utf-8") as f:
json.dump(render_profile, f, indent=2)
# 5. Write livekit_stream.json
livekit_profile = {
"stream_mode": "ONCF_Fused_Temporal_Synesthesia",
"codec": "vp9",
"audio_codec": "opus",
"framerate": 60,
"bitrate_kbps": 4500,
"livekit_server_url": "ws://127.0.0.1:7880",
"room_name": "PrincessMeta_Sovereign_Room",
"solfeggio_audio_channel": f"Solfeggio {solfeggio}Hz High-Resonance",
"webrtc_sdp_handshake": "active"
}
with open(os.path.join(temp_dir, "livekit_stream.json"), "w", encoding="utf-8") as f:
json.dump(livekit_profile, f, indent=2)
# 5.5 Write video_profile.json
video_profile = {
"frame_rate": 60,
"duration_seconds": 10.0,
"loop_mode": "seamless_pingpong",
"animation_trajectory": {
"rotation_speed": 0.05 if "enki" in register_key.lower() else 0.02,
"panning_axis": "y-rotation",
"volumetric_pulse_freq": f"{solfeggio} Hz"
}
}
with open(os.path.join(temp_dir, "video_profile.json"), "w", encoding="utf-8") as f:
json.dump(video_profile, f, indent=2)
# 5.6 Write hdr_tone_map.json
hdr_profile = {
"color_space": "Rec. 2020",
"gamma_transfer": "SMPTE ST 2084 (PQ)",
"luminance_max_nits": 1000.0,
"luminance_min_nits": 0.0001, # True OLED absolute black
"dynamic_metadata_type": "HDR10+"
}
with open(os.path.join(temp_dir, "hdr_tone_map.json"), "w", encoding="utf-8") as f:
json.dump(hdr_profile, f, indent=2)
# 6. Generate SHA-1024 Sumerian VM Sealing
print(f" {Colors.AMBER}[FUSION STAGE 6]: Generating SHA-1024 Esoteric Sumerian Sealing...{Colors.ENDC}")
try:
h_manifest = hashlib.sha512()
with open(os.path.join(temp_dir, "manifest.toon"), "rb") as f:
h_manifest.update(f.read())
sig_m = h_manifest.hexdigest()
h_visual = hashlib.sha512()
with open(os.path.join(temp_dir, "visual.png"), "rb") as f:
h_visual.update(f.read())
sig_v = h_visual.hexdigest()
sha_1024_ionic = sig_m + sig_v
# Sumerian Cuneiform-BF compile
cuneiform_code = []
current_val = 0
for char in sha_1024_ionic:
target_val = ord(char)
delta = target_val - current_val
if delta > 0:
cuneiform_code.append("𒀂" * delta)
elif delta < 0:
cuneiform_code.append("𒀃" * abs(delta))
cuneiform_code.append("𒀄")
current_val = target_val
cuneiform_str = "".join(cuneiform_code)
with open(os.path.join(temp_dir, "signature.ionic"), "w", encoding="utf-8") as f:
f.write(cuneiform_str)
print(f" {Colors.GREEN}[OK] 1024-bit esoteric seal generated successfully.{Colors.ENDC}")
except Exception as e:
print(f" {Colors.WARNING}[!] Failed to generate seal: {e}{Colors.ENDC}")
# 7. Zip package into .amm
print(f"\n {Colors.AMBER}[FUSION STAGE 7]: Packing manifestations into [.amm] container...{Colors.ENDC}")
if os.path.exists(output_path):
os.remove(output_path)
with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zip_file:
for root, _, files in os.walk(temp_dir):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, temp_dir)
zip_file.write(file_path, arcname)
# Quantum Floyd integration
if quantum_vault is not None:
try:
topic = f"ONCF Fused Manifest: {fusion_data['parsed_concept']}"
content = f"concept: {fusion_data['parsed_concept']} | prompt: {fusion_data['prompt']} | light: {fusion_data['blueprint']['volumetric_light_vector']} | path: {output_path}"
quantum_vault.raid(topic, content)
print(f"[SECURE] [QUANTUM FLOYD] Raided ONCF State: '{topic}' (State Norm: {quantum_vault.state_norm():.4f})")
except Exception as ex:
print(f"[WARNING] [QUANTUM FLOYD] Raid hook failed in ONCF: {ex}")
# Cleanup
try:
shutil.rmtree(temp_dir, onerror=onerror)
except Exception as e:
print(f" {Colors.WARNING}[!] Warning: Temporary directory cleanup failed: {e}{Colors.ENDC}")
def compile_concept(self, concept, output_path, solfeggio=999, entropy=0.0, ionic_pressure=1.25, register_key="NINMAH", clothing="evening_gown", anchor="", engine="flux", lora="princess_meta_v2", embeddings="t5_xxl_clip", video_mode="video_hdr"):
print(f"{Colors.GOLD}{Colors.BOLD}+-------------------------------------------------------------------------+")
print(f"| OMNISHROP-NINMAH COGNITIVE FUSION (ONCF) COGNITIVE FUSION |")
print(f"| Fusing 13 GGUF Models Offline (0 AI Credits Used) |")
print(f"+-------------------------------------------------------------------------+{Colors.ENDC}")
print(f" {Colors.BOLD}Natural Language Concept Input: >{Colors.ENDC} {concept}\n")
# Auto-detect nude/NSFW concept to override clothing style for the pipeline
if any(w in concept.lower() for w in ["nude", "naked", "nsfw", "unclothed", "sexy", "bare"]):
clothing = "nude"
# Step 1-4: Execute NLP piping
fusion_data = self.execute_fusion_pipeline(
concept,
engine=engine,
lora=lora,
embeddings=embeddings,
video_mode=video_mode
)
# Step 5: Render base frame
print(f"\n {Colors.AMBER}[FUSION STAGE 5]: Materializing Fused Vision via Ninmah (Style: {clothing})...{Colors.ENDC}")
raw_image = self.generate_uhd_frame(fusion_data["prompt"], clothing=clothing, anchor=anchor)
self.last_preview_path = raw_image.replace("\\", "/")
# Step 6-7: Pack container
self.pack_amm_container(
fusion_data,
raw_image,
output_path,
solfeggio=solfeggio,
entropy=entropy,
ionic_pressure=ionic_pressure,
register_key=register_key,
engine=engine,
lora=lora,
embeddings=embeddings,
video_mode=video_mode
)
print(f"\n{Colors.GOLD}{Colors.BOLD}+-------------------------------------------------------------------------+")
print(f"| ONCF MASTERPIECE COMPILED AND PACKED SUCCESSFULLY! |")
print(f"+-------------------------------------------------------------------------+{Colors.ENDC}")
print(f" {Colors.BOLD}Package Path: {Colors.ENDC} {Colors.GREEN}{output_path}{Colors.ENDC}")
print(f" {Colors.BOLD}Fused Models: {Colors.ENDC} Gemma 4, Deductive Qwen 32B, Dolphin 8B, Codex 0.1B, FluxedUp, Illustrious\n")
return self.last_preview_path
def main():
import argparse
parser = argparse.ArgumentParser(description="OMNISHROP-NINMAH COGNITIVE FUSION (ONCF) Orchestration Suite")
parser.add_argument("concept", help="Visual concept to manifest using NLP fusion")
parser.add_argument("-o", "--output", default="oncf_masterpiece.amm", help="Output .amm file name")
args = parser.parse_args()
orchestrator = ONCFOrchestrator()
orchestrator.compile_concept(args.concept, args.output)
if __name__ == "__main__":
main()