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
123456789101112131415161718192021222 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import 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=["*"],2 unmodified linesallow_headers=["*"],)# Variable global para el pipeline (se cargará una vez al iniciar)pipe = None@app.on_event("startup")async def load_model():global pipelogger.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 memoriapipe.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 subidasimage1_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 referenciaresult = pipe(prompt=prompt,ip_adapter_image=[img1, img2], # ¡Ambas imágenes aquí!num_inference_steps=25, # Reducido para CPUguidance_scale=5.0, # Valor conservador para mejor calidad en CPUwidth=512, # Tamaño reducido para CPUheight=512)logger.info("Imagen generada exitosamente")# Obtener la primera imagen del resultadooutput_image = result.images[0]# Convertir la imagen a bytes para enviarla en la respuestaimg_byte_arr = io.BytesIO()output_image.save(img_byte_arr, format='PNG')img_byte_arr.seek(0)# Devolver la imagen generadareturn 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"}12345678910111213141516172 unmodified lines2021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import ioimport torchfrom fastapi import FastAPI, UploadFile, File, Formfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse, StreamingResponsefrom diffusers import AutoPipelineForImage2Imagefrom PIL import Imageimport logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)app = FastAPI()app.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)pipe = None@app.on_event("startup")async def load_model():global pipelogger.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ágenesimg1_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ónsize = (512, 512)img1 = img1.resize(size, Image.Resampling.LANCZOS)img2 = img2.resize(size, Image.Resampling.LANCZOS)# COMBINAMOS AMBAS IMÁGENES lado a ladocombined = 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 referenciaresult = pipe(prompt=prompt,image=combined,strength=0.75, # Cuánto modifica la imagen basenum_inference_steps=30,guidance_scale=7.5)output_image = result.images[0]# Convertir a bytesimg_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"}}
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