""" Turing Diffusion Canvas — Territory Battle Edition ==================================================== Core: Step 0 = TAESD-decoded real init noise, Steps 1..N = intermediates time_hit → active_time → step_index (preserved from v6) New: 1. Organic boundary: fixed spatial noise field perturbs distance, creating slime-mold / digital-erosion edges (no sine waves) 2. Slow wave: WAVE_SPEED halved for heavy, contemplative expansion 3. Pixelation: frontier=32px blocks → center=1px, quantized lookup 4. Territory battle: multiple Seeds coexist, inverse-distance blend where waves collide — different prompts fight for territory Model: runwayml/stable-diffusion-v1-5 + madebyollin/taesd ThreadPool max_workers=2 for Kaggle single-GPU. """ import io, os, json, time, base64, asyncio, logging, threading from pathlib import Path from concurrent.futures import ThreadPoolExecutor import numpy as np from PIL import Image, ImageFilter logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(message)s") log = logging.getLogger("turing") try: import torch; HAS_TORCH = True except ImportError: HAS_TORCH = False HAS_DIFFUSERS = False try: from diffusers import StableDiffusionPipeline, AutoencoderTiny, DDIMScheduler HAS_DIFFUSERS = True except ImportError: pass from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.responses import FileResponse, HTMLResponse from fastapi.middleware.cors import CORSMiddleware # ═══════════════════════════ CONFIG ══════════════════════════════════════ CW, CH = 512, 512 NUM_STEPS = 12 GUIDANCE = 7.5 JPEG_Q = 74 FPS = 10 # Wave (slowed down: ~25 px/s instead of 55) WAVE_SPEED = 25.0 STEP_DURATION = 0.9 # seconds per step transition # Organic boundary SCATTER_AMP = 0.40 # how much spatial noise warps distance (0=circle, 1=chaos) # Pixelation MAX_BLOCK = 32 # block size at frontier (active_time ≈ 0) MIN_BLOCK = 1 # full resolution deep inside PIXEL_CURVE = 1.6 # non-linear: fast crystallization near center # ═══════════════════════════ APP ═════════════════════════════════════════ app = FastAPI(title="Turing Diffusion — Territory Battle") app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) _pipe = None _device = "cpu" _dtype = None _pool = ThreadPoolExecutor(max_workers=2) def load_pipeline(): global _pipe, _device, _dtype if _pipe is not None: return _pipe if not HAS_TORCH or not HAS_DIFFUSERS: return None _device = "cuda" if torch.cuda.is_available() else "cpu" _dtype = torch.float16 if _device == "cuda" else torch.float32 taesd = None try: taesd = AutoencoderTiny.from_pretrained( "madebyollin/taesd", torch_dtype=_dtype).to(_device) log.info("TAESD ✓") except Exception as e: log.warning(f"TAESD: {e}") try: mid = "runwayml/stable-diffusion-v1-5" log.info(f"Loading {mid}…") _pipe = StableDiffusionPipeline.from_pretrained( mid, torch_dtype=_dtype, safety_checker=None, variant="fp16" if _device == "cuda" else None, low_cpu_mem_usage=False, ).to(_device) _pipe.scheduler = DDIMScheduler.from_config(_pipe.scheduler.config) if taesd: _pipe.vae = taesd log.info("VAE → TAESD ✓") if _device == "cuda": try: _pipe.enable_xformers_memory_efficient_attention() except: pass try: _pipe.enable_attention_slicing() except: pass log.info(f"Pipeline ({_device}) ✓") return _pipe except Exception as e: log.warning(f"Pipeline: {e}"); return None def decode_latents_gray(latents): with torch.no_grad(): sf = getattr(_pipe.vae.config, "scaling_factor", 0.18215) decoded = _pipe.vae.decode(latents / sf).sample decoded = (decoded / 2 + 0.5).clamp(0, 1) rgb = decoded[0].cpu().permute(1, 2, 0).numpy() gray = 0.299 * rgb[:,:,0] + 0.587 * rgb[:,:,1] + 0.114 * rgb[:,:,2] return (gray * 255).clip(0, 255).astype(np.uint8) # ═══════════════════════════ SPATIAL NOISE FIELD ═════════════════════════ def _build_noise_field(w, h, seed_val): """ Fixed spatial noise: each pixel gets a random value in [-1, 1]. Used to warp distance for organic boundaries. Multi-octave for richer structure. """ rng = np.random.RandomState(seed_val) # Coarse octave (8×8 upscaled) — large-scale warping coarse = rng.uniform(-1, 1, (h // 8, w // 8)).astype(np.float32) from PIL import Image as PILImage coarse_up = np.array(PILImage.fromarray( ((coarse + 1) * 127.5).astype(np.uint8), "L" ).resize((w, h), PILImage.BILINEAR), dtype=np.float32) / 127.5 - 1.0 # Fine octave — pixel-level scatter fine = rng.uniform(-1, 1, (h, w)).astype(np.float32) # Combine: 70% coarse structure + 30% fine detail return (0.7 * coarse_up + 0.3 * fine).astype(np.float32) _noise_field = _build_noise_field(CW, CH, 42) _noise_counter = 0 def reset_noise_field(): global _noise_field, _noise_counter _noise_counter += 1 _noise_field = _build_noise_field(CW, CH, _noise_counter * 7 + 13) # ═══════════════════════════ SEED ════════════════════════════════════════ class Seed: _counter = 0 def __init__(self, cx, cy, prompt): Seed._counter += 1 self.uid = Seed._counter self.cx = cx self.cy = cy self.prompt = prompt self.birth = time.time() self.steps = [] # step[0] = real init noise decoded self._stack = None self._stack_n = 0 self.done = False self.killed = False def push_gray(self, arr): self.steps.append(arr) self._stack = None def stack(self): n = len(self.steps) if n == 0: return None if self._stack is None or self._stack_n != n: self._stack = np.stack(self.steps[:n]) self._stack_n = n return self._stack @property def n(self): return len(self.steps) # ═══════════════════════════ GENERATION ══════════════════════════════════ def run_real(seed): pipe = load_pipeline() if pipe is None: run_mock(seed); return gen_seed = int(time.time() * 1000 + seed.uid * 137) % (2**32) gen = torch.Generator(device=_device).manual_seed(gen_seed) init_noise = torch.randn( 1, pipe.unet.config.in_channels, CH // 8, CW // 8, generator=gen, device=_device, dtype=_dtype, ) # Step 0: REAL decoded init noise step0 = decode_latents_gray(init_noise) seed.push_gray(step0) log.info(f"Seed {seed.uid}: Step 0 (real init noise)") def on_step_end(p, step_idx, timestep, kwargs): if seed.killed: return kwargs lat = kwargs.get("latents") if lat is not None: try: seed.push_gray(decode_latents_gray(lat)) except Exception as e: log.warning(f"Step {step_idx}: {e}") return kwargs def on_step_old(step_idx, ts, latents): if seed.killed: return if latents is not None: try: seed.push_gray(decode_latents_gray(latents)) except: pass try: try: out = pipe( prompt=seed.prompt, num_inference_steps=NUM_STEPS, guidance_scale=GUIDANCE, width=CW, height=CH, latents=init_noise.clone(), callback_on_step_end=on_step_end, ) except TypeError: out = pipe( prompt=seed.prompt, num_inference_steps=NUM_STEPS, guidance_scale=GUIDANCE, width=CW, height=CH, latents=init_noise.clone(), callback=on_step_old, callback_steps=1, ) final_rgb = np.array(out.images[0].resize((CW, CH))) final_gray = (0.299 * final_rgb[:,:,0] + 0.587 * final_rgb[:,:,1] + 0.114 * final_rgb[:,:,2]).astype(np.uint8) seed.push_gray(final_gray) except Exception as e: if not seed.killed: log.exception(f"Seed {seed.uid} failed: {e}") seed.done = True log.info(f"Seed {seed.uid} done ({seed.n} steps)") def run_mock(seed): rng = np.random.RandomState(abs(hash(seed.prompt) + seed.uid) % (2**31)) Yn, Xn = np.mgrid[0:CH, 0:CW].astype(np.float32) Yn /= CH; Xn /= CW target = np.zeros((CH, CW), np.float32) for _ in range(rng.randint(5, 12)): bx, by = rng.uniform(0.05, 0.95, 2) sig = rng.uniform(0.08, 0.4) target += np.exp(-((Xn-bx)**2+(Yn-by)**2)/(2*sig**2)) * rng.uniform(0.1, 0.5) for _ in range(rng.randint(1, 4)): bx, by = rng.uniform(0.1, 0.9, 2) sig = rng.uniform(0.04, 0.15) target -= np.exp(-((Xn-bx)**2+(Yn-by)**2)/(2*sig**2)) * rng.uniform(0.05, 0.2) target = (target.clip(0, 1) * 255).astype(np.float32) # Step 0: pure noise noise = rng.randint(0, 255, (CH, CW)).astype(np.uint8) seed.push_gray(noise) for step in range(1, NUM_STEPS + 1): if seed.killed: return t = step / NUM_STEPS alpha = t ** 0.5 mixed = noise.astype(np.float32) * (1 - alpha) + target * alpha img = Image.fromarray(mixed.clip(0,255).astype(np.uint8), "L") blur_r = max(0, int(10 * (1 - t ** 0.6))) if blur_r > 0: img = img.filter(ImageFilter.GaussianBlur(blur_r)) arr = np.array(img).astype(np.float32) if t < 0.75: arr += rng.normal(0, 25*(1-t), (CH, CW)) seed.push_gray(arr.clip(0,255).astype(np.uint8)) time.sleep(0.5) seed.done = True log.info(f"Seed {seed.uid} mock done ({seed.n} steps)") # ═══════════════════════════ COMPOSITOR ══════════════════════════════════ class Canvas: """ Compose one frame via pure NumPy vector arithmetic. Per-pixel per-seed: 1. raw_dist = euclidean distance from seed center 2. perturbed_dist = raw_dist * (1 + SCATTER_AMP * noise_field[y,x]) → organic, slime-mold boundary instead of circle 3. time_hit = perturbed_dist / WAVE_SPEED active_time = age - time_hit 4. Pixelation: block_size = lerp(MAX_BLOCK, MIN_BLOCK, progress^CURVE) Quantize lookup coords: qX = (X // block) * block 5. step_i = clamp(active_time / STEP_DURATION, 0, N-1) pixel = stk[step_i, qY, qX] 6. Territory battle: weight = reached / (perturbed_dist + epsilon) Accumulate weighted pixels across all seeds, normalise. """ def __init__(self): self.seeds = [] self.lock = threading.Lock() self._Yf, self._Xf = np.mgrid[0:CH, 0:CW].astype(np.float32) self._Yi, self._Xi = np.mgrid[0:CH, 0:CW].astype(np.int32) def add_seed(self, cx, cy, prompt): s = Seed(cx, cy, prompt) with self.lock: self.seeds.append(s) fn = run_real if load_pipeline() else run_mock _pool.submit(fn, s) log.info(f"Seed {s.uid} @ ({cx:.2f},{cy:.2f})") return s def clear(self): with self.lock: for s in self.seeds: s.killed = True self.seeds.clear() reset_noise_field() log.info("Canvas cleared") def compose(self): now = time.time() Xi, Yi = self._Xi, self._Yi Xf, Yf = self._Xf, self._Yf nf = _noise_field # (H, W) float32 in [-1, 1] # Accumulators for territory battle blending out = np.zeros((CH, CW), dtype=np.float32) wt = np.zeros((CH, CW), dtype=np.float32) with self.lock: active = [s for s in self.seeds if not s.killed] for sd in active: n = sd.n if n == 0: continue stk = sd.stack() if stk is None: continue age = now - sd.birth cx_px = sd.cx * CW cy_px = sd.cy * CH # ── [1] Distance with organic noise perturbation ── dx = Xf - cx_px dy = Yf - cy_px raw_dist = np.sqrt(dx * dx + dy * dy) # Warp distance by spatial noise → slime-mold boundary perturbed_dist = raw_dist * (1.0 + SCATTER_AMP * nf) # Clamp to avoid negative distances perturbed_dist = np.maximum(perturbed_dist, 0.0) # ── [2] Time-space mapping (slow wave) ── time_hit = perturbed_dist / WAVE_SPEED active_time = age - time_hit reached = active_time >= 0.0 if not reached.any(): continue # ── [3] Pixelation: block size from active_time ── # Max active_time for full resolution max_at = STEP_DURATION * n progress = np.clip(active_time / max(max_at, 0.1), 0.0, 1.0) # Block size: frontier=MAX_BLOCK, center=MIN_BLOCK block_f = MAX_BLOCK - (MAX_BLOCK - MIN_BLOCK) * (progress ** PIXEL_CURVE) block_i = np.clip(block_f.astype(np.int32), MIN_BLOCK, MAX_BLOCK) # Quantize lookup coordinates qX = np.clip((Xi // block_i) * block_i, 0, CW - 1) qY = np.clip((Yi // block_i) * block_i, 0, CH - 1) # ── Step index from active_time ── step_f = active_time / STEP_DURATION step_i = np.clip(step_f.astype(np.int32), 0, n - 1) # ── Gather with pixelated coords ── pixels = stk[step_i, qY, qX].astype(np.float32) # ── [4] Territory weight: inverse perturbed distance ── w = reached.astype(np.float32) / (perturbed_dist + 8.0) out += pixels * w wt += w # Normalise — uncovered stays black (0) covered = wt > 1e-8 result = np.zeros((CH, CW), dtype=np.float32) result[covered] = out[covered] / wt[covered] return result.clip(0, 255).astype(np.uint8) # ═══════════════════════════ GLOBAL ══════════════════════════════════════ canvas = Canvas() def gray_to_b64(arr): buf = io.BytesIO() Image.fromarray(arr, mode="L").save(buf, format="JPEG", quality=JPEG_Q) return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode() # ═══════════════════════════ WEBSOCKET ═══════════════════════════════════ @app.websocket("/ws/canvas") async def ws_handler(ws: WebSocket): await ws.accept() log.info("WS connected") loop = asyncio.get_event_loop() stop = asyncio.Event() async def frame_loop(): interval = 1.0 / FPS while not stop.is_set(): t0 = time.time() try: frame = await loop.run_in_executor(None, canvas.compose) b64 = await loop.run_in_executor(None, gray_to_b64, frame) n_seeds = len(canvas.seeds) total_steps = sum(s.n for s in canvas.seeds if not s.killed) n_done = sum(1 for s in canvas.seeds if s.done and not s.killed) await ws.send_text(json.dumps({ "type": "frame", "image": b64, "seeds": n_seeds, "steps": total_steps, "done": n_done, })) except Exception as e: if not stop.is_set(): log.warning(f"Frame: {e}") break elapsed = time.time() - t0 await asyncio.sleep(max(0.01, interval - elapsed)) task = asyncio.create_task(frame_loop()) try: while True: raw = await ws.receive_text() msg = json.loads(raw) action = msg.get("action") if action == "seed": x = max(0.0, min(1.0, float(msg.get("x", 0.5)))) y = max(0.0, min(1.0, float(msg.get("y", 0.5)))) prompt = str(msg.get("prompt", "monochrome abstract art")) canvas.add_seed(x, y, prompt) elif action == "clear": canvas.clear() except WebSocketDisconnect: log.info("WS disconnected") except Exception as e: log.exception(f"WS: {e}") finally: stop.set() task.cancel() try: await task except asyncio.CancelledError: pass # ═══════════════════════════ HTTP ═════════════════════════════════════════ @app.get("/health") async def health(): gpu = HAS_TORCH and torch.cuda.is_available() if HAS_TORCH else False return {"status": "ok", "gpu": gpu, "diffusers": HAS_DIFFUSERS} @app.get("/") async def index(): p = Path(__file__).parent / "index.html" return FileResponse(p) if p.exists() else HTMLResponse("

index.html?

") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8000)), ws_ping_interval=30, ws_ping_timeout=30)