Spaces:
Runtime error
Runtime error
File size: 3,512 Bytes
3a6d7bf bd3b7dc 3a6d7bf b9a3a77 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 3a6d7bf 0db592e bd3b7dc 68cec17 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 3a6d7bf 84e19b6 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 3a6d7bf bd3b7dc 84e19b6 bd3b7dc | 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 | import io
import torch
from fastapi import FastAPI, UploadFile, File, Form
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, StreamingResponse
from diffusers import AutoPipelineForImage2Image
from PIL import Image
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
pipe = None
@app.on_event("startup")
async def load_model():
global pipe
logger.info("Cargando modelo SDXL img2img...")
try:
pipe = AutoPipelineForImage2Image.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
torch_dtype=torch.float32,
use_safetensors=True
)
pipe.to("cpu")
pipe.enable_attention_slicing()
pipe.enable_vae_slicing()
logger.info("Modelo cargado exitosamente")
except Exception as e:
logger.error(f"Error al cargar modelo: {str(e)}")
raise
@app.post("/generate")
async def generate_image(
prompt: str = Form(...),
image1: UploadFile = File(..., description="Habitación con cama"),
image2: UploadFile = File(..., description="Patrón para las sábanas")
):
logger.info(f"Generando con prompt: '{prompt}'")
try:
# Leer imágenes
img1_bytes = await image1.read()
img2_bytes = await image2.read()
img1 = Image.open(io.BytesIO(img1_bytes)).convert("RGB")
img2 = Image.open(io.BytesIO(img2_bytes)).convert("RGB")
# Redimensionar para optimización
size = (512, 512)
img1 = img1.resize(size, Image.Resampling.LANCZOS)
img2 = img2.resize(size, Image.Resampling.LANCZOS)
# COMBINAMOS AMBAS IMÁGENES lado a lado
combined = Image.new('RGB', (1024, 512))
combined.paste(img1, (0, 0))
combined.paste(img2, (512, 0))
logger.info("Imágenes combinadas, generando...")
# Generar con img2img usando la imagen combinada
# El modelo tomará la imagen combinada como referencia
result = pipe(
prompt=prompt,
image=combined,
strength=0.75, # Cuánto modifica la imagen base
num_inference_steps=30,
guidance_scale=7.5
)
output_image = result.images[0]
# Convertir a bytes
img_byte_arr = io.BytesIO()
output_image.save(img_byte_arr, format='PNG')
img_byte_arr.seek(0)
return StreamingResponse(
img_byte_arr,
media_type="image/png",
headers={"Content-Disposition": "attachment; filename=generated_image.png"}
)
except Exception as e:
logger.error(f"Error: {str(e)}", exc_info=True)
return JSONResponse(
status_code=500,
content={"error": str(e), "type": type(e).__name__}
)
@app.get("/health")
async def health_check():
return {"status": "ok", "model_loaded": pipe is not None}
@app.get("/")
async def root():
return {
"message": "SDXL Image Generator API",
"docs": "/docs",
"usage": {
"image1": "Room with bed (habitación)",
"image2": "Pattern for sheets (patrón)",
"prompt": "Describe the desired result"
}
} |