import spaces # must come before torch / diffusers import random import cv2 import gradio as gr import numpy as np import qrcode import torch import zxingcpp from diffusers import ControlNetModel, EulerAncestralDiscreteScheduler, StableDiffusionControlNetPipeline from PIL import Image CONTROLNET_ID = "monster-labs/control_v1p_sd15_qrcode_monster" BASE_ID = "stable-diffusion-v1-5/stable-diffusion-v1-5" MAX_SEED = 2**31 - 1 MODULE_PX = 16 # the model was trained on 16px QR modules controlnet = ControlNetModel.from_pretrained(CONTROLNET_ID, subfolder="v2", dtype=torch.float16) pipe = StableDiffusionControlNetPipeline.from_pretrained( BASE_ID, controlnet=controlnet, variant="fp16", dtype=torch.float16 ).to("cuda") pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config) # the Aruco detector reads codes with no quiet zone; the plain one can't qr_detector = cv2.QRCodeDetectorAruco() def make_condition(content: str, quiet_zone: bool = True) -> Image.Image: """Black/white QR with 16px modules, pasted on a #808080 canvas sized to a multiple of 256. Scanners need a light margin around the code to find it; without one the model paints art right up to the finder patterns and the result rarely scans. """ qr = qrcode.QRCode( error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=MODULE_PX, border=2 if quiet_zone else 0 ) qr.add_data(content) qr.make(fit=True) code = qr.make_image(fill_color="black", back_color="white").convert("L") margin = 8 * MODULE_PX w, h = ((s + 255 + margin) // 256 * 256 for s in code.size) if max(w, h) > 1024: raise gr.Error("That content makes a QR code too large for the model. Try something shorter.") canvas = Image.new("L", (w, h), 128) # keep the code aligned to the 16px module grid canvas.paste(code, ((w - code.width) // 2 // MODULE_PX * MODULE_PX, (h - code.height) // 2 // MODULE_PX * MODULE_PX)) return canvas.convert("RGB") def scan(image: Image.Image) -> str | None: """Decode a QR code from the whole image, or None if nothing reads.""" gray = np.asarray(image.convert("L")) for result in zxingcpp.read_barcodes(gray, formats=zxingcpp.BarcodeFormat.QRCode): if result.text: return result.text text, _, _ = qr_detector.detectAndDecode(gray) return text or None @spaces.GPU(duration=40) def generate( content: str, prompt: str, controlnet_scale: float = 1.5, negative_prompt: str = "ugly, disfigured, low quality, blurry, nsfw", guidance_scale: float = 7.5, steps: int = 30, seed: int = 0, randomize_seed: bool = True, quiet_zone: bool = True, ) -> tuple[Image.Image, Image.Image, str, int]: """Generate artistic, scannable QR code art with ControlNet QR Code Monster v2 on Stable Diffusion 1.5. Args: content: Text or URL to encode in the QR code. prompt: What the artwork should depict. controlnet_scale: Higher reads more reliably, lower looks more creative. negative_prompt: What to steer away from. guidance_scale: How strongly to follow the prompt. steps: Number of denoising steps. seed: Random seed, used when randomize_seed is False. randomize_seed: Pick a fresh random seed. quiet_zone: Keep a light margin around the code so scanners can find it. Returns: The artwork, the QR condition image, a scan check, and the seed used. """ if not content: raise gr.Error("Enter the text or URL to encode.") if not prompt: raise gr.Error("Enter a prompt.") if randomize_seed: seed = random.randint(0, MAX_SEED) condition = make_condition(content, quiet_zone) out = pipe( prompt=prompt, negative_prompt=negative_prompt or None, image=condition, width=condition.width, height=condition.height, controlnet_conditioning_scale=float(controlnet_scale), guidance_scale=guidance_scale, num_inference_steps=int(steps), generator=torch.Generator("cuda").manual_seed(int(seed)), ) if out.nsfw_content_detected and out.nsfw_content_detected[0]: raise gr.Error("The safety checker flagged this output. Try a different prompt or seed.") art = out.images[0] decoded = scan(art) if decoded == content: status = "✅ Scans: reads back the exact content." elif decoded: status = f"⚠️ Scans, but reads `{decoded}`." else: status = "❌ Didn't scan here. Raise the QR strength, keep the quiet zone on, or try another seed." return art, condition, status, seed with gr.Blocks(title="QR Code Monster") as demo: gr.Markdown( "# QR Code Monster v2\n" f"Turn a link into art that still scans, using [`{CONTROLNET_ID}`](https://huggingface.co/{CONTROLNET_ID}) " "(v2) on Stable Diffusion 1.5. **QR strength** trades readability against creativity." ) with gr.Row(): with gr.Column(): content = gr.Textbox(label="QR content", value="https://qrcode.monster") prompt = gr.Textbox(label="Prompt", placeholder="a blue monster, digital art, highly detailed") controlnet_scale = gr.Slider(0.5, 2.5, value=1.5, step=0.05, label="QR strength (ControlNet scale)") run = gr.Button("Generate", variant="primary") with gr.Accordion("Advanced", open=False): negative_prompt = gr.Textbox(label="Negative prompt", value="ugly, disfigured, low quality, blurry, nsfw") guidance_scale = gr.Slider(1.0, 15.0, value=7.5, step=0.5, label="Guidance scale") steps = gr.Slider(15, 50, value=30, step=1, label="Steps") seed = gr.Slider(0, MAX_SEED, value=0, step=1, label="Seed") randomize_seed = gr.Checkbox(label="Randomize seed", value=True) quiet_zone = gr.Checkbox(label="Quiet zone (light margin; much more scannable)", value=True) with gr.Column(): art = gr.Image(label="Result", format="png") status = gr.Markdown() with gr.Row(): condition = gr.Image(label="QR condition", height=200) seed_out = gr.Number(label="Seed used", precision=0) inputs = [content, prompt, controlnet_scale, negative_prompt, guidance_scale, steps, seed, randomize_seed, quiet_zone] outputs = [art, condition, status, seed_out] gr.on([run.click, prompt.submit], generate, inputs=inputs, outputs=outputs) # prompts after the model card's showcase images gr.Examples( examples=[ ["https://qrcode.monster", "a cute blue monster, digital art, highly detailed, vibrant", 1.5], ["https://huggingface.co", "a giant ancient tree, roots and branches, fantasy forest, detailed", 1.5], ], inputs=[content, prompt, controlnet_scale], outputs=outputs, fn=generate, cache_examples=True, cache_mode="lazy", ) demo.launch(mcp_server=True)