Spaces:
No application file
No application file
Download server.py from hahahararara/dada: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/spaces/hahahararara/dada/resolve/main/server.py
- Command line
-
hf download hf://spaces/hahahararara/dada/server.py
-
curl -L -o server.py https://huggingface.co/spaces/hahahararara/dada/resolve/main/server.py
14.1 kB
| """ | |
| Void & Typography Destroyer β Backend | |
| ====================================== | |
| Generates hyper-detailed imagery INSIDE a user-drawn mask (text / bezier paths) | |
| while enforcing absolute void (pure white or black) OUTSIDE the mask. | |
| Two generation strategies: | |
| Strategy A (default): StableDiffusionInpaintPipeline β uses the mask directly. | |
| After generation, the background is forcibly composited to pure void. | |
| Strategy B (advanced): Custom latent-loop hijack β at every denoising step, | |
| the latents outside the mask are overwritten with the latent encoding of | |
| a solid-color image, preventing any AI hallucination in the void region. | |
| Both strategies guarantee a perfectly clean background. | |
| """ | |
| import io, base64, time, logging | |
| from typing import Optional | |
| import torch | |
| import numpy as np | |
| from PIL import Image, ImageFilter, ImageOps | |
| from pydantic import BaseModel | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import JSONResponse | |
| try: | |
| from diffusers import ( | |
| StableDiffusionInpaintPipeline, | |
| AutoencoderKL, | |
| UNet2DConditionModel, | |
| DDIMScheduler, | |
| ) | |
| DIFFUSERS_OK = True | |
| except ImportError: | |
| DIFFUSERS_OK = False | |
| logging.basicConfig(level=logging.INFO) | |
| log = logging.getLogger("void-typo") | |
| # βββββββββββββββββββββββββββββββββββ MODELS βββββββββββββββββββββββββββββββ | |
| class GenRequest(BaseModel): | |
| prompt: str = "a dense jungle with exotic flowers, ultra detailed, 8k" | |
| negative_prompt: str = "blurry, low quality, deformed, text, watermark, noise, artifacts" | |
| mask_b64: str # Base64 PNG: white = generate, black = void | |
| width: int = 512 | |
| height: int = 512 | |
| num_steps: int = 35 | |
| guidance_scale: float = 9.0 | |
| seed: int = -1 | |
| void_color: str = "white" # "white" | "black" | |
| strategy: str = "inpaint" # "inpaint" | "latent_hijack" | |
| detail_boost: float = 1.0 # 1.0 = normal, >1 = more detail inside mask | |
| # βββββββββββββββββββββββββββββββββββ APP ββββββββββββββββββββββββββββββββββ | |
| app = FastAPI(title="Void & Typography Destroyer") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], | |
| ) | |
| _pipe = None | |
| _pipe_type = None | |
| def get_inpaint_pipeline(): | |
| """Load the inpainting pipeline (lazy singleton).""" | |
| global _pipe, _pipe_type | |
| if _pipe is not None and _pipe_type == "inpaint": | |
| return _pipe | |
| if not DIFFUSERS_OK: | |
| raise RuntimeError("diffusers not installed") | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| dtype = torch.float16 if device == "cuda" else torch.float32 | |
| model_id = "runwayml/stable-diffusion-inpainting" | |
| log.info(f"Loading {model_id} on {device}") | |
| _pipe = StableDiffusionInpaintPipeline.from_pretrained( | |
| model_id, torch_dtype=dtype, safety_checker=None, | |
| ).to(device) | |
| _pipe.scheduler = DDIMScheduler.from_config(_pipe.scheduler.config) | |
| if device == "cuda": | |
| _pipe.enable_attention_slicing() | |
| try: | |
| _pipe.enable_xformers_memory_efficient_attention() | |
| except Exception: | |
| pass | |
| _pipe_type = "inpaint" | |
| log.info("Inpaint pipeline loaded β") | |
| return _pipe | |
| def get_sd_pipeline(): | |
| """Load standard SD pipeline for latent-hijack strategy.""" | |
| global _pipe, _pipe_type | |
| if _pipe is not None and _pipe_type == "sd": | |
| return _pipe | |
| if not DIFFUSERS_OK: | |
| raise RuntimeError("diffusers not installed") | |
| from diffusers import StableDiffusionPipeline | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| dtype = torch.float16 if device == "cuda" else torch.float32 | |
| model_id = "runwayml/stable-diffusion-v1-5" | |
| log.info(f"Loading {model_id} on {device}") | |
| _pipe = StableDiffusionPipeline.from_pretrained( | |
| model_id, torch_dtype=dtype, safety_checker=None, | |
| ).to(device) | |
| _pipe.scheduler = DDIMScheduler.from_config(_pipe.scheduler.config) | |
| if device == "cuda": | |
| _pipe.enable_attention_slicing() | |
| try: | |
| _pipe.enable_xformers_memory_efficient_attention() | |
| except Exception: | |
| pass | |
| _pipe_type = "sd" | |
| log.info("SD pipeline loaded β") | |
| return _pipe | |
| # βββββββββββββββββββββββββββββββ UTILITIES ββββββββββββββββββββββββββββββββ | |
| def decode_b64_image(b64: str, size: tuple) -> Image.Image: | |
| raw = base64.b64decode(b64.split(",")[-1] if "," in b64 else b64) | |
| img = Image.open(io.BytesIO(raw)).convert("L") | |
| return img.resize(size, Image.LANCZOS) | |
| def make_void_image(w: int, h: int, color: str) -> Image.Image: | |
| c = (255, 255, 255) if color == "white" else (0, 0, 0) | |
| return Image.new("RGB", (w, h), c) | |
| def composite_void(generated: Image.Image, mask: Image.Image, void_color: str) -> Image.Image: | |
| """Hard composite: generated pixels inside mask, pure void outside.""" | |
| w, h = generated.size | |
| void_img = make_void_image(w, h, void_color) | |
| # Ensure mask is same size | |
| mask_resized = mask.resize((w, h), Image.LANCZOS) | |
| # Threshold mask for clean edges | |
| mask_arr = np.array(mask_resized) | |
| mask_hard = Image.fromarray(((mask_arr > 127) * 255).astype(np.uint8)) | |
| # Optional: slightly feather for anti-aliasing (2px) | |
| mask_feather = mask_hard.filter(ImageFilter.GaussianBlur(radius=1.5)) | |
| mask_feather_arr = np.array(mask_feather).astype(np.float32) / 255.0 | |
| gen_arr = np.array(generated).astype(np.float32) | |
| void_arr = np.array(void_img).astype(np.float32) | |
| # Blend | |
| alpha = mask_feather_arr[:, :, np.newaxis] | |
| result = gen_arr * alpha + void_arr * (1.0 - alpha) | |
| return Image.fromarray(result.astype(np.uint8)) | |
| # βββββββββββββββββββββββ STRATEGY A: INPAINTING ββββββββββββββββββββββββββ | |
| def generate_inpaint(pipe, req: GenRequest) -> Image.Image: | |
| """ | |
| Use the official inpainting pipeline. | |
| The mask semantics for SD-inpaint are: | |
| white = inpaint (generate here) | |
| black = keep original | |
| We feed a void-colored init image so "keep original" = pure void. | |
| """ | |
| device = pipe._execution_device | |
| generator = torch.Generator(device=device) | |
| if req.seed >= 0: | |
| generator.manual_seed(req.seed) | |
| w, h = req.width, req.height | |
| # Decode user mask | |
| user_mask = decode_b64_image(req.mask_b64, (w, h)) | |
| # Init image = pure void | |
| init_image = make_void_image(w, h, req.void_color) | |
| # For SD-inpaint: white mask = area to generate | |
| mask_image = user_mask # already white=generate, black=keep | |
| # Boost detail via higher resolution decode or prompt engineering | |
| prompt = req.prompt | |
| if req.detail_boost > 1.0: | |
| prompt += ", extremely detailed, intricate, sharp focus, masterpiece" | |
| result = pipe( | |
| prompt=prompt, | |
| negative_prompt=req.negative_prompt, | |
| image=init_image, | |
| mask_image=mask_image, | |
| width=w, | |
| height=h, | |
| num_inference_steps=req.num_steps, | |
| guidance_scale=req.guidance_scale, | |
| generator=generator, | |
| ).images[0] | |
| # Hard composite to guarantee perfectly clean void | |
| final = composite_void(result, user_mask, req.void_color) | |
| return final | |
| # βββββββββββββββββββ STRATEGY B: LATENT HIJACK βββββββββββββββββββββββββββ | |
| def generate_latent_hijack(pipe, req: GenRequest) -> Image.Image: | |
| """ | |
| Custom denoising loop. At every step, the latents in the void region | |
| are overwritten with the VAE-encoded void image latents, completely | |
| preventing any AI generation outside the mask. | |
| """ | |
| device = pipe._execution_device | |
| dtype = pipe.unet.dtype | |
| generator = torch.Generator(device=device) | |
| if req.seed >= 0: | |
| generator.manual_seed(req.seed) | |
| w, h = req.width, req.height | |
| lh, lw = h // 8, w // 8 | |
| # Encode void image into latent space | |
| void_img = make_void_image(w, h, req.void_color) | |
| void_tensor = torch.from_numpy( | |
| np.array(void_img).astype(np.float32) / 255.0 | |
| ).permute(2, 0, 1).unsqueeze(0).to(device=device, dtype=dtype) | |
| void_tensor = void_tensor * 2.0 - 1.0 | |
| void_latents = pipe.vae.encode(void_tensor).latent_dist.mean * 0.18215 | |
| # Decode mask β latent-space resolution | |
| user_mask = decode_b64_image(req.mask_b64, (lw, lh)) | |
| mask_tensor = torch.from_numpy( | |
| np.array(user_mask).astype(np.float32) / 255.0 | |
| ).unsqueeze(0).unsqueeze(0).to(device=device, dtype=dtype) | |
| # mask_tensor: 1=generate, 0=void | |
| # Encode prompt | |
| prompt = req.prompt | |
| if req.detail_boost > 1.0: | |
| prompt += ", extremely detailed, intricate, sharp focus, masterpiece" | |
| tok = pipe.tokenizer( | |
| prompt, padding="max_length", | |
| max_length=pipe.tokenizer.model_max_length, | |
| truncation=True, return_tensors="pt", | |
| ) | |
| cond = pipe.text_encoder(tok.input_ids.to(device))[0].to(dtype) | |
| tok_neg = pipe.tokenizer( | |
| req.negative_prompt, padding="max_length", | |
| max_length=pipe.tokenizer.model_max_length, | |
| truncation=True, return_tensors="pt", | |
| ) | |
| uncond = pipe.text_encoder(tok_neg.input_ids.to(device))[0].to(dtype) | |
| prompt_embeds = torch.cat([uncond, cond]) | |
| # Init random latents | |
| latents = torch.randn( | |
| (1, pipe.unet.config.in_channels, lh, lw), | |
| generator=generator, device=device, dtype=dtype, | |
| ) | |
| pipe.scheduler.set_timesteps(req.num_steps, device=device) | |
| latents = latents * pipe.scheduler.init_noise_sigma | |
| for i, t in enumerate(pipe.scheduler.timesteps): | |
| # ββ Hijack: force void in background ββ | |
| # Blend: keep AI latents where mask=1, force void latents where mask=0 | |
| # Add matching noise to void_latents for current timestep | |
| noise = torch.randn_like(void_latents) | |
| noisy_void = pipe.scheduler.add_noise(void_latents, noise, t) | |
| latents = latents * mask_tensor + noisy_void * (1.0 - mask_tensor) | |
| # Standard CFG denoising | |
| model_input = torch.cat([latents] * 2) | |
| model_input = pipe.scheduler.scale_model_input(model_input, t) | |
| noise_pred = pipe.unet( | |
| model_input, t, encoder_hidden_states=prompt_embeds, | |
| ).sample | |
| noise_uncond, noise_text = noise_pred.chunk(2) | |
| noise_pred = noise_uncond + req.guidance_scale * (noise_text - noise_uncond) | |
| latents = pipe.scheduler.step(noise_pred, t, latents).prev_sample | |
| # Final hijack: ensure perfect void | |
| latents = latents * mask_tensor + void_latents * (1.0 - mask_tensor) | |
| # Decode | |
| latents = latents / 0.18215 | |
| image = pipe.vae.decode(latents).sample | |
| image = (image / 2 + 0.5).clamp(0, 1) | |
| arr = image.cpu().permute(0, 2, 3, 1).numpy()[0] | |
| result = Image.fromarray((arr * 255).astype(np.uint8)) | |
| # Hard composite for pixel-perfect edges | |
| user_mask_full = decode_b64_image(req.mask_b64, (w, h)) | |
| return composite_void(result, user_mask_full, req.void_color) | |
| # βββββββββββββββββββββββ MOCK (no GPU) βββββββββββββββββββββββββββββββββββ | |
| def mock_generate(req: GenRequest) -> Image.Image: | |
| """Visual mock for frontend development without GPU.""" | |
| w, h = req.width, req.height | |
| mask = decode_b64_image(req.mask_b64, (w, h)) | |
| mask_arr = np.array(mask).astype(np.float32) / 255.0 | |
| # Create a colourful noise pattern inside the mask | |
| np.random.seed(abs(req.seed) if req.seed >= 0 else 42) | |
| noise = np.random.randint(0, 255, (h, w, 3), dtype=np.uint8) | |
| # Apply a colour tint | |
| tint = np.array([180, 60, 220], dtype=np.float32) | |
| noise_f = noise.astype(np.float32) * 0.5 + tint * 0.5 | |
| # Void | |
| vc = 255.0 if req.void_color == "white" else 0.0 | |
| void_arr = np.full((h, w, 3), vc, dtype=np.float32) | |
| alpha = mask_arr[:, :, np.newaxis] | |
| # Feathered edge | |
| mask_blur = Image.fromarray(mask).filter(ImageFilter.GaussianBlur(2)) | |
| alpha_blur = np.array(mask_blur).astype(np.float32) / 255.0 | |
| alpha = alpha_blur[:, :, np.newaxis] | |
| result = noise_f * alpha + void_arr * (1.0 - alpha) | |
| return Image.fromarray(result.astype(np.uint8)) | |
| # βββββββββββββββββββββββ ENDPOINTS βββββββββββββββββββββββββββββββββββββββ | |
| async def health(): | |
| return { | |
| "status": "ok", | |
| "gpu": torch.cuda.is_available() if DIFFUSERS_OK else False, | |
| "diffusers": DIFFUSERS_OK, | |
| } | |
| async def generate(req: GenRequest): | |
| t0 = time.time() | |
| try: | |
| if not DIFFUSERS_OK: | |
| log.warning("Mock mode (no diffusers)") | |
| image = mock_generate(req) | |
| elif req.strategy == "latent_hijack": | |
| pipe = get_sd_pipeline() | |
| image = generate_latent_hijack(pipe, req) | |
| else: | |
| pipe = get_inpaint_pipeline() | |
| image = generate_inpaint(pipe, req) | |
| except Exception as e: | |
| log.exception("Generation failed") | |
| raise HTTPException(500, detail=str(e)) | |
| buf = io.BytesIO() | |
| image.save(buf, format="PNG") | |
| b64 = base64.b64encode(buf.getvalue()).decode() | |
| elapsed = time.time() - t0 | |
| log.info(f"Done in {elapsed:.1f}s ({req.strategy})") | |
| return JSONResponse({ | |
| "image": f"data:image/png;base64,{b64}", | |
| "elapsed": round(elapsed, 2), | |
| }) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=8000) | |