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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 1. PARADIGM SHIFT: Native CUDA Base
|
| 2 |
+
# Moving from python-slim to NVIDIA's optimized runtime ensures deep hardware access
|
| 3 |
+
FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04
|
| 4 |
+
|
| 5 |
+
ENV DEBIAN_FRONTEND=noninteractive
|
| 6 |
+
ENV PYTHONUNBUFFERED=1
|
| 7 |
+
|
| 8 |
+
WORKDIR /app
|
| 9 |
+
|
| 10 |
+
# Install Python and core dependencies
|
| 11 |
+
RUN apt-get update && apt-get install -y \
|
| 12 |
+
python3.10 python3-pip python3.10-venv curl git libgomp1 libglib2.0-0 libsm6 libxrender1 libxext6 \
|
| 13 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 14 |
+
|
| 15 |
+
RUN ln -s /usr/bin/python3.10 /usr/bin/python
|
| 16 |
+
|
| 17 |
+
# 2. OPTIMIZED PIPELINE: Install PyTorch with specific CUDA index and Flash Attention capabilities
|
| 18 |
+
RUN pip3 install --no-cache-dir --upgrade pip && \
|
| 19 |
+
pip3 install --no-cache-dir torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
|
| 20 |
+
|
| 21 |
+
# Install core packages + flash-attn for LLM speedups
|
| 22 |
+
RUN pip3 install --no-cache-dir numpy flask flask-sock diffusers transformers accelerate peft pillow diskcache safetensors scipy sentencepiece
|
| 23 |
+
|
| 24 |
+
RUN useradd -m -u 1000 user
|
| 25 |
+
USER user
|
| 26 |
+
ENV HOME=/home/user PATH=/home/user/.local/bin:$PATH
|
| 27 |
+
|
| 28 |
+
COPY --chown=user <<'HYPER_EOF' app.py
|
| 29 |
+
import sys, os, io, base64, json, warnings, time, threading
|
| 30 |
+
from queue import Queue
|
| 31 |
+
import torch
|
| 32 |
+
import torch.nn.functional as F
|
| 33 |
+
import numpy as np
|
| 34 |
+
from dataclasses import dataclass
|
| 35 |
+
from typing import Dict, List, Optional, Tuple
|
| 36 |
+
from flask import Flask
|
| 37 |
+
from flask_sock import Sock
|
| 38 |
+
from PIL import Image
|
| 39 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 40 |
+
from diffusers import StableDiffusionPipeline, AutoencoderTiny, LCMScheduler
|
| 41 |
+
import diskcache
|
| 42 |
+
|
| 43 |
+
warnings.filterwarnings("ignore")
|
| 44 |
+
|
| 45 |
+
# Enable CuDNN auto-tuner for hardware-specific algorithmic optimization
|
| 46 |
+
torch.backends.cudnn.benchmark = True
|
| 47 |
+
|
| 48 |
+
HTML=r"""<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"><title>NeuralOS HyperCore v2.1</title><script src="https://cdn.tailwindcss.com"></script><script src="https://unpkg.com/react@18/umd/react.production.min.js"></script><script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script><script src="https://unpkg.com/@babel/standalone/babel.min.js"></script><style>*{box-sizing:border-box}body{background:#000;color:#e2e2e2;margin:0;overflow:hidden;font-family:Tahoma,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;width:100vw}#desktop-container{position:relative;width:1024px;height:1024px;transform-origin:center;box-shadow:0 0 80px rgba(0,150,255,.4);background:#3A6EA5;border:2px solid #2a5c8f}.canvas-viewport{position:absolute;top:0;left:0;width:100%;height:100%;image-rendering:pixelated;cursor:pointer}.canvas-viewport img{width:100%;height:100%;display:block;image-rendering:pixelated}.taskbar{position:absolute;bottom:0;left:0;right:0;height:64px;background:linear-gradient(to bottom,#245EDB 0%,#1F4FB5 50%,#1941A5 100%);border-top:2px solid #5C9CFF;display:flex;align-items:center;padding:0 10px;gap:10px;z-index:50;box-shadow:0 -2px 10px rgba(0,0,0,.3)}.start-btn{background:linear-gradient(to bottom,#3FA23F,#2E862E);border:2px outset #5FCF5F;color:#fff;font-weight:700;padding:8px 20px;border-radius:6px;cursor:pointer;font-size:18px;font-style:italic;text-shadow:1px 1px 2px #000;display:flex;align-items:center;gap:8px;transition:all .15s;user-select:none}.start-btn:hover{background:linear-gradient(to bottom,#4CB24C,#359535);transform:translateY(-1px)}.start-btn:active{border-style:inset;transform:translateY(0)}.start-btn::before{content:"β";font-style:normal;font-size:22px}.start-menu{position:absolute;bottom:70px;left:10px;width:320px;background:linear-gradient(to right,#245EDB 0,#245EDB 60px,#D6DFF7 60px);border:3px outset #8BB8FF;border-radius:8px 8px 0 0;box-shadow:2px 2px 10px rgba(0,0,0,.5);z-index:100;overflow:hidden}.start-menu-header{background:linear-gradient(to bottom,#5C9CFF,#245EDB);color:#fff;font-weight:700;padding:8px 12px;border-bottom:2px solid #8BB8FF;font-size:16px;text-shadow:1px 1px 1px #000}.start-menu-content{display:flex}.start-menu-sidebar{width:60px;background:#245EDB;padding:10px 5px;color:#fff;font-size:11px;writing-mode:vertical-rl;text-orientation:mixed;font-weight:700;text-shadow:1px 1px 1px #000}.start-menu-items{flex:1;background:#D6DFF7;padding:8px 0}.start-menu-item{padding:10px 15px;cursor:pointer;display:flex;align-items:center;gap:12px;color:#000;font-size:14px;transition:background .1s}.start-menu-item:hover{background:#4A7FD5;color:#fff}.start-menu-icon{width:32px;height:32px;background:#999;border:1px solid #666;border-radius:3px;display:flex;align-items:center;justify-content:center;font-size:18px}.console-log{position:absolute;top:20px;right:20px;width:400px;max-height:250px;background:rgba(0,0,0,.92);color:#0f0;font-family:'Fira Code',monospace;font-size:13px;line-height:1.5;padding:15px;border:2px solid #0a0;border-radius:6px;overflow-y:auto;z-index:1000;pointer-events:none;box-shadow:0 4px 20px rgba(0,255,0,.2);backdrop-filter:blur(5px)}.log-entry{margin-bottom:4px;animation:fadeIn .3s}@keyframes fadeIn{from{opacity:0;transform:translateX(-10px)}to{opacity:1;transform:translateX(0)}}.fps-counter{position:absolute;top:20px;left:20px;background:rgba(0,0,0,.7);color:#0ff;padding:8px 12px;border-radius:4px;font-family:'Fira Code',monospace;font-size:12px;z-index:1000;pointer-events:none}</style></head><body><div id="root"></div><script type="text/babel">const{useState,useEffect,useRef}=React;function App(){const[desktopImage,setDesktopImage]=useState(null);const[logs,setLogs]=useState(["β‘ NeuralOS HyperCore v2.1","βοΈ Initializing Engine...","π§ AI Engines: STANDBY"]);const[scale,setScale]=useState(1);const[startMenuOpen,setStartMenuOpen]=useState(false);const[fps,setFps]=useState(0);const socketRef=useRef(null);const containerRef=useRef(null);const frameCountRef=useRef(0);const lastTimeRef=useRef(Date.now());const addLog=msg=>setLogs(p=>[...p.slice(-12),msg]);useEffect(()=>{const i=setInterval(()=>{const now=Date.now();const delta=(now-lastTimeRef.current)/1e3;const f=Math.round(frameCountRef.current/delta);setFps(f);frameCountRef.current=0;lastTimeRef.current=now},1e3);return()=>clearInterval(i)},[]);useEffect(()=>{const h=()=>{const p=20;const w=window.innerWidth-p;const ht=window.innerHeight-p;const sw=w/1024;const sh=ht/1024;const s=Math.min(sw,sh,1);setScale(s)};window.addEventListener('resize',h);h();return()=>window.removeEventListener('resize',h)},[]);useEffect(()=>{const proto=window.location.protocol==='https:'?'wss':'ws';const ws=new WebSocket(`${proto}://${window.location.host}/kernel`);socketRef.current=ws;ws.onopen=()=>addLog("π Kernel Connected");ws.onmessage=e=>{const msg=JSON.parse(e.data);if(msg.type==='frame_update'||msg.type==='desktop_ready'){setDesktopImage(msg.data);frameCountRef.current++}if(msg.type==='log')addLog(msg.data)};ws.onerror=()=>addLog("β Error");ws.onclose=()=>addLog("π Disconnected");return()=>ws.close()},[]);const handleClick=e=>{if(!containerRef.current)return;const rect=containerRef.current.getBoundingClientRect();const cx=(e.clientX-rect.left)/scale;const cy=(e.clientY-rect.top)/scale;const gx=Math.floor((cx/1024)*128);const gy=Math.floor((cy/1024)*128);if(gx>=0&&gx<=128&&gy>=0&&gy<=128){socketRef.current?.send(JSON.stringify({type:'click',x:gx,y:gy}));setStartMenuOpen(false)}};const toggleStartMenu=e=>{e.stopPropagation();setStartMenuOpen(!startMenuOpen)};const launchApp=app=>{socketRef.current?.send(JSON.stringify({type:'launch_app',app:app}));setStartMenuOpen(false)};return(<div id="desktop-container" ref={containerRef} style={{transform:`scale(${scale})`}}><div className="canvas-viewport" onClick={handleClick}>{desktopImage&&<img src={`data:image/webp;base64,${desktopImage}`} draggable="false"/>}</div><div className="fps-counter">FPS:{fps}|Neural Active</div><div className="taskbar"><div className="start-btn" onClick={toggleStartMenu}>start</div></div>{startMenuOpen&&(<div className="start-menu"><div className="start-menu-header">NeuralOS Programs</div><div className="start-menu-content"><div className="start-menu-sidebar">HyperCore v2</div><div className="start-menu-items"><div className="start-menu-item" onClick={()=>launchApp('notepad')}><div className="start-menu-icon">π</div><span>Notepad</span></div><div className="start-menu-item" onClick={()=>launchApp('paint')}><div className="start-menu-icon">π¨</div><span>Paint</span></div><div className="start-menu-item" onClick={()=>launchApp('cmd')}><div className="start-menu-icon">β¨οΈ</div><span>Command Prompt</span></div><div className="start-menu-item" onClick={()=>launchApp('explorer')}><div className="start-menu-icon">π</div><span>File Explorer</span></div><div className="start-menu-item" onClick={()=>launchApp('browser')}><div className="start-menu-icon">π</div><span>Browser</span></div></div></div></div>)}<div className="console-log">{logs.map((l,i)=><div key={i} className="log-entry">>{l}</div>)}</div></div>);}ReactDOM.createRoot(document.getElementById('root')).render(<App/>);</script></body></html>"""
|
| 49 |
+
|
| 50 |
+
@dataclass
|
| 51 |
+
class Application:
|
| 52 |
+
name: str
|
| 53 |
+
icon_prompt: str
|
| 54 |
+
content_prompt: str
|
| 55 |
+
default_size: Tuple[int, int]
|
| 56 |
+
refinement_steps: int = 2
|
| 57 |
+
|
| 58 |
+
@dataclass
|
| 59 |
+
class Process:
|
| 60 |
+
pid: int
|
| 61 |
+
name: str
|
| 62 |
+
app_type: str
|
| 63 |
+
position: Tuple[int, int]
|
| 64 |
+
size: Tuple[int, int]
|
| 65 |
+
latent_state: torch.Tensor
|
| 66 |
+
z_order: int
|
| 67 |
+
refinement_level: int = 0
|
| 68 |
+
last_refined: float = 0
|
| 69 |
+
|
| 70 |
+
PROGRAMS = {
|
| 71 |
+
"notepad": Application("Notepad", "pixel art notepad icon yellow paper blue lines 32x32 crisp detailed", "windows notepad white background courier font menu bar detailed UI", (48, 38), 3),
|
| 72 |
+
"paint": Application("Paint", "pixel art paint icon colorful palette brush 32x32 crisp detailed", "ms paint white canvas color palette toolbar brushes detailed", (56, 44), 3),
|
| 73 |
+
"cmd": Application("CMD", "pixel art terminal icon black screen white prompt 32x32 crisp", "command prompt black white monospace C:\\ detailed", (52, 36), 2),
|
| 74 |
+
"explorer": Application("Explorer", "pixel art folder icon yellow folder 32x32 crisp detailed", "windows explorer folder tree file icons toolbar detailed UI", (60, 46), 3),
|
| 75 |
+
"browser": Application("Browser", "pixel art browser icon blue globe 32x32 crisp detailed", "web browser address bar navigation buttons detailed UI", (64, 48), 3)
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
class IconCache:
|
| 79 |
+
def __init__(self): self.cache = {}
|
| 80 |
+
def get(self, k): return self.cache.get(k)
|
| 81 |
+
def set(self, k, v): self.cache[k] = v
|
| 82 |
+
|
| 83 |
+
ICON_CACHE = IconCache()
|
| 84 |
+
DRIVERS = {}
|
| 85 |
+
|
| 86 |
+
def initialize_drivers():
|
| 87 |
+
bg = torch.zeros((1, 4, 128, 128), dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32)
|
| 88 |
+
for y in range(128):
|
| 89 |
+
i = 0.3 + (y / 128) * 0.5
|
| 90 |
+
bg[:, 0, y, :] = i * 0.4
|
| 91 |
+
bg[:, 1, y, :] = i * 0.9
|
| 92 |
+
bg[:, 2, y, :] = i * 0.2
|
| 93 |
+
DRIVERS["DESKTOP_BG"] = bg
|
| 94 |
+
print("[β] Drivers Init - HQ Background")
|
| 95 |
+
|
| 96 |
+
class OSKernel:
|
| 97 |
+
def __init__(self):
|
| 98 |
+
self.processes: Dict[int, Process] = {}
|
| 99 |
+
self.next_pid = 1
|
| 100 |
+
self.focused_pid: Optional[int] = None
|
| 101 |
+
self.refinement_queue = Queue()
|
| 102 |
+
self.desktop_icons = [
|
| 103 |
+
{"app": "notepad", "x": 6, "y": 6, "label": "Notepad"},
|
| 104 |
+
{"app": "paint", "x": 6, "y": 20, "label": "Paint"},
|
| 105 |
+
{"app": "cmd", "x": 6, "y": 34, "label": "CMD"},
|
| 106 |
+
{"app": "explorer", "x": 6, "y": 48, "label": "Explorer"},
|
| 107 |
+
{"app": "browser", "x": 6, "y": 62, "label": "Browser"}
|
| 108 |
+
]
|
| 109 |
+
|
| 110 |
+
def spawn_process(self, app_type: str, x: int = 32, y: int = 24) -> int:
|
| 111 |
+
if app_type not in PROGRAMS: return -1
|
| 112 |
+
app = PROGRAMS[app_type]
|
| 113 |
+
pid = self.next_pid
|
| 114 |
+
self.next_pid += 1
|
| 115 |
+
w, h = app.default_size
|
| 116 |
+
latent = torch.zeros((1, 4, h, w), dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32)
|
| 117 |
+
proc = Process(pid, app.name, app_type, (x, y), (w, h), latent, pid, 0, time.time())
|
| 118 |
+
self.processes[pid] = proc
|
| 119 |
+
self.focus_process(pid)
|
| 120 |
+
self.refinement_queue.put(pid)
|
| 121 |
+
return pid
|
| 122 |
+
|
| 123 |
+
def kill_process(self, pid: int):
|
| 124 |
+
if pid in self.processes:
|
| 125 |
+
del self.processes[pid]
|
| 126 |
+
if self.focused_pid == pid: self.focused_pid = None
|
| 127 |
+
|
| 128 |
+
def focus_process(self, pid: int):
|
| 129 |
+
if pid in self.processes:
|
| 130 |
+
self.focused_pid = pid
|
| 131 |
+
max_z = max((p.z_order for p in self.processes.values()), default=0)
|
| 132 |
+
self.processes[pid].z_order = max_z + 1
|
| 133 |
+
|
| 134 |
+
def handle_click(self, x: int, y: int) -> Dict:
|
| 135 |
+
sorted_procs = sorted(self.processes.values(), key=lambda p: p.z_order, reverse=True)
|
| 136 |
+
for proc in sorted_procs:
|
| 137 |
+
px, py = proc.position
|
| 138 |
+
pw, ph = proc.size
|
| 139 |
+
if px <= x < px + pw and py <= y < py + ph:
|
| 140 |
+
if py <= y < py + 4 and px + pw - 4 <= x < px + pw:
|
| 141 |
+
self.kill_process(proc.pid)
|
| 142 |
+
return {"action": "close", "pid": proc.pid, "name": proc.name}
|
| 143 |
+
self.focus_process(proc.pid)
|
| 144 |
+
return {"action": "focus", "pid": proc.pid, "name": proc.name}
|
| 145 |
+
for icon in self.desktop_icons:
|
| 146 |
+
ix, iy = icon['x'], icon['y']
|
| 147 |
+
if ix <= x < ix + 10 and iy <= y < iy + 10:
|
| 148 |
+
pid = self.spawn_process(icon['app'], 28 + (len(self.processes) % 3) * 12, 20 + (len(self.processes) % 3) * 8)
|
| 149 |
+
return {"action": "launch", "pid": pid, "app": icon['app']}
|
| 150 |
+
return {"action": "desktop_click", "x": x, "y": y}
|
| 151 |
+
|
| 152 |
+
class NeuralSystem:
|
| 153 |
+
def __init__(self):
|
| 154 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 155 |
+
# BFloat16 is highly optimized on Ampere+ architectures, offering pure speed over FP16 without precision penalties
|
| 156 |
+
self.dt = torch.bfloat16 if self.device == "cuda" else torch.float32
|
| 157 |
+
print(f"[β‘] Device: {self.device} | Type: {self.dt}")
|
| 158 |
+
|
| 159 |
+
print("[π§ ] Loading Neural Renderer...")
|
| 160 |
+
self.pipe = StableDiffusionPipeline.from_pretrained(
|
| 161 |
+
"runwayml/stable-diffusion-v1-5",
|
| 162 |
+
torch_dtype=self.dt,
|
| 163 |
+
safety_checker=None,
|
| 164 |
+
requires_safety_checker=False
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
if self.device == "cuda":
|
| 168 |
+
self.pipe = self.pipe.to("cuda")
|
| 169 |
+
self.pipe.enable_attention_slicing()
|
| 170 |
+
# Compile models to deeply fuse kernels and strip python overhead
|
| 171 |
+
print("[βοΈ] JIT Compiling Neural Engine (First run takes a moment)...")
|
| 172 |
+
self.pipe.unet = torch.compile(self.pipe.unet, mode="reduce-overhead", fullgraph=True)
|
| 173 |
+
|
| 174 |
+
self.pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5")
|
| 175 |
+
self.pipe.scheduler = LCMScheduler.from_config(self.pipe.scheduler.config)
|
| 176 |
+
self.pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taesd", torch_dtype=self.dt).to(self.device)
|
| 177 |
+
|
| 178 |
+
if self.device == "cuda":
|
| 179 |
+
self.pipe.vae = torch.compile(self.pipe.vae, mode="max-autotune")
|
| 180 |
+
|
| 181 |
+
print("[π§ ] Loading LLM Cognitive Layer...")
|
| 182 |
+
self.model_id = "Qwen/Qwen2.5-Coder-0.5B-Instruct"
|
| 183 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
|
| 184 |
+
if self.tokenizer.pad_token_id is None:
|
| 185 |
+
self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
|
| 186 |
+
|
| 187 |
+
self.llm = AutoModelForCausalLM.from_pretrained(
|
| 188 |
+
self.model_id,
|
| 189 |
+
torch_dtype=self.dt,
|
| 190 |
+
device_map="auto"
|
| 191 |
+
)
|
| 192 |
+
self.content_cache = diskcache.Cache('/tmp/neural_cache')
|
| 193 |
+
print("[β] Systems Online")
|
| 194 |
+
|
| 195 |
+
@torch.inference_mode()
|
| 196 |
+
def think(self, prompt: str, max_tok: int = 48) -> str:
|
| 197 |
+
cache_key = f"think_{hash(prompt)}"
|
| 198 |
+
cached = self.content_cache.get(cache_key)
|
| 199 |
+
if cached: return cached
|
| 200 |
+
|
| 201 |
+
inputs = self.tokenizer(prompt, return_tensors="pt", padding=True, truncation=True).to(self.device)
|
| 202 |
+
outputs = self.llm.generate(
|
| 203 |
+
inputs.input_ids,
|
| 204 |
+
attention_mask=inputs.attention_mask,
|
| 205 |
+
max_new_tokens=max_tok,
|
| 206 |
+
do_sample=True,
|
| 207 |
+
temperature=0.7,
|
| 208 |
+
pad_token_id=self.tokenizer.eos_token_id
|
| 209 |
+
)
|
| 210 |
+
response = self.tokenizer.decode(outputs[0][len(inputs.input_ids[0]):], skip_special_tokens=True).strip()
|
| 211 |
+
self.content_cache.set(cache_key, response, expire=3600)
|
| 212 |
+
return response
|
| 213 |
+
|
| 214 |
+
@torch.inference_mode()
|
| 215 |
+
def generate_icon(self, app_type: str) -> torch.Tensor:
|
| 216 |
+
cache_key = f"icon_{app_type}"
|
| 217 |
+
cached = ICON_CACHE.get(cache_key)
|
| 218 |
+
if cached is not None: return cached
|
| 219 |
+
|
| 220 |
+
app = PROGRAMS[app_type]
|
| 221 |
+
latents = torch.randn((1, 4, 10, 10), device=self.device, dtype=self.dt) * 0.8
|
| 222 |
+
result = self.pipe(app.icon_prompt, latents=latents, num_inference_steps=2, guidance_scale=1.0, output_type="latent").images
|
| 223 |
+
result = result * 1.3
|
| 224 |
+
ICON_CACHE.set(cache_key, result)
|
| 225 |
+
return result
|
| 226 |
+
|
| 227 |
+
@torch.inference_mode()
|
| 228 |
+
def generate_window_content(self, proc: Process, steps: int = 1):
|
| 229 |
+
app_def = PROGRAMS[proc.app_type]
|
| 230 |
+
ref_desc = f" refinement {proc.refinement_level}" if proc.refinement_level > 0 else ""
|
| 231 |
+
prompt = f"windows xp {app_def.name}{ref_desc} {app_def.content_prompt} highly detailed sharp"
|
| 232 |
+
|
| 233 |
+
if proc.refinement_level == 0:
|
| 234 |
+
latents = torch.randn((1, 4, proc.size[1], proc.size[0]), device=self.device, dtype=self.dt) * 0.5
|
| 235 |
+
else:
|
| 236 |
+
latents = proc.latent_state.to(self.device, dtype=self.dt)
|
| 237 |
+
noise = torch.randn_like(latents) * 0.1
|
| 238 |
+
latents = latents + noise
|
| 239 |
+
|
| 240 |
+
img_latents = self.pipe(prompt, latents=latents, num_inference_steps=steps, guidance_scale=1.0, output_type="latent").images
|
| 241 |
+
img_latents[:, 1, 0:4, :] = 1.5
|
| 242 |
+
img_latents[:, 0, 0:4, :] = 0.5
|
| 243 |
+
img_latents[:, 2, 1:3, -4:-1] = 2.0
|
| 244 |
+
|
| 245 |
+
proc.latent_state = img_latents
|
| 246 |
+
proc.refinement_level += 1
|
| 247 |
+
proc.last_refined = time.time()
|
| 248 |
+
|
| 249 |
+
@torch.inference_mode()
|
| 250 |
+
def render_frame(self, kernel: OSKernel):
|
| 251 |
+
canvas = DRIVERS["DESKTOP_BG"].clone().to(self.device)
|
| 252 |
+
for icon in kernel.desktop_icons:
|
| 253 |
+
icon_latent = self.generate_icon(icon['app']).to(self.device, dtype=self.dt)
|
| 254 |
+
x, y = icon['x'], icon['y']
|
| 255 |
+
canvas[:, :, y:y+10, x:x+10] = icon_latent
|
| 256 |
+
|
| 257 |
+
sorted_procs = sorted(kernel.processes.values(), key=lambda p: p.z_order)
|
| 258 |
+
for proc in sorted_procs:
|
| 259 |
+
x, y = proc.position
|
| 260 |
+
w, h = proc.size
|
| 261 |
+
if x + w <= 128 and y + h <= 128:
|
| 262 |
+
proc_latent = proc.latent_state.to(self.device, dtype=self.dt)
|
| 263 |
+
canvas[:, :, y:y+h, x:x+w] = proc_latent
|
| 264 |
+
|
| 265 |
+
img = self.pipe.vae.decode(canvas / 0.18215).sample
|
| 266 |
+
img = (img / 2 + 0.5).clamp(0, 1).cpu().permute(0, 2, 3, 1).numpy()
|
| 267 |
+
return self.pipe.numpy_to_pil(img)[0]
|
| 268 |
+
|
| 269 |
+
sys_engine = None
|
| 270 |
+
kernel_instance = OSKernel()
|
| 271 |
+
initialize_drivers()
|
| 272 |
+
|
| 273 |
+
app = Flask(__name__)
|
| 274 |
+
sock = Sock(app)
|
| 275 |
+
|
| 276 |
+
def refinement_worker(sys_engine, kernel):
|
| 277 |
+
while True:
|
| 278 |
+
if not kernel.refinement_queue.empty():
|
| 279 |
+
pid = kernel.refinement_queue.get()
|
| 280 |
+
if pid in kernel.processes:
|
| 281 |
+
proc = kernel.processes[pid]
|
| 282 |
+
app_def = PROGRAMS[proc.app_type]
|
| 283 |
+
if proc.refinement_level < app_def.refinement_steps:
|
| 284 |
+
sys_engine.generate_window_content(proc, steps=1)
|
| 285 |
+
kernel.refinement_queue.put(pid)
|
| 286 |
+
time.sleep(0.05) # Dramatically lowered sleep time for hyper-responsive indexing
|
| 287 |
+
|
| 288 |
+
def encode_frame(img) -> str:
|
| 289 |
+
# 3. I/O UPGRADE: PNG encoding is a massive CPU bottleneck. WebP reduces payload size by ~80% and encodes in fractions of a millisecond.
|
| 290 |
+
buf = io.BytesIO()
|
| 291 |
+
img.save(buf, format="WebP", quality=85, method=0)
|
| 292 |
+
return base64.b64encode(buf.getvalue()).decode()
|
| 293 |
+
|
| 294 |
+
@sock.route('/kernel')
|
| 295 |
+
def socket_handler(ws):
|
| 296 |
+
global sys_engine
|
| 297 |
+
if sys_engine is None:
|
| 298 |
+
sys_engine = NeuralSystem()
|
| 299 |
+
ref_thread = threading.Thread(target=refinement_worker, args=(sys_engine, kernel_instance), daemon=True)
|
| 300 |
+
ref_thread.start()
|
| 301 |
+
|
| 302 |
+
ws.send(json.dumps({"type": "log", "data": "Kernel Attached"}))
|
| 303 |
+
img = sys_engine.render_frame(kernel_instance)
|
| 304 |
+
ws.send(json.dumps({"type": "desktop_ready", "data": encode_frame(img)}))
|
| 305 |
+
|
| 306 |
+
while True:
|
| 307 |
+
data = ws.receive()
|
| 308 |
+
if not data: break
|
| 309 |
+
msg = json.loads(data)
|
| 310 |
+
|
| 311 |
+
if msg['type'] == 'click':
|
| 312 |
+
res = kernel_instance.handle_click(msg['x'], msg['y'])
|
| 313 |
+
if res['action'] == 'launch':
|
| 314 |
+
ws.send(json.dumps({"type": "log", "data": f"π Launching {res['app']}..."}))
|
| 315 |
+
proc = kernel_instance.processes[res['pid']]
|
| 316 |
+
sys_engine.generate_window_content(proc)
|
| 317 |
+
elif res['action'] == 'close':
|
| 318 |
+
ws.send(json.dumps({"type": "log", "data": f"β Closed {res['name']}"}))
|
| 319 |
+
elif res['action'] == 'desktop_click':
|
| 320 |
+
thought = sys_engine.think(f"User clicked desktop at {msg['x']},{msg['y']}. Witty system log:")
|
| 321 |
+
ws.send(json.dumps({"type": "log", "data": f"π {thought}"}))
|
| 322 |
+
|
| 323 |
+
img = sys_engine.render_frame(kernel_instance)
|
| 324 |
+
ws.send(json.dumps({"type": "frame_update", "data": encode_frame(img)}))
|
| 325 |
+
|
| 326 |
+
elif msg['type'] == 'launch_app':
|
| 327 |
+
pid = kernel_instance.spawn_process(msg['app'])
|
| 328 |
+
if pid != -1:
|
| 329 |
+
ws.send(json.dumps({"type": "log", "data": f"π± Started {msg['app']}"}))
|
| 330 |
+
proc = kernel_instance.processes[pid]
|
| 331 |
+
sys_engine.generate_window_content(proc)
|
| 332 |
+
img = sys_engine.render_frame(kernel_instance)
|
| 333 |
+
ws.send(json.dumps({"type": "frame_update", "data": encode_frame(img)}))
|
| 334 |
+
|
| 335 |
+
@app.route('/')
|
| 336 |
+
def index(): return HTML
|
| 337 |
+
|
| 338 |
+
if __name__ == '__main__':
|
| 339 |
+
# Use threaded=True to prevent Flask blocking on latent compute loops
|
| 340 |
+
app.run(host='0.0.0.0', port=7860, threaded=True)
|
| 341 |
+
HYPER_EOF
|
| 342 |
+
|
| 343 |
+
EXPOSE 7860
|
| 344 |
+
CMD ["python", "app.py"]
|