# Use a lightweight Python base
FROM python:3.10-slim
# Set working directory
WORKDIR /app
# 1. Install System Dependencies
# 'build-essential' is added to compile llama-cpp-python wheels.
# 'git' and 'curl' are retained for asset downloads and diffusers compatibility.
RUN apt-get update && apt-get install -y \
git \
curl \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# 2. Download Retro Font (VT323)
# Keeps the aesthetic consistent with your "NeuralOS" theme.
RUN curl -L -o /app/VT323.ttf https://github.com/google/fonts/raw/main/ofl/vt323/VT323-Regular.ttf
# 3. Install Python Dependencies
# Merged from your requirements.txt.
# Note: llama-cpp-python is installed with default settings (CPU only) for broad compatibility.
RUN pip install --no-cache-dir \
torch \
torchvision \
numpy \
flask \
flask-sock \
diffusers \
transformers \
accelerate \
peft \
llama-cpp-python \
pillow \
diskcache \
safetensors \
scipy
# 4. Create a non-root user (Best practice for security)
RUN useradd -m -u 1000 user
USER user
ENV HOME=/home/user \
PATH=/home/user/.local/bin:$PATH
# 5. Write the Monolith Application to disk
# This merges drivers.py, index.html, and server.py into one file.
COPY --chown=user <<'EOF' app.py
import sys, os, io, base64, json, pickle, time
import numpy as np
import torch
from pathlib import Path
from dataclasses import dataclass
from typing import Dict, List, Optional
from flask import Flask, request, send_file, render_template_string
from flask_sock import Sock
from diffusers import StableDiffusionPipeline, AutoencoderTiny, LCMScheduler
from PIL import Image, ImageDraw
from llama_cpp import Llama
# ============================================================================
# 1. FRONTEND ASSET (index.html embedded)
# ============================================================================
HTML_TEMPLATE = r"""
LiteWin XP - Neural OS Desktop
"""
# ============================================================================
# 2. DRIVERS & KERNEL LOGIC
# ============================================================================
DRIVERS = {
"TITLE_BAR": torch.zeros((1, 4, 4, 32), dtype=torch.float16),
"TITLE_BAR_INACTIVE": torch.zeros((1, 4, 4, 32), dtype=torch.float16),
"CLOSE_BTN": torch.zeros((1, 4, 4, 4), dtype=torch.float16),
"TASKBAR": torch.zeros((1, 4, 6, 128), dtype=torch.float16),
"START_BTN": torch.zeros((1, 4, 6, 24), dtype=torch.float16),
"DESKTOP_BG": torch.zeros((1, 4, 128, 128), dtype=torch.float16),
"ICON_NOTEPAD": torch.zeros((1, 4, 8, 8), dtype=torch.float16),
"ICON_PAINT": torch.zeros((1, 4, 8, 8), dtype=torch.float16),
"ICON_CMD": torch.zeros((1, 4, 8, 8), dtype=torch.float16),
"ICON_FOLDER": torch.zeros((1, 4, 8, 8), dtype=torch.float16),
}
def initialize_drivers():
DRIVERS["TITLE_BAR"][:, 0, 0:1, :] = 2.0
DRIVERS["TITLE_BAR"][:, 0, 1:3, :] = 1.2
DRIVERS["TITLE_BAR"][:, 1, :, :] = -1.0
DRIVERS["CLOSE_BTN"][:, 2, :, :] = 2.5
DRIVERS["TASKBAR"][:, 0, 0, :] = 1.2
DRIVERS["START_BTN"][:, 1, 1:5, 2:22] = 1.8
DRIVERS["DESKTOP_BG"][:, 1, 0:80, :] = 1.2
DRIVERS["DESKTOP_BG"][:, 2, 0:80, :] = 1.5
DRIVERS["DESKTOP_BG"][:, 1, 80:128, :] = 0.8
DRIVERS["ICON_NOTEPAD"][:, 0, :, :] = 1.5
print("[*] LiteWin High-Fidelity DNA v4 initialized")
@dataclass
class Process:
pid: int
name: str
app_type: str
position: tuple
size: tuple
latent_state: torch.Tensor
status: str = "running"
z_order: int = 0
def to_dict(self):
return {"pid": self.pid, "name": self.name, "app_type": self.app_type, "position": self.position, "size": self.size}
@dataclass
class Application:
name: str
icon_dna: str
window_prompt: str
content_prompt: str
default_size: tuple
PROGRAMS = {
"notepad": Application("Notepad", "ICON_NOTEPAD", "high quality windows_xp notepad", "white text editor", (48, 40)),
"paint": Application("Paint", "ICON_PAINT", "official MS Paint", "white canvas", (64, 48)),
"cmd": Application("Command Prompt", "ICON_CMD", "windows terminal", "black console", (56, 40)),
"explorer": Application("Explorer", "ICON_FOLDER", "windows explorer", "file browser", (72, 56))
}
class OSKernel:
def __init__(self):
self.processes: Dict[int, Process] = {}
self.next_pid = 1
self.focused_pid: Optional[int] = None
self.desktop_latent = DRIVERS["DESKTOP_BG"].clone()
self.desktop_icons = [
{"app": "notepad", "x": 4, "y": 4, "label": "Notepad"},
{"app": "paint", "x": 4, "y": 16, "label": "Paint"},
{"app": "cmd", "x": 4, "y": 28, "label": "Command Prompt"},
{"app": "explorer", "x": 4, "y": 40, "label": "My Computer"},
]
self.start_menu_open = False
def spawn_process(self, app_type: str, x: int, y: int) -> int:
if app_type not in PROGRAMS: return -1
app = PROGRAMS[app_type]
pid = self.next_pid
self.next_pid += 1
w, h = app.default_size
proc = Process(pid, app.name, app_type, (x, y), (w, h), torch.zeros((1, 4, h, w), dtype=torch.float16), "running", pid)
self.processes[pid] = proc
self.focus_process(pid)
return pid
def kill_process(self, pid: int):
if pid in self.processes:
del self.processes[pid]
if self.focused_pid == pid: self.focused_pid = None
def focus_process(self, pid: int):
if pid in self.processes:
self.focused_pid = pid
max_z = max((p.z_order for p in self.processes.values()), default=0)
self.processes[pid].z_order = max_z + 1
def composite_frame(self) -> torch.Tensor:
output = self.desktop_latent.clone()
for icon in self.desktop_icons:
app = PROGRAMS[icon['app']]
if app.icon_dna in DRIVERS:
dna = DRIVERS[app.icon_dna]
x, y = icon['x'], icon['y']
output[:, :, y:y+8, x:x+8] = dna
running_procs = [p for p in self.processes.values() if p.status == "running"]
for proc in sorted(running_procs, key=lambda p: p.z_order):
x, y = proc.position
w, h = proc.size
if x + w > 128 or y + h > 128: continue
output[:, :, y:y+h, x:x+w] = proc.latent_state
taskbar = DRIVERS["TASKBAR"].clone()
taskbar[:, :, :, 0:24] = DRIVERS["START_BTN"]
output[:, :, 122:128, :] = taskbar
return output
def handle_click(self, x: int, y: int) -> Dict:
if y >= 122:
if x < 24:
self.start_menu_open = not self.start_menu_open
return {"action": "toggle_start_menu", "open": self.start_menu_open}
return {"action": "none"}
for icon in self.desktop_icons:
ix, iy = icon['x'], icon['y']
if ix <= x < ix+8 and iy <= y < iy+8:
pid = self.spawn_process(icon['app'], x=32, y=24)
return {"action": "launch", "app": icon['app'], "pid": pid}
for proc in sorted(self.processes.values(), key=lambda p: p.z_order, reverse=True):
if proc.status != "running": continue
px, py = proc.position
pw, ph = proc.size
if px <= x < px+pw and py <= y < py+ph:
self.focus_process(proc.pid)
if py <= y < py+4 and px+pw-4 <= x < px+pw:
self.kill_process(proc.pid)
return {"action": "close", "pid": proc.pid}
return {"action": "focus", "pid": proc.pid}
return {"action": "none"}
class LatentFileSystem:
def __init__(self, root_path="./litewin_disk"):
self.root = Path(root_path)
self.root.mkdir(exist_ok=True)
class LatentVM:
def execute(self, bytecode: str, target_latent: torch.Tensor) -> torch.Tensor:
return target_latent # Placeholder for VM execution
# ============================================================================
# 3. SERVER & ML PIPELINE
# ============================================================================
app = Flask(__name__)
sock = Sock(app)
pipe = None
llm = None
kernel = OSKernel()
GGUF_MODEL_PATH = "models/qwen2.5-coder-0.5b-instruct-q8_0.gguf"
STEPS = 1
def get_pipe():
global pipe, STEPS
if pipe is None:
print("[*] Booting Neural Kernel...")
device = "cuda" if torch.cuda.is_available() else "cpu"
dt = torch.float16 if device == "cuda" else torch.float32
pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=dt).to(device)
try:
if device == "cuda":
pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5")
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taesd", torch_dtype=dt).to(device)
STEPS = 1
print("[✓] LCM + TAE Enabled")
else:
STEPS = 4
except Exception as e:
print(f"[!] Optimization failed: {e}")
return pipe
def decode_layer(latents, p):
with torch.no_grad():
latents = 1 / 0.18215 * latents
latents = latents.to(device=p.device, dtype=p.vae.dtype)
image = p.vae.decode(latents).sample
image = (image / 2 + 0.5).clamp(0, 1).nan_to_num()
image = image.cpu().permute(0, 2, 3, 1).numpy()
image = p.numpy_to_pil(image)[0]
buf = io.BytesIO()
image.save(buf, format="PNG")
return base64.b64encode(buf.getvalue()).decode()
def render_perfect_window_latent(p, w_blocks, h_blocks, title="Window"):
width, height = w_blocks * 8, h_blocks * 8
img = Image.new('RGB', (width, height), color=(236, 233, 216))
draw = ImageDraw.Draw(img)
draw.rectangle([0, 0, width-1, height-1], outline=(0, 0, 0))
draw.rectangle([1, 1, width-2, 31], fill=(0, 84, 227)) # Blue Title
draw.rectangle([4, 32, width-5, height-5], fill=(255, 255, 255)) # Content
img_t = torch.from_numpy(np.array(img)).permute(2, 0, 1).float() / 255.0
img_t = (img_t * 2.0 - 1.0).unsqueeze(0).to(device=p.device, dtype=p.vae.dtype)
with torch.no_grad():
latent = p.vae.encode(img_t).latent_dist.sample() * 0.18215
return latent.cpu()
def generate_window_fast(p, kernel, pid):
device = p.device
proc = kernel.processes[pid]
app = PROGRAMS[proc.app_type]
w, h = proc.size
# Inject Frame
base_latent = render_perfect_window_latent(p, w, h, title=app.name)
# Fill Content (Simplified for Monolith)
prompt = f"{app.content_prompt}, pixel perfect"
text_inputs = p.tokenizer([prompt], padding="max_length", max_length=p.tokenizer.model_max_length, truncation=True, return_tensors="pt")
prompt_embeds = p.text_encoder(text_inputs.input_ids.to(device))[0]
uncond_inputs = p.tokenizer(["blurry"], padding="max_length", max_length=p.tokenizer.model_max_length, truncation=True, return_tensors="pt")
neg_embeds = p.text_encoder(uncond_inputs.input_ids.to(device))[0]
embeds = torch.cat([neg_embeds, prompt_embeds])
latents = base_latent.to(device)
p.scheduler.set_timesteps(STEPS, device=device)
for t in p.scheduler.timesteps:
latent_input = torch.cat([latents] * 2)
latent_input = p.scheduler.scale_model_input(latent_input, t)
with torch.no_grad():
noise_pred = p.unet(latent_input, t, encoder_hidden_states=embeds, return_dict=False)[0]
uncond, text = noise_pred.chunk(2)
noise_pred = uncond + (1.0 if STEPS==1 else 7.5) * (text - uncond)
next_latents = p.scheduler.step(noise_pred, t, latents).prev_sample
# Lock Title Bar (Top 4 blocks)
mask = torch.ones_like(latents)
mask[:, :, 0:4, :] = 0.0
latents = (mask * next_latents) + ((1.0 - mask) * latents)
proc.latent_state = latents.cpu()
@sock.route('/kernel')
def kernel_ws(ws):
p = get_pipe()
initialize_drivers()
print("[*] Client connected to Monolith Kernel")
frame = kernel.composite_frame()
ws.send(json.dumps({
"type": "desktop_ready",
"data": decode_layer(frame, p),
"processes": [proc.to_dict() for proc in kernel.processes.values()]
}))
while True:
try:
data = ws.receive()
if not data: break
msg = json.loads(data)
if msg['type'] == 'click':
res = kernel.handle_click(msg['x'], msg['y'])
if res['action'] == 'launch':
generate_window_fast(p, kernel, res['pid'])
elif msg['type'] == 'launch_app':
pid = kernel.spawn_process(msg['app'], 12, 12)
generate_window_fast(p, kernel, pid)
ws.send(json.dumps({
"type": "frame_update",
"data": decode_layer(kernel.composite_frame(), p),
"processes": [proc.to_dict() for proc in kernel.processes.values()]
}))
except Exception as e:
print(f"[ERR] {e}")
break
@app.route('/')
def index():
return render_template_string(HTML_TEMPLATE)
if __name__ == '__main__':
print("="*40)
print(" NEURAL OS MONOLITH v1.0 RUNNING")
print("="*40)
app.run(host='0.0.0.0', port=7860, threaded=True)
EOF
# 6. Launch the Monolith
EXPOSE 7860
CMD ["python", "app.py"]