Spaces:
Runtime error
Runtime error
ready to see working the model
Browse files- .gitignore +35 -0
- app.py +128 -0
- download_model.py +28 -0
- requirements.txt +8 -0
.gitignore
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modelos descargados (muy pesados para git)
|
| 2 |
+
models/
|
| 3 |
+
|
| 4 |
+
# Python
|
| 5 |
+
__pycache__/
|
| 6 |
+
*.py[cod]
|
| 7 |
+
*$py.class
|
| 8 |
+
*.so
|
| 9 |
+
.Python
|
| 10 |
+
env/
|
| 11 |
+
venv/
|
| 12 |
+
ENV/
|
| 13 |
+
.venv
|
| 14 |
+
|
| 15 |
+
# Gradio
|
| 16 |
+
flagged/
|
| 17 |
+
|
| 18 |
+
# Imágenes de prueba
|
| 19 |
+
*.jpg
|
| 20 |
+
*.jpeg
|
| 21 |
+
*.png
|
| 22 |
+
*.gif
|
| 23 |
+
!examples/*.jpg
|
| 24 |
+
!examples/*.jpeg
|
| 25 |
+
!examples/*.png
|
| 26 |
+
|
| 27 |
+
# IDE
|
| 28 |
+
.vscode/
|
| 29 |
+
.idea/
|
| 30 |
+
*.swp
|
| 31 |
+
*.swo
|
| 32 |
+
|
| 33 |
+
# OS
|
| 34 |
+
.DS_Store
|
| 35 |
+
Thumbs.db
|
app.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from diffusers import StableDiffusionInstructPix2PixPipeline
|
| 3 |
+
import torch
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Configuración del modelo
|
| 8 |
+
# Usar MPS en Mac M4 con configuración especial para evitar imágenes negras
|
| 9 |
+
if torch.backends.mps.is_available():
|
| 10 |
+
device = "mps"
|
| 11 |
+
# Configurar variables de entorno para MPS
|
| 12 |
+
os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1'
|
| 13 |
+
elif torch.cuda.is_available():
|
| 14 |
+
device = "cuda"
|
| 15 |
+
else:
|
| 16 |
+
device = "cpu"
|
| 17 |
+
|
| 18 |
+
print(f"Usando dispositivo: {device}")
|
| 19 |
+
|
| 20 |
+
MODEL_DIR = "./models/instruct-pix2pix"
|
| 21 |
+
MODEL_ONLINE = "timbrooks/instruct-pix2pix"
|
| 22 |
+
|
| 23 |
+
# Cargar el modelo (local si existe, sino desde HuggingFace)
|
| 24 |
+
if os.path.exists(MODEL_DIR):
|
| 25 |
+
print(f"Cargando modelo LOCAL desde {MODEL_DIR}...")
|
| 26 |
+
model_path = MODEL_DIR
|
| 27 |
+
else:
|
| 28 |
+
print(f"Modelo local no encontrado. Descargando desde HuggingFace...")
|
| 29 |
+
print("(Ejecuta 'python download_model.py' para descargar el modelo localmente)")
|
| 30 |
+
model_path = MODEL_ONLINE
|
| 31 |
+
|
| 32 |
+
# Siempre usar float32 para evitar problemas de compatibilidad
|
| 33 |
+
torch_dtype = torch.float32
|
| 34 |
+
|
| 35 |
+
pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(
|
| 36 |
+
model_path,
|
| 37 |
+
torch_dtype=torch_dtype,
|
| 38 |
+
safety_checker=None
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# Optimizaciones de memoria
|
| 42 |
+
pipe.enable_attention_slicing(1)
|
| 43 |
+
|
| 44 |
+
# Si es MPS, mover componentes individualmente para evitar problemas
|
| 45 |
+
if device == "mps":
|
| 46 |
+
pipe.to(device)
|
| 47 |
+
# Forzar que use float32 en todos los componentes
|
| 48 |
+
pipe.vae.to(dtype=torch.float32)
|
| 49 |
+
pipe.unet.to(dtype=torch.float32)
|
| 50 |
+
pipe.text_encoder.to(dtype=torch.float32)
|
| 51 |
+
else:
|
| 52 |
+
pipe.to(device)
|
| 53 |
+
|
| 54 |
+
print("Modelo cargado exitosamente!")
|
| 55 |
+
|
| 56 |
+
def rejuvenecer_imagen(imagen, intensidad=1.5, steps=20, guidance_scale=7.5):
|
| 57 |
+
"""
|
| 58 |
+
Rejuvenece una imagen usando Stable Diffusion InstructPix2Pix
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
imagen: PIL Image o numpy array
|
| 62 |
+
intensidad: Qué tanto seguir las instrucciones (1.0-2.5)
|
| 63 |
+
steps: Número de pasos de inferencia (más pasos = mejor calidad)
|
| 64 |
+
guidance_scale: Escala de guidance (mayor = más adherencia al prompt)
|
| 65 |
+
"""
|
| 66 |
+
if imagen is None:
|
| 67 |
+
return None
|
| 68 |
+
|
| 69 |
+
# Convertir a PIL Image si es necesario
|
| 70 |
+
if not isinstance(imagen, Image.Image):
|
| 71 |
+
imagen = Image.fromarray(imagen)
|
| 72 |
+
|
| 73 |
+
# Redimensionar imagen si es muy grande (para reducir uso de memoria)
|
| 74 |
+
max_size = 768
|
| 75 |
+
if max(imagen.size) > max_size:
|
| 76 |
+
ratio = max_size / max(imagen.size)
|
| 77 |
+
new_size = tuple(int(dim * ratio) for dim in imagen.size)
|
| 78 |
+
imagen = imagen.resize(new_size, Image.Resampling.LANCZOS)
|
| 79 |
+
|
| 80 |
+
# Prompt para rejuvenecer
|
| 81 |
+
prompt = "make the person look 20 years younger, remove wrinkles, smooth skin, youthful appearance"
|
| 82 |
+
|
| 83 |
+
# Limpiar memoria antes de generar
|
| 84 |
+
if device == "mps":
|
| 85 |
+
torch.mps.empty_cache()
|
| 86 |
+
|
| 87 |
+
# Generar imagen
|
| 88 |
+
resultado = pipe(
|
| 89 |
+
prompt=prompt,
|
| 90 |
+
image=imagen,
|
| 91 |
+
num_inference_steps=steps,
|
| 92 |
+
image_guidance_scale=intensidad,
|
| 93 |
+
guidance_scale=guidance_scale
|
| 94 |
+
).images[0]
|
| 95 |
+
|
| 96 |
+
# Limpiar memoria después de generar
|
| 97 |
+
if device == "mps":
|
| 98 |
+
torch.mps.empty_cache()
|
| 99 |
+
|
| 100 |
+
return resultado
|
| 101 |
+
|
| 102 |
+
# Interfaz Gradio
|
| 103 |
+
with gr.Blocks(title="Rejuvenecedor de Imágenes 🌟") as demo:
|
| 104 |
+
gr.Markdown("""
|
| 105 |
+
# 🌟 Rejuvenecedor de Imágenes con IA
|
| 106 |
+
Sube una foto y hazla lucir más joven usando Stable Diffusion + InstructPix2Pix
|
| 107 |
+
""")
|
| 108 |
+
|
| 109 |
+
with gr.Row():
|
| 110 |
+
with gr.Column():
|
| 111 |
+
imagen_input = gr.Image(
|
| 112 |
+
label="Sube tu imagen",
|
| 113 |
+
type="pil",
|
| 114 |
+
sources=["upload", "webcam"]
|
| 115 |
+
)
|
| 116 |
+
boton_procesar = gr.Button("✨ Rejuvenecer", variant="primary", size="lg")
|
| 117 |
+
|
| 118 |
+
with gr.Column():
|
| 119 |
+
imagen_output = gr.Image(label="Resultado")
|
| 120 |
+
|
| 121 |
+
boton_procesar.click(
|
| 122 |
+
fn=rejuvenecer_imagen,
|
| 123 |
+
inputs=[imagen_input],
|
| 124 |
+
outputs=imagen_output
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
if __name__ == "__main__":
|
| 128 |
+
demo.launch(share=False, server_name="0.0.0.0")
|
download_model.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Script para descargar el modelo Stable Diffusion InstructPix2Pix localmente
|
| 3 |
+
Ejecuta este script UNA VEZ para descargar el modelo
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from diffusers import StableDiffusionInstructPix2PixPipeline
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
# Directorio donde se guardará el modelo
|
| 10 |
+
MODEL_DIR = "./models/instruct-pix2pix"
|
| 11 |
+
|
| 12 |
+
print("Descargando modelo Stable Diffusion InstructPix2Pix...")
|
| 13 |
+
print(f"Se guardará en: {MODEL_DIR}")
|
| 14 |
+
print("Esto puede tomar varios minutos dependiendo de tu conexión...\n")
|
| 15 |
+
|
| 16 |
+
# Descargar y guardar el modelo
|
| 17 |
+
pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(
|
| 18 |
+
"timbrooks/instruct-pix2pix",
|
| 19 |
+
torch_dtype=torch.float16,
|
| 20 |
+
safety_checker=None
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
# Guardar el modelo localmente
|
| 24 |
+
pipe.save_pretrained(MODEL_DIR)
|
| 25 |
+
|
| 26 |
+
print(f"\n✅ Modelo descargado exitosamente en: {MODEL_DIR}")
|
| 27 |
+
print(f"Tamaño aproximado: ~5GB")
|
| 28 |
+
print("\nAhora puedes usar app.py y cargará el modelo desde el disco local.")
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.0.0
|
| 2 |
+
diffusers>=0.25.0
|
| 3 |
+
transformers>=4.35.0
|
| 4 |
+
torch>=2.0.0
|
| 5 |
+
torchvision>=0.15.0
|
| 6 |
+
accelerate>=0.24.0
|
| 7 |
+
safetensors>=0.4.0
|
| 8 |
+
Pillow>=10.0.0
|