AEUPH commited on
Commit
2c14c01
·
verified ·
1 Parent(s): 6962bce

Update Dockerfile

Browse files
Files changed (1) hide show
  1. Dockerfile +119 -387
Dockerfile CHANGED
@@ -5,21 +5,22 @@ FROM python:3.10-slim
5
  WORKDIR /app
6
 
7
  # 1. Install System Dependencies
8
- # Basic tools required for the OS simulation
9
  RUN apt-get update && apt-get install -y \
10
  curl \
11
  git \
12
  libgomp1 \
13
  && rm -rf /var/lib/apt/lists/*
14
 
15
- # 2. Upgrade pip (Essential for finding modern wheels)
16
- RUN pip install --upgrade pip setuptools wheel
17
 
18
  # 3. Download Retro Font (VT323)
19
  RUN curl -L -o /app/VT323.ttf https://github.com/google/fonts/raw/main/ofl/vt323/VT323-Regular.ttf
20
 
21
- # 4. Install Core Python Dependencies (Split for caching)
22
- # These are safe and install quickly.
 
23
  RUN pip install --no-cache-dir \
24
  torch \
25
  torchvision \
@@ -33,52 +34,33 @@ RUN pip install --no-cache-dir \
33
  pillow \
34
  diskcache \
35
  safetensors \
36
- scipy
 
37
 
38
- # 5. ATTEMPT Fast Llama Install (Optional)
39
- # --only-binary: Prevents the slow compilation loop.
40
- # || true: Allows the build to continue even if this fails.
41
- # We will handle the missing library in app.py
42
- RUN pip install llama-cpp-python \
43
- --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu \
44
- --only-binary=llama-cpp-python \
45
- || echo "⚠️ Llama-CPP wheel not found. Skipping to avoid compile hang."
46
-
47
- # 6. Create a non-root user
48
  RUN useradd -m -u 1000 user
49
  USER user
50
  ENV HOME=/home/user \
51
  PATH=/home/user/.local/bin:$PATH
52
 
53
- # 7. Write the Monolith Application to disk
54
  COPY --chown=user <<'EOF' app.py
55
- import sys, os, io, base64, json, pickle, time
56
- import numpy as np
57
  import torch
58
- from pathlib import Path
59
- from dataclasses import dataclass
60
- from typing import Dict, List, Optional
61
- from flask import Flask, request, send_file, render_template_string
62
  from flask_sock import Sock
63
- from diffusers import StableDiffusionPipeline, AutoencoderTiny, LCMScheduler
64
  from PIL import Image, ImageDraw
 
 
 
65
 
66
- # ============================================================================
67
- # SAFE IMPORT LOGIC
68
- # ============================================================================
69
- try:
70
- from llama_cpp import Llama
71
- HAS_LLM = True
72
- print("[*] Llama-CPP module loaded successfully.")
73
- except ImportError:
74
- HAS_LLM = False
75
- print("[!] NOTICE: Llama-CPP not found. Text generation features will be disabled.")
76
- print("[!] The graphical OS and image generation will still work perfectly.")
77
 
78
  # ============================================================================
79
- # 1. FRONTEND ASSET
80
  # ============================================================================
81
-
82
  HTML_TEMPLATE = r"""
83
  <!DOCTYPE html>
84
  <html lang="en">
@@ -91,420 +73,170 @@ HTML_TEMPLATE = r"""
91
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
92
  <link href="https://fonts.googleapis.com/css2?family=Tahoma:wght@400;700&family=Fira+Code:wght@300;500&display=swap" rel="stylesheet">
93
  <style>
94
- * { box-sizing: border-box; }
95
- body {
96
- background: #010102;
97
- color: #e2e2e2;
98
- font-family: 'Tahoma', sans-serif;
99
- margin: 0;
100
- overflow: hidden;
101
- cursor: auto;
102
- }
103
- .desktop-area {
104
- position: relative;
105
- width: 100vw;
106
- height: 100vh;
107
- background: #3A6EA5;
108
- background-image: linear-gradient(to bottom, #5A9FD4 0%, #306088 100%);
109
- }
110
- .canvas-viewport {
111
- position: absolute;
112
- top: 50%;
113
- left: 50%;
114
- transform: translate(-50%, -50%);
115
- width: 1024px;
116
- height: 1024px;
117
- background: #000;
118
- box-shadow: 0 0 100px rgba(0,0,0,0.9);
119
- border: 2px solid #1a1a1e;
120
- image-rendering: pixelated;
121
- }
122
- .canvas-viewport img { width: 100%; height: 100%; image-rendering: pixelated; }
123
- .taskbar {
124
- position: absolute; bottom: 0; left: 0; right: 0; height: 48px;
125
- background: linear-gradient(to bottom, #1F4788 0%, #1A3E6F 50%, #0E2950 100%);
126
- border-top: 2px solid #4D7DB5; display: flex; align-items: center; padding: 0 4px; gap: 4px;
127
- }
128
- .start-button {
129
- background: linear-gradient(to bottom, #3F8B3F 0%, #2F6B2F 100%);
130
- border: 2px outset #5FAF5F; color: white; font-weight: bold; padding: 4px 12px;
131
- border-radius: 3px; cursor: pointer; font-size: 13px; display: flex; align-items: center; gap: 6px;
132
  }
133
- .taskbar-window {
134
- background: linear-gradient(to bottom, #B5D3E7 0%, #7BA7C7 100%);
135
- border: 2px outset #D0E5F5; padding: 4px 10px; border-radius: 3px; cursor: pointer;
136
- font-size: 11px; max-width: 160px; color: #000;
 
137
  }
138
- .taskbar-window.active { background: linear-gradient(to bottom, #7BA7C7 0%, #5A86A7 100%); border-style: inset; color: white; }
139
- .sidebar {
140
- position: fixed; left: 0; top: 0; bottom: 48px; width: 320px;
141
- background: rgba(10, 10, 12, 0.95); border-right: 1px solid #1a1a1e;
142
- backdrop-filter: blur(10px); z-index: 1000; overflow-y: auto; padding: 20px;
143
- font-family: 'Fira Code', monospace;
144
- }
145
- .inspector {
146
- position: fixed; right: 0; top: 0; bottom: 48px; width: 340px;
147
- background: rgba(10, 10, 12, 0.95); border-left: 1px solid #1a1a1e;
148
- backdrop-filter: blur(10px); padding: 20px; font-family: 'Fira Code', monospace; overflow-y: auto;
149
- }
150
- .code-block { background: #0a0a0c; border: 1px solid #1a1a1e; padding: 12px; font-size: 10px; color: #34d399; }
151
  </style>
152
  </head>
153
  <body>
154
  <div id="root"></div>
155
  <script type="text/babel">
156
  const { useState, useEffect, useRef } = React;
157
- const APPS = [
158
- { id: 'notepad', name: 'Notepad', icon: '📝' },
159
- { id: 'paint', name: 'Paint', icon: '🎨' },
160
- { id: 'cmd', name: 'Command Prompt', icon: '⌨️' },
161
- { id: 'explorer', name: 'Explorer', icon: '📁' },
162
- ];
163
  function App() {
164
  const [desktopImage, setDesktopImage] = useState(null);
165
- const [processes, setProcesses] = useState([]);
166
- const [startMenuOpen, setStartMenuOpen] = useState(false);
167
  const socketRef = useRef(null);
168
- const canvasRef = useRef(null);
 
169
 
170
  useEffect(() => {
171
- const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
172
- const ws = new WebSocket(`${proto}://${window.location.host}/kernel`);
173
  socketRef.current = ws;
174
  ws.onmessage = (e) => {
175
  const msg = JSON.parse(e.data);
176
- if (msg.type === 'desktop_ready' || msg.type === 'frame_update') {
177
  setDesktopImage(msg.data);
178
- if (msg.processes) setProcesses(msg.processes);
179
  }
 
180
  };
181
  return () => ws.close();
182
  }, []);
183
 
184
- const handleCanvasClick = (e) => {
185
- if (!canvasRef.current) return;
186
- const rect = canvasRef.current.getBoundingClientRect();
187
  const x = Math.floor(((e.clientX - rect.left) / rect.width) * 128);
188
  const y = Math.floor(((e.clientY - rect.top) / rect.height) * 128);
189
  socketRef.current?.send(JSON.stringify({ type: 'click', x, y }));
190
  };
191
 
192
- const launchApp = (appId) => {
193
- socketRef.current?.send(JSON.stringify({ type: 'launch_app', app: appId }));
194
- setStartMenuOpen(false);
195
- };
196
-
197
  return (
198
- <div className="desktop-area">
199
- <div ref={canvasRef} className="canvas-viewport" onClick={handleCanvasClick}>
200
  {desktopImage && <img src={`data:image/png;base64,${desktopImage}`} />}
201
  </div>
202
- <div className="taskbar">
203
- <div className="start-button" onClick={() => setStartMenuOpen(!startMenuOpen)}>start</div>
204
- {processes.map(p => <div key={p.pid} className="taskbar-window">{p.name}</div>)}
205
- </div>
206
- {startMenuOpen && (
207
- <div style={{ position: 'absolute', bottom: '50px', left: '4px', width: '220px', background: '#f0f0f0', border: '2px outset #ccc' }}>
208
- {APPS.map(app => (
209
- <div key={app.id} onClick={() => launchApp(app.id)} style={{ padding: '8px', cursor: 'pointer', color: 'black' }}>
210
- {app.icon} {app.name}
211
- </div>
212
- ))}
213
- </div>
214
- )}
215
- <div className="sidebar">
216
- <h1>🔧 Neural_IDE</h1>
217
- <p>Monolith Build v9.3</p>
218
  </div>
219
  </div>
220
  );
221
  }
222
- const root = ReactDOM.createRoot(document.getElementById('root'));
223
- root.render(<App />);
224
  </script>
225
  </body>
226
  </html>
227
  """
228
 
229
  # ============================================================================
230
- # 2. DRIVERS & KERNEL LOGIC
231
  # ============================================================================
232
 
233
- DRIVERS = {
234
- "TITLE_BAR": torch.zeros((1, 4, 4, 32), dtype=torch.float16),
235
- "TITLE_BAR_INACTIVE": torch.zeros((1, 4, 4, 32), dtype=torch.float16),
236
- "CLOSE_BTN": torch.zeros((1, 4, 4, 4), dtype=torch.float16),
237
- "TASKBAR": torch.zeros((1, 4, 6, 128), dtype=torch.float16),
238
- "START_BTN": torch.zeros((1, 4, 6, 24), dtype=torch.float16),
239
- "DESKTOP_BG": torch.zeros((1, 4, 128, 128), dtype=torch.float16),
240
- "ICON_NOTEPAD": torch.zeros((1, 4, 8, 8), dtype=torch.float16),
241
- "ICON_PAINT": torch.zeros((1, 4, 8, 8), dtype=torch.float16),
242
- "ICON_CMD": torch.zeros((1, 4, 8, 8), dtype=torch.float16),
243
- "ICON_FOLDER": torch.zeros((1, 4, 8, 8), dtype=torch.float16),
244
- }
245
-
246
- def initialize_drivers():
247
- DRIVERS["TITLE_BAR"][:, 0, 0:1, :] = 2.0
248
- DRIVERS["TITLE_BAR"][:, 0, 1:3, :] = 1.2
249
- DRIVERS["TITLE_BAR"][:, 1, :, :] = -1.0
250
- DRIVERS["CLOSE_BTN"][:, 2, :, :] = 2.5
251
- DRIVERS["TASKBAR"][:, 0, 0, :] = 1.2
252
- DRIVERS["START_BTN"][:, 1, 1:5, 2:22] = 1.8
253
- DRIVERS["DESKTOP_BG"][:, 1, 0:80, :] = 1.2
254
- DRIVERS["DESKTOP_BG"][:, 2, 0:80, :] = 1.5
255
- DRIVERS["DESKTOP_BG"][:, 1, 80:128, :] = 0.8
256
- DRIVERS["ICON_NOTEPAD"][:, 0, :, :] = 1.5
257
- print("[*] LiteWin High-Fidelity DNA v4 initialized")
258
-
259
- @dataclass
260
- class Process:
261
- pid: int
262
- name: str
263
- app_type: str
264
- position: tuple
265
- size: tuple
266
- latent_state: torch.Tensor
267
- status: str = "running"
268
- z_order: int = 0
269
- def to_dict(self):
270
- return {"pid": self.pid, "name": self.name, "app_type": self.app_type, "position": self.position, "size": self.size}
271
-
272
- @dataclass
273
- class Application:
274
- name: str
275
- icon_dna: str
276
- window_prompt: str
277
- content_prompt: str
278
- default_size: tuple
279
-
280
- PROGRAMS = {
281
- "notepad": Application("Notepad", "ICON_NOTEPAD", "high quality windows_xp notepad", "white text editor", (48, 40)),
282
- "paint": Application("Paint", "ICON_PAINT", "official MS Paint", "white canvas", (64, 48)),
283
- "cmd": Application("Command Prompt", "ICON_CMD", "windows terminal", "black console", (56, 40)),
284
- "explorer": Application("Explorer", "ICON_FOLDER", "windows explorer", "file browser", (72, 56))
285
- }
286
-
287
- class OSKernel:
288
  def __init__(self):
289
- self.processes: Dict[int, Process] = {}
290
- self.next_pid = 1
291
- self.focused_pid: Optional[int] = None
292
- self.desktop_latent = DRIVERS["DESKTOP_BG"].clone()
293
- self.desktop_icons = [
294
- {"app": "notepad", "x": 4, "y": 4, "label": "Notepad"},
295
- {"app": "paint", "x": 4, "y": 16, "label": "Paint"},
296
- {"app": "cmd", "x": 4, "y": 28, "label": "Command Prompt"},
297
- {"app": "explorer", "x": 4, "y": 40, "label": "My Computer"},
298
- ]
299
- self.start_menu_open = False
300
 
301
- def spawn_process(self, app_type: str, x: int, y: int) -> int:
302
- if app_type not in PROGRAMS: return -1
303
- app = PROGRAMS[app_type]
304
- pid = self.next_pid
305
- self.next_pid += 1
306
- w, h = app.default_size
307
- proc = Process(pid, app.name, app_type, (x, y), (w, h), torch.zeros((1, 4, h, w), dtype=torch.float16), "running", pid)
308
- self.processes[pid] = proc
309
- self.focus_process(pid)
310
- return pid
311
-
312
- def kill_process(self, pid: int):
313
- if pid in self.processes:
314
- del self.processes[pid]
315
- if self.focused_pid == pid: self.focused_pid = None
316
-
317
- def focus_process(self, pid: int):
318
- if pid in self.processes:
319
- self.focused_pid = pid
320
- max_z = max((p.z_order for p in self.processes.values()), default=0)
321
- self.processes[pid].z_order = max_z + 1
322
-
323
- def composite_frame(self) -> torch.Tensor:
324
- output = self.desktop_latent.clone()
325
- for icon in self.desktop_icons:
326
- app = PROGRAMS[icon['app']]
327
- if app.icon_dna in DRIVERS:
328
- dna = DRIVERS[app.icon_dna]
329
- x, y = icon['x'], icon['y']
330
- output[:, :, y:y+8, x:x+8] = dna
331
- running_procs = [p for p in self.processes.values() if p.status == "running"]
332
- for proc in sorted(running_procs, key=lambda p: p.z_order):
333
- x, y = proc.position
334
- w, h = proc.size
335
- if x + w > 128 or y + h > 128: continue
336
- output[:, :, y:y+h, x:x+w] = proc.latent_state
337
- taskbar = DRIVERS["TASKBAR"].clone()
338
- taskbar[:, :, :, 0:24] = DRIVERS["START_BTN"]
339
- output[:, :, 122:128, :] = taskbar
340
- return output
341
-
342
- def handle_click(self, x: int, y: int) -> Dict:
343
- if y >= 122:
344
- if x < 24:
345
- self.start_menu_open = not self.start_menu_open
346
- return {"action": "toggle_start_menu", "open": self.start_menu_open}
347
- return {"action": "none"}
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", "app": icon['app'], "pid": pid}
353
- for proc in sorted(self.processes.values(), key=lambda p: p.z_order, reverse=True):
354
- if proc.status != "running": continue
355
- px, py = proc.position
356
- pw, ph = proc.size
357
- if px <= x < px+pw and py <= y < py+ph:
358
- self.focus_process(proc.pid)
359
- if py <= y < py+4 and px+pw-4 <= x < px+pw:
360
- self.kill_process(proc.pid)
361
- return {"action": "close", "pid": proc.pid}
362
- return {"action": "focus", "pid": proc.pid}
363
- return {"action": "none"}
364
 
365
  # ============================================================================
366
- # 3. SERVER & ML PIPELINE
367
  # ============================================================================
368
 
 
 
 
369
  app = Flask(__name__)
370
  sock = Sock(app)
371
- pipe = None
372
- llm = None
373
- kernel = OSKernel()
374
- GGUF_MODEL_PATH = "models/qwen2.5-coder-0.5b-instruct-q8_0.gguf"
375
- STEPS = 1
376
-
377
- def get_pipe():
378
- global pipe, STEPS
379
- if pipe is None:
380
- print("[*] Booting Neural Kernel...")
381
- device = "cuda" if torch.cuda.is_available() else "cpu"
382
- dt = torch.float16 if device == "cuda" else torch.float32
383
- pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=dt).to(device)
384
- try:
385
- if device == "cuda":
386
- pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5")
387
- pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
388
- pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taesd", torch_dtype=dt).to(device)
389
- STEPS = 1
390
- print("[✓] LCM + TAE Enabled")
391
- else:
392
- STEPS = 4
393
- except Exception as e:
394
- print(f"[!] Optimization failed: {e}")
395
- return pipe
396
-
397
- def decode_layer(latents, p):
398
- with torch.no_grad():
399
- latents = 1 / 0.18215 * latents
400
- latents = latents.to(device=p.device, dtype=p.vae.dtype)
401
- image = p.vae.decode(latents).sample
402
- image = (image / 2 + 0.5).clamp(0, 1).nan_to_num()
403
- image = image.cpu().permute(0, 2, 3, 1).numpy()
404
- image = p.numpy_to_pil(image)[0]
405
- buf = io.BytesIO()
406
- image.save(buf, format="PNG")
407
- return base64.b64encode(buf.getvalue()).decode()
408
 
409
- def render_perfect_window_latent(p, w_blocks, h_blocks, title="Window"):
410
- width, height = w_blocks * 8, h_blocks * 8
411
- img = Image.new('RGB', (width, height), color=(236, 233, 216))
412
- draw = ImageDraw.Draw(img)
413
- draw.rectangle([0, 0, width-1, height-1], outline=(0, 0, 0))
414
- draw.rectangle([1, 1, width-2, 31], fill=(0, 84, 227)) # Blue Title
415
- draw.rectangle([4, 32, width-5, height-5], fill=(255, 255, 255)) # Content
416
-
417
- img_t = torch.from_numpy(np.array(img)).permute(2, 0, 1).float() / 255.0
418
- img_t = (img_t * 2.0 - 1.0).unsqueeze(0).to(device=p.device, dtype=p.vae.dtype)
419
- with torch.no_grad():
420
- latent = p.vae.encode(img_t).latent_dist.sample() * 0.18215
421
- return latent.cpu()
422
-
423
- def generate_window_fast(p, kernel, pid):
424
- device = p.device
425
- proc = kernel.processes[pid]
426
- app = PROGRAMS[proc.app_type]
427
- w, h = proc.size
428
-
429
- # Inject Frame
430
- base_latent = render_perfect_window_latent(p, w, h, title=app.name)
431
 
432
- # Fill Content (Simplified for Monolith)
433
- prompt = f"{app.content_prompt}, pixel perfect"
434
- text_inputs = p.tokenizer([prompt], padding="max_length", max_length=p.tokenizer.model_max_length, truncation=True, return_tensors="pt")
435
- prompt_embeds = p.text_encoder(text_inputs.input_ids.to(device))[0]
436
- uncond_inputs = p.tokenizer(["blurry"], padding="max_length", max_length=p.tokenizer.model_max_length, truncation=True, return_tensors="pt")
437
- neg_embeds = p.text_encoder(uncond_inputs.input_ids.to(device))[0]
438
- embeds = torch.cat([neg_embeds, prompt_embeds])
439
 
440
- latents = base_latent.to(device)
441
- p.scheduler.set_timesteps(STEPS, device=device)
 
 
 
442
 
443
- for t in p.scheduler.timesteps:
444
- latent_input = torch.cat([latents] * 2)
445
- latent_input = p.scheduler.scale_model_input(latent_input, t)
446
- with torch.no_grad():
447
- noise_pred = p.unet(latent_input, t, encoder_hidden_states=embeds, return_dict=False)[0]
448
- uncond, text = noise_pred.chunk(2)
449
- noise_pred = uncond + (1.0 if STEPS==1 else 7.5) * (text - uncond)
450
- next_latents = p.scheduler.step(noise_pred, t, latents).prev_sample
451
-
452
- # Lock Title Bar (Top 4 blocks)
453
- mask = torch.ones_like(latents)
454
- mask[:, :, 0:4, :] = 0.0
455
- latents = (mask * next_latents) + ((1.0 - mask) * latents)
456
-
457
- proc.latent_state = latents.cpu()
458
-
459
- @sock.route('/kernel')
460
- def kernel_ws(ws):
461
- p = get_pipe()
462
- initialize_drivers()
463
- print("[*] Client connected to Monolith Kernel")
464
-
465
- frame = kernel.composite_frame()
466
  ws.send(json.dumps({
467
- "type": "desktop_ready",
468
- "data": decode_layer(frame, p),
469
- "processes": [proc.to_dict() for proc in kernel.processes.values()]
470
  }))
471
-
472
- while True:
473
- try:
474
- data = ws.receive()
475
- if not data: break
476
- msg = json.loads(data)
477
-
478
- if msg['type'] == 'click':
479
- res = kernel.handle_click(msg['x'], msg['y'])
480
- if res['action'] == 'launch':
481
- generate_window_fast(p, kernel, res['pid'])
482
-
483
- elif msg['type'] == 'launch_app':
484
- pid = kernel.spawn_process(msg['app'], 12, 12)
485
- generate_window_fast(p, kernel, pid)
486
 
487
- ws.send(json.dumps({
488
- "type": "frame_update",
489
- "data": decode_layer(kernel.composite_frame(), p),
490
- "processes": [proc.to_dict() for proc in kernel.processes.values()]
491
- }))
492
-
493
- except Exception as e:
494
- print(f"[ERR] {e}")
495
- break
496
 
497
  @app.route('/')
498
  def index():
499
  return render_template_string(HTML_TEMPLATE)
500
 
501
  if __name__ == '__main__':
502
- print("="*40)
503
- print(" NEURAL OS MONOLITH v1.0 RUNNING")
504
- print("="*40)
505
- app.run(host='0.0.0.0', port=7860, threaded=True)
506
  EOF
507
 
508
- # 8. Launch the Monolith
509
  EXPOSE 7860
510
  CMD ["python", "app.py"]
 
5
  WORKDIR /app
6
 
7
  # 1. Install System Dependencies
8
+ # Minimal runtime libs only. No compilers needed.
9
  RUN apt-get update && apt-get install -y \
10
  curl \
11
  git \
12
  libgomp1 \
13
  && rm -rf /var/lib/apt/lists/*
14
 
15
+ # 2. Upgrade pip
16
+ RUN pip install --upgrade pip
17
 
18
  # 3. Download Retro Font (VT323)
19
  RUN curl -L -o /app/VT323.ttf https://github.com/google/fonts/raw/main/ofl/vt323/VT323-Regular.ttf
20
 
21
+ # 4. Install Python Dependencies
22
+ # - transformers & accelerate: For running Qwen via Hugging Face
23
+ # - diffusers: For the Neural Desktop (GUI)
24
  RUN pip install --no-cache-dir \
25
  torch \
26
  torchvision \
 
34
  pillow \
35
  diskcache \
36
  safetensors \
37
+ scipy \
38
+ sentencepiece
39
 
40
+ # 5. Create a non-root user
 
 
 
 
 
 
 
 
 
41
  RUN useradd -m -u 1000 user
42
  USER user
43
  ENV HOME=/home/user \
44
  PATH=/home/user/.local/bin:$PATH
45
 
46
+ # 6. Write the Application
47
  COPY --chown=user <<'EOF' app.py
48
+ import sys, os, io, base64, json, warnings
 
49
  import torch
50
+ import numpy as np
51
+ from flask import Flask, render_template_string
 
 
52
  from flask_sock import Sock
 
53
  from PIL import Image, ImageDraw
54
+ # [CHANGED] Import Hugging Face Transformers instead of Llama-cpp
55
+ from transformers import AutoModelForCausalLM, AutoTokenizer
56
+ from diffusers import StableDiffusionPipeline, AutoencoderTiny, LCMScheduler
57
 
58
+ # Silence Warnings
59
+ warnings.filterwarnings("ignore")
 
 
 
 
 
 
 
 
 
60
 
61
  # ============================================================================
62
+ # 1. FRONTEND (React Desktop)
63
  # ============================================================================
 
64
  HTML_TEMPLATE = r"""
65
  <!DOCTYPE html>
66
  <html lang="en">
 
73
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
74
  <link href="https://fonts.googleapis.com/css2?family=Tahoma:wght@400;700&family=Fira+Code:wght@300;500&display=swap" rel="stylesheet">
75
  <style>
76
+ body { background: #000; color: #e2e2e2; margin: 0; overflow: hidden; font-family: 'Tahoma', sans-serif; }
77
+ .canvas-viewport {
78
+ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
79
+ width: 1024px; height: 1024px; border: 2px solid #333;
80
+ image-rendering: pixelated;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  }
82
+ .canvas-viewport img { width: 100%; height: 100%; }
83
+ .console-log {
84
+ position: fixed; bottom: 0; left: 0; width: 300px; height: 200px;
85
+ background: rgba(0,0,0,0.8); color: #0f0; font-family: 'Fira Code', monospace;
86
+ font-size: 10px; padding: 10px; overflow-y: auto; z-index: 1000;
87
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  </style>
89
  </head>
90
  <body>
91
  <div id="root"></div>
92
  <script type="text/babel">
93
  const { useState, useEffect, useRef } = React;
 
 
 
 
 
 
94
  function App() {
95
  const [desktopImage, setDesktopImage] = useState(null);
96
+ const [logs, setLogs] = useState(["System Booting..."]);
 
97
  const socketRef = useRef(null);
98
+
99
+ const addLog = (msg) => setLogs(prev => [...prev.slice(-10), msg]);
100
 
101
  useEffect(() => {
102
+ const ws = new WebSocket(`ws://${window.location.host}/kernel`);
 
103
  socketRef.current = ws;
104
  ws.onmessage = (e) => {
105
  const msg = JSON.parse(e.data);
106
+ if (msg.type === 'frame_update' || msg.type === 'desktop_ready') {
107
  setDesktopImage(msg.data);
 
108
  }
109
+ if (msg.type === 'log') addLog(msg.data);
110
  };
111
  return () => ws.close();
112
  }, []);
113
 
114
+ const handleClick = (e) => {
115
+ const rect = e.target.getBoundingClientRect();
 
116
  const x = Math.floor(((e.clientX - rect.left) / rect.width) * 128);
117
  const y = Math.floor(((e.clientY - rect.top) / rect.height) * 128);
118
  socketRef.current?.send(JSON.stringify({ type: 'click', x, y }));
119
  };
120
 
 
 
 
 
 
121
  return (
122
+ <div style={{width: '100vw', height: '100vh', background: '#3A6EA5'}}>
123
+ <div className="canvas-viewport" onClick={handleClick}>
124
  {desktopImage && <img src={`data:image/png;base64,${desktopImage}`} />}
125
  </div>
126
+ <div className="console-log">
127
+ {logs.map((l, i) => <div key={i}>{l}</div>)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  </div>
129
  </div>
130
  );
131
  }
132
+ ReactDOM.createRoot(document.getElementById('root')).render(<App />);
 
133
  </script>
134
  </body>
135
  </html>
136
  """
137
 
138
  # ============================================================================
139
+ # 2. AI ENGINES (QWEN + DIFFUSION)
140
  # ============================================================================
141
 
142
+ class NeuralSystem:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  def __init__(self):
144
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
145
+ self.dt = torch.float16 if self.device == "cuda" else torch.float32
146
+ print(f"[*] System Device: {self.device}")
 
 
 
 
 
 
 
 
147
 
148
+ # A. LOAD DIFFUSION (The Display)
149
+ print("[*] Loading Neural GPU (Diffusion)...")
150
+ self.pipe = StableDiffusionPipeline.from_pretrained(
151
+ "runwayml/stable-diffusion-v1-5", torch_dtype=self.dt
152
+ ).to(self.device)
153
+ self.pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taesd", torch_dtype=self.dt).to(self.device)
154
+
155
+ # B. LOAD QWEN (The Brain)
156
+ # [CHANGED] Using AutoModelForCausalLM
157
+ print("[*] Downloading/Loading Qwen 2.5 (0.5B)...")
158
+ self.model_id = "Qwen/Qwen2.5-Coder-0.5B-Instruct"
159
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
160
+ self.llm = AutoModelForCausalLM.from_pretrained(
161
+ self.model_id,
162
+ torch_dtype=self.dt,
163
+ low_cpu_mem_usage=True
164
+ ).to(self.device)
165
+ print("[*] Qwen Online.")
166
+
167
+ def think(self, prompt_text):
168
+ """ Runs Qwen to generate text or commands """
169
+ inputs = self.tokenizer.apply_chat_template(
170
+ [{"role": "user", "content": prompt_text}],
171
+ return_tensors="pt",
172
+ add_generation_prompt=True
173
+ ).to(self.device)
174
+
175
+ outputs = self.llm.generate(
176
+ inputs,
177
+ max_new_tokens=128,
178
+ do_sample=True,
179
+ temperature=0.7
180
+ )
181
+ response = self.tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)
182
+ return response
183
+
184
+ def render_window(self, app_name, context):
185
+ """ Generates a window image """
186
+ prompt = f"pixel art windows xp window of {app_name}, {context}, sharp focus"
187
+ # Simple rendering logic for brevity
188
+ with torch.no_grad():
189
+ img = self.pipe(prompt, num_inference_steps=1, guidance_scale=1.0).images[0]
190
+ return img
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
  # ============================================================================
193
+ # 3. KERNEL LOGIC
194
  # ============================================================================
195
 
196
+ # Initialize System Global
197
+ sys_engine = None
198
+
199
  app = Flask(__name__)
200
  sock = Sock(app)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
+ @sock.route('/kernel')
203
+ def kernel(ws):
204
+ global sys_engine
205
+ if sys_engine is None:
206
+ sys_engine = NeuralSystem()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
 
208
+ # Send initial boot screen
209
+ ws.send(json.dumps({"type": "log", "data": "Qwen Kernel Loaded."}))
 
 
 
 
 
210
 
211
+ # Generate initial desktop
212
+ desktop = sys_engine.render_window("Desktop", "blue wallpaper")
213
+ buf = io.BytesIO()
214
+ desktop.save(buf, format="PNG")
215
+ b64_img = base64.b64encode(buf.getvalue()).decode()
216
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  ws.send(json.dumps({
218
+ "type": "desktop_ready",
219
+ "data": b64_img
 
220
  }))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
+ while True:
223
+ data = ws.receive()
224
+ if not data: break
225
+ msg = json.loads(data)
226
+
227
+ if msg['type'] == 'click':
228
+ # Example: Ask Qwen what happened
229
+ response = sys_engine.think(f"The user clicked at coordinate {msg['x']},{msg['y']}. What app should open?")
230
+ ws.send(json.dumps({"type": "log", "data": f"Qwen: {response}"}))
231
 
232
  @app.route('/')
233
  def index():
234
  return render_template_string(HTML_TEMPLATE)
235
 
236
  if __name__ == '__main__':
237
+ app.run(host='0.0.0.0', port=7860)
 
 
 
238
  EOF
239
 
240
+ # 7. Launch
241
  EXPOSE 7860
242
  CMD ["python", "app.py"]