Spaces:
Runtime error
Runtime error
Emalbornoz commited on
Commit ·
bd3b7dc
1
Parent(s): a24c6af
Fix: mas cambios otro modelo
Browse files- app.py +50 -55
- app.py.backpPreClaude +126 -0
app.py
CHANGED
|
@@ -1,22 +1,17 @@
|
|
| 1 |
import io
|
| 2 |
-
import os
|
| 3 |
import torch
|
| 4 |
from fastapi import FastAPI, UploadFile, File, Form
|
| 5 |
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
-
from
|
|
|
|
| 7 |
from PIL import Image
|
| 8 |
import logging
|
| 9 |
-
from fastapi.responses import JSONResponse
|
| 10 |
-
# from diffusers.models.ip_adapter import IPAdapter
|
| 11 |
|
| 12 |
-
# Configurar logging
|
| 13 |
logging.basicConfig(level=logging.INFO)
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
|
| 16 |
-
# Crear la aplicación FastAPI
|
| 17 |
app = FastAPI()
|
| 18 |
|
| 19 |
-
# Configurar CORS para permitir solicitudes desde cualquier origen
|
| 20 |
app.add_middleware(
|
| 21 |
CORSMiddleware,
|
| 22 |
allow_origins=["*"],
|
|
@@ -25,102 +20,102 @@ app.add_middleware(
|
|
| 25 |
allow_headers=["*"],
|
| 26 |
)
|
| 27 |
|
| 28 |
-
# Variable global para el pipeline (se cargará una vez al iniciar)
|
| 29 |
pipe = None
|
| 30 |
|
| 31 |
@app.on_event("startup")
|
| 32 |
async def load_model():
|
| 33 |
global pipe
|
| 34 |
-
logger.info("Cargando
|
| 35 |
|
| 36 |
try:
|
| 37 |
-
|
| 38 |
-
pipe = StableDiffusionXLPipeline.from_pretrained(
|
| 39 |
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 40 |
torch_dtype=torch.float32,
|
| 41 |
-
use_safetensors=True
|
| 42 |
-
)
|
| 43 |
-
|
| 44 |
-
pipe.load_ip_adapter(
|
| 45 |
-
"h94/IP-Adapter",
|
| 46 |
-
subfolder="sdxl_models",
|
| 47 |
-
weight_name="ip-adapter_sdxl.bin"
|
| 48 |
)
|
| 49 |
|
| 50 |
-
# Usar CPU (no hay GPU en el plan gratuito)
|
| 51 |
pipe.to("cpu")
|
| 52 |
-
# Reducir el uso de memoria
|
| 53 |
pipe.enable_attention_slicing()
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
# pipe.vae.to(torch.float32)
|
| 58 |
-
# pipe.text_encoder.to(torch.float32)
|
| 59 |
-
# pipe.text_encoder_2.to(torch.float32)
|
| 60 |
-
|
| 61 |
-
logger.info("Modelo cargado exitosamente en CPU")
|
| 62 |
except Exception as e:
|
| 63 |
-
logger.error(f"Error al cargar
|
| 64 |
raise
|
| 65 |
|
| 66 |
|
| 67 |
@app.post("/generate")
|
| 68 |
async def generate_image(
|
| 69 |
-
prompt: str = Form(...
|
| 70 |
-
image1: UploadFile = File(..., description="
|
| 71 |
-
image2: UploadFile = File(..., description="
|
| 72 |
):
|
| 73 |
-
logger.info(f"
|
| 74 |
|
| 75 |
try:
|
| 76 |
-
# Leer
|
| 77 |
-
|
| 78 |
-
|
| 79 |
|
| 80 |
-
img1 = Image.open(io.BytesIO(
|
| 81 |
-
img2 = Image.open(io.BytesIO(
|
| 82 |
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
result = pipe(
|
| 87 |
prompt=prompt,
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
height=512
|
| 93 |
)
|
| 94 |
|
| 95 |
-
logger.info("Imagen generada exitosamente")
|
| 96 |
-
|
| 97 |
-
# Obtener la primera imagen del resultado
|
| 98 |
output_image = result.images[0]
|
| 99 |
|
| 100 |
-
# Convertir
|
| 101 |
img_byte_arr = io.BytesIO()
|
| 102 |
output_image.save(img_byte_arr, format='PNG')
|
| 103 |
img_byte_arr.seek(0)
|
| 104 |
|
| 105 |
-
# Devolver la imagen generada
|
| 106 |
return StreamingResponse(
|
| 107 |
-
img_byte_arr,
|
| 108 |
media_type="image/png",
|
| 109 |
headers={"Content-Disposition": "attachment; filename=generated_image.png"}
|
| 110 |
)
|
| 111 |
|
| 112 |
except Exception as e:
|
| 113 |
-
logger.error(f"Error
|
| 114 |
return JSONResponse(
|
| 115 |
status_code=500,
|
| 116 |
-
content={"error": str(e)}
|
| 117 |
)
|
| 118 |
|
|
|
|
| 119 |
@app.get("/health")
|
| 120 |
async def health_check():
|
| 121 |
-
"""Endpoint para verificar que la API está funcionando"""
|
| 122 |
return {"status": "ok", "model_loaded": pipe is not None}
|
| 123 |
|
|
|
|
| 124 |
@app.get("/")
|
| 125 |
async def root():
|
| 126 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import io
|
|
|
|
| 2 |
import torch
|
| 3 |
from fastapi import FastAPI, UploadFile, File, Form
|
| 4 |
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
+
from fastapi.responses import JSONResponse, StreamingResponse
|
| 6 |
+
from diffusers import AutoPipelineForImage2Image
|
| 7 |
from PIL import Image
|
| 8 |
import logging
|
|
|
|
|
|
|
| 9 |
|
|
|
|
| 10 |
logging.basicConfig(level=logging.INFO)
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
|
|
|
| 13 |
app = FastAPI()
|
| 14 |
|
|
|
|
| 15 |
app.add_middleware(
|
| 16 |
CORSMiddleware,
|
| 17 |
allow_origins=["*"],
|
|
|
|
| 20 |
allow_headers=["*"],
|
| 21 |
)
|
| 22 |
|
|
|
|
| 23 |
pipe = None
|
| 24 |
|
| 25 |
@app.on_event("startup")
|
| 26 |
async def load_model():
|
| 27 |
global pipe
|
| 28 |
+
logger.info("Cargando modelo SDXL img2img...")
|
| 29 |
|
| 30 |
try:
|
| 31 |
+
pipe = AutoPipelineForImage2Image.from_pretrained(
|
|
|
|
| 32 |
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 33 |
torch_dtype=torch.float32,
|
| 34 |
+
use_safetensors=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
)
|
| 36 |
|
|
|
|
| 37 |
pipe.to("cpu")
|
|
|
|
| 38 |
pipe.enable_attention_slicing()
|
| 39 |
+
pipe.enable_vae_slicing()
|
| 40 |
+
|
| 41 |
+
logger.info("Modelo cargado exitosamente")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
except Exception as e:
|
| 43 |
+
logger.error(f"Error al cargar modelo: {str(e)}")
|
| 44 |
raise
|
| 45 |
|
| 46 |
|
| 47 |
@app.post("/generate")
|
| 48 |
async def generate_image(
|
| 49 |
+
prompt: str = Form(...),
|
| 50 |
+
image1: UploadFile = File(..., description="Habitación con cama"),
|
| 51 |
+
image2: UploadFile = File(..., description="Patrón para las sábanas")
|
| 52 |
):
|
| 53 |
+
logger.info(f"Generando con prompt: '{prompt}'")
|
| 54 |
|
| 55 |
try:
|
| 56 |
+
# Leer imágenes
|
| 57 |
+
img1_bytes = await image1.read()
|
| 58 |
+
img2_bytes = await image2.read()
|
| 59 |
|
| 60 |
+
img1 = Image.open(io.BytesIO(img1_bytes)).convert("RGB")
|
| 61 |
+
img2 = Image.open(io.BytesIO(img2_bytes)).convert("RGB")
|
| 62 |
|
| 63 |
+
# Redimensionar para optimización
|
| 64 |
+
size = (512, 512)
|
| 65 |
+
img1 = img1.resize(size, Image.Resampling.LANCZOS)
|
| 66 |
+
img2 = img2.resize(size, Image.Resampling.LANCZOS)
|
| 67 |
|
| 68 |
+
# COMBINAMOS AMBAS IMÁGENES lado a lado
|
| 69 |
+
combined = Image.new('RGB', (1024, 512))
|
| 70 |
+
combined.paste(img1, (0, 0))
|
| 71 |
+
combined.paste(img2, (512, 0))
|
| 72 |
+
|
| 73 |
+
logger.info("Imágenes combinadas, generando...")
|
| 74 |
+
|
| 75 |
+
# Generar con img2img usando la imagen combinada
|
| 76 |
+
# El modelo tomará la imagen combinada como referencia
|
| 77 |
result = pipe(
|
| 78 |
prompt=prompt,
|
| 79 |
+
image=combined,
|
| 80 |
+
strength=0.75, # Cuánto modifica la imagen base
|
| 81 |
+
num_inference_steps=30,
|
| 82 |
+
guidance_scale=7.5
|
|
|
|
| 83 |
)
|
| 84 |
|
|
|
|
|
|
|
|
|
|
| 85 |
output_image = result.images[0]
|
| 86 |
|
| 87 |
+
# Convertir a bytes
|
| 88 |
img_byte_arr = io.BytesIO()
|
| 89 |
output_image.save(img_byte_arr, format='PNG')
|
| 90 |
img_byte_arr.seek(0)
|
| 91 |
|
|
|
|
| 92 |
return StreamingResponse(
|
| 93 |
+
img_byte_arr,
|
| 94 |
media_type="image/png",
|
| 95 |
headers={"Content-Disposition": "attachment; filename=generated_image.png"}
|
| 96 |
)
|
| 97 |
|
| 98 |
except Exception as e:
|
| 99 |
+
logger.error(f"Error: {str(e)}", exc_info=True)
|
| 100 |
return JSONResponse(
|
| 101 |
status_code=500,
|
| 102 |
+
content={"error": str(e), "type": type(e).__name__}
|
| 103 |
)
|
| 104 |
|
| 105 |
+
|
| 106 |
@app.get("/health")
|
| 107 |
async def health_check():
|
|
|
|
| 108 |
return {"status": "ok", "model_loaded": pipe is not None}
|
| 109 |
|
| 110 |
+
|
| 111 |
@app.get("/")
|
| 112 |
async def root():
|
| 113 |
+
return {
|
| 114 |
+
"message": "SDXL Image Generator API",
|
| 115 |
+
"docs": "/docs",
|
| 116 |
+
"usage": {
|
| 117 |
+
"image1": "Room with bed (habitación)",
|
| 118 |
+
"image2": "Pattern for sheets (patrón)",
|
| 119 |
+
"prompt": "Describe the desired result"
|
| 120 |
+
}
|
| 121 |
+
}
|
app.py.backpPreClaude
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import os
|
| 3 |
+
import torch
|
| 4 |
+
from fastapi import FastAPI, UploadFile, File, Form
|
| 5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
from diffusers import StableDiffusionXLPipeline
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import logging
|
| 9 |
+
from fastapi.responses import JSONResponse
|
| 10 |
+
# from diffusers.models.ip_adapter import IPAdapter
|
| 11 |
+
|
| 12 |
+
# Configurar logging
|
| 13 |
+
logging.basicConfig(level=logging.INFO)
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
# Crear la aplicación FastAPI
|
| 17 |
+
app = FastAPI()
|
| 18 |
+
|
| 19 |
+
# Configurar CORS para permitir solicitudes desde cualquier origen
|
| 20 |
+
app.add_middleware(
|
| 21 |
+
CORSMiddleware,
|
| 22 |
+
allow_origins=["*"],
|
| 23 |
+
allow_credentials=True,
|
| 24 |
+
allow_methods=["*"],
|
| 25 |
+
allow_headers=["*"],
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Variable global para el pipeline (se cargará una vez al iniciar)
|
| 29 |
+
pipe = None
|
| 30 |
+
|
| 31 |
+
@app.on_event("startup")
|
| 32 |
+
async def load_model():
|
| 33 |
+
global pipe
|
| 34 |
+
logger.info("Cargando el modelo IP-Adapter...")
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
|
| 38 |
+
pipe = StableDiffusionXLPipeline.from_pretrained(
|
| 39 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 40 |
+
torch_dtype=torch.float32,
|
| 41 |
+
use_safetensors=True,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
pipe.load_ip_adapter(
|
| 45 |
+
"h94/IP-Adapter",
|
| 46 |
+
subfolder="sdxl_models",
|
| 47 |
+
weight_name="ip-adapter_sdxl.bin"
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# Usar CPU (no hay GPU en el plan gratuito)
|
| 51 |
+
pipe.to("cpu")
|
| 52 |
+
# Reducir el uso de memoria
|
| 53 |
+
pipe.enable_attention_slicing()
|
| 54 |
+
|
| 55 |
+
# forzar float32
|
| 56 |
+
# pipe.unet.to(torch.float32)
|
| 57 |
+
# pipe.vae.to(torch.float32)
|
| 58 |
+
# pipe.text_encoder.to(torch.float32)
|
| 59 |
+
# pipe.text_encoder_2.to(torch.float32)
|
| 60 |
+
|
| 61 |
+
logger.info("Modelo cargado exitosamente en CPU")
|
| 62 |
+
except Exception as e:
|
| 63 |
+
logger.error(f"Error al cargar el modelo: {str(e)}")
|
| 64 |
+
raise
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@app.post("/generate")
|
| 68 |
+
async def generate_image(
|
| 69 |
+
prompt: str = Form(..., description="Texto descriptivo para generar la imagen"),
|
| 70 |
+
image1: UploadFile = File(..., description="Primera imagen de referencia"),
|
| 71 |
+
image2: UploadFile = File(..., description="Segunda imagen de referencia")
|
| 72 |
+
):
|
| 73 |
+
logger.info(f"Recibiendo solicitud de generación con prompt: '{prompt}'")
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
# Leer y procesar las imágenes subidas
|
| 77 |
+
image1_bytes = await image1.read()
|
| 78 |
+
image2_bytes = await image2.read()
|
| 79 |
+
|
| 80 |
+
img1 = Image.open(io.BytesIO(image1_bytes)).convert("RGB")
|
| 81 |
+
img2 = Image.open(io.BytesIO(image2_bytes)).convert("RGB")
|
| 82 |
+
|
| 83 |
+
logger.info("Imágenes de referencia cargadas correctamente")
|
| 84 |
+
|
| 85 |
+
# Generar la imagen usando IP-Adapter con ambas imágenes de referencia
|
| 86 |
+
result = pipe(
|
| 87 |
+
prompt=prompt,
|
| 88 |
+
ip_adapter_image=[img1, img2], # ¡Ambas imágenes aquí!
|
| 89 |
+
num_inference_steps=25, # Reducido para CPU
|
| 90 |
+
guidance_scale=5.0, # Valor conservador para mejor calidad en CPU
|
| 91 |
+
width=512, # Tamaño reducido para CPU
|
| 92 |
+
height=512
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
logger.info("Imagen generada exitosamente")
|
| 96 |
+
|
| 97 |
+
# Obtener la primera imagen del resultado
|
| 98 |
+
output_image = result.images[0]
|
| 99 |
+
|
| 100 |
+
# Convertir la imagen a bytes para enviarla en la respuesta
|
| 101 |
+
img_byte_arr = io.BytesIO()
|
| 102 |
+
output_image.save(img_byte_arr, format='PNG')
|
| 103 |
+
img_byte_arr.seek(0)
|
| 104 |
+
|
| 105 |
+
# Devolver la imagen generada
|
| 106 |
+
return StreamingResponse(
|
| 107 |
+
img_byte_arr,
|
| 108 |
+
media_type="image/png",
|
| 109 |
+
headers={"Content-Disposition": "attachment; filename=generated_image.png"}
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
except Exception as e:
|
| 113 |
+
logger.error(f"Error durante la generación: {str(e)}")
|
| 114 |
+
return JSONResponse(
|
| 115 |
+
status_code=500,
|
| 116 |
+
content={"error": str(e)}
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
@app.get("/health")
|
| 120 |
+
async def health_check():
|
| 121 |
+
"""Endpoint para verificar que la API está funcionando"""
|
| 122 |
+
return {"status": "ok", "model_loaded": pipe is not None}
|
| 123 |
+
|
| 124 |
+
@app.get("/")
|
| 125 |
+
async def root():
|
| 126 |
+
return {"message": "Image Generator API with IP-Adapter is running!", "docs": "/docs"}
|