AEUPH commited on
Commit
035a382
·
verified ·
1 Parent(s): 0bde6f1

Update Dockerfile

Browse files
Files changed (1) hide show
  1. Dockerfile +224 -463
Dockerfile CHANGED
@@ -1,526 +1,287 @@
1
- # Use a lightweight Python base
2
  FROM python:3.10-slim
3
 
4
- # Set working directory
5
  WORKDIR /app
6
 
7
- # 1. Install System Dependencies
8
- RUN apt-get update && apt-get install -y \
9
- curl \
10
- git \
11
- libgomp1 \
12
- && rm -rf /var/lib/apt/lists/*
13
-
14
- # 2. Upgrade pip
15
  RUN pip install --upgrade pip
16
 
17
- # 3. Download Retro Font (VT323)
18
- RUN curl -L -o /app/VT323.ttf https://github.com/google/fonts/raw/main/ofl/vt323/VT323-Regular.ttf
19
-
20
- # 4. Install Python Dependencies
21
- RUN pip install --no-cache-dir \
22
- torch \
23
- torchvision \
24
- numpy \
25
- flask \
26
- flask-sock \
27
- diffusers \
28
- transformers \
29
- accelerate \
30
- peft \
31
- pillow \
32
- diskcache \
33
- safetensors \
34
- scipy \
35
- sentencepiece
36
 
37
- # 5. Create a non-root user
38
  RUN useradd -m -u 1000 user
39
  USER user
40
- ENV HOME=/home/user \
41
- PATH=/home/user/.local/bin:$PATH
42
 
43
- # 6. Write the Application
44
- COPY --chown=user <<'EOF' app.py
45
- import sys, os, io, base64, json, warnings, time
46
  import torch
 
47
  import numpy as np
48
  from dataclasses import dataclass
49
- from typing import Dict, List, Optional, Tuple
50
- from flask import Flask, render_template_string
51
  from flask_sock import Sock
52
- from PIL import Image, ImageDraw
53
- from transformers import AutoModelForCausalLM, AutoTokenizer
54
- from diffusers import StableDiffusionPipeline, AutoencoderTiny, LCMScheduler
 
55
 
56
- # Silence Warnings
57
  warnings.filterwarnings("ignore")
58
 
59
- # ============================================================================
60
- # 1. FRONTEND (Responsive React Desktop)
61
- # ============================================================================
62
- HTML_TEMPLATE = r"""
63
- <!DOCTYPE html>
64
- <html lang="en">
65
- <head>
66
- <meta charset="UTF-8">
67
- <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
68
- <title>LiteWin XP - Neural OS Desktop</title>
69
- <script src="https://cdn.tailwindcss.com"></script>
70
- <script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
71
- <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
72
- <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
73
- <link href="https://fonts.googleapis.com/css2?family=Tahoma:wght@400;700&family=Fira+Code:wght@300;500&display=swap" rel="stylesheet">
74
- <style>
75
- body {
76
- background: #111;
77
- color: #e2e2e2;
78
- margin: 0;
79
- overflow: hidden;
80
- font-family: 'Tahoma', sans-serif;
81
- display: flex;
82
- align-items: center;
83
- justify-content: center;
84
- height: 100vh;
85
- width: 100vw;
86
- }
87
-
88
- /* container for scaling */
89
- #desktop-container {
90
- position: relative;
91
- width: 1024px;
92
- height: 1024px;
93
- transform-origin: center center;
94
- box-shadow: 0 0 50px rgba(0,0,0,0.5);
95
- background: #3A6EA5;
96
- }
97
-
98
- .canvas-viewport {
99
- position: absolute;
100
- top: 0; left: 0;
101
- width: 100%; height: 100%;
102
- image-rendering: pixelated;
103
- }
104
- .canvas-viewport img { width: 100%; height: 100%; display: block; }
105
-
106
- .taskbar {
107
- position: absolute; bottom: 0; left: 0; right: 0; height: 60px; /* Taller for mobile */
108
- background: linear-gradient(to bottom, #1F4788 0%, #1A3E6F 50%, #0E2950 100%);
109
- border-top: 3px solid #4D7DB5;
110
- display: flex; align-items: center; padding: 0 8px; gap: 8px;
111
- z-index: 50;
112
- }
113
-
114
- .start-btn {
115
- background: linear-gradient(to bottom, #3F8B3F 0%, #2F6B2F 100%);
116
- border: 3px outset #5FAF5F;
117
- color: white;
118
- font-weight: bold;
119
- padding: 6px 18px;
120
- border-radius: 4px;
121
- cursor: pointer;
122
- font-size: 20px; /* Larger text */
123
- font-style: italic;
124
- text-shadow: 1px 1px 1px #000;
125
- display: flex; align-items: center; gap: 8px;
126
- }
127
-
128
- .start-btn::before {
129
- content: "❖"; /* Windows-ish icon */
130
- font-style: normal;
131
- }
132
-
133
- .console-log {
134
- position: absolute; top: 20px; right: 20px; width: 350px; height: 200px;
135
- background: rgba(0,0,0,0.85);
136
- color: #0f0;
137
- font-family: 'Fira Code', monospace;
138
- font-size: 14px; /* Readable text */
139
- line-height: 1.4;
140
- padding: 15px;
141
- border: 2px solid #333;
142
- border-radius: 4px;
143
- overflow-y: auto;
144
- z-index: 1000;
145
- pointer-events: none;
146
- box-shadow: 0 4px 10px rgba(0,0,0,0.5);
147
- }
148
-
149
- /* Mobile Overlay for logs when very small */
150
- @media (max-width: 600px) {
151
- .console-log {
152
- top: auto; bottom: 80px; left: 10px; right: 10px; width: auto; height: 120px;
153
- }
154
- }
155
- </style>
156
- </head>
157
- <body>
158
- <div id="root"></div>
159
- <script type="text/babel">
160
- const { useState, useEffect, useRef } = React;
161
-
162
- function App() {
163
- const [desktopImage, setDesktopImage] = useState(null);
164
- const [logs, setLogs] = useState(["Neural Bios v9.7", "Booting Kernel..."]);
165
- const [scale, setScale] = useState(1);
166
-
167
- const socketRef = useRef(null);
168
- const containerRef = useRef(null);
169
-
170
- const addLog = (msg) => setLogs(prev => [...prev.slice(-8), msg]);
171
-
172
- // Resize Logic
173
- useEffect(() => {
174
- const handleResize = () => {
175
- const padding = 20; // px
176
- const availableWidth = window.innerWidth - padding;
177
- const availableHeight = window.innerHeight - padding;
178
-
179
- const scaleW = availableWidth / 1024;
180
- const scaleH = availableHeight / 1024;
181
-
182
- // Fit contain
183
- const newScale = Math.min(scaleW, scaleH, 1.0); // Max scale 1.0 (crisp)
184
- setScale(newScale);
185
- };
186
-
187
- window.addEventListener('resize', handleResize);
188
- handleResize(); // Initial calc
189
- return () => window.removeEventListener('resize', handleResize);
190
- }, []);
191
-
192
- // Websocket Logic
193
- useEffect(() => {
194
- const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
195
- const ws = new WebSocket(`${proto}://${window.location.host}/kernel`);
196
- socketRef.current = ws;
197
- ws.onmessage = (e) => {
198
- const msg = JSON.parse(e.data);
199
- if (msg.type === 'frame_update' || msg.type === 'desktop_ready') {
200
- setDesktopImage(msg.data);
201
- }
202
- if (msg.type === 'log') addLog(msg.data);
203
- };
204
- return () => ws.close();
205
- }, []);
206
-
207
- const handleClick = (e) => {
208
- if (!containerRef.current) return;
209
-
210
- // Get click coordinates relative to the scaled container
211
- const rect = containerRef.current.getBoundingClientRect();
212
-
213
- // Calculate position (0-1024)
214
- const clickX = (e.clientX - rect.left) / scale;
215
- const clickY = (e.clientY - rect.top) / scale;
216
-
217
- // Convert to Neural Grid (0-128)
218
- const gridX = Math.floor((clickX / 1024) * 128);
219
- const gridY = Math.floor((clickY / 1024) * 128);
220
-
221
- if(gridX >= 0 && gridX <= 128 && gridY >= 0 && gridY <= 128) {
222
- socketRef.current?.send(JSON.stringify({ type: 'click', x: gridX, y: gridY }));
223
- }
224
- };
225
-
226
- return (
227
- <div
228
- id="desktop-container"
229
- ref={containerRef}
230
- style={{ transform: `scale(${scale})` }}
231
- >
232
- <div className="canvas-viewport" onClick={handleClick}>
233
- {desktopImage && <img src={`data:image/png;base64,${desktopImage}`} draggable="false" />}
234
- </div>
235
-
236
- <div className="taskbar">
237
- <div className="start-btn">start</div>
238
- </div>
239
-
240
- <div className="console-log">
241
- {logs.map((l, i) => <div key={i}>&gt; {l}</div>)}
242
- </div>
243
- </div>
244
- );
245
- }
246
- ReactDOM.createRoot(document.getElementById('root')).render(<App />);
247
- </script>
248
- </body>
249
- </html>
250
- """
251
-
252
- # ============================================================================
253
- # 2. OS KERNEL & PROCESS MANAGEMENT
254
- # ============================================================================
255
 
256
  @dataclass
257
  class Application:
258
- name: str
259
- icon_dna: str
260
- content_prompt: str
261
- default_size: Tuple[int, int]
 
262
 
263
  @dataclass
264
  class Process:
265
- pid: int
266
- name: str
267
- app_type: str
268
- position: Tuple[int, int]
269
- size: Tuple[int, int]
270
- latent_state: torch.Tensor
271
- z_order: int
272
-
273
- PROGRAMS = {
274
- "notepad": Application("Notepad", "ICON_NOTEPAD", "white text editor, courier font", (40, 32)),
275
- "paint": Application("Paint", "ICON_PAINT", "white canvas, ms paint toolbar", (48, 40)),
276
- "cmd": Application("Command Prompt", "ICON_CMD", "black console window, white text", (48, 32)),
277
- "explorer": Application("Explorer", "ICON_FOLDER", "file explorer, icons grid", (56, 40))
 
 
 
278
  }
279
 
280
- DRIVERS = {}
 
 
 
281
 
282
- def initialize_drivers():
283
- bg = torch.zeros((1, 4, 128, 128), dtype=torch.float32)
284
- bg[:, 0, :, :] = 0.5
285
- bg[:, 1, :, :] = 0.8
286
- bg[:, 2, :, :] = 0.2
287
- DRIVERS["DESKTOP_BG"] = bg
288
 
289
- icon = torch.zeros((1, 4, 8, 8), dtype=torch.float32)
290
- icon[:, 0, 2:6, 2:6] = 2.0
291
- DRIVERS["ICON_GENERIC"] = icon
292
- print("[*] Drivers Initialized.")
 
 
 
 
 
293
 
294
  class OSKernel:
295
  def __init__(self):
296
- self.processes: Dict[int, Process] = {}
297
- self.next_pid = 1
298
- self.focused_pid: Optional[int] = None
299
- self.desktop_icons = [
300
- {"app": "notepad", "x": 4, "y": 4, "label": "Notepad"},
301
- {"app": "paint", "x": 4, "y": 16, "label": "Paint"},
302
- {"app": "cmd", "x": 4, "y": 28, "label": "Command Prompt"},
 
 
 
303
  ]
304
-
305
- def spawn_process(self, app_type: str, x: int, y: int) -> int:
306
- if app_type not in PROGRAMS: return -1
307
- app = PROGRAMS[app_type]
308
- pid = self.next_pid
309
- self.next_pid += 1
310
-
311
- w, h = app.default_size
312
- latent = torch.zeros((1, 4, h, w), dtype=torch.float32)
313
-
314
- proc = Process(
315
- pid=pid, name=app.name, app_type=app_type,
316
- position=(x, y), size=(w, h),
317
- latent_state=latent, z_order=pid
318
- )
319
- self.processes[pid] = proc
320
  self.focus_process(pid)
 
321
  return pid
322
-
323
- def kill_process(self, pid: int):
324
  if pid in self.processes:
325
  del self.processes[pid]
326
- if self.focused_pid == pid: self.focused_pid = None
327
-
328
- def focus_process(self, pid: int):
329
  if pid in self.processes:
330
- self.focused_pid = pid
331
- max_z = max((p.z_order for p in self.processes.values()), default=0)
332
- self.processes[pid].z_order = max_z + 1
333
-
334
- def handle_click(self, x: int, y: int) -> Dict:
335
- # Check Windows (Reverse Z)
336
- sorted_procs = sorted(self.processes.values(), key=lambda p: p.z_order, reverse=True)
337
  for proc in sorted_procs:
338
- px, py = proc.position
339
- pw, ph = proc.size
340
- if px <= x < px+pw and py <= y < py+ph:
341
- self.focus_process(proc.pid)
342
- if py <= y < py+4 and px+pw-4 <= x < px+pw:
343
  self.kill_process(proc.pid)
344
- return {"action": "close", "pid": proc.pid, "name": proc.name}
345
- return {"action": "focus", "pid": proc.pid, "name": proc.name}
346
-
347
- # Check Icons
348
  for icon in self.desktop_icons:
349
- ix, iy = icon['x'], icon['y']
350
- if ix <= x < ix+8 and iy <= y < iy+8:
351
- pid = self.spawn_process(icon['app'], x=32, y=24)
352
- return {"action": "launch", "pid": pid, "app": icon['app']}
353
-
354
- return {"action": "desktop_click"}
355
-
356
- # ============================================================================
357
- # 3. AI ENGINES (QWEN + DIFFUSION)
358
- # ============================================================================
359
 
360
  class NeuralSystem:
361
  def __init__(self):
362
- self.device = "cuda" if torch.cuda.is_available() else "cpu"
363
- self.dt = torch.float16 if self.device == "cuda" else torch.float32
364
- print(f"[*] System Device: {self.device} | Type: {self.dt}")
365
-
366
- # A. LOAD DIFFUSION
367
- print("[*] Loading Neural GPU...")
368
- self.pipe = StableDiffusionPipeline.from_pretrained(
369
- "runwayml/stable-diffusion-v1-5",
370
- torch_dtype=self.dt,
371
- safety_checker=None,
372
- requires_safety_checker=False
373
- )
374
- if self.device == "cuda":
375
- self.pipe = self.pipe.to("cuda")
376
-
377
  self.pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5")
378
- self.pipe.scheduler = LCMScheduler.from_config(self.pipe.scheduler.config)
379
- self.pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taesd", torch_dtype=self.dt).to(self.device)
380
-
381
- # B. LOAD QWEN
382
- print("[*] Loading Qwen 2.5...")
383
- self.model_id = "Qwen/Qwen2.5-Coder-0.5B-Instruct"
384
- self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
385
- if self.tokenizer.pad_token_id is None:
386
- self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
387
-
388
- # FIX: Using 'dtype' instead of 'torch_dtype' to silence deprecation warning
389
- # FIX: Removed device_map to prevent meta-tensor error on CPU
390
- self.llm = AutoModelForCausalLM.from_pretrained(
391
- self.model_id,
392
- dtype=self.dt
393
- ).to(self.device)
394
-
395
- print("[*] Systems Online.")
396
-
397
- def think(self, prompt_text):
398
- inputs = self.tokenizer(
399
- prompt_text,
400
- return_tensors="pt",
401
- padding=True,
402
- truncation=True
403
- ).to(self.device)
404
-
405
- outputs = self.llm.generate(
406
- inputs.input_ids,
407
- attention_mask=inputs.attention_mask,
408
- max_new_tokens=64,
409
- do_sample=True,
410
- temperature=0.6,
411
- pad_token_id=self.tokenizer.eos_token_id
412
- )
413
- response = self.tokenizer.decode(outputs[0][len(inputs.input_ids[0]):], skip_special_tokens=True)
414
  return response
415
-
416
- def render_frame(self, kernel: OSKernel):
417
- canvas = DRIVERS["DESKTOP_BG"].clone().to(self.device)
418
- icon_dna = DRIVERS["ICON_GENERIC"].to(self.device)
419
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
  for icon in kernel.desktop_icons:
421
- x, y = icon['x'], icon['y']
422
- canvas[:, :, y:y+8, x:x+8] = icon_dna
423
-
424
- sorted_procs = sorted(kernel.processes.values(), key=lambda p: p.z_order)
425
  for proc in sorted_procs:
426
- x, y = proc.position
427
- w, h = proc.size
428
- if x+w <= 128 and y+h <= 128:
429
- proc_latent = proc.latent_state.to(self.device, dtype=self.dt)
430
- canvas[:, :, y:y+h, x:x+w] = proc_latent
431
-
432
  with torch.no_grad():
433
- img = self.pipe.vae.decode(canvas / 0.18215).sample
434
- img = (img / 2 + 0.5).clamp(0, 1).cpu().permute(0, 2, 3, 1).numpy()
435
- img = self.pipe.numpy_to_pil(img)[0]
436
-
437
  return img
438
 
439
- def generate_window_content(self, proc: Process):
440
- app_def = PROGRAMS[proc.app_type]
441
- prompt = f"pixel art windows xp {app_def.name} window content, {app_def.content_prompt}, crisp UI"
442
-
443
- with torch.no_grad():
444
- latents = torch.randn(
445
- (1, 4, proc.size[1], proc.size[0]),
446
- device=self.device,
447
- dtype=self.dt
448
- )
449
- img_latents = self.pipe(
450
- prompt,
451
- latents=latents,
452
- num_inference_steps=1,
453
- output_type="latent"
454
- ).images
455
-
456
- # Simple Title Bar Injection
457
- img_latents[:, 1, 0:4, :] = 1.5
458
- img_latents[:, 0, 0:4, :] = -0.5
459
- proc.latent_state = img_latents
460
-
461
- # ============================================================================
462
- # 4. MAIN SERVER
463
- # ============================================================================
464
-
465
- sys_engine = None
466
- kernel_instance = OSKernel()
467
  initialize_drivers()
468
 
469
- app = Flask(__name__)
470
- sock = Sock(app)
 
 
 
 
 
 
 
 
 
 
 
 
471
 
472
  @sock.route('/kernel')
473
  def socket_handler(ws):
474
  global sys_engine
475
  if sys_engine is None:
476
- sys_engine = NeuralSystem()
477
-
478
- ws.send(json.dumps({"type": "log", "data": "Kernel Attached."}))
479
-
480
- img = sys_engine.render_frame(kernel_instance)
481
- buf = io.BytesIO()
482
- img.save(buf, format="PNG")
483
- ws.send(json.dumps({
484
- "type": "desktop_ready",
485
- "data": base64.b64encode(buf.getvalue()).decode()
486
- }))
487
-
488
  while True:
489
- data = ws.receive()
490
- if not data: break
491
- msg = json.loads(data)
492
-
493
- if msg['type'] == 'click':
494
- res = kernel_instance.handle_click(msg['x'], msg['y'])
495
-
496
- if res['action'] == 'launch':
497
- ws.send(json.dumps({"type": "log", "data": f"Launching {res['app']}..."}))
498
- proc = kernel_instance.processes[res['pid']]
499
  sys_engine.generate_window_content(proc)
500
-
501
- elif res['action'] == 'close':
502
- ws.send(json.dumps({"type": "log", "data": f"Closed {res['name']}"}))
503
-
504
- elif res['action'] == 'desktop_click':
505
- thought = sys_engine.think(f"User clicked background at {msg['x']},{msg['y']}. Short witty system log:")
506
- ws.send(json.dumps({"type": "log", "data": f"SYS: {thought}"}))
507
-
508
- img = sys_engine.render_frame(kernel_instance)
509
- buf = io.BytesIO()
510
- img.save(buf, format="PNG")
511
- ws.send(json.dumps({
512
- "type": "frame_update",
513
- "data": base64.b64encode(buf.getvalue()).decode()
514
- }))
 
 
 
 
515
 
516
  @app.route('/')
517
- def index():
518
- return HTML_TEMPLATE
519
 
520
- if __name__ == '__main__':
521
- app.run(host='0.0.0.0', port=7860)
522
- EOF
523
 
524
- # 7. Launch
525
  EXPOSE 7860
526
- CMD ["python", "app.py"]
 
1
+ # NEURAL OS HYPER-CORE v2.0 - 100% Performance Boost
2
  FROM python:3.10-slim
3
 
 
4
  WORKDIR /app
5
 
6
+ RUN apt-get update && apt-get install -y curl git libgomp1 && rm -rf /var/lib/apt/lists/*
 
 
 
 
 
 
 
7
  RUN pip install --upgrade pip
8
 
9
+ RUN pip install --no-cache-dir torch torchvision numpy flask flask-sock \
10
+ diffusers transformers accelerate peft pillow diskcache safetensors scipy sentencepiece
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
 
12
  RUN useradd -m -u 1000 user
13
  USER user
14
+ ENV HOME=/home/user PATH=/home/user/.local/bin:$PATH
 
15
 
16
+ COPY --chown=user <<'HYPER_EOF' app.py
17
+ import sys,os,io,base64,json,warnings,time,threading
18
+ from queue import Queue
19
  import torch
20
+ import torch.nn.functional as F
21
  import numpy as np
22
  from dataclasses import dataclass
23
+ from typing import Dict,List,Optional,Tuple
24
+ from flask import Flask
25
  from flask_sock import Sock
26
+ from PIL import Image,ImageDraw,ImageFont
27
+ from transformers import AutoModelForCausalLM,AutoTokenizer
28
+ from diffusers import StableDiffusionPipeline,AutoencoderTiny,LCMScheduler
29
+ import diskcache
30
 
 
31
  warnings.filterwarnings("ignore")
32
 
33
+ 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</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.0","⚙️ Initializing...","🧠 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/png;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">&gt;{l}</div>)}</div></div>);}ReactDOM.createRoot(document.getElementById('root')).render(<App/>);</script></body></html>"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  @dataclass
36
  class Application:
37
+ name:str
38
+ icon_prompt:str
39
+ content_prompt:str
40
+ default_size:Tuple[int,int]
41
+ refinement_steps:int=2
42
 
43
  @dataclass
44
  class Process:
45
+ pid:int
46
+ name:str
47
+ app_type:str
48
+ position:Tuple[int,int]
49
+ size:Tuple[int,int]
50
+ latent_state:torch.Tensor
51
+ z_order:int
52
+ refinement_level:int=0
53
+ last_refined:float=0
54
+
55
+ PROGRAMS={
56
+ "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),
57
+ "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),
58
+ "cmd":Application("CMD","pixel art terminal icon black screen white prompt 32x32 crisp","command prompt black white monospace C:\\ detailed",(52,36),2),
59
+ "explorer":Application("Explorer","pixel art folder icon yellow folder 32x32 crisp detailed","windows explorer folder tree file icons toolbar detailed UI",(60,46),3),
60
+ "browser":Application("Browser","pixel art browser icon blue globe 32x32 crisp detailed","web browser address bar navigation buttons detailed UI",(64,48),3)
61
  }
62
 
63
+ class IconCache:
64
+ def __init__(self):self.cache={}
65
+ def get(self,k):return self.cache.get(k)
66
+ def set(self,k,v):self.cache[k]=v
67
 
68
+ ICON_CACHE=IconCache()
69
+ DRIVERS={}
 
 
 
 
70
 
71
+ def initialize_drivers():
72
+ bg=torch.zeros((1,4,128,128),dtype=torch.float32)
73
+ for y in range(128):
74
+ i=0.3+(y/128)*0.5
75
+ bg[:, 0,y,:]=i*0.4
76
+ bg[:,1,y,:]=i*0.9
77
+ bg[:,2,y,:]=i*0.2
78
+ DRIVERS["DESKTOP_BG"]=bg
79
+ print("[✓] Drivers Init - HQ Background")
80
 
81
  class OSKernel:
82
  def __init__(self):
83
+ self.processes:Dict[int,Process]={}
84
+ self.next_pid=1
85
+ self.focused_pid:Optional[int]=None
86
+ self.refinement_queue=Queue()
87
+ self.desktop_icons=[
88
+ {"app":"notepad","x":6,"y":6,"label":"Notepad"},
89
+ {"app":"paint","x":6,"y":20,"label":"Paint"},
90
+ {"app":"cmd","x":6,"y":34,"label":"CMD"},
91
+ {"app":"explorer","x":6,"y":48,"label":"Explorer"},
92
+ {"app":"browser","x":6,"y":62,"label":"Browser"}
93
  ]
94
+
95
+ def spawn_process(self,app_type:str,x:int=32,y:int=24)->int:
96
+ if app_type not in PROGRAMS:return -1
97
+ app=PROGRAMS[app_type]
98
+ pid=self.next_pid
99
+ self.next_pid+=1
100
+ w,h=app.default_size
101
+ latent=torch.zeros((1,4,h,w),dtype=torch.float32)
102
+ proc=Process(pid,app.name,app_type,(x,y),(w,h),latent,pid,0,time.time())
103
+ self.processes[pid]=proc
 
 
 
 
 
 
104
  self.focus_process(pid)
105
+ self.refinement_queue.put(pid)
106
  return pid
107
+
108
+ def kill_process(self,pid:int):
109
  if pid in self.processes:
110
  del self.processes[pid]
111
+ if self.focused_pid==pid:self.focused_pid=None
112
+
113
+ def focus_process(self,pid:int):
114
  if pid in self.processes:
115
+ self.focused_pid=pid
116
+ max_z=max((p.z_order for p in self.processes.values()),default=0)
117
+ self.processes[pid].z_order=max_z+1
118
+
119
+ def handle_click(self,x:int,y:int)->Dict:
120
+ sorted_procs=sorted(self.processes.values(),key=lambda p:p.z_order,reverse=True)
 
121
  for proc in sorted_procs:
122
+ px,py=proc.position
123
+ pw,ph=proc.size
124
+ if px<=x<px+pw and py<=y<py+ph:
125
+ if py<=y<py+4 and px+pw-4<=x<px+pw:
 
126
  self.kill_process(proc.pid)
127
+ return{"action":"close","pid":proc.pid,"name":proc.name}
128
+ self.focus_process(proc.pid)
129
+ return{"action":"focus","pid":proc.pid,"name":proc.name}
 
130
  for icon in self.desktop_icons:
131
+ ix,iy=icon['x'],icon['y']
132
+ if ix<=x<ix+10 and iy<=y<iy+10:
133
+ pid=self.spawn_process(icon['app'],28+(len(self.processes)%3)*12,20+(len(self.processes)%3)*8)
134
+ return{"action":"launch","pid":pid,"app":icon['app']}
135
+ return{"action":"desktop_click","x":x,"y":y}
 
 
 
 
 
136
 
137
  class NeuralSystem:
138
  def __init__(self):
139
+ self.device="cuda" if torch.cuda.is_available() else "cpu"
140
+ self.dt=torch.float16 if self.device=="cuda" else torch.float32
141
+ print(f"[] Device:{self.device}|Type:{self.dt}")
142
+ print("[🧠] Loading Neural Renderer...")
143
+ self.pipe=StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5",torch_dtype=self.dt,safety_checker=None,requires_safety_checker=False)
144
+ if self.device=="cuda":
145
+ self.pipe=self.pipe.to("cuda")
146
+ self.pipe.enable_attention_slicing()
 
 
 
 
 
 
 
147
  self.pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5")
148
+ self.pipe.scheduler=LCMScheduler.from_config(self.pipe.scheduler.config)
149
+ self.pipe.vae=AutoencoderTiny.from_pretrained("madebyollin/taesd",torch_dtype=self.dt).to(self.device)
150
+ print("[🧠] Loading AI...")
151
+ self.model_id="Qwen/Qwen2.5-Coder-0.5B-Instruct"
152
+ self.tokenizer=AutoTokenizer.from_pretrained(self.model_id)
153
+ if self.tokenizer.pad_token_id is None:self.tokenizer.pad_token_id=self.tokenizer.eos_token_id
154
+ self.llm=AutoModelForCausalLM.from_pretrained(self.model_id,torch_dtype=self.dt).to(self.device)
155
+ self.content_cache=diskcache.Cache('/tmp/neural_cache')
156
+ print("[✓] Systems Online")
157
+
158
+ def think(self,prompt:str,max_tok:int=48)->str:
159
+ cache_key=f"think_{hash(prompt)}"
160
+ cached=self.content_cache.get(cache_key)
161
+ if cached:return cached
162
+ inputs=self.tokenizer(prompt,return_tensors="pt",padding=True,truncation=True).to(self.device)
163
+ with torch.no_grad():
164
+ outputs=self.llm.generate(inputs.input_ids,attention_mask=inputs.attention_mask,max_new_tokens=max_tok,do_sample=True,temperature=0.7,pad_token_id=self.tokenizer.eos_token_id)
165
+ response=self.tokenizer.decode(outputs[0][len(inputs.input_ids[0]):],skip_special_tokens=True).strip()
166
+ self.content_cache.set(cache_key,response,expire=3600)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  return response
168
+
169
+ def generate_icon(self,app_type:str)->torch.Tensor:
170
+ cache_key=f"icon_{app_type}"
171
+ cached=ICON_CACHE.get(cache_key)
172
+ if cached is not None:return cached
173
+ app=PROGRAMS[app_type]
174
+ with torch.no_grad():
175
+ latents=torch.randn((1,4,10,10),device=self.device,dtype=self.dt)*0.8
176
+ result=self.pipe(app.icon_prompt,latents=latents,num_inference_steps=2,guidance_scale=1.0,output_type="latent").images
177
+ result=result*1.3
178
+ ICON_CACHE.set(cache_key,result)
179
+ return result
180
+
181
+ def generate_window_content(self,proc:Process,steps:int=1):
182
+ app_def=PROGRAMS[proc.app_type]
183
+ ref_desc=f" refinement {proc.refinement_level}" if proc.refinement_level>0 else ""
184
+ prompt=f"windows xp {app_def.name}{ref_desc} {app_def.content_prompt} highly detailed sharp"
185
+ with torch.no_grad():
186
+ if proc.refinement_level==0:
187
+ latents=torch.randn((1,4,proc.size[1],proc.size[0]),device=self.device,dtype=self.dt)*0.5
188
+ else:
189
+ latents=proc.latent_state.to(self.device,dtype=self.dt)
190
+ noise=torch.randn_like(latents)*0.1
191
+ latents=latents+noise
192
+ img_latents=self.pipe(prompt,latents=latents,num_inference_steps=steps,guidance_scale=1.0,output_type="latent").images
193
+ img_latents[:,1,0:4,:]=1.5
194
+ img_latents[:,0,0:4,:]=0.5
195
+ img_latents[:,2,1:3,-4:-1]=2.0
196
+ proc.latent_state=img_latents
197
+ proc.refinement_level+=1
198
+ proc.last_refined=time.time()
199
+
200
+ def render_frame(self,kernel:OSKernel):
201
+ canvas=DRIVERS["DESKTOP_BG"].clone().to(self.device)
202
  for icon in kernel.desktop_icons:
203
+ icon_latent=self.generate_icon(icon['app']).to(self.device,dtype=self.dt)
204
+ x,y=icon['x'],icon['y']
205
+ canvas[:,:,y:y+10,x:x+10]=icon_latent
206
+ sorted_procs=sorted(kernel.processes.values(),key=lambda p:p.z_order)
207
  for proc in sorted_procs:
208
+ x,y=proc.position
209
+ w,h=proc.size
210
+ if x+w<=128 and y+h<=128:
211
+ proc_latent=proc.latent_state.to(self.device,dtype=self.dt)
212
+ canvas[:,:,y:y+h,x:x+w]=proc_latent
 
213
  with torch.no_grad():
214
+ img=self.pipe.vae.decode(canvas/0.18215).sample
215
+ img=(img/2+0.5).clamp(0,1).cpu().permute(0,2,3,1).numpy()
216
+ img=self.pipe.numpy_to_pil(img)[0]
 
217
  return img
218
 
219
+ sys_engine=None
220
+ kernel_instance=OSKernel()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
  initialize_drivers()
222
 
223
+ app=Flask(__name__)
224
+ sock=Sock(app)
225
+
226
+ def refinement_worker(sys_engine,kernel):
227
+ while True:
228
+ if not kernel.refinement_queue.empty():
229
+ pid=kernel.refinement_queue.get()
230
+ if pid in kernel.processes:
231
+ proc=kernel.processes[pid]
232
+ app=PROGRAMS[proc.app_type]
233
+ if proc.refinement_level<app.refinement_steps:
234
+ sys_engine.generate_window_content(proc,steps=1)
235
+ kernel.refinement_queue.put(pid)
236
+ time.sleep(0.5)
237
 
238
  @sock.route('/kernel')
239
  def socket_handler(ws):
240
  global sys_engine
241
  if sys_engine is None:
242
+ sys_engine=NeuralSystem()
243
+ ref_thread=threading.Thread(target=refinement_worker,args=(sys_engine,kernel_instance),daemon=True)
244
+ ref_thread.start()
245
+ ws.send(json.dumps({"type":"log","data":"Kernel Attached"}))
246
+ img=sys_engine.render_frame(kernel_instance)
247
+ buf=io.BytesIO()
248
+ img.save(buf,format="PNG")
249
+ ws.send(json.dumps({"type":"desktop_ready","data":base64.b64encode(buf.getvalue()).decode()}))
 
 
 
 
250
  while True:
251
+ data=ws.receive()
252
+ if not data:break
253
+ msg=json.loads(data)
254
+ if msg['type']=='click':
255
+ res=kernel_instance.handle_click(msg['x'],msg['y'])
256
+ if res['action']=='launch':
257
+ ws.send(json.dumps({"type":"log","data":f"🚀 Launching {res['app']}..."}))
258
+ proc=kernel_instance.processes[res['pid']]
 
 
259
  sys_engine.generate_window_content(proc)
260
+ elif res['action']=='close':
261
+ ws.send(json.dumps({"type":"log","data":f"❌ Closed {res['name']}"}))
262
+ elif res['action']=='desktop_click':
263
+ thought=sys_engine.think(f"User clicked desktop at {msg['x']},{msg['y']}. Witty system log:")
264
+ ws.send(json.dumps({"type":"log","data":f"💭 {thought}"}))
265
+ img=sys_engine.render_frame(kernel_instance)
266
+ buf=io.BytesIO()
267
+ img.save(buf,format="PNG")
268
+ ws.send(json.dumps({"type":"frame_update","data":base64.b64encode(buf.getvalue()).decode()}))
269
+ elif msg['type']=='launch_app':
270
+ pid=kernel_instance.spawn_process(msg['app'])
271
+ if pid!=-1:
272
+ ws.send(json.dumps({"type":"log","data":f"📱 Started {msg['app']}"}))
273
+ proc=kernel_instance.processes[pid]
274
+ sys_engine.generate_window_content(proc)
275
+ img=sys_engine.render_frame(kernel_instance)
276
+ buf=io.BytesIO()
277
+ img.save(buf,format="PNG")
278
+ ws.send(json.dumps({"type":"frame_update","data":base64.b64encode(buf.getvalue()).decode()}))
279
 
280
  @app.route('/')
281
+ def index():return HTML
 
282
 
283
+ if __name__=='__main__':app.run(host='0.0.0.0',port=7860)
284
+ HYPER_EOF
 
285
 
 
286
  EXPOSE 7860
287
+ CMD ["python","app.py"]