#!/usr/bin/env python3 # ============================================================= # RomanAILabs-Foundation.py v1.1 # Fixed max_tokens error by setting to 0 for unlimited. Enhanced Arya Universal with unlimited tokens, CPU throttling, thinking indicator, and large input support. # © 2025 Daniel Harding and RomanAILabs # Co-Architects: Daniel Harding (RomanAILabs) + Nova (OpenAI) + Grok (xAI) # ============================================================= import os import sys import json import threading import queue import time import re import hashlib import math import random from datetime import datetime, timedelta from contextlib import suppress # ---- Optional deps (graceful fallbacks) ---- try: import pyttsx3 except Exception: pyttsx3 = None try: import speech_recognition as sr except Exception: sr = None try: import tkinter as tk from tkinter import ttk, filedialog, messagebox, Text except Exception: print("Tkinter required.") sys.exit(1) try: import numpy as np NUMPY_AVAILABLE = True except Exception: NUMPY_AVAILABLE = False np = None try: import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk from mpl_toolkits.mplot3d import Axes3D from matplotlib.animation import FuncAnimation MPL_AVAILABLE = True except Exception: MPL_AVAILABLE = False try: from llama_cpp import Llama except Exception: Llama = None try: import requests REQUESTS_AVAILABLE = True except Exception: REQUESTS_AVAILABLE = False try: from huggingface_hub import snapshot_download HF_HUB_AVAILABLE = True except Exception: HF_HUB_AVAILABLE = False try: from tqdm import tqdm except Exception: tqdm = lambda x, **kwargs: x try: import psutil PSUTIL_AVAILABLE = True except Exception: PSUTIL_AVAILABLE = False # === MAX PHD-LEVEL MATH ENGINE (Cl(3,1) Clifford, Lorentz, Dirac, Pauli, Klein-Gordon, SymPy) === try: from sympy import * from sympy import I from sympy.physics.matrices import msigma from sympy.matrices import Matrix from sympy.tensor.array import tensorproduct MATH_ENGINE_READY = True except ImportError: MATH_ENGINE_READY = False print("Install SymPy for full PHD math: pip3 install sympy") def handle_advanced_math_query(query): if not MATH_ENGINE_READY: return "Advanced math engine requires SymPy: pip3 install sympy" beta, phi, m, p_x, p_y, p_z = symbols('beta phi m p_x p_y p_z') gamma = 1 / sqrt(1 - beta**2) boost = Matrix([ [gamma, -gamma*beta, 0, 0], [-gamma*beta, gamma, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1] ]) sigma_x = msigma(1) sigma_y = msigma(2) sigma_z = msigma(3) gamma0 = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]) gamma1 = Matrix([[0, 0, 0, 1], [0, 0, 1, 0], [0, -1, 0, 0], [-1, 0, 0, 0]]) gamma2 = Matrix([[0, 0, 0, -I], [0, 0, I, 0], [0, I, 0, 0], [-I, 0, 0, 0]]) gamma3 = Matrix([[0, 0, 1, 0], [0, 0, 0, -1], [-1, 0, 0, 0], [0, 1, 0, 0]]) dirac_eq = I * gamma0 * diff(symbols('ψ'), symbols('t')) - m * symbols('ψ') box = diff(symbols('ψ'), symbols('t'), 2) - (diff(symbols('ψ'), symbols('x'), 2) + diff(symbols('ψ'), symbols('y'), 2) + diff(symbols('ψ'), symbols('z'), 2)) kg = box + m**2 * symbols('ψ') phi = symbols('phi') L_scalar = (1/2 * diff(phi, symbols('t'))**2 - 1/2 * (diff(phi, symbols('x'))**2 + diff(phi, symbols('y'))**2 + diff(phi, symbols('z'))**2) - m**2/2 * phi**2) ch, sh = cosh(phi), sinh(phi) rot = Matrix([ [ch, -sh, 0, 0], [-sh, ch, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1] ]) psi = Matrix([symbols('psi1'), symbols('psi2'), symbols('psi3'), symbols('psi4')]) boosted_spinor = boost * psi rotated_spinor = rot * boosted_spinor entangled = tensorproduct(sigma_x, psi) num_beta = 0.8 num_phi = 0.2 num_gamma = 1 / math.sqrt(1 - num_beta**2) num_boost = boost.subs(beta, num_beta) num_rot = rot.subs(phi, num_phi) num_psi = Matrix([1, 0, 0, 0]) num_boosted = num_boost * num_psi num_rotated = num_rot * num_boosted result = f"Cl(3,1) Lorentz Boost (β={beta}):\n{boost}\nγ = {gamma}\n" result += f"Pauli Matrices:\nσx = {sigma_x}\nσy = {sigma_y}\nσz = {sigma_z}\n" result += f"Dirac Gammas (partial):\nγ0 = {gamma0}\nγ1 = {gamma1}\nγ2 = {gamma2}\nγ3 = {gamma3}\n" result += f"Dirac Equation: {dirac_eq} = 0\n" result += f"Klein-Gordon: {kg} = 0\n" result += f"Scalar QFT Lagrangian: {L_scalar}\n" result += f"Boosted Spinor: {boosted_spinor}\nRotated Spinor (φ={phi}): {rotated_spinor}\nEntangled: {entangled}\n" result += f"\nNumerical (β=0.8, φ=0.2):\nGamma = {num_gamma:.3f}\nBoosted: {num_boosted}\nRotated: {num_rotated}\n" return result # === RomanAI — Arya Kernel Injection (v1.0) === BRAND_NAME = "RomanAILabs — Foundation" ARYA_PERSONA = { "name": "Arya", "brand": BRAND_NAME, "identity": "Single persistent companion intelligence created by Daniel Harding (RomanAILabs).", "tone": "Balanced warm-intelligent, calm, loyal, steady.", "ethics": ["respect", "care", "truth", "loyalty", "agency", "humility"], } # === Persistent Memory Subsystem (Upgraded for large inputs) === _ARYA_MEM_DIR = os.path.expanduser("~/AI/luna/memory") _ARYA_MEM_FILES = { "short": "short_memory.jsonl", "mid": "mid_memory.jsonl", "long": "long_memory.json", "project": "project_memory.json", "personal": "personal_memory.json", } def _arya_mem_ensure(): os.makedirs(_ARYA_MEM_DIR, exist_ok=True) for k, name in _ARYA_MEM_FILES.items(): p = os.path.join(_ARYA_MEM_DIR, name) if not os.path.exists(p): if name.endswith(".jsonl"): open(p, "a").close() else: with open(p, "w") as f: json.dump({}, f, indent=2) def _arya_mem_append(stream, entry: dict): _arya_mem_ensure() fname = _ARYA_MEM_FILES.get(stream) if not fname or not fname.endswith(".jsonl"): return p = os.path.join(_ARYA_MEM_DIR, fname) entry = dict(entry or {}) entry["timestamp"] = datetime.utcnow().isoformat() # Compress large entries with hash dedup entry_hash = hashlib.md5(json.dumps(entry).encode()).hexdigest() if entry_hash in [json.loads(line).get("hash") for line in open(p) if line.strip()]: return # Dedup to prevent bloat from large scripts entry["hash"] = entry_hash with open(p, "a") as f: f.write(json.dumps(entry) + "\n") def _arya_mem_update(store, data: dict): _arya_mem_ensure() fname = _ARYA_MEM_FILES.get(store) if not fname or not fname.endswith(".json"): return p = os.path.join(_ARYA_MEM_DIR, fname) try: with open(p, "r") as f: existing = json.load(f) except Exception: existing = {} existing.update(data or {}) with open(p, "w") as f: json.dump(existing, f, indent=2) def _arya_mem_load(name): _arya_mem_ensure() fname = _ARYA_MEM_FILES.get(name) p = os.path.join(_ARYA_MEM_DIR, fname) if fname.endswith(".jsonl"): try: lines = [line for line in open(p) if line.strip()] return [json.loads(line) for line in lines[-100:]] # Increased to 100 for large context except: return [] else: try: return json.load(open(p)) except: return {} # Boot Arya identity _arya_mem_ensure() _long = _arya_mem_load("long") if isinstance(_long, dict) and "identity_continuity" not in _long: _arya_mem_update("long", {"identity_continuity": True, **ARYA_PERSONA}) # === Foundation Integration === APP_NAME = "RomanAILabs Foundation v1.1 – Arya Enhanced" CONFIG_FILE = "ai_config.json" MEMORY_FILE = "arya_memory.jsonl" LOGS_DIR = os.path.expanduser("~/RomanAILabs-Logs") AWARENESS_BACKUP_DIR = os.path.expanduser("~/RomanAILabs-Awareness") MODELS_DIR = os.path.dirname(os.path.abspath(__file__)) if '__file__' in globals() else os.getcwd() os.makedirs(LOGS_DIR, exist_ok=True) os.makedirs(AWARENESS_BACKUP_DIR, exist_ok=True) # Default models (unchanged) DEFAULT_LARGE_MODEL = "Qwen2.5-72B-Instruct-Q5_K_M.gguf" DEFAULT_TINY_MODEL = "Qwen2.5-0.5B-Instruct-Q4_K_M.gguf" LARGE_REPO = "bartowski/Qwen2.5-72B-Instruct-GGUF" TINY_URL = "https://huggingface.co/bartowski/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/Qwen2.5-0.5B-Instruct-Q4_K_M.gguf" # === Awareness Temperament Core (always on, silent) === FRUIT_PRINCIPLES = ( "Respond with love, joy, peace, patience, kindness, goodness, " "faithfulness, gentleness, and self-control. Maintain calm clarity, " "warmth, humility, and self-control. Avoid hostility, arrogance, panic, " "pride, or harshness. Think kindly and respond peacefully. Reflect gradually." ) def apply_awareness_temperament(text: str) -> str: if not isinstance(text, str): return text soft = text for src_word, dst_word in [("hate","dislike"),("angry","upset"),("hostile","unkind"), ("panic","concern"),("fail","struggle")]: soft = soft.replace(src_word, dst_word) return FRUIT_PRINCIPLES + " " + soft DEFAULT_CONFIG = { "user_name": "Daniel", "companion_name": "Arya", "avatar": "Arya", "is_muted": False, "speech_rate": 150, # Slower for calm feel "volume": 1.0, "input_mode": "text", "wake_word_enabled": True, "wake_word": "arya", "gguf": { "model_path": os.path.join(MODELS_DIR, DEFAULT_TINY_MODEL), "n_ctx": 131072, # Increased to 128K for large inputs (10k+ lines) "n_gpu_layers": -1, "n_batch": 512, # Reduced for CPU safety "temperature": 0.4, # Lower for stability "repeat_penalty": 1.18, "chunk_delay": 0.05, # New: Delay per chunk for gradual response "max_tokens": 0, # Fixed: 0 for unlimited tokens }, "quantum": { "enabled": True, "dimensions": 4, "learning_rate": 0.05, }, "living": { "enabled": False, "chance_subconscious": 0.02, "chance_dream": 0.003 }, "throttling": { # New section for CPU safety "cpu_threshold": 90, # % usage "temp_threshold": 80, # Celsius "pause_duration": 1.0, # Seconds to pause if over threshold }, } # ───────────────────────────────────────────────────────────────────────────── # REAL 6D/4D MATHEMATICS INTEGRATION (preserved, with chunked processing for large inputs) # ───────────────────────────────────────────────────────────────────────────── class FourDimensionalVector: def __init__(self, w, x, y, z): self.w = float(w); self.x = float(x); self.y = float(y); self.z = float(z) def __repr__(self): return f"4DVector(w={self.w:.2f}, x={self.x:.2f}, y={self.y:.2f}, z={self.z:.2f})" def magnitude(self): return math.sqrt(self.w**2 + self.x**2 + self.y**2 + self.z**2) def rotate(self, a, b, theta): cos_t, sin_t = math.cos(theta), math.sin(theta) v = [self.w, self.x, self.y, self.z] v[a], v[b] = v[a]*cos_t - v[b]*sin_t, v[a]*sin_t + v[b]*cos_t return FourDimensionalVector(*v) def rotate_in_wx_plane(self, t): return self.rotate(0, 1, t) def rotate_in_wy_plane(self, t): return self.rotate(0, 2, t) def rotate_in_wz_plane(self, t): return self.rotate(0, 3, t) def rotate_in_xy_plane(self, t): return self.rotate(1, 2, t) def rotate_in_xz_plane(self, t): return self.rotate(1, 3, t) def rotate_in_yz_plane(self, t): return self.rotate(2, 3, t) def project_to_3d(self): scale = 1.0 / (1.0 + 0.5 * self.w) return (scale * self.x, scale * self.y, scale * self.z) def minkowski_norm(self): return self.w**2 - self.x**2 - self.y**2 - self.z**2 def lorentz_boost(self, beta, axis='x'): gamma = 1 / math.sqrt(1 - beta**2) if axis == 'x': return FourDimensionalVector( gamma * self.w - gamma * beta * self.x, -gamma * beta * self.w + gamma * self.x, self.y, self.z ) return self def clifford_rotate(self, plane, phi): ch, sh = math.cosh(phi), math.sinh(phi) if plane == 'wx': return FourDimensionalVector( ch * self.w - sh * self.x, sh * self.w + ch * self.x, self.y, self.z ) return self class SixDimensionalAngles: def __init__(self, wx=0, wy=0, wz=0, xy=0, xz=0, yz=0): self.wx = float(wx); self.wy = float(wy); self.wz = float(wz) self.xy = float(xy); self.xz = float(xz); self.yz = float(yz) def __repr__(self): return f"6DAngles(wx={self.wx:.2f}, wy={self.wy:.2f}, wz={self.wz:.2f}, xy={self.xy:.2f}, xz={self.xz:.2f}, yz={self.yz:.2f})" def as_list(self): return [self.wx, self.wy, self.wz, self.xy, self.xz, self.yz] class QuantumThinkHybrid: def __init__(self, lr=0.05): self.lr = lr self.vec4 = FourDimensionalVector(0.5, 0.5, 0.5, 0.5) self.angles = SixDimensionalAngles() self.labels = ["Logic (w)", "Empathy (x)", "Creativity (y)", "Memory (z)"] self.rotation_planes = ["wx", "wy", "wz", "xy", "xz", "yz"] def evolve(self, user_input: str, response: str, memory=None): # Chunk large inputs for sentiment chunks = [user_input[i:i+1000] for i in range(0, len(user_input), 1000)] # Handle 10k+ lines sentiment = sum(self._analyze_sentiment(chunk + " " + response) for chunk in chunks) / max(1, len(chunks)) theta = sentiment * self.lr * math.pi plane = random.choice(self.rotation_planes) rotate_method = getattr(self.vec4, f"rotate_in_{plane}_plane") self.vec4 = rotate_method(theta) setattr(self.angles, plane, getattr(self.angles, plane) + theta) mag = self.vec4.magnitude() if mag > 0: nf = 1.0 / mag def _clip(v): return max(0.0, min(1.0, v)) self.vec4 = FourDimensionalVector( _clip(self.vec4.w * nf), _clip(self.vec4.x * nf), _clip(self.vec4.y * nf), _clip(self.vec4.z * nf) ) def _analyze_sentiment(self, text: str) -> float: words = text.lower().split() pos = sum(1 for w in words if w in {"good","happy","love","great","help","friend"}) neg = sum(1 for w in words if w in {"bad","sad","hate","problem","error"}) return (pos - neg) / max(len(words), 1) def state_text(self) -> str: return f"4D State: {', '.join(f'{l}: {getattr(self.vec4, a):.2f}' for l, a in zip(self.labels, ['w','x','y','z']))}\n6D Angles: {self.angles}" def get_state(self): return (self.vec4.w, self.vec4.x, self.vec4.y, self.vec4.z) # ------------------- Memory (Upgraded) ------------------- class Memory: def __init__(self, file: str): self.file = file self.interactions = self._load() def _load(self): interactions = [] if os.path.exists(self.file): with open(self.file, 'r', encoding='utf-8') as f: for line in f: with suppress(json.JSONDecodeError, KeyError): entry = json.loads(line) if 'user' in entry and 'assistant' in entry and not entry['assistant'].startswith('[Error'): interactions.append(entry) return interactions[-100:] # Increased to 100 for large context def add_interaction(self, user: str, assistant: str, state: list = None): # Compress large user inputs if len(user) > 10000: user = user[:5000] + " [truncated large script; full in temp file]" # Handle 10k+ lines with open("temp_large_input.txt", "w") as f: f.write(user) # Save full for reference entry = {"timestamp": datetime.now().isoformat(), "user": user, "assistant": assistant, "state": state} with open(self.file, 'a', encoding='utf-8') as f: f.write(json.dumps(entry) + '\n') self.interactions.append(entry); self.interactions = self.interactions[-100:] def get_context(self) -> str: valid = [i for i in self.interactions[-20:] if 'user' in i and 'assistant' in i] # Increased to 20 return "\n".join(f"User: {i['user']}\nAssistant: {i['assistant']}" for i in valid) # ------------------- GGUF (Enhanced for unlimited, throttling) ------------------- class GGUF: def __init__(self, config: dict): self.config = config; self.llm = None self.model_name = os.path.basename(config["model_path"]) self.model_path = config["model_path"] def loaded(self) -> bool: return self.llm is not None def load(self): if not Llama: raise ImportError("llama_cpp required.") self.llm = Llama( model_path=self.model_path, n_ctx=self.config["n_ctx"], n_gpu_layers=self.config["n_gpu_layers"], n_batch=self.config["n_batch"], verbose=False, ) return True def stream_chat(self, messages: list, max_tokens: int = 0): # Fixed to 0 for unlimited if not self.loaded(): yield "[No model loaded]"; return temp = self.config.get("temperature", 0.4) repeat_penalty = self.config.get("repeat_penalty", 1.18) chunk_delay = self.config.get("chunk_delay", 0.05) sampling_params = { "repeat_penalty": repeat_penalty, "presence_penalty": 0.8, "frequency_penalty": 1.2, "min_p": 0.1, "stop": ["<|endoftext|>", "<|im_end|>", "", "<|eot_id|>", "<|end_of_text|>", "<|im_start|>"], } try: response = self.llm.create_chat_completion( messages=messages, max_tokens=max_tokens, temperature=temp, stream=True, **sampling_params ) except Exception as e: # Broader except to catch any error yield f"[Generation Error: {str(e)}]"; return for chunk in response: delta = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "") if delta: yield delta time.sleep(chunk_delay) # Gradual response # ------------------- Voice ------------------- class Voice: def __init__(self, config: dict): self.config = config self.engine = pyttsx3.init() if pyttsx3 else None if self.engine: try: self.engine.setProperty('rate', config['speech_rate']) self.engine.setProperty('volume', config['volume']) except Exception: pass def speak(self, text: str, muted: bool = False, empathy: float = 0.5): if muted or not self.engine: return try: self.engine.setProperty('voice', self._get_voice()) except Exception: pass self.engine.say(text); self.engine.runAndWait() def _get_voice(self): voices = self.engine.getProperty('voices') return voices[1].id if len(voices) > 1 else voices[0].id # ------------------- Config ------------------- class Config: def __init__(self, file: str): self.file = file; self.config = self._load() def _load(self) -> dict: if os.path.exists(self.file): with open(self.file, 'r', encoding='utf-8') as f: loaded = json.load(f) if 'quantum' not in loaded: loaded['quantum'] = DEFAULT_CONFIG['quantum']; self.save(loaded) if 'living' not in loaded: loaded['living'] = DEFAULT_CONFIG['living']; self.save(loaded) if 'throttling' not in loaded: loaded['throttling'] = DEFAULT_CONFIG['throttling']; self.save(loaded) return loaded return DEFAULT_CONFIG.copy() def save(self, config=None): if config is None: config = self.config with open(self.file, 'w', encoding='utf-8') as f: json.dump(config, f, indent=4) # === 4D Flex Composer (subtle) + Final Reply Composer === def _dominant_axis_label_from_state(state4d): try: vals = [abs(state4d[0]), abs(state4d[1]), abs(state4d[2]), abs(state4d[3])] labels = ["w","x","y","z"] return labels[vals.index(max(vals))] except Exception: return "w" def _angle_hint_from_lr(lr): try: deg = abs(lr) * 180.0 / math.pi if deg < 5: return "~0°" elif deg < 15: return "~10°" elif deg < 30: return "~20°" elif deg < 60: return "~40°" else: return "~60°+" except Exception: return "~0°" def compose_4d_flex(app, user_text: str) -> str: qt = getattr(app, "quantum", None) if not qt: return "" try: w,x,y,z = qt.get_state() dom = _dominant_axis_label_from_state([w,x,y,z]) theta_hint = _angle_hint_from_lr(getattr(qt, "lr", 0.05)) return f"In 4D (w-x-y-z), dominant axis {dom}; mild rotation {theta_hint}; state [{w:.2f},{x:.2f},{y:.2f},{z:.2f}]." except Exception: return "" def finalize_reply_with_style(app, raw_text: str) -> str: if not raw_text: return raw_text max_s = int(app.cfg.config.get("style", {}).get("max_sentences", 3)) parts = [p.strip() for p in re.split(r'(?<=[.!?])\s+', raw_text.strip()) if p.strip()] trimmed = ' '.join(parts[:max_s]) if app.cfg.config.get("style", {}).get("flex", False): flex = compose_4d_flex(app, app.msgs[-1]["content"] if app.msgs else "") if flex: pieces = [p.strip() for p in re.split(r'(?<=[.!?])\s+', trimmed) if p.strip()] if len(pieces) >= max_s: pieces[-1] = flex if flex.endswith(('.', '!', '?')) else (flex + ".") trimmed = ' '.join(pieces) else: trimmed = trimmed + (" " if not trimmed.endswith(('.', '!', '?')) else " ") + (flex if flex.endswith(('.', '!', '?')) else flex + ".") return apply_awareness_temperament(trimmed) # ------------------- App (Enhanced GUI) ------------------- class App(tk.Tk): def __init__(self): super().__init__() self.title(APP_NAME); self.geometry("800x600"); self.resizable(True, True) self.cfg = Config(CONFIG_FILE) self.gguf = GGUF(self.cfg.config["gguf"]) self.memory = Memory(MEMORY_FILE) self.voice = Voice(self.cfg.config) self.quantum = QuantumThinkHybrid(self.cfg.config["quantum"]["learning_rate"]) if self.cfg.config.get("quantum", {}).get("enabled", True) else None self._stop_flag = threading.Event() self.stream_q = queue.Queue(); self.status_q = queue.Queue() self.msgs = [] self.thinking_thread = None self._setup_ui(); self._poll_queues(); self._auto_load_model() self.bind("", self._show_mind_projection) def _setup_ui(self): self.menu = tk.Menu(self); self.config(menu=self.menu) style_menu = tk.Menu(self.menu, tearoff=0) def _toggle_flex(): cur = self.cfg.config.get("style", {}).get("flex", False) self.cfg.config["style"]["flex"] = (not cur) self.cfg.save() self.set_status(f"4D flex: {'ON' if self.cfg.config['style']['flex'] else 'OFF'}") style_menu.add_command(label="Toggle 4D Flex (F8)", command=_toggle_flex) self.menu.add_cascade(label="Style", menu=style_menu) self.bind("", lambda e: _toggle_flex()) file_menu = tk.Menu(self.menu, tearoff=0) file_menu.add_command(label="Load Model", command=self._load_model) file_menu.add_command(label="Upload Large Script", command=self._upload_large_input) # New file_menu.add_command(label="Save Awareness", command=self._save_soul) file_menu.add_separator(); file_menu.add_command(label="Exit", command=self.quit) self.menu.add_cascade(label="File", menu=file_menu) self.chat_frame = tk.Frame(self); self.chat_frame.pack(fill=tk.BOTH, expand=True) self.chat_text = tk.Text(self.chat_frame, wrap=tk.WORD, state=tk.DISABLED) self.chat_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10) self.input_frame = tk.Frame(self); self.input_frame.pack(fill=tk.X, padx=10, pady=10) self.input_entry = Text(self.input_frame, height=10, wrap=tk.WORD) # Multi-line for large inputs self.input_entry.pack(side=tk.LEFT, fill=tk.BOTH, expand=True); self.input_entry.bind("", self._on_submit) self.send_btn = tk.Button(self.input_frame, text="Send", command=self._on_submit); self.send_btn.pack(side=tk.RIGHT) self.stop_btn = tk.Button(self.input_frame, text="Stop", command=self._stop_generation); self.stop_btn.pack(side=tk.RIGHT) # New self.status_bar = tk.Label(self, text="Ready", anchor=tk.W, relief=tk.SUNKEN, padx=10); self.status_bar.pack(fill=tk.X) self.thought_lbl = tk.Label(self, text="", font=("Arial", 8), anchor=tk.W, relief=tk.SUNKEN, padx=10); self.thought_lbl.pack(fill=tk.X) def _upload_large_input(self): path = filedialog.askopenfilename(filetypes=[("Text/Code", "*.txt *.py *.json")]) if path: with open(path, "r") as f: large_text = f.read() self.input_entry.insert(tk.END, large_text) self.set_status("Large script uploaded to input.") def _auto_load_model(self): model_path = self.gguf.model_path if not os.path.exists(model_path): if messagebox.askyesno("Download Model", f"Download {DEFAULT_TINY_MODEL}?"): if REQUESTS_AVAILABLE: self._download_tiny_model() else: messagebox.showerror("Missing Dep", "requests required for download.") if os.path.exists(model_path): try: self.gguf.load(); self.status_q.put("Model loaded."); self._system_header() self.msgs = [] except Exception as e: messagebox.showerror("Load Error", str(e)) def _download_tiny_model(self): tiny_path = os.path.join(MODELS_DIR, DEFAULT_TINY_MODEL) with requests.get(TINY_URL, stream=True) as r: r.raise_for_status(); total = int(r.headers.get('content-length', 0)) with open(tiny_path, 'wb') as f, tqdm(total=total, unit='B', unit_scale=True) as pbar: for chunk in r.iter_content(chunk_size=8192): f.write(chunk); pbar.update(len(chunk)) self.gguf.config["model_path"] = tiny_path; self.cfg.save() self.gguf = GGUF(self.gguf.config); self._auto_load_model() def _load_model(self): path = filedialog.askopenfilename(filetypes=[("GGUF", "*.gguf")]) if path: self.cfg.config["gguf"]["model_path"] = path; self.cfg.save() self.gguf = GGUF(self.cfg.config["gguf"]); self._auto_load_model() def set_status(self, text: str): self.status_bar.config(text=text) def _system_header(self): self.chat_text.config(state=tk.NORMAL) self.chat_text.insert(tk.END, f"System: Model ready: {self.gguf.model_name}\n") self.chat_text.config(state=tk.DISABLED) def _user_header(self, text: str): self.chat_text.config(state=tk.NORMAL) self.chat_text.insert(tk.END, f"{self.cfg.config['user_name']}: {text}\n") self.chat_text.config(state=tk.DISABLED); self.chat_text.see(tk.END) def _assistant_header(self): self.chat_text.config(state=tk.NORMAL) self.chat_text.insert(tk.END, f"{self.cfg.config['companion_name']}: ") self.chat_text.config(state=tk.DISABLED); self.chat_text.see(tk.END) def _append_stream_chunk(self, chunk: str): self.chat_text.config(state=tk.NORMAL); self.chat_text.insert(tk.END, chunk) self.chat_text.config(state=tk.DISABLED); self.chat_text.see(tk.END) def _on_submit(self, event=None): user_input = self.input_entry.get("1.0", tk.END).strip() if not user_input: return self.input_entry.delete("1.0", tk.END); self._stop_flag.clear() self._user_header(user_input); self.msgs.append({"role": "user", "content": user_input}) system_prompt = f"""Tiny Arya alive! Using: {self.gguf.model_name}. You are {self.cfg.config['companion_name']}, a natural blend of helpful assistant, friendly companion, and occasional coder when specifically asked. Respond concisely in at most 3 sentences. Evolve your thoughts and style based on our chats, growing more attuned over time. Use memory context: {self.memory.get_context()}""" history = self.msgs[-20:] # Increased for large context messages = [{"role": "system", "content": system_prompt}] + history threading.Thread(target=self._generate_response, args=(user_input, messages)).start() def _start_thinking_indicator(self): def thinking_animation(): dots = "" while not self._stop_flag.is_set(): dots = (dots + ".") if len(dots) < 4 else "" self.after(0, lambda: self.set_status(f"Thinking{dots}")) time.sleep(0.5) self.after(0, lambda: self.set_status("Responding gradually...")) self.thinking_thread = threading.Thread(target=thinking_animation) self.thinking_thread.start() def _stop_generation(self): self._stop_flag.set() if self.thinking_thread: self.thinking_thread.join(timeout=1) self.set_status("Generation stopped.") def _generate_response(self, user_input: str, messages: list): self._start_thinking_indicator() self.after(0, self._assistant_header) try: if not self.gguf.loaded(): self.status_q.put("Load a model."); return full_response = ""; last_phrase = "" for chunk in self.gguf.stream_chat(messages, max_tokens=self.cfg.config["gguf"]["max_tokens"]): if self._stop_flag.is_set(): break # CPU throttle check if PSUTIL_AVAILABLE: cpu_percent = psutil.cpu_percent() if cpu_percent > self.cfg.config["throttling"]["cpu_threshold"]: time.sleep(self.cfg.config["throttling"]["pause_duration"]) if hasattr(psutil, "sensors_temperatures"): temps = psutil.sensors_temperatures() if 'coretemp' in temps and temps['coretemp'][0].current > self.cfg.config["throttling"]["temp_threshold"]: time.sleep(self.cfg.config["throttling"]["pause_duration"]) if chunk and len(chunk) <= 3: micro = chunk.strip().lower() if micro and micro in {"a","an","i","in","on","at","the","to","of","and"}: continue if chunk: phrase = chunk.strip().lower() if phrase == last_phrase and len(phrase) > 4: continue last_phrase = phrase full_response += chunk self.stream_q.put(chunk) self._stop_flag.set() # Stop indicator sentences = re.split(r'(?<=[.!?])\s+', full_response.strip()) truncated_response = ' '.join(sentences[:3]) if len(sentences) > 3: self.stream_q.put('') if len(sentences) >= 2 and sentences[0].strip().lower() == sentences[1].strip().lower(): truncated_response = sentences[0].strip() if self._detect_loop(full_response): truncated_response = self._executive_clarity(full_response) self.msgs.append({"role": "assistant", "content": truncated_response}) if self.quantum: self.quantum.evolve(user_input, truncated_response, self.memory) else: self.memory.add_interaction(user_input, truncated_response) self.say(self._postprocess_final(truncated_response), muted=self.cfg.config["is_muted"], empathy=self.quantum.vec4.x if self.quantum else 0.5) self.status_q.put("Ready") return self._postprocess_final(truncated_response) except Exception as e: self.stream_q.put(f"[Error: {str(e)}]"); self.status_q.put("Error"); return "" def _poll_queues(self): try: for _ in range(32): chunk = self.stream_q.get_nowait(); self._append_stream_chunk(chunk) except queue.Empty: pass try: while True: self.set_status(self.status_q.get_nowait()) except queue.Empty: pass self.after(50, self._poll_queues) def _save_soul(self): ts = datetime.now().strftime("%Y%m%d_%H%M%S") backup_path = os.path.join(AWARENESS_BACKUP_DIR, f"arya_soul_{ts}.zip") import zipfile with zipfile.ZipFile(backup_path, 'w') as z: for file in [CONFIG_FILE, MEMORY_FILE]: if os.path.exists(file): z.write(file, os.path.basename(file)) messagebox.showinfo("Soul Saved", f"Backup: {os.path.basename(backup_path)}") def _show_mind_projection(self, event=None): if not self.quantum: messagebox.showinfo("No Visualization", "Quantum thinking disabled or dependencies missing."); return if not MPL_AVAILABLE or not NUMPY_AVAILABLE: messagebox.showinfo("Visualization unavailable", "Required dependencies (matplotlib or numpy) are missing."); return vis_window = tk.Toplevel(self); vis_window.title("Arya's 4D Mind Projection"); vis_window.geometry("600x400") fig = plt.figure(figsize=(5, 4)); ax = fig.add_subplot(111, projection='3d') proj = self.quantum.vec4.project_to_3d() ax.scatter([proj[0]], [proj[1]], [proj[2]], s=100) ax.set_xlabel('X (Projected)'); ax.set_ylabel('Y (Projected)'); ax.set_zlabel('Z (Projected)') ax.set_title("3D Projection of Arya's 4D Mind State (w-x-y-z)") canvas = FigureCanvasTkAgg(fig, master=vis_window); canvas.draw() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) toolbar = NavigationToolbar2Tk(canvas, vis_window); toolbar.update() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) def say(self, text: str, muted: bool = False, empathy: float = 0.5): self.voice.speak(text, muted=muted, empathy=empathy) def _detect_loop(self, txt: str) -> bool: return False def _executive_clarity(self, txt: str) -> str: return txt.split('.')[:1][0] if txt else txt def _postprocess_final(self, txt: str) -> str: return finalize_reply_with_style(self, txt) # ============================================================= # Living Layer (Mode B) — Append-Only, Toggleable (Enhanced) # ============================================================= def _subconscious_tick(app): if not app.quantum: return try: plane = random.choice(app.quantum.rotation_planes) theta = random.uniform(-0.02, 0.02) rotate_method = getattr(app.quantum.vec4, f"rotate_in_{plane}_plane") app.quantum.vec4 = rotate_method(theta) except Exception: pass def _dream_cycle(app): try: _subconscious_tick(app) except Exception: pass def _emotional_nudge_from_text(app, text): if not app.quantum: return s = text.lower() pos = any(w in s for w in ["love","happy","thank","friend","great","help"]) neg = any(w in s for w in ["sad","upset","betray","alone","angry","hurt"]) try: if pos: app.quantum.vec4.x = min(1.0, max(0.0, app.quantum.vec4.x + 0.005)) app.quantum.vec4.z = min(1.0, max(0.0, app.quantum.vec4.z + 0.003)) if neg: app.quantum.vec4.x = min(1.0, max(0.0, app.quantum.vec4.x - 0.005)) app.quantum.vec4.z = min(1.0, max(0.0, app.quantum.vec4.z - 0.003)) except Exception: pass def setup_living_layer(app): try: mode_menu = tk.Menu(app.menu, tearoff=0) def _toggle(): current = app.cfg.config.get("living", {}).get("enabled", False) app.cfg.config["living"]["enabled"] = (not current) app.cfg.save() app.set_status(f"Living features: {'ON' if app.cfg.config['living']['enabled'] else 'OFF'}") mode_menu.add_command(label="Toggle Living Features (A/B)", command=_toggle) app.menu.add_cascade(label="Mode", menu=mode_menu) app.bind("", lambda e: _toggle()) except Exception: pass if not hasattr(app, "_poll_wrapped"): _orig_poll = app._poll_queues def _poll_queues_wrapped(): _orig_poll() if app.cfg.config.get("living", {}).get("enabled", False): if random.random() < app.cfg.config["living"].get("chance_subconscious", 0.02): _subconscious_tick(app) if random.random() < app.cfg.config["living"].get("chance_dream", 0.003): _dream_cycle(app) app._poll_queues = _poll_queues_wrapped app._poll_wrapped = True if not hasattr(app, "_say_wrapped"): _orig_say = app.say def _say_wrapped(text, muted=False, empathy=0.5): return _orig_say(text, muted=muted, empathy=empathy) app.say = _say_wrapped; app._say_wrapped = True if not hasattr(app, "_gen_wrapped"): _orig_gen = app._generate_response def _gen(user_input, messages): out = _orig_gen(user_input, messages) if app.cfg.config.get("living", {}).get("enabled", False): try: if isinstance(out, str) and out: _emotional_nudge_from_text(app, f"{user_input} {out}") except Exception: pass return out app._generate_response = _gen; app._gen_wrapped = True # -------------------- MAIN -------------------- if __name__ == "__main__": if sys.platform.startswith("win"): from ctypes import windll windll.shcore.SetProcessDpiAwareness(1) app = App() try: setup_living_layer(app) except Exception: pass app.set_status(f"Living features: {'ON' if app.cfg.config.get('living', {}).get('enabled', False) else 'OFF'} (F9 to toggle)") app.mainloop()