Spaces:
Sleeping
Sleeping
Download app.py from hahahararara/cellular-diffusion-ui: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/spaces/hahahararara/cellular-diffusion-ui/resolve/main/app.py
- Command line
-
hf download hf://spaces/hahahararara/cellular-diffusion-ui/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hahahararara/cellular-diffusion-ui/resolve/main/app.py
11.9 kB
| import torch | |
| import numpy as np | |
| import gradio as gr | |
| import json | |
| import base64 | |
| from PIL import Image | |
| from diffusers import StableDiffusionPipeline, DDIMScheduler | |
| # 1. モデルのロード | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| dtype = torch.float16 if device == "cuda" else torch.float32 | |
| pipe = StableDiffusionPipeline.from_pretrained( | |
| "runwayml/stable-diffusion-v1-5", | |
| torch_dtype=dtype | |
| ).to(device) | |
| pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config) | |
| # 2. 生成メイン関数 | |
| def generate_image(bg_prompt, shape_data_json, steps, seed, progress=gr.Progress()): | |
| LATENT_CANVAS = 128 | |
| LATENT_CELL = 64 | |
| LATENT_STRIDE = 16 | |
| def get_embeds(prompt): | |
| return pipe.encode_prompt(prompt, pipe.device, 1, do_classifier_free_guidance=True) | |
| e_bg, n_bg = get_embeds(bg_prompt) | |
| try: | |
| shapes = json.loads(shape_data_json) | |
| except: | |
| shapes = [] | |
| shape_embeds = [] | |
| for s in shapes: | |
| if s["prompt"].strip() == "": | |
| continue | |
| e, n = get_embeds(s["prompt"]) | |
| shape_embeds.append({ | |
| "e": e, "n": n, | |
| "x": (s["x"] / 100.0) * LATENT_CANVAS, | |
| "y": (s["y"] / 100.0) * LATENT_CANVAS, | |
| "r": (s["r"] / 100.0) * LATENT_CANVAS | |
| }) | |
| generator = torch.Generator(device=pipe.device).manual_seed(int(seed)) | |
| latents = torch.randn((1, pipe.unet.config.in_channels, LATENT_CANVAS, LATENT_CANVAS), generator=generator, device=pipe.device, dtype=dtype) | |
| pipe.scheduler.set_timesteps(steps) | |
| for i, t in enumerate(progress.tqdm(pipe.scheduler.timesteps, desc="空間を変異中...")): | |
| global_noise_pred = torch.zeros_like(latents) | |
| global_count = torch.zeros_like(latents) | |
| for y in range(0, LATENT_CANVAS - LATENT_CELL + 1, LATENT_STRIDE): | |
| for x in range(0, LATENT_CANVAS - LATENT_CELL + 1, LATENT_STRIDE): | |
| cell_cx = x + LATENT_CELL / 2.0 | |
| cell_cy = y + LATENT_CELL / 2.0 | |
| w_list = [] | |
| sum_w = 0.0 | |
| for s_emb in shape_embeds: | |
| d_sq = (cell_cx - s_emb["x"])**2 + (cell_cy - s_emb["y"])**2 | |
| w = np.exp(-d_sq / (2 * (s_emb["r"]**2) + 1e-5)) | |
| w_list.append(w) | |
| sum_w += w | |
| w_bg = max(0.0, 1.0 - sum_w) | |
| total_w = w_bg + sum_w + 1e-5 | |
| w_bg = w_bg / total_w | |
| w_list = [w / total_w for w in w_list] | |
| blended_embeds = w_bg * e_bg | |
| blended_neg = w_bg * n_bg | |
| for w, s_emb in zip(w_list, shape_embeds): | |
| blended_embeds += w * s_emb["e"] | |
| blended_neg += w * s_emb["n"] | |
| final_embeds = torch.cat([blended_neg, blended_embeds]) | |
| latent_cell = latents[:, :, y:y+LATENT_CELL, x:x+LATENT_CELL] | |
| latent_model_input = pipe.scheduler.scale_model_input(latent_cell, t) | |
| latent_model_input = torch.cat([latent_model_input] * 2) | |
| with torch.no_grad(): | |
| noise_pred = pipe.unet(latent_model_input, t, encoder_hidden_states=final_embeds).sample | |
| noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) | |
| noise_pred_cell = noise_pred_uncond + 7.5 * (noise_pred_text - noise_pred_uncond) | |
| global_noise_pred[:, :, y:y+LATENT_CELL, x:x+LATENT_CELL] += noise_pred_cell | |
| global_count[:, :, y:y+LATENT_CELL, x:x+LATENT_CELL] += 1 | |
| global_noise_pred = global_noise_pred / global_count | |
| latents = pipe.scheduler.step(global_noise_pred, t, latents).prev_sample | |
| progress(1.0, desc="変換中...") | |
| with torch.no_grad(): | |
| image = pipe.vae.decode(latents / pipe.vae.config.scaling_factor, return_dict=False)[0] | |
| image = (image / 2 + 0.5).clamp(0, 1) | |
| image = image.cpu().permute(0, 2, 3, 1).numpy()[0] | |
| return Image.fromarray((image * 255).astype(np.uint8)) | |
| # 3. 独立したオールインワンUIの設計図(※文字化け防止のため英語UIにしています) | |
| fabric_html = """ | |
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"></script> | |
| <style> | |
| body { font-family: 'Segoe UI', system-ui, sans-serif; display: flex; flex-wrap: wrap; gap: 20px; margin: 0; padding: 10px; background: transparent; color: #333; justify-content: center;} | |
| .canvas-container { border: 1px solid #d4d4d8; border-radius: 8px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); background: #fff; flex-shrink: 0;} | |
| .sidebar { flex: 1; min-width: 300px; display: flex; flex-direction: column; gap: 12px; max-height: 512px; overflow-y: auto; padding-right: 5px; } | |
| .add-btn { background: #18181b; color: white; border: none; border-radius: 6px; padding: 12px; font-weight: 600; cursor: pointer; transition: 0.2s; display: flex; align-items: center; justify-content: center; gap: 8px;} | |
| .add-btn:hover { background: #3f3f46; } | |
| .area-card { background: #fff; border: 1px solid #e4e4e7; border-radius: 8px; padding: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); } | |
| .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; } | |
| .color-wrap { display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 14px;} | |
| .color-picker { border: none; width: 28px; height: 28px; border-radius: 4px; cursor: pointer; padding: 0; background: none; outline: none; } | |
| .color-picker::-webkit-color-swatch-wrapper { padding: 0; } | |
| .color-picker::-webkit-color-swatch { border: 1px solid #d4d4d8; border-radius: 4px; } | |
| .del-btn { color: #ef4444; background: #fef2f2; border: 1px solid #fecaca; border-radius: 4px; padding: 4px 8px; cursor: pointer; font-size: 12px; transition: 0.2s;} | |
| .del-btn:hover { background: #fee2e2; } | |
| .prompt { width: 100%; box-sizing: border-box; padding: 8px 10px; border: 1px solid #d4d4d8; border-radius: 6px; resize: vertical; min-height: 60px; font-family: inherit; font-size: 13px; outline: none; transition: border 0.2s;} | |
| .prompt:focus { border-color: #a1a1aa; } | |
| </style> | |
| </head> | |
| <body> | |
| <div> | |
| <canvas id="c" width="512" height="512"></canvas> | |
| </div> | |
| <div class="sidebar"> | |
| <button class="add-btn" onclick="addArea()">+ Add New Shape</button> | |
| <div id="list" style="display: flex; flex-direction: column; gap: 12px;"></div> | |
| </div> | |
| <script> | |
| var canvas = new fabric.Canvas('c', { backgroundColor: '#f9fafb' }); | |
| fabric.Object.prototype.transparentCorners = false; | |
| fabric.Object.prototype.cornerColor = '#18181b'; | |
| fabric.Object.prototype.borderColor = '#18181b'; | |
| fabric.Object.prototype.cornerSize = 8; | |
| var areaCount = 0; | |
| var areas = {}; | |
| function hexToRgba(hex, alpha) { | |
| var r = parseInt(hex.substr(1,2), 16), g = parseInt(hex.substr(3,2), 16), b = parseInt(hex.substr(5,2), 16); | |
| return 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')'; | |
| } | |
| function addArea(initColor, initPrompt, initLeft, initTop) { | |
| areaCount++; | |
| var id = 'area_' + Date.now(); | |
| var colors = ['#ef4444', '#3b82f6', '#10b981', '#f59e0b', '#8b5cf6']; | |
| var color = initColor || colors[(areaCount-1) % colors.length]; | |
| var circle = new fabric.Circle({ | |
| left: initLeft || 256, top: initTop || 256, radius: 55, | |
| fill: hexToRgba(color, 0.4), stroke: color, strokeWidth: 2, | |
| originX: 'center', originY: 'center' | |
| }); | |
| circle.areaId = id; | |
| canvas.add(circle); | |
| canvas.setActiveObject(circle); | |
| var list = document.getElementById('list'); | |
| var card = document.createElement('div'); | |
| card.className = 'area-card'; | |
| card.id = 'card_' + id; | |
| card.innerHTML = ` | |
| <div class="header"> | |
| <div class="color-wrap"> | |
| <input type="color" class="color-picker" id="color_${id}" value="${color}"> | |
| <span>Area ${areaCount}</span> | |
| </div> | |
| <button class="del-btn" onclick="deleteArea('${id}')">Delete</button> | |
| </div> | |
| <textarea class="prompt" id="prompt_${id}" placeholder="Prompt for this area (e.g. cyberpunk city)">${initPrompt || ''}</textarea> | |
| `; | |
| list.prepend(card); | |
| document.getElementById('color_' + id).addEventListener('input', function(e) { | |
| circle.set('fill', hexToRgba(e.target.value, 0.4)); | |
| circle.set('stroke', e.target.value); | |
| canvas.renderAll(); | |
| }); | |
| areas[id] = { obj: circle, promptId: 'prompt_' + id }; | |
| } | |
| function deleteArea(id) { | |
| var obj = areas[id].obj; | |
| canvas.remove(obj); | |
| document.getElementById('card_' + id).remove(); | |
| delete areas[id]; | |
| } | |
| window.getShapesData = function() { | |
| var data = []; | |
| for(var id in areas) { | |
| var obj = areas[id].obj; | |
| var prompt = document.getElementById(areas[id].promptId).value; | |
| data.push({ | |
| prompt: prompt, | |
| x: (obj.left / 512) * 100, | |
| y: (obj.top / 512) * 100, | |
| r: ((obj.radius * obj.scaleX) / 512) * 100 | |
| }); | |
| } | |
| return JSON.stringify(data); | |
| }; | |
| addArea('#ef4444', 'A futuristic glowing sci-fi city, cyberpunk', 150, 256); | |
| addArea('#3b82f6', 'A dark magic scary evil wizard tower', 362, 256); | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| # 【ここが魔法のコード】UI設計図をBase64に暗号化してシステムを騙す | |
| b64_html = base64.b64encode(fabric_html.encode('utf-8')).decode('utf-8') | |
| # クライアント(ブラウザ)側で暗号を解読し、安全に表示させるスクリプト | |
| inject_js = f""" | |
| function() {{ | |
| var container = document.getElementById('my-canvas-container'); | |
| if(!container) return; | |
| var iframe = document.createElement('iframe'); | |
| iframe.id = 'fabric-iframe'; | |
| iframe.width = "100%"; | |
| iframe.height = "540px"; | |
| iframe.style.border = "none"; | |
| iframe.srcdoc = decodeURIComponent(escape(atob('{b64_html}'))); | |
| container.appendChild(iframe); | |
| }} | |
| """ | |
| # 4. Gradio UI | |
| with gr.Blocks(theme=gr.themes.Base()) as demo: | |
| gr.Markdown("## ⚗️ Spatial Diffusion Studio") | |
| gr.Markdown("**「+ Add New Shape」**ボタンで図形を無限に追加できます。図形の横の**色四角**を押すと色が変更できます。") | |
| with gr.Row(): | |
| bg_prompt = gr.Textbox(label="背景 (Base Environment)", value="A vast peaceful grassy field, sunny day", scale=3) | |
| steps = gr.Slider(5, 30, value=15, step=1, label="計算ステップ数", scale=1) | |
| seed = gr.Number(value=42, label="シード値", scale=1) | |
| # 空の容器を用意し、アプリ起動直後に先ほどの暗号解読スクリプトを実行してUIを流し込む | |
| gr.HTML('<div id="my-canvas-container"></div>') | |
| demo.load(js=inject_js) | |
| hidden_data = gr.Textbox(visible=False) | |
| generate_btn = gr.Button("✨ この配置とプロンプトで生成する", variant="primary", size="lg") | |
| output_image = gr.Image(label="Output Image", type="pil", interactive=False) | |
| # データ取得用スクリプト | |
| fetch_js = """ | |
| (bg, hidden, steps, seed) => { | |
| var iframe = document.getElementById('fabric-iframe'); | |
| if(!iframe) return [bg, "[]", steps, seed]; | |
| var data = iframe.contentWindow.getShapesData(); | |
| return [bg, data, steps, seed]; | |
| } | |
| """ | |
| generate_btn.click( | |
| fn=generate_image, | |
| inputs=[bg_prompt, hidden_data, steps, seed], | |
| outputs=output_image, | |
| js=fetch_js | |
| ) | |
| demo.launch() |