Spaces:
Runtime error
Runtime error
Emalbornoz commited on
Commit ·
bd3b7dc
1
Parent(s): a24c6af
Fix: mas cambios otro modelo
Browse filesFiles changed (2)
- app.py+50-55
- app.py.backpPreClaudeAdded+126
1223465678910912101112161314191516172 unmodified lines20212228232425262734282930373831323341424344454647343536503752385455565758596061394041426343444546474869707149505152735354557677785657585980816061628363646566678568697071727374757677788889909192798081828384959697858610087888990911059210793949596979811399100101116102103104105106107121108109110111112126113114115116117118119120121import ioimport osimport torchfrom fastapi import FastAPI, UploadFile, File, Formfrom fastapi.middleware.cors import CORSMiddlewarefrom diffusers import StableDiffusionXLPipelinefrom fastapi.responses import JSONResponse, StreamingResponsefrom diffusers import AutoPipelineForImage2Imagefrom PIL import Imageimport loggingfrom fastapi.responses import JSONResponse# from diffusers.models.ip_adapter import IPAdapter
# Configurar logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
# Crear la aplicación FastAPIapp = FastAPI()
# Configurar CORS para permitir solicitudes desde cualquier origenapp.add_middleware( CORSMiddleware, allow_origins=["*"],2 unmodified lines allow_headers=["*"],)
# Variable global para el pipeline (se cargará una vez al iniciar)pipe = None
@app.on_event("startup")async def load_model(): global pipe logger.info("Cargando el modelo IP-Adapter...") logger.info("Cargando modelo SDXL img2img...") try:
pipe = StableDiffusionXLPipeline.from_pretrained( pipe = AutoPipelineForImage2Image.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float32, use_safetensors=True, )
pipe.load_ip_adapter( "h94/IP-Adapter", subfolder="sdxl_models", weight_name="ip-adapter_sdxl.bin" use_safetensors=True ) # Usar CPU (no hay GPU en el plan gratuito) pipe.to("cpu") # Reducir el uso de memoria pipe.enable_attention_slicing()
# forzar float32 # pipe.unet.to(torch.float32) # pipe.vae.to(torch.float32) # pipe.text_encoder.to(torch.float32) # pipe.text_encoder_2.to(torch.float32)
logger.info("Modelo cargado exitosamente en CPU") pipe.enable_vae_slicing() logger.info("Modelo cargado exitosamente") except Exception as e: logger.error(f"Error al cargar el modelo: {str(e)}") logger.error(f"Error al cargar modelo: {str(e)}") raise
@app.post("/generate")async def generate_image( prompt: str = Form(..., description="Texto descriptivo para generar la imagen"), image1: UploadFile = File(..., description="Primera imagen de referencia"), image2: UploadFile = File(..., description="Segunda imagen de referencia") prompt: str = Form(...), image1: UploadFile = File(..., description="Habitación con cama"), image2: UploadFile = File(..., description="Patrón para las sábanas")): logger.info(f"Recibiendo solicitud de generación con prompt: '{prompt}'") logger.info(f"Generando con prompt: '{prompt}'") try: # Leer y procesar las imágenes subidas image1_bytes = await image1.read() image2_bytes = await image2.read() # Leer imágenes img1_bytes = await image1.read() img2_bytes = await image2.read() img1 = Image.open(io.BytesIO(image1_bytes)).convert("RGB") img2 = Image.open(io.BytesIO(image2_bytes)).convert("RGB") img1 = Image.open(io.BytesIO(img1_bytes)).convert("RGB") img2 = Image.open(io.BytesIO(img2_bytes)).convert("RGB") logger.info("Imágenes de referencia cargadas correctamente") # Redimensionar para optimización size = (512, 512) img1 = img1.resize(size, Image.Resampling.LANCZOS) img2 = img2.resize(size, Image.Resampling.LANCZOS) # Generar la imagen usando IP-Adapter con ambas imágenes de referencia # 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, ip_adapter_image=[img1, img2], # ¡Ambas imágenes aquí! num_inference_steps=25, # Reducido para CPU guidance_scale=5.0, # Valor conservador para mejor calidad en CPU width=512, # Tamaño reducido para CPU height=512 image=combined, strength=0.75, # Cuánto modifica la imagen base num_inference_steps=30, guidance_scale=7.5 ) logger.info("Imagen generada exitosamente") # Obtener la primera imagen del resultado output_image = result.images[0] # Convertir la imagen a bytes para enviarla en la respuesta # Convertir a bytes img_byte_arr = io.BytesIO() output_image.save(img_byte_arr, format='PNG') img_byte_arr.seek(0) # Devolver la imagen generada return StreamingResponse( img_byte_arr, img_byte_arr, media_type="image/png", headers={"Content-Disposition": "attachment; filename=generated_image.png"} ) except Exception as e: logger.error(f"Error durante la generación: {str(e)}") logger.error(f"Error: {str(e)}", exc_info=True) return JSONResponse( status_code=500, content={"error": str(e)} content={"error": str(e), "type": type(e).__name__} )
@app.get("/health")async def health_check(): """Endpoint para verificar que la API está funcionando""" return {"status": "ok", "model_loaded": pipe is not None}
@app.get("/")async def root(): return {"message": "Image Generator API with IP-Adapter is running!", "docs": "/docs"} 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" } }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import ioimport osimport torchfrom fastapi import FastAPI, UploadFile, File, Formfrom fastapi.middleware.cors import CORSMiddlewarefrom diffusers import StableDiffusionXLPipelinefrom PIL import Imageimport loggingfrom fastapi.responses import JSONResponse# from diffusers.models.ip_adapter import IPAdapter
# Configurar logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
# Crear la aplicación FastAPIapp = FastAPI()
# Configurar CORS para permitir solicitudes desde cualquier origenapp.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# Variable global para el pipeline (se cargará una vez al iniciar)pipe = None
@app.on_event("startup")async def load_model(): global pipe logger.info("Cargando el modelo IP-Adapter...") try:
pipe = StableDiffusionXLPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float32, use_safetensors=True, )
pipe.load_ip_adapter( "h94/IP-Adapter", subfolder="sdxl_models", weight_name="ip-adapter_sdxl.bin" ) # Usar CPU (no hay GPU en el plan gratuito) pipe.to("cpu") # Reducir el uso de memoria pipe.enable_attention_slicing()
# forzar float32 # pipe.unet.to(torch.float32) # pipe.vae.to(torch.float32) # pipe.text_encoder.to(torch.float32) # pipe.text_encoder_2.to(torch.float32)
logger.info("Modelo cargado exitosamente en CPU") except Exception as e: logger.error(f"Error al cargar el modelo: {str(e)}") raise
@app.post("/generate")async def generate_image( prompt: str = Form(..., description="Texto descriptivo para generar la imagen"), image1: UploadFile = File(..., description="Primera imagen de referencia"), image2: UploadFile = File(..., description="Segunda imagen de referencia")): logger.info(f"Recibiendo solicitud de generación con prompt: '{prompt}'") try: # Leer y procesar las imágenes subidas image1_bytes = await image1.read() image2_bytes = await image2.read() img1 = Image.open(io.BytesIO(image1_bytes)).convert("RGB") img2 = Image.open(io.BytesIO(image2_bytes)).convert("RGB") logger.info("Imágenes de referencia cargadas correctamente") # Generar la imagen usando IP-Adapter con ambas imágenes de referencia result = pipe( prompt=prompt, ip_adapter_image=[img1, img2], # ¡Ambas imágenes aquí! num_inference_steps=25, # Reducido para CPU guidance_scale=5.0, # Valor conservador para mejor calidad en CPU width=512, # Tamaño reducido para CPU height=512 ) logger.info("Imagen generada exitosamente") # Obtener la primera imagen del resultado output_image = result.images[0] # Convertir la imagen a bytes para enviarla en la respuesta img_byte_arr = io.BytesIO() output_image.save(img_byte_arr, format='PNG') img_byte_arr.seek(0) # Devolver la imagen generada 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 durante la generación: {str(e)}") return JSONResponse( status_code=500, content={"error": str(e)} )
@app.get("/health")async def health_check(): """Endpoint para verificar que la API está funcionando""" return {"status": "ok", "model_loaded": pipe is not None}
@app.get("/")async def root(): return {"message": "Image Generator API with IP-Adapter is running!", "docs": "/docs"}app.py+50-55
app.py.backpPreClaudeAdded+126