Spaces:
Runtime error
Runtime error
Download app.py from malbornoz/image-generator-api: direct link, hf CLI and curl.
- Browser
- Download file 3.51 kB
-
https://huggingface.co/spaces/malbornoz/image-generator-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/malbornoz/image-generator-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/malbornoz/image-generator-api/resolve/main/app.py
3.51 kB
| 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 | |
| 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 | |
| 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__} | |
| ) | |
| async def health_check(): | |
| return {"status": "ok", "model_loaded": pipe is not None} | |
| 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" | |
| } | |
| } |