Spaces:
Running
on
Zero
Running
on
Zero
Update optimizer.py
Browse files- optimizer.py +35 -22
optimizer.py
CHANGED
|
@@ -30,6 +30,8 @@ class UltraSupremeOptimizer:
|
|
| 30 |
self.usage_count = 0
|
| 31 |
self.device = self._get_device()
|
| 32 |
self.is_initialized = False
|
|
|
|
|
|
|
| 33 |
|
| 34 |
@staticmethod
|
| 35 |
def _get_device() -> str:
|
|
@@ -42,27 +44,25 @@ class UltraSupremeOptimizer:
|
|
| 42 |
return "cpu"
|
| 43 |
|
| 44 |
def initialize_model(self) -> bool:
|
| 45 |
-
"""Initialize the CLIP interrogator model"""
|
| 46 |
if self.is_initialized:
|
| 47 |
return True
|
| 48 |
|
| 49 |
try:
|
|
|
|
| 50 |
config = Config(
|
| 51 |
clip_model_name="ViT-L-14/openai",
|
| 52 |
download_cache=True,
|
| 53 |
chunk_size=2048,
|
| 54 |
quiet=True,
|
| 55 |
-
device=
|
| 56 |
)
|
| 57 |
|
| 58 |
self.interrogator = Interrogator(config)
|
| 59 |
self.is_initialized = True
|
| 60 |
|
| 61 |
# Clean up memory after initialization
|
| 62 |
-
|
| 63 |
-
gc.collect()
|
| 64 |
-
else:
|
| 65 |
-
torch.cuda.empty_cache()
|
| 66 |
|
| 67 |
return True
|
| 68 |
|
|
@@ -149,18 +149,36 @@ class UltraSupremeOptimizer:
|
|
| 149 |
return final_prompt
|
| 150 |
|
| 151 |
@spaces.GPU
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
def generate_ultra_supreme_prompt(self, image: Any) -> Tuple[str, str, int, Dict[str, int]]:
|
| 153 |
"""
|
| 154 |
Generate ultra supreme prompt from image usando el pipeline completo
|
|
|
|
| 155 |
|
| 156 |
Returns:
|
| 157 |
Tuple of (prompt, analysis_info, score, breakdown)
|
| 158 |
"""
|
| 159 |
try:
|
| 160 |
-
#
|
| 161 |
if not self.is_initialized:
|
| 162 |
-
|
| 163 |
-
return "❌ Model initialization failed.", "Please refresh and try again.", 0, {}
|
| 164 |
|
| 165 |
# Validate input
|
| 166 |
if image is None:
|
|
@@ -178,15 +196,10 @@ class UltraSupremeOptimizer:
|
|
| 178 |
# NUEVO PIPELINE: Usar CLIP Interrogator completo
|
| 179 |
logger.info("ULTRA SUPREME ANALYSIS - Usando pipeline completo de CLIP Interrogator")
|
| 180 |
|
| 181 |
-
#
|
| 182 |
-
|
| 183 |
-
full_prompt = self.interrogator.interrogate(image)
|
| 184 |
-
logger.info(f"Prompt completo de CLIP Interrogator: {full_prompt}")
|
| 185 |
-
|
| 186 |
-
# 2. También obtener los análisis individuales para el reporte
|
| 187 |
-
clip_fast = self.interrogator.interrogate_fast(image)
|
| 188 |
-
clip_classic = self.interrogator.interrogate_classic(image)
|
| 189 |
|
|
|
|
| 190 |
logger.info(f"Análisis Fast: {clip_fast}")
|
| 191 |
logger.info(f"Análisis Classic: {clip_classic}")
|
| 192 |
|
|
@@ -217,9 +230,8 @@ class UltraSupremeOptimizer:
|
|
| 217 |
duration = (end_time - start_time).total_seconds()
|
| 218 |
|
| 219 |
# Memory cleanup
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
else:
|
| 223 |
torch.cuda.empty_cache()
|
| 224 |
|
| 225 |
# Generate analysis report
|
|
@@ -298,7 +310,7 @@ class UltraSupremeOptimizer:
|
|
| 298 |
**🧠 INTELLIGENT DETECTION:**
|
| 299 |
- **Detected Style:** {detected_style}
|
| 300 |
- **Main Subject:** {detected_subject}
|
| 301 |
-
- **Pipeline:**
|
| 302 |
|
| 303 |
**📊 CLIP INTERROGATOR ANALYSIS:**
|
| 304 |
- **Base Prompt:** {base_prompt_preview}
|
|
@@ -306,7 +318,8 @@ class UltraSupremeOptimizer:
|
|
| 306 |
- **Classic Analysis:** {analysis.get('clip_classic', '')[:80]}...
|
| 307 |
|
| 308 |
**⚡ OPTIMIZATION APPLIED:**
|
| 309 |
-
- ✅
|
|
|
|
| 310 |
- ✅ Added professional camera specifications
|
| 311 |
- ✅ Enhanced lighting descriptions
|
| 312 |
- ✅ Applied Flux-specific optimizations
|
|
|
|
| 30 |
self.usage_count = 0
|
| 31 |
self.device = self._get_device()
|
| 32 |
self.is_initialized = False
|
| 33 |
+
# Inicializar modelo inmediatamente en CPU
|
| 34 |
+
self.initialize_model()
|
| 35 |
|
| 36 |
@staticmethod
|
| 37 |
def _get_device() -> str:
|
|
|
|
| 44 |
return "cpu"
|
| 45 |
|
| 46 |
def initialize_model(self) -> bool:
|
| 47 |
+
"""Initialize the CLIP interrogator model - SIN decorador GPU"""
|
| 48 |
if self.is_initialized:
|
| 49 |
return True
|
| 50 |
|
| 51 |
try:
|
| 52 |
+
# Inicializar en CPU para evitar timeout de GPU
|
| 53 |
config = Config(
|
| 54 |
clip_model_name="ViT-L-14/openai",
|
| 55 |
download_cache=True,
|
| 56 |
chunk_size=2048,
|
| 57 |
quiet=True,
|
| 58 |
+
device="cpu" # Inicializar en CPU primero
|
| 59 |
)
|
| 60 |
|
| 61 |
self.interrogator = Interrogator(config)
|
| 62 |
self.is_initialized = True
|
| 63 |
|
| 64 |
# Clean up memory after initialization
|
| 65 |
+
gc.collect()
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
return True
|
| 68 |
|
|
|
|
| 149 |
return final_prompt
|
| 150 |
|
| 151 |
@spaces.GPU
|
| 152 |
+
def run_clip_inference(self, image: Image.Image) -> Tuple[str, str, str]:
|
| 153 |
+
"""Solo la inferencia CLIP usa GPU - modelo ya inicializado"""
|
| 154 |
+
try:
|
| 155 |
+
# Mover modelo a GPU solo para inferencia
|
| 156 |
+
if hasattr(self.interrogator, 'clip_model') and self.device == "cuda":
|
| 157 |
+
self.interrogator.clip_model = self.interrogator.clip_model.to("cuda")
|
| 158 |
+
|
| 159 |
+
# Ejecutar inferencias CLIP
|
| 160 |
+
full_prompt = self.interrogator.interrogate(image)
|
| 161 |
+
clip_fast = self.interrogator.interrogate_fast(image)
|
| 162 |
+
clip_classic = self.interrogator.interrogate_classic(image)
|
| 163 |
+
|
| 164 |
+
return full_prompt, clip_fast, clip_classic
|
| 165 |
+
|
| 166 |
+
except Exception as e:
|
| 167 |
+
logger.error(f"CLIP inference error: {e}")
|
| 168 |
+
raise e
|
| 169 |
+
|
| 170 |
def generate_ultra_supreme_prompt(self, image: Any) -> Tuple[str, str, int, Dict[str, int]]:
|
| 171 |
"""
|
| 172 |
Generate ultra supreme prompt from image usando el pipeline completo
|
| 173 |
+
INICIALIZACIÓN EN CPU, SOLO INFERENCIA EN GPU
|
| 174 |
|
| 175 |
Returns:
|
| 176 |
Tuple of (prompt, analysis_info, score, breakdown)
|
| 177 |
"""
|
| 178 |
try:
|
| 179 |
+
# Verificar que el modelo esté inicializado
|
| 180 |
if not self.is_initialized:
|
| 181 |
+
return "❌ Model initialization failed.", "Please refresh and try again.", 0, {}
|
|
|
|
| 182 |
|
| 183 |
# Validate input
|
| 184 |
if image is None:
|
|
|
|
| 196 |
# NUEVO PIPELINE: Usar CLIP Interrogator completo
|
| 197 |
logger.info("ULTRA SUPREME ANALYSIS - Usando pipeline completo de CLIP Interrogator")
|
| 198 |
|
| 199 |
+
# Ejecutar inferencia CLIP en GPU (modelo ya inicializado en CPU)
|
| 200 |
+
full_prompt, clip_fast, clip_classic = self.run_clip_inference(image)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
+
logger.info(f"Prompt completo de CLIP Interrogator: {full_prompt}")
|
| 203 |
logger.info(f"Análisis Fast: {clip_fast}")
|
| 204 |
logger.info(f"Análisis Classic: {clip_classic}")
|
| 205 |
|
|
|
|
| 230 |
duration = (end_time - start_time).total_seconds()
|
| 231 |
|
| 232 |
# Memory cleanup
|
| 233 |
+
gc.collect()
|
| 234 |
+
if torch.cuda.is_available():
|
|
|
|
| 235 |
torch.cuda.empty_cache()
|
| 236 |
|
| 237 |
# Generate analysis report
|
|
|
|
| 310 |
**🧠 INTELLIGENT DETECTION:**
|
| 311 |
- **Detected Style:** {detected_style}
|
| 312 |
- **Main Subject:** {detected_subject}
|
| 313 |
+
- **Pipeline:** CPU Init → GPU Inference → Flux Optimization
|
| 314 |
|
| 315 |
**📊 CLIP INTERROGATOR ANALYSIS:**
|
| 316 |
- **Base Prompt:** {base_prompt_preview}
|
|
|
|
| 318 |
- **Classic Analysis:** {analysis.get('clip_classic', '')[:80]}...
|
| 319 |
|
| 320 |
**⚡ OPTIMIZATION APPLIED:**
|
| 321 |
+
- ✅ Model initialized in CPU (no timeout)
|
| 322 |
+
- ✅ GPU used only for inference
|
| 323 |
- ✅ Added professional camera specifications
|
| 324 |
- ✅ Enhanced lighting descriptions
|
| 325 |
- ✅ Applied Flux-specific optimizations
|