rastof9 commited on
Commit
6cd47db
·
verified ·
1 Parent(s): ad5728b

Update generate.py

Browse files
Files changed (1) hide show
  1. generate.py +12 -15
generate.py CHANGED
@@ -1,13 +1,14 @@
1
  # generate.py
2
- # --- VERSION 6 ---
3
 
4
- print("--- RUNNING GENERATE.PY VERSION 6 ---")
5
 
6
  import torch
7
  import cv2
8
  import os
9
  import logging
10
  import uuid
 
11
  from diffusers import StableDiffusionPipeline, DDIMScheduler, AutoencoderKL
12
  from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
13
  from transformers import CLIPVisionModelWithProjection
@@ -16,7 +17,7 @@ from insightface.utils import face_align
16
  from huggingface_hub import hf_hub_download
17
  from storage3.utils import StorageException
18
  import config
19
- from database import supabase # Import the initialized supabase client
20
 
21
  # --- Setup Logging ---
22
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
@@ -60,9 +61,6 @@ class GenerationService:
60
  raise RuntimeError(f"Could not initialize GenerationService: {e}") from e
61
 
62
  def generate_magic_image(self, face_images: list, gender: str, prompt: str, plan: str = 'free') -> str | None:
63
- """
64
- Generates an image, uploads it to cloud storage, and returns the public URL.
65
- """
66
  logger.info("Starting image generation process...")
67
 
68
  full_prompt = f"{prompt}, 4k, high-resolution, photorealistic, masterpiece, single person, solo portrait, centered composition"
@@ -92,8 +90,6 @@ class GenerationService:
92
  try:
93
  final_embedding = average_embedding.unsqueeze(0)
94
 
95
- # --- ROBUST FIX for diffusers version mismatch ---
96
- # This handles both old and new output formats from the pipeline.
97
  output = self.pipe(
98
  prompt=full_prompt,
99
  negative_prompt=negative_prompt,
@@ -104,20 +100,16 @@ class GenerationService:
104
  height=768,
105
  )
106
 
107
- # Check if the output is the modern object or an old tuple
108
  if isinstance(output, StableDiffusionPipelineOutput):
109
  image = output.images[0]
110
  else:
111
- # Handle older tuple-based output
112
  image = output[0][0]
113
 
114
- # --- Save image locally first ---
115
  temp_dir = "temp_images"
116
  os.makedirs(temp_dir, exist_ok=True)
117
  local_path = os.path.join(temp_dir, f"{uuid.uuid4()}.png")
118
  image.save(local_path)
119
 
120
- # --- Upload to Supabase Storage ---
121
  storage_path = f"public/{os.path.basename(local_path)}"
122
  logger.info(f"Uploading {local_path} to Supabase bucket '{config.SUPABASE_BUCKET_NAME}' at path '{storage_path}'")
123
 
@@ -131,7 +123,6 @@ class GenerationService:
131
  public_url = supabase.storage.from_(config.SUPABASE_BUCKET_NAME).get_public_url(storage_path)
132
  logger.info(f"Upload successful. Public URL: {public_url}")
133
 
134
- # --- Clean up local file ---
135
  os.remove(local_path)
136
 
137
  return public_url
@@ -140,7 +131,13 @@ class GenerationService:
140
  logger.error(f"Supabase Storage Error: {e}")
141
  return None
142
  except Exception as e:
143
- logger.error(f"An error occurred during image generation or upload: {e}")
 
 
 
 
 
 
144
  if 'local_path' in locals() and os.path.exists(local_path):
145
  os.remove(local_path)
146
  return None
@@ -158,6 +155,6 @@ if __name__ == '__main__':
158
  if result_url:
159
  print(f"\n✅ Test successful! Image URL: {result_url}")
160
  else:
161
- print("\n❌ Test failed. Check logs for details.")
162
  else:
163
  print("To run a test, place an image named 'test_face.jpg' in the root directory.")
 
1
  # generate.py
2
+ # --- VERSION 7 ---
3
 
4
+ print("--- RUNNING GENERATE.PY VERSION 7 (WITH TRACEBACK) ---")
5
 
6
  import torch
7
  import cv2
8
  import os
9
  import logging
10
  import uuid
11
+ import traceback # <-- ADDED FOR DETAILED ERROR LOGGING
12
  from diffusers import StableDiffusionPipeline, DDIMScheduler, AutoencoderKL
13
  from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
14
  from transformers import CLIPVisionModelWithProjection
 
17
  from huggingface_hub import hf_hub_download
18
  from storage3.utils import StorageException
19
  import config
20
+ from database import supabase
21
 
22
  # --- Setup Logging ---
23
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
 
61
  raise RuntimeError(f"Could not initialize GenerationService: {e}") from e
62
 
63
  def generate_magic_image(self, face_images: list, gender: str, prompt: str, plan: str = 'free') -> str | None:
 
 
 
64
  logger.info("Starting image generation process...")
65
 
66
  full_prompt = f"{prompt}, 4k, high-resolution, photorealistic, masterpiece, single person, solo portrait, centered composition"
 
90
  try:
91
  final_embedding = average_embedding.unsqueeze(0)
92
 
 
 
93
  output = self.pipe(
94
  prompt=full_prompt,
95
  negative_prompt=negative_prompt,
 
100
  height=768,
101
  )
102
 
 
103
  if isinstance(output, StableDiffusionPipelineOutput):
104
  image = output.images[0]
105
  else:
 
106
  image = output[0][0]
107
 
 
108
  temp_dir = "temp_images"
109
  os.makedirs(temp_dir, exist_ok=True)
110
  local_path = os.path.join(temp_dir, f"{uuid.uuid4()}.png")
111
  image.save(local_path)
112
 
 
113
  storage_path = f"public/{os.path.basename(local_path)}"
114
  logger.info(f"Uploading {local_path} to Supabase bucket '{config.SUPABASE_BUCKET_NAME}' at path '{storage_path}'")
115
 
 
123
  public_url = supabase.storage.from_(config.SUPABASE_BUCKET_NAME).get_public_url(storage_path)
124
  logger.info(f"Upload successful. Public URL: {public_url}")
125
 
 
126
  os.remove(local_path)
127
 
128
  return public_url
 
131
  logger.error(f"Supabase Storage Error: {e}")
132
  return None
133
  except Exception as e:
134
+ # --- THIS IS THE IMPORTANT PART ---
135
+ # It will print the full error details to the log.
136
+ logger.error("An unexpected error occurred. Full traceback below:")
137
+ traceback.print_exc()
138
+ # ---
139
+
140
+ logger.error(f"Error summary: {e}")
141
  if 'local_path' in locals() and os.path.exists(local_path):
142
  os.remove(local_path)
143
  return None
 
155
  if result_url:
156
  print(f"\n✅ Test successful! Image URL: {result_url}")
157
  else:
158
+ print(f"\n❌ Test failed. Please check the new traceback logs for details.")
159
  else:
160
  print("To run a test, place an image named 'test_face.jpg' in the root directory.")