Upload 3 files
Browse files- README.md +18 -7
- app.py +169 -0
- requirements.txt +6 -0
README.md
CHANGED
|
@@ -1,14 +1,25 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.31.0
|
| 8 |
-
python_version:
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
-
license:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
---
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: De garabato a obra de arte
|
| 3 |
+
emoji: 🎨
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: pink
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.31.0
|
| 8 |
+
python_version: "3.12"
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
+
license: openrail++
|
| 12 |
+
short_description: Dibujá un garabato y convertilo en una obra de arte
|
| 13 |
+
models:
|
| 14 |
+
- stabilityai/stable-diffusion-xl-base-1.0
|
| 15 |
+
- ByteDance/SDXL-Lightning
|
| 16 |
+
- xinsir/controlnet-scribble-sdxl-1.0
|
| 17 |
+
- madebyollin/sdxl-vae-fp16-fix
|
| 18 |
---
|
| 19 |
|
| 20 |
+
# De garabato a obra de arte
|
| 21 |
+
|
| 22 |
+
Demo para ZeroGPU que convierte un dibujo a mano en una imagen con SDXL Lightning (4 pasos) y ControlNet Scribble.
|
| 23 |
+
|
| 24 |
+
- Hardware: ZeroGPU.
|
| 25 |
+
- Secret opcional: `HF_TOKEN`.
|
app.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
from diffusers import (
|
| 9 |
+
AutoencoderKL,
|
| 10 |
+
ControlNetModel,
|
| 11 |
+
EulerDiscreteScheduler,
|
| 12 |
+
StableDiffusionXLControlNetPipeline,
|
| 13 |
+
UNet2DConditionModel,
|
| 14 |
+
)
|
| 15 |
+
from huggingface_hub import hf_hub_download
|
| 16 |
+
from PIL import Image
|
| 17 |
+
from safetensors.torch import load_file
|
| 18 |
+
|
| 19 |
+
BASE = "stabilityai/stable-diffusion-xl-base-1.0"
|
| 20 |
+
LIGHTNING = "ByteDance/SDXL-Lightning"
|
| 21 |
+
LIGHTNING_UNET = "sdxl_lightning_4step_unet.safetensors"
|
| 22 |
+
CONTROLNET = "xinsir/controlnet-scribble-sdxl-1.0"
|
| 23 |
+
VAE = "madebyollin/sdxl-vae-fp16-fix"
|
| 24 |
+
|
| 25 |
+
PASOS = 4 # Tiene que coincidir con el checkpoint de Lightning.
|
| 26 |
+
LADO = 1024
|
| 27 |
+
SEMILLA_MAX = 2**32 - 1
|
| 28 |
+
|
| 29 |
+
# Secret del Space. Es opcional: estos modelos son públicos.
|
| 30 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") or None
|
| 31 |
+
|
| 32 |
+
ESTILOS = {
|
| 33 |
+
"🖼️ Óleo": "oil painting of {}, thick impasto brushstrokes, rich colors, museum quality",
|
| 34 |
+
"💧 Acuarela": "watercolor painting of {}, soft washes, delicate paper texture, luminous",
|
| 35 |
+
"🌸 Anime": "anime key visual of {}, clean lineart, vibrant colors, detailed background",
|
| 36 |
+
"🧸 Render 3D": "3D render of {}, cute stylized character design, soft studio lighting, high detail",
|
| 37 |
+
"⛪ Vitral": "stained glass window depicting {}, bright jewel tones, lead lines, backlit, cathedral",
|
| 38 |
+
"👾 Pixel art": "pixel art of {}, 16-bit video game style, crisp pixels, limited palette",
|
| 39 |
+
"📷 Foto": "professional photograph of {}, natural light, sharp focus, 85mm lens",
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def cargar_pipeline():
|
| 44 |
+
# ZeroGPU pide ubicar los modelos en "cuda" al importar el módulo: fuera de
|
| 45 |
+
# @spaces.GPU es una emulación y la GPU real se asigna solo al generar.
|
| 46 |
+
config_unet = UNet2DConditionModel.load_config(BASE, subfolder="unet", token=HF_TOKEN)
|
| 47 |
+
unet = UNet2DConditionModel.from_config(config_unet)
|
| 48 |
+
unet.load_state_dict(load_file(hf_hub_download(LIGHTNING, LIGHTNING_UNET, token=HF_TOKEN)))
|
| 49 |
+
unet.to(dtype=torch.float16)
|
| 50 |
+
|
| 51 |
+
controlnet = ControlNetModel.from_pretrained(CONTROLNET, torch_dtype=torch.float16, token=HF_TOKEN)
|
| 52 |
+
vae = AutoencoderKL.from_pretrained(VAE, torch_dtype=torch.float16, token=HF_TOKEN)
|
| 53 |
+
pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
|
| 54 |
+
BASE,
|
| 55 |
+
unet=unet,
|
| 56 |
+
controlnet=controlnet,
|
| 57 |
+
vae=vae,
|
| 58 |
+
torch_dtype=torch.float16,
|
| 59 |
+
variant="fp16",
|
| 60 |
+
token=HF_TOKEN,
|
| 61 |
+
)
|
| 62 |
+
pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
|
| 63 |
+
return pipe.to("cuda")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
pipe = cargar_pipeline()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def preparar_control(dibujo):
|
| 70 |
+
"""Convierte el dibujo en líneas blancas puras sobre fondo negro, o None si está vacío."""
|
| 71 |
+
compuesto = (dibujo or {}).get("composite")
|
| 72 |
+
if compuesto is None:
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
lienzo = Image.new("RGBA", compuesto.size, "white")
|
| 76 |
+
lienzo.alpha_composite(compuesto.convert("RGBA"))
|
| 77 |
+
gris = lienzo.convert("L").resize((LADO, LADO), Image.LANCZOS)
|
| 78 |
+
|
| 79 |
+
lineas = np.array(gris) < 200
|
| 80 |
+
if lineas.mean() < 0.001:
|
| 81 |
+
return None
|
| 82 |
+
return Image.fromarray(lineas.astype(np.uint8) * 255).convert("RGB")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@spaces.GPU(duration=20)
|
| 86 |
+
def generar(prompt, control, fidelidad, semilla):
|
| 87 |
+
generador = torch.Generator("cpu").manual_seed(semilla)
|
| 88 |
+
return pipe(
|
| 89 |
+
prompt=prompt,
|
| 90 |
+
image=control,
|
| 91 |
+
num_inference_steps=PASOS,
|
| 92 |
+
guidance_scale=0,
|
| 93 |
+
controlnet_conditioning_scale=fidelidad,
|
| 94 |
+
width=LADO,
|
| 95 |
+
height=LADO,
|
| 96 |
+
generator=generador,
|
| 97 |
+
).images[0]
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def transformar(dibujo, descripcion, estilo, fidelidad, semilla, semilla_al_azar):
|
| 101 |
+
# Todo lo que no necesita GPU se valida acá para no gastar cuota.
|
| 102 |
+
descripcion = (descripcion or "").strip()
|
| 103 |
+
if not descripcion:
|
| 104 |
+
raise gr.Error("Contame qué dibujaste.")
|
| 105 |
+
|
| 106 |
+
control = preparar_control(dibujo)
|
| 107 |
+
if control is None:
|
| 108 |
+
raise gr.Error("El lienzo está vacío: dibujá algo primero.")
|
| 109 |
+
|
| 110 |
+
if semilla_al_azar:
|
| 111 |
+
semilla = random.randint(0, SEMILLA_MAX)
|
| 112 |
+
semilla = int(semilla)
|
| 113 |
+
|
| 114 |
+
prompt = ESTILOS[estilo].format(descripcion)
|
| 115 |
+
return generar(prompt, control, fidelidad, semilla), semilla
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
with gr.Blocks(title="De garabato a obra de arte") as demo:
|
| 119 |
+
gr.Markdown(
|
| 120 |
+
"# 🎨 De garabato a obra de arte\n"
|
| 121 |
+
"Tocá el **pincel 🖌️ a la izquierda del lienzo**, dibujá algo horrible, "
|
| 122 |
+
"elegí un estilo y dejá que la IA se haga cargo."
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
with gr.Row():
|
| 126 |
+
with gr.Column():
|
| 127 |
+
dibujo = gr.Sketchpad(
|
| 128 |
+
label="Tu garabato",
|
| 129 |
+
type="pil",
|
| 130 |
+
image_mode="RGBA",
|
| 131 |
+
canvas_size=(512, 512),
|
| 132 |
+
fixed_canvas=True,
|
| 133 |
+
height=600,
|
| 134 |
+
layers=False,
|
| 135 |
+
transforms=(),
|
| 136 |
+
brush=gr.Brush(default_size=2, colors=["#000000"], color_mode="fixed"),
|
| 137 |
+
)
|
| 138 |
+
descripcion = gr.Textbox(
|
| 139 |
+
label="¿Qué dibujaste? (funciona mejor en inglés)",
|
| 140 |
+
placeholder="a cat riding a skateboard",
|
| 141 |
+
max_length=200,
|
| 142 |
+
)
|
| 143 |
+
estilo = gr.Radio(choices=list(ESTILOS), value="🖼️ Óleo", label="Estilo")
|
| 144 |
+
boton = gr.Button("Transformar", variant="primary")
|
| 145 |
+
|
| 146 |
+
with gr.Accordion("Ajustes", open=False):
|
| 147 |
+
fidelidad = gr.Slider(
|
| 148 |
+
0.3,
|
| 149 |
+
1.0,
|
| 150 |
+
value=0.75,
|
| 151 |
+
step=0.05,
|
| 152 |
+
label="Fidelidad al dibujo",
|
| 153 |
+
info="Más bajo le da más libertad a la IA para corregir tu garabato.",
|
| 154 |
+
)
|
| 155 |
+
semilla = gr.Number(label="Semilla", value=0, precision=0, minimum=0, maximum=SEMILLA_MAX)
|
| 156 |
+
semilla_al_azar = gr.Checkbox(label="Semilla al azar", value=True)
|
| 157 |
+
|
| 158 |
+
with gr.Column():
|
| 159 |
+
resultado = gr.Image(label="Tu obra", type="pil", format="png", interactive=False)
|
| 160 |
+
|
| 161 |
+
boton.click(
|
| 162 |
+
transformar,
|
| 163 |
+
inputs=[dibujo, descripcion, estilo, fidelidad, semilla, semilla_al_azar],
|
| 164 |
+
outputs=[resultado, semilla],
|
| 165 |
+
api_name="transformar",
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
if __name__ == "__main__":
|
| 169 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.13.0
|
| 2 |
+
diffusers==0.42.1
|
| 3 |
+
transformers==5.22.2
|
| 4 |
+
accelerate==1.15.0
|
| 5 |
+
safetensors
|
| 6 |
+
spaces
|