Spaces:
Sleeping
Sleeping
File size: 18,339 Bytes
7058b43 5e8c601 3cc1f2b 5e8c601 7058b43 f08566e dc6f2ca 91d0818 7058b43 96641af 3cc1f2b dc6f2ca 3cc1f2b dc6f2ca 91d0818 dc6f2ca 7058b43 3c8b03f 7058b43 a377b87 3c8b03f 7058b43 a377b87 96641af dc6f2ca a377b87 dc6f2ca 7058b43 3cc1f2b 54ba101 91d0818 3cc1f2b a5d62b4 5e8c601 54ba101 3cc1f2b 54ba101 5e8c601 3cc1f2b dc6f2ca 96641af dc6f2ca 3cc1f2b 5e8c601 3cc1f2b 54ba101 dc6f2ca 3cc1f2b dc6f2ca 3cc1f2b 54ba101 3c8b03f da6956b 3cc1f2b f08566e 3c8b03f 3cc1f2b 54ba101 3cc1f2b da6956b 3cc1f2b 5b45421 a377b87 3cc1f2b dc6f2ca a377b87 3cc1f2b a377b87 dc6f2ca 3cc1f2b 5b45421 91d0818 dc6f2ca a377b87 3cc1f2b 91d0818 5e8c601 91d0818 3cc1f2b 91d0818 5e8c601 3cc1f2b 91d0818 5e8c601 91d0818 3cc1f2b 91d0818 3cc1f2b 91d0818 5e8c601 91d0818 3cc1f2b 3e232ba 3cc1f2b 3e232ba 91d0818 3cc1f2b 5e8c601 3e232ba 91d0818 54ba101 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 5e8c601 91d0818 3cc1f2b 5e8c601 3cc1f2b 91d0818 3cc1f2b 91d0818 3cc1f2b 91d0818 3cc1f2b 91d0818 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 91d0818 3cc1f2b 5e8c601 3cc1f2b 91d0818 3cc1f2b 91d0818 3cc1f2b 91d0818 3cc1f2b 91d0818 3cc1f2b 91d0818 5e8c601 3cc1f2b 91d0818 3cc1f2b 5e8c601 91d0818 5e8c601 3cc1f2b 91d0818 3cc1f2b 91d0818 3cc1f2b 5e8c601 3cc1f2b 91d0818 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 5e8c601 3cc1f2b 91d0818 54ba101 3cc1f2b 54ba101 3cc1f2b 91d0818 54ba101 91d0818 3cc1f2b 54ba101 91d0818 3cc1f2b 54ba101 3cc1f2b 91d0818 3cc1f2b 91d0818 3cc1f2b 91d0818 c927492 3cc1f2b c927492 7058b43 3cc1f2b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | """
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("<h1>index.html?</h1>")
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)
|