Spaces:
Running
on
Zero
Running
on
Zero
File size: 17,825 Bytes
be92860 7ab7e54 be92860 7ab7e54 be92860 139d89b 7ab7e54 be92860 7ab7e54 be92860 7ab7e54 be92860 7ab7e54 3d9a188 7ab7e54 be92860 7ab7e54 3e277be 7ab7e54 3f01bc9 7ab7e54 3d9a188 7ab7e54 3d9a188 7ab7e54 b9c8ca4 3d9a188 7ab7e54 be92860 7ab7e54 3d9a188 7ab7e54 3d9a188 7ab7e54 3f01bc9 7ab7e54 3f01bc9 7ab7e54 be92860 3d9a188 b9c8ca4 3e277be b9c8ca4 3d9a188 3e277be 3d9a188 3e277be 3d9a188 b9c8ca4 3d9a188 3e277be b9c8ca4 3d9a188 b9c8ca4 7ab7e54 3d9a188 7ab7e54 3d9a188 7ab7e54 3e277be 7ab7e54 3d9a188 b9c8ca4 7ab7e54 3d9a188 7ab7e54 3d9a188 7ab7e54 3d9a188 7ab7e54 3d9a188 7ab7e54 b9c8ca4 7ab7e54 3d9a188 7ab7e54 be92860 7ab7e54 3d9a188 7ab7e54 3d9a188 7ab7e54 3f01bc9 7ab7e54 3d9a188 7ab7e54 3d9a188 be92860 7ab7e54 be92860 7ab7e54 be92860 7ab7e54 be92860 7ab7e54 be92860 7ab7e54 be92860 3d9a188 be92860 7ab7e54 be92860 7ab7e54 3e277be 7ab7e54 3d9a188 3f01bc9 7ab7e54 3f01bc9 7ab7e54 3d9a188 7ab7e54 3e277be 7ab7e54 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
"""
Ultra Supreme Optimizer - Main optimization engine for image analysis
VERSIÓN MEJORADA - Usa el prompt completo de CLIP Interrogator
"""
# IMPORTANT: spaces must be imported BEFORE torch or any CUDA-using library
import spaces
import gc
import logging
import re
from datetime import datetime
from typing import Tuple, Dict, Any, Optional
import torch
import numpy as np
from PIL import Image
from clip_interrogator import Config, Interrogator
from analyzer import UltraSupremeAnalyzer
logger = logging.getLogger(__name__)
class UltraSupremeOptimizer:
"""Main optimizer class for ultra supreme image analysis"""
def __init__(self):
self.interrogator: Optional[Interrogator] = None
self.analyzer = UltraSupremeAnalyzer()
self.usage_count = 0
self.device = self._get_device()
self.is_initialized = False
# NO inicializar modelo aquí - hacerlo lazy
@staticmethod
def _get_device() -> str:
"""Determine the best available device for computation"""
if torch.cuda.is_available():
return "cuda"
elif torch.backends.mps.is_available():
return "mps"
else:
return "cpu"
def initialize_model(self) -> bool:
"""Initialize the CLIP interrogator model"""
if self.is_initialized:
return True
try:
# Configuración para CPU inicialmente
config = Config(
clip_model_name="ViT-L-14/openai",
download_cache=True,
chunk_size=2048,
quiet=True,
device="cpu" # Siempre inicializar en CPU
)
self.interrogator = Interrogator(config)
self.is_initialized = True
# Clean up memory after initialization
gc.collect()
logger.info("Model initialized successfully on CPU")
return True
except Exception as e:
logger.error(f"Initialization error: {e}")
return False
def optimize_image(self, image: Any) -> Optional[Image.Image]:
"""Optimize image for processing"""
if image is None:
return None
try:
# Convert to PIL Image if necessary
if isinstance(image, np.ndarray):
image = Image.fromarray(image)
elif not isinstance(image, Image.Image):
image = Image.open(image)
# Convert to RGB if necessary
if image.mode != 'RGB':
image = image.convert('RGB')
# Resize if too large
max_size = 768 # Reducir tamaño para evitar problemas de memoria
if image.size[0] > max_size or image.size[1] > max_size:
image.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
return image
except Exception as e:
logger.error(f"Image optimization error: {e}")
return None
def apply_flux_rules(self, base_prompt: str) -> str:
"""Aplica las reglas de Flux a un prompt base de CLIP Interrogator"""
# Limpiar el prompt de elementos no deseados
cleanup_patterns = [
r',\s*trending on artstation',
r',\s*trending on [^,]+',
r',\s*\d+k\s*',
r',\s*\d+k resolution',
r',\s*artstation',
r',\s*concept art',
r',\s*digital art',
r',\s*by greg rutkowski',
]
cleaned_prompt = base_prompt
for pattern in cleanup_patterns:
cleaned_prompt = re.sub(pattern, '', cleaned_prompt, flags=re.IGNORECASE)
# Detectar el tipo de imagen para añadir configuración de cámara apropiada
camera_config = ""
if any(word in base_prompt.lower() for word in ['portrait', 'person', 'man', 'woman', 'face']):
camera_config = ", Shot on Hasselblad X2D 100C, 90mm f/2.5 lens at f/2.8, professional portrait photography"
elif any(word in base_prompt.lower() for word in ['landscape', 'mountain', 'nature', 'outdoor']):
camera_config = ", Shot on Phase One XT, 40mm f/4 lens at f/8, epic landscape photography"
elif any(word in base_prompt.lower() for word in ['street', 'urban', 'city']):
camera_config = ", Shot on Leica M11, 35mm f/1.4 lens at f/2.8, documentary street photography"
else:
camera_config = ", Shot on Phase One XF IQ4, 80mm f/2.8 lens at f/4, professional photography"
# Añadir mejoras de iluminación si no están presentes
if 'lighting' not in cleaned_prompt.lower():
if 'dramatic' in cleaned_prompt.lower():
cleaned_prompt += ", dramatic cinematic lighting"
elif 'portrait' in cleaned_prompt.lower():
cleaned_prompt += ", professional studio lighting with subtle rim light"
else:
cleaned_prompt += ", masterful natural lighting"
# Construir el prompt final
final_prompt = cleaned_prompt + camera_config
# Asegurar que empiece con mayúscula
final_prompt = final_prompt[0].upper() + final_prompt[1:] if final_prompt else final_prompt
# Limpiar espacios y comas duplicadas
final_prompt = re.sub(r'\s+', ' ', final_prompt)
final_prompt = re.sub(r',\s*,+', ',', final_prompt)
return final_prompt
def _prepare_models_for_gpu(self):
"""Prepara los modelos para GPU con la precisión correcta"""
try:
if hasattr(self.interrogator, 'caption_model'):
self.interrogator.caption_model = self.interrogator.caption_model.half().to("cuda")
if hasattr(self.interrogator, 'clip_model'):
self.interrogator.clip_model = self.interrogator.clip_model.half().to("cuda")
if hasattr(self.interrogator, 'blip_model'):
self.interrogator.blip_model = self.interrogator.blip_model.half().to("cuda")
self.interrogator.config.device = "cuda"
logger.info("Models prepared for GPU with FP16")
except Exception as e:
logger.error(f"Error preparing models for GPU: {e}")
raise
def _prepare_models_for_cpu(self):
"""Prepara los modelos para CPU con float32"""
try:
if hasattr(self.interrogator, 'caption_model'):
self.interrogator.caption_model = self.interrogator.caption_model.float().to("cpu")
if hasattr(self.interrogator, 'clip_model'):
self.interrogator.clip_model = self.interrogator.clip_model.float().to("cpu")
if hasattr(self.interrogator, 'blip_model'):
self.interrogator.blip_model = self.interrogator.blip_model.float().to("cpu")
self.interrogator.config.device = "cpu"
logger.info("Models prepared for CPU with FP32")
except Exception as e:
logger.error(f"Error preparing models for CPU: {e}")
raise
@spaces.GPU(duration=60)
def run_clip_inference(self, image: Image.Image) -> Tuple[str, str, str]:
"""Solo la inferencia CLIP usa GPU"""
try:
# Preparar modelos para GPU
self._prepare_models_for_gpu()
# Usar autocast para manejar precisión mixta
with torch.cuda.amp.autocast(enabled=True, dtype=torch.float16):
# Convertir imagen a tensor y asegurar que esté en half precision
from torchvision import transforms
preprocess = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
std=[0.26862954, 0.26130258, 0.27577711]),
])
# Procesar imagen manualmente para controlar la precisión
image_tensor = preprocess(image).unsqueeze(0).half().to("cuda")
# Ejecutar inferencias con manejo especial
full_prompt = self._safe_interrogate(image, 'interrogate')
clip_fast = self._safe_interrogate(image, 'interrogate_fast')
clip_classic = self._safe_interrogate(image, 'interrogate_classic')
return full_prompt, clip_fast, clip_classic
except Exception as e:
logger.error(f"GPU inference error: {e}")
# Intentar en CPU como fallback
return self._run_cpu_inference(image)
def _safe_interrogate(self, image: Image.Image, method: str) -> str:
"""Ejecuta interrogate de forma segura manejando precisión"""
try:
# Temporalmente parchear el método de procesamiento de imagen
original_method = getattr(self.interrogator, method)
# Ejecutar el método
result = original_method(image)
return result
except Exception as e:
logger.error(f"Error in {method}: {e}")
return f"Error processing with {method}"
def _run_cpu_inference(self, image: Image.Image) -> Tuple[str, str, str]:
"""Ejecuta inferencia en CPU como fallback"""
try:
logger.info("Running CPU inference as fallback")
# Preparar modelos para CPU
self._prepare_models_for_cpu()
# Ejecutar en CPU sin autocast
full_prompt = self.interrogator.interrogate(image)
clip_fast = self.interrogator.interrogate_fast(image)
clip_classic = self.interrogator.interrogate_classic(image)
return full_prompt, clip_fast, clip_classic
except Exception as e:
logger.error(f"CPU inference also failed: {e}")
return "Error: Failed to process image", "Error", "Error"
def generate_ultra_supreme_prompt(self, image: Any) -> Tuple[str, str, int, Dict[str, int]]:
"""
Generate ultra supreme prompt from image usando el pipeline completo
Returns:
Tuple of (prompt, analysis_info, score, breakdown)
"""
try:
# Inicializar modelo si no está inicializado
if not self.is_initialized:
if not self.initialize_model():
return "❌ Model initialization failed.", "Please refresh and try again.", 0, {}
# Validate input
if image is None:
return "❌ Please upload an image.", "No image provided.", 0, {}
self.usage_count += 1
# Optimize image
image = self.optimize_image(image)
if image is None:
return "❌ Image processing failed.", "Invalid image format.", 0, {}
start_time = datetime.now()
logger.info("ULTRA SUPREME ANALYSIS - Starting pipeline")
# Ejecutar inferencia CLIP
full_prompt, clip_fast, clip_classic = self.run_clip_inference(image)
# Verificar si hubo errores
if "Error" in full_prompt:
logger.warning("Using fallback prompt due to inference error")
full_prompt = "A photograph"
clip_fast = "image"
clip_classic = "picture"
logger.info(f"Prompt completo: {full_prompt[:100]}...")
logger.info(f"Fast: {clip_fast[:50]}...")
logger.info(f"Classic: {clip_classic[:50]}...")
# Aplicar reglas de Flux al prompt completo
optimized_prompt = self.apply_flux_rules(full_prompt)
# Crear análisis para el reporte
analysis_summary = {
"base_prompt": full_prompt,
"clip_fast": clip_fast,
"clip_classic": clip_classic,
"optimized": optimized_prompt,
"detected_style": self._detect_style(full_prompt),
"detected_subject": self._detect_subject(full_prompt)
}
# Calcular score
score = self._calculate_score(optimized_prompt, full_prompt)
breakdown = {
"base_quality": min(len(full_prompt) // 10, 25),
"technical_enhancement": 25 if "Shot on" in optimized_prompt else 0,
"lighting_quality": 25 if "lighting" in optimized_prompt.lower() else 0,
"composition": 25 if any(word in optimized_prompt.lower() for word in ["professional", "masterful", "epic"]) else 0
}
score = sum(breakdown.values())
end_time = datetime.now()
duration = (end_time - start_time).total_seconds()
# Memory cleanup
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
# Generate analysis report
analysis_info = self._generate_analysis_report(
analysis_summary, score, breakdown, duration
)
return optimized_prompt, analysis_info, score, breakdown
except Exception as e:
logger.error(f"Ultra supreme generation error: {e}", exc_info=True)
return f"❌ Error: {str(e)}", "Please try with a different image.", 0, {}
def _detect_style(self, prompt: str) -> str:
"""Detecta el estilo principal del prompt"""
styles = {
"portrait": ["portrait", "person", "face", "headshot"],
"landscape": ["landscape", "mountain", "nature", "scenery"],
"street": ["street", "urban", "city"],
"artistic": ["artistic", "abstract", "conceptual"],
"dramatic": ["dramatic", "cinematic", "moody"]
}
prompt_lower = prompt.lower()
for style_name, keywords in styles.items():
if any(keyword in prompt_lower for keyword in keywords):
return style_name
return "general"
def _detect_subject(self, prompt: str) -> str:
"""Detecta el sujeto principal del prompt"""
if not prompt:
return "Unknown"
# Tomar las primeras palabras significativas
words = prompt.split(',')[0].split()
if len(words) > 3:
return ' '.join(words[:4])
return prompt.split(',')[0] if prompt else "Unknown"
def _calculate_score(self, optimized_prompt: str, base_prompt: str) -> int:
"""Calcula el score basado en la calidad del prompt"""
score = 0
# Base score por longitud y riqueza
score += min(len(base_prompt) // 10, 25)
# Technical enhancement
if "Shot on" in optimized_prompt:
score += 25
# Lighting quality
if "lighting" in optimized_prompt.lower():
score += 25
# Professional quality
if any(word in optimized_prompt.lower() for word in ["professional", "masterful", "epic", "cinematic"]):
score += 25
return min(score, 100)
def _generate_analysis_report(self, analysis: Dict[str, Any],
score: int, breakdown: Dict[str, int],
duration: float) -> str:
"""Generate detailed analysis report"""
device_used = "cuda" if torch.cuda.is_available() else "cpu"
gpu_status = "⚡ ZeroGPU" if device_used == "cuda" else "💻 CPU"
precision_info = "Half Precision (FP16)" if device_used == "cuda" else "Full Precision (FP32)"
# Extraer información clave
detected_style = analysis.get("detected_style", "general").title()
detected_subject = analysis.get("detected_subject", "Unknown")
base_prompt_preview = analysis.get("base_prompt", "")[:100] + "..." if len(analysis.get("base_prompt", "")) > 100 else analysis.get("base_prompt", "")
analysis_info = f"""**🚀 ULTRA SUPREME ANALYSIS COMPLETE**
**Processing:** {gpu_status} • {duration:.1f}s • {precision_info}
**Ultra Score:** {score}/100 • Breakdown: Base({breakdown.get('base_quality',0)}) Technical({breakdown.get('technical_enhancement',0)}) Lighting({breakdown.get('lighting_quality',0)}) Composition({breakdown.get('composition',0)})
**Generation:** #{self.usage_count}
**🧠 INTELLIGENT DETECTION:**
- **Detected Style:** {detected_style}
- **Main Subject:** {detected_subject}
- **Precision:** Using {precision_info} for optimal performance
- **Quality:** Maximum resolution processing (768px)
**📊 CLIP INTERROGATOR ANALYSIS:**
- **Base Prompt:** {base_prompt_preview}
- **Fast Analysis:** {analysis.get('clip_fast', '')[:80]}...
- **Classic Analysis:** {analysis.get('clip_classic', '')[:80]}...
**⚡ OPTIMIZATION APPLIED:**
- ✅ Mixed precision handling for stability
- ✅ Automatic GPU/CPU fallback
- ✅ Memory-efficient processing
- ✅ Added professional camera specifications
- ✅ Enhanced lighting descriptions
- ✅ Applied Flux-specific optimizations
- ✅ Removed redundant/generic elements
**🔬 Powered by Pariente AI Research + CLIP Interrogator**"""
return analysis_info |