File size: 6,165 Bytes
21d7c62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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")


@spaces.GPU(duration=20)
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()