Download app.py from jupadev/data-test: direct link, hf CLI and curl.
- Browser
- Download file 6.17 kB
-
https://huggingface.co/spaces/jupadev/data-test/resolve/main/app.py
- Command line
-
hf download hf://spaces/jupadev/data-test/app.py
-
curl -L -o app.py https://huggingface.co/spaces/jupadev/data-test/resolve/main/app.py
6.17 kB
| import os | |
| import random | |
| import gradio as gr | |
| import numpy as np | |
| import spaces | |
| import torch | |
| from diffusers import ( | |
| AutoencoderKL, | |
| ControlNetModel, | |
| EulerDiscreteScheduler, | |
| StableDiffusionXLControlNetPipeline, | |
| UNet2DConditionModel, | |
| ) | |
| from huggingface_hub import hf_hub_download | |
| from PIL import Image | |
| from safetensors.torch import load_file | |
| BASE = "stabilityai/stable-diffusion-xl-base-1.0" | |
| LIGHTNING = "ByteDance/SDXL-Lightning" | |
| LIGHTNING_UNET = "sdxl_lightning_4step_unet.safetensors" | |
| CONTROLNET = "xinsir/controlnet-scribble-sdxl-1.0" | |
| VAE = "madebyollin/sdxl-vae-fp16-fix" | |
| PASOS = 4 # Tiene que coincidir con el checkpoint de Lightning. | |
| LADO = 1024 | |
| SEMILLA_MAX = 2**32 - 1 | |
| # Secret del Space. Es opcional: estos modelos son públicos. | |
| HF_TOKEN = os.environ.get("HF_TOKEN") or None | |
| ESTILOS = { | |
| "🖼️ Óleo": "oil painting of {}, thick impasto brushstrokes, rich colors, museum quality", | |
| "💧 Acuarela": "watercolor painting of {}, soft washes, delicate paper texture, luminous", | |
| "🌸 Anime": "anime key visual of {}, clean lineart, vibrant colors, detailed background", | |
| "🧸 Render 3D": "3D render of {}, cute stylized character design, soft studio lighting, high detail", | |
| "⛪ Vitral": "stained glass window depicting {}, bright jewel tones, lead lines, backlit, cathedral", | |
| "👾 Pixel art": "pixel art of {}, 16-bit video game style, crisp pixels, limited palette", | |
| "📷 Foto": "professional photograph of {}, natural light, sharp focus, 85mm lens", | |
| } | |
| def cargar_pipeline(): | |
| # ZeroGPU pide ubicar los modelos en "cuda" al importar el módulo: fuera de | |
| # @spaces.GPU es una emulación y la GPU real se asigna solo al generar. | |
| config_unet = UNet2DConditionModel.load_config(BASE, subfolder="unet", token=HF_TOKEN) | |
| unet = UNet2DConditionModel.from_config(config_unet) | |
| unet.load_state_dict(load_file(hf_hub_download(LIGHTNING, LIGHTNING_UNET, token=HF_TOKEN))) | |
| unet.to(dtype=torch.float16) | |
| controlnet = ControlNetModel.from_pretrained(CONTROLNET, torch_dtype=torch.float16, token=HF_TOKEN) | |
| vae = AutoencoderKL.from_pretrained(VAE, torch_dtype=torch.float16, token=HF_TOKEN) | |
| pipe = StableDiffusionXLControlNetPipeline.from_pretrained( | |
| BASE, | |
| unet=unet, | |
| controlnet=controlnet, | |
| vae=vae, | |
| torch_dtype=torch.float16, | |
| variant="fp16", | |
| token=HF_TOKEN, | |
| ) | |
| pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing") | |
| return pipe.to("cuda") | |
| pipe = cargar_pipeline() | |
| def preparar_control(dibujo): | |
| """Convierte el dibujo en líneas blancas puras sobre fondo negro, o None si está vacío.""" | |
| compuesto = (dibujo or {}).get("composite") | |
| if compuesto is None: | |
| return None | |
| lienzo = Image.new("RGBA", compuesto.size, "white") | |
| lienzo.alpha_composite(compuesto.convert("RGBA")) | |
| gris = lienzo.convert("L").resize((LADO, LADO), Image.LANCZOS) | |
| lineas = np.array(gris) < 200 | |
| if lineas.mean() < 0.001: | |
| return None | |
| return Image.fromarray(lineas.astype(np.uint8) * 255).convert("RGB") | |
| def generar(prompt, control, fidelidad, semilla): | |
| generador = torch.Generator("cpu").manual_seed(semilla) | |
| return pipe( | |
| prompt=prompt, | |
| image=control, | |
| num_inference_steps=PASOS, | |
| guidance_scale=0, | |
| controlnet_conditioning_scale=fidelidad, | |
| width=LADO, | |
| height=LADO, | |
| generator=generador, | |
| ).images[0] | |
| def transformar(dibujo, descripcion, estilo, fidelidad, semilla, semilla_al_azar): | |
| # Todo lo que no necesita GPU se valida acá para no gastar cuota. | |
| descripcion = (descripcion or "").strip() | |
| if not descripcion: | |
| raise gr.Error("Contame qué dibujaste.") | |
| control = preparar_control(dibujo) | |
| if control is None: | |
| raise gr.Error("El lienzo está vacío: dibujá algo primero.") | |
| if semilla_al_azar: | |
| semilla = random.randint(0, SEMILLA_MAX) | |
| semilla = int(semilla) | |
| prompt = ESTILOS[estilo].format(descripcion) | |
| return generar(prompt, control, fidelidad, semilla), semilla | |
| with gr.Blocks(title="De garabato a obra de arte") as demo: | |
| gr.Markdown( | |
| "# 🎨 De garabato a obra de arte\n" | |
| "Tocá el **pincel 🖌️ a la izquierda del lienzo**, dibujá algo horrible, " | |
| "elegí un estilo y dejá que la IA se haga cargo." | |
| ) | |
| with gr.Row(): | |
| with gr.Column(): | |
| dibujo = gr.Sketchpad( | |
| label="Tu garabato", | |
| type="pil", | |
| image_mode="RGBA", | |
| canvas_size=(512, 512), | |
| fixed_canvas=True, | |
| height=600, | |
| layers=False, | |
| transforms=(), | |
| brush=gr.Brush(default_size=2, colors=["#000000"], color_mode="fixed"), | |
| ) | |
| descripcion = gr.Textbox( | |
| label="¿Qué dibujaste? (funciona mejor en inglés)", | |
| placeholder="a cat riding a skateboard", | |
| max_length=200, | |
| ) | |
| estilo = gr.Radio(choices=list(ESTILOS), value="🖼️ Óleo", label="Estilo") | |
| boton = gr.Button("Transformar", variant="primary") | |
| with gr.Accordion("Ajustes", open=False): | |
| fidelidad = gr.Slider( | |
| 0.3, | |
| 1.0, | |
| value=0.75, | |
| step=0.05, | |
| label="Fidelidad al dibujo", | |
| info="Más bajo le da más libertad a la IA para corregir tu garabato.", | |
| ) | |
| semilla = gr.Number(label="Semilla", value=0, precision=0, minimum=0, maximum=SEMILLA_MAX) | |
| semilla_al_azar = gr.Checkbox(label="Semilla al azar", value=True) | |
| with gr.Column(): | |
| resultado = gr.Image(label="Tu obra", type="pil", format="png", interactive=False) | |
| boton.click( | |
| transformar, | |
| inputs=[dibujo, descripcion, estilo, fidelidad, semilla, semilla_al_azar], | |
| outputs=[resultado, semilla], | |
| api_name="transformar", | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |