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 = """