Spaces:
Build error
Build error
Update generate.py
Browse files123456789101112132 unmodified lines1617181920212237 unmodified lines60616263646566676823 unmodified lines92939495969798994 unmodified lines1041051061071081091101111121131141151161171181191201211221237 unmodified lines1311321331341351361372 unmodified lines14014114214314414514611 unmodified lines158159160161162163# generate.py# --- VERSION 6 ---print("--- RUNNING GENERATE.PY VERSION 6 ---")import torchimport cv2import osimport loggingimport uuidfrom diffusers import StableDiffusionPipeline, DDIMScheduler, AutoencoderKLfrom diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutputfrom transformers import CLIPVisionModelWithProjection2 unmodified linesfrom huggingface_hub import hf_hub_downloadfrom storage3.utils import StorageExceptionimport configfrom database import supabase # Import the initialized supabase client# --- Setup Logging ---logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')37 unmodified linesraise RuntimeError(f"Could not initialize GenerationService: {e}") from edef generate_magic_image(self, face_images: list, gender: str, prompt: str, plan: str = 'free') -> str | None:"""Generates an image, uploads it to cloud storage, and returns the public URL."""logger.info("Starting image generation process...")full_prompt = f"{prompt}, 4k, high-resolution, photorealistic, masterpiece, single person, solo portrait, centered composition"23 unmodified linestry:final_embedding = average_embedding.unsqueeze(0)# --- ROBUST FIX for diffusers version mismatch ---# This handles both old and new output formats from the pipeline.output = self.pipe(prompt=full_prompt,negative_prompt=negative_prompt,4 unmodified linesheight=768,)# Check if the output is the modern object or an old tupleif isinstance(output, StableDiffusionPipelineOutput):image = output.images[0]else:# Handle older tuple-based outputimage = output[0][0]# --- Save image locally first ---temp_dir = "temp_images"os.makedirs(temp_dir, exist_ok=True)local_path = os.path.join(temp_dir, f"{uuid.uuid4()}.png")image.save(local_path)# --- Upload to Supabase Storage ---storage_path = f"public/{os.path.basename(local_path)}"logger.info(f"Uploading {local_path} to Supabase bucket '{config.SUPABASE_BUCKET_NAME}' at path '{storage_path}'")7 unmodified linespublic_url = supabase.storage.from_(config.SUPABASE_BUCKET_NAME).get_public_url(storage_path)logger.info(f"Upload successful. Public URL: {public_url}")# --- Clean up local file ---os.remove(local_path)return public_url2 unmodified lineslogger.error(f"Supabase Storage Error: {e}")return Noneexcept Exception as e:logger.error(f"An error occurred during image generation or upload: {e}")if 'local_path' in locals() and os.path.exists(local_path):os.remove(local_path)return None11 unmodified linesif result_url:print(f"\n✅ Test successful! Image URL: {result_url}")else:print("\n❌ Test failed. Check logs for details.")else:print("To run a test, place an image named 'test_face.jpg' in the root directory.")12345678910111213142 unmodified lines1718192021222337 unmodified lines61626364656623 unmodified lines9091929394954 unmodified lines1001011021031041051061071081091101111121131141157 unmodified lines1231241251261271282 unmodified lines13113213313413513613713813914014114214311 unmodified lines155156157158159160# generate.py# --- VERSION 7 ---print("--- RUNNING GENERATE.PY VERSION 7 (WITH TRACEBACK) ---")import torchimport cv2import osimport loggingimport uuidimport traceback # <-- ADDED FOR DETAILED ERROR LOGGINGfrom diffusers import StableDiffusionPipeline, DDIMScheduler, AutoencoderKLfrom diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutputfrom transformers import CLIPVisionModelWithProjection2 unmodified linesfrom huggingface_hub import hf_hub_downloadfrom storage3.utils import StorageExceptionimport configfrom database import supabase# --- Setup Logging ---logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')37 unmodified linesraise RuntimeError(f"Could not initialize GenerationService: {e}") from edef generate_magic_image(self, face_images: list, gender: str, prompt: str, plan: str = 'free') -> str | None:logger.info("Starting image generation process...")full_prompt = f"{prompt}, 4k, high-resolution, photorealistic, masterpiece, single person, solo portrait, centered composition"23 unmodified linestry:final_embedding = average_embedding.unsqueeze(0)output = self.pipe(prompt=full_prompt,negative_prompt=negative_prompt,4 unmodified linesheight=768,)if isinstance(output, StableDiffusionPipelineOutput):image = output.images[0]else:image = output[0][0]temp_dir = "temp_images"os.makedirs(temp_dir, exist_ok=True)local_path = os.path.join(temp_dir, f"{uuid.uuid4()}.png")image.save(local_path)storage_path = f"public/{os.path.basename(local_path)}"logger.info(f"Uploading {local_path} to Supabase bucket '{config.SUPABASE_BUCKET_NAME}' at path '{storage_path}'")7 unmodified linespublic_url = supabase.storage.from_(config.SUPABASE_BUCKET_NAME).get_public_url(storage_path)logger.info(f"Upload successful. Public URL: {public_url}")os.remove(local_path)return public_url2 unmodified lineslogger.error(f"Supabase Storage Error: {e}")return Noneexcept Exception as e:# --- THIS IS THE IMPORTANT PART ---# It will print the full error details to the log.logger.error("An unexpected error occurred. Full traceback below:")traceback.print_exc()# ---logger.error(f"Error summary: {e}")if 'local_path' in locals() and os.path.exists(local_path):os.remove(local_path)return None11 unmodified linesif result_url:print(f"\n✅ Test successful! Image URL: {result_url}")else:print(f"\n❌ Test failed. Please check the new traceback logs for details.")else:print("To run a test, place an image named 'test_face.jpg' in the root directory.")
generate.py+12-15