Malaji71 commited on
Commit
5834e7d
·
verified ·
1 Parent(s): 7761235

Update sara_v3_interfaz_optimizada.py

Browse files
Files changed (1) hide show
  1. sara_v3_interfaz_optimizada.py +247 -141
sara_v3_interfaz_optimizada.py CHANGED
@@ -1,6 +1,6 @@
1
  # sara_v3_interfaz_optimizada.py
2
  # SARA v3 - INTERFAZ GRADIO NEGRA PROFESIONAL COMPLETA
3
- # Fondo negro, tipografía profesional, análisis visible
4
 
5
  import gradio as gr
6
  import traceback
@@ -9,7 +9,7 @@ import traceback
9
  from sara_v3_interfaz_core import sara_optimized
10
 
11
  def create_optimized_interface():
12
- """Crear interfaz Gradio NEGRA PROFESIONAL - que MUESTRA el análisis"""
13
 
14
  # CSS NEGRO PROFESIONAL
15
  professional_css = """
@@ -160,6 +160,23 @@ def create_optimized_interface():
160
  box-shadow: 0 6px 20px rgba(59, 130, 246, 0.4) !important;
161
  }
162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  .btn-secondary {
164
  background: var(--bg-tertiary) !important;
165
  color: var(--text-primary) !important;
@@ -324,84 +341,43 @@ def create_optimized_interface():
324
  }
325
  """
326
 
327
- # Función mejorada para mostrar análisis completo
328
- def analyze_with_detailed_display(image, user_idea=""):
329
- """Análisis con display detallado de lo que ve la IA"""
 
 
 
330
 
331
  if image is None:
332
- return "❌ Sube una imagen primero", "", "", "", "", ""
333
 
334
- # Verificar modelos
335
  if not sara_optimized.blip_ready:
336
- return "⚠️ BLIP no está listo. Carga los modelos primero.", "", "", "", "", ""
337
 
338
  try:
339
- # Ejecutar análisis normal
340
- result = sara_optimized.analyze_image_fast(image, user_idea)
341
- status, basic, intermediate, advanced, experimental = result
342
 
343
- # CREAR ANÁLISIS DETALLADO VISIBLE
344
- if sara_optimized.sara_ready:
345
- # Análisis completo con SARA
346
- try:
347
- from sara_v3_parte_13 import analyze_image_sara_v3_complete
348
-
349
- complete_result = analyze_image_sara_v3_complete(image, user_idea)
350
-
351
- if complete_result['success']:
352
- # Extraer datos del análisis
353
- img_analysis = complete_result['image_analysis']
354
- caption = img_analysis['caption']
355
- confidence = img_analysis['confidence']
356
- visual_context = img_analysis['visual_context']
357
- composition = img_analysis['composition']
358
-
359
- # Crear display detallado
360
- detailed_analysis = f"""## 🔍 ANÁLISIS DETALLADO DE LA IMAGEN
361
-
362
- ### 📝 LO QUE LA IA DETECTA:
363
- **Descripción:** {caption}
364
- **Confianza:** {confidence:.1%}
365
- **Composición:** {composition}
366
-
367
- ### 🎨 CARACTERÍSTICAS VISUALES:
368
- **💡 Iluminación:** {visual_context.get('lighting_description', 'Natural')}
369
- **🌈 Colores:** {visual_context.get('color_description', 'Equilibrados')}
370
- **🎭 Atmósfera:** {visual_context.get('mood_suggestion', 'Neutral')}
371
-
372
- ### ⚡ RENDIMIENTO:
373
- **Tiempo total:** {complete_result['performance']['total_time']:.2f}s
374
- **Método:** BLIP + SARA-v2 completo
375
- **Calidad promedio:** {complete_result['quality_summary']['average_score']:.2f}/5.0
376
- **Mejor prompt:** {complete_result['quality_summary']['best_prompt_level'].upper()}
377
-
378
- ### 🎬 ELEMENTOS SARA EXTRAÍDOS:
379
- **Total elementos:** {complete_result['sara_elements_count']}
380
- **Mejoras aplicadas:** {complete_result['optimization_summary']['total_improvements']}"""
381
-
382
- return status, detailed_analysis, basic, intermediate, advanced, experimental
383
-
384
- except ImportError:
385
- pass
386
 
387
- # Análisis básico con BLIP solamente
388
- try:
389
- from sara_v3_parte_6 import analyze_image_with_sara_v3
390
-
391
- analysis = analyze_image_with_sara_v3(image)
392
- caption = analysis['caption_analysis']['enhanced_caption']
393
- confidence = analysis['caption_analysis']['confidence_score']
394
- visual_context = analysis['caption_analysis']['visual_context']
395
- visual_chars = analysis['image_analysis']['visual_characteristics']
396
- composition = analysis['image_analysis']['composition_type']
397
- analysis_time = analysis['total_analysis_time']
398
-
399
- # Extraer características detalladas
400
- color_info = visual_chars.get('color', {})
401
- lighting_info = visual_chars.get('lighting', {})
402
-
403
- # Crear display detallado básico
404
- detailed_analysis = f"""## 🔍 ANÁLISIS BÁSICO DE LA IMAGEN (BLIP)
405
 
406
  ### 📝 LO QUE LA IA DETECTA:
407
  **Descripción:** {caption}
@@ -413,31 +389,121 @@ def create_optimized_interface():
413
  - Descripción: {visual_context.get('lighting_description', 'Natural')}
414
  - Brillo promedio: {lighting_info.get('avg_brightness', 'N/A')}
415
  - Contraste: {lighting_info.get('contrast_level', 'N/A')}
416
- - Dirección: {lighting_info.get('lighting_direction', 'N/A')}
417
 
418
  **🌈 Análisis de color:**
419
  - Descripción: {visual_context.get('color_description', 'Equilibrados')}
420
  - Temperatura: {color_info.get('temperature', 'N/A')}
421
  - Saturación: {color_info.get('saturation_level', 'N/A')}
 
422
 
423
  **🎭 Atmósfera:** {visual_context.get('mood_suggestion', 'Neutral')}
 
424
 
425
  ### ⚡ RENDIMIENTO:
426
  **Tiempo:** {analysis_time:.2f}s
427
  **Modelo:** BLIP (análisis de imágenes)
428
- **Estado SARA:** Usando prompts mejorados basados en análisis
429
 
430
- ### 💡 NOTA:
431
- Los prompts están basados en el análisis REAL de tu imagen."""
432
-
433
- return status, detailed_analysis, basic, intermediate, advanced, experimental
434
-
435
- except ImportError:
436
- return status, "❌ No se puede acceder al análisis detallado", basic, intermediate, advanced, experimental
437
 
438
  except Exception as e:
439
  error_msg = f"❌ Error en análisis: {str(e)}"
440
- return error_msg, "", "", "", "", ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
441
 
442
  # Crear interfaz con tema negro
443
  with gr.Blocks(
@@ -455,21 +521,20 @@ Los prompts están basados en el análisis REAL de tu imagen."""
455
  </div>
456
  """)
457
 
458
- # Instrucciones
459
  with gr.Row():
460
  gr.Markdown("""
461
  <div class="section-container markdown-content">
462
- <div class="section-title">🚀 Inicio Rápido</div>
463
- <p><strong>1. Cargar Modelos IA</strong> - Solo primera vez (3-5 minutos)</p>
464
- <p><strong>2. Subir Imagen</strong> - Cualquier imagen para análisis</p>
465
- <p><strong>3. Dirección Creativa</strong> - Tu visión artística (opcional)</p>
466
- <p><strong>4. Generar Prompts</strong> - Análisis completo + 4 prompts profesionales</p>
467
  </div>
468
  """)
469
 
470
  # Sección principal
471
  with gr.Row():
472
- # Columna izquierda - Input
473
  with gr.Column(scale=1):
474
  gr.HTML('<div class="section-title">📸 Análisis de Imagen</div>')
475
 
@@ -480,6 +545,14 @@ Los prompts están basados en el análisis REAL de tu imagen."""
480
  )
481
  gr.HTML('<div class="description-text">📷 Sube cualquier imagen para análisis completo</div>')
482
 
 
 
 
 
 
 
 
 
483
  user_idea_input = gr.Textbox(
484
  label="💡 Dirección Creativa (Opcional)",
485
  placeholder="ej: 'cámara orbita lentamente', 'iluminación dramática', 'movimiento cinematográfico'",
@@ -487,19 +560,20 @@ Los prompts están basados en el análisis REAL de tu imagen."""
487
  )
488
  gr.HTML('<div class="description-text">🎨 Describe tu visión para el video</div>')
489
 
490
- analyze_btn = gr.Button(
491
- "⚡ Analizar y Generar Prompts",
492
- variant="primary",
 
493
  size="lg",
494
- elem_classes="btn-primary"
495
  )
496
 
497
- # Columna derecha - Estado y Análisis
498
  with gr.Column(scale=1):
499
  gr.HTML('<div class="section-title">📊 Estado del Sistema</div>')
500
 
501
  status_display = gr.Markdown(
502
- "ℹ️ **Listo para analizar** - Sube imagen y genera prompts",
503
  elem_classes="status-info"
504
  )
505
 
@@ -527,16 +601,26 @@ Los prompts están basados en el análisis REAL de tu imagen."""
527
  gr.HTML('<div class="section-title">🔍 Análisis Detallado de la Imagen</div>')
528
 
529
  analysis_display = gr.Markdown(
530
- """## 💡 Aquí aparecerá el análisis detallado
531
 
532
- Cuando subas una imagen, verás exactamente:
 
 
533
  - 📝 **Lo que la IA detecta** en tu imagen
534
- - 🎨 **Características visuales** (colores, iluminación, composición)
535
  - ⚡ **Métricas de rendimiento** y confianza
536
- - 🎬 **Elementos SARA** extraídos para los prompts""",
 
 
537
  elem_classes="analysis-display"
538
  )
539
 
 
 
 
 
 
 
540
  # Prompts generados
541
  gr.HTML('<div class="section-title">✨ Prompts Generados</div>')
542
 
@@ -571,13 +655,23 @@ Cuando subas una imagen, verás exactamente:
571
  )
572
  gr.HTML('<div class="description-text">🎭 Interpretación artística</div>')
573
 
574
- # Event handlers
 
 
575
  analyze_btn.click(
576
- fn=analyze_with_detailed_display,
577
- inputs=[image_input, user_idea_input],
578
- outputs=[status_display, analysis_display, basic_output, intermediate_output, advanced_output, experimental_output]
 
 
 
 
 
 
 
579
  )
580
 
 
581
  load_btn.click(
582
  fn=sara_optimized.start_loading,
583
  outputs=model_status
@@ -591,43 +685,48 @@ Cuando subas una imagen, verás exactamente:
591
  # Footer
592
  gr.HTML("""
593
  <div style="margin-top: 2rem; padding: 2rem; background: var(--bg-secondary); border-radius: 12px;">
594
- <div class="section-title">💡 Características Profesionales</div>
595
 
596
  <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1.5rem; margin-top: 1rem;">
597
  <div>
598
- <h4 style="color: var(--text-primary); margin-bottom: 0.5rem;">🎬 Ejemplos Creativos</h4>
599
  <ul style="color: var(--text-secondary); line-height: 1.8;">
600
- <li><code>"cámara orbita lentamente alrededor del sujeto"</code></li>
601
- <li><code>"iluminación dramática con sombras profundas"</code></li>
602
- <li><code>"movimiento en cámara lenta cinematográfico"</code></li>
603
- <li><code>"estilo documental con cámara en mano"</code></li>
604
- <li><code>"toma aérea revelando el paisaje"</code></li>
605
  </ul>
606
  </div>
607
 
608
  <div>
609
- <h4 style="color: var(--text-primary); margin-bottom: 0.5rem;">🚀 Plataformas Compatibles</h4>
610
  <ul style="color: var(--text-secondary); line-height: 1.8;">
611
- <li><strong>RunwayML</strong> Gen-3</li>
612
- <li><strong>Pika Labs</strong></li>
613
- <li><strong>Stable Video Diffusion</strong></li>
614
- <li><strong>Luma AI</strong></li>
615
- <li><strong>Kling AI</strong></li>
616
- <li><strong>Sora</strong> (OpenAI)</li>
617
  </ul>
618
  </div>
619
 
620
  <div>
621
- <h4 style="color: var(--text-primary); margin-bottom: 0.5rem;">🧠 Tecnología IA</h4>
622
  <ul style="color: var(--text-secondary); line-height: 1.8;">
623
- <li><strong>BLIP:</strong> Análisis avanzado de imágenes</li>
624
- <li><strong>SARA-v2:</strong> Generación especializada</li>
625
- <li><strong>Framework SARA:</strong> Subject + Action + Reference + Atmosphere</li>
626
- <li><strong>Cache inteligente:</strong> Análisis instantáneo</li>
627
  </ul>
628
  </div>
629
  </div>
630
 
 
 
 
 
 
 
 
 
631
  <div style="text-align: center; margin-top: 2rem; padding-top: 1rem; border-top: 1px solid var(--border-color); color: var(--text-muted);">
632
  🎬 <strong>SARA v3 Professional</strong> | Framework SARA - WGA Registration Number: 2208356
633
  </div>
@@ -648,20 +747,21 @@ def launch_optimized_sara(**kwargs):
648
  def main():
649
  """Función principal de lanzamiento"""
650
 
651
- print("⚡ SARA v3 - Interfaz Negra Profesional")
652
- print("🎨 Fondo negro, tipografía profesional, análisis visible")
653
  print("📄 Framework SARA - WGA Registration Number: 2208356")
654
  print("=" * 60)
655
 
656
  try:
657
  interface = create_optimized_interface()
658
 
659
- print("🌐 Lanzando interfaz profesional negra...")
660
  print("💡 CARACTERÍSTICAS:")
 
 
661
  print(" ✅ Fondo negro profesional")
662
  print(" ✅ Tipografía Inter sin serifa")
663
  print(" ✅ Análisis detallado VISIBLE")
664
- print(" ✅ Prompts basados en análisis real")
665
  print("-" * 60)
666
 
667
  interface.launch(
@@ -680,20 +780,26 @@ if __name__ == "__main__":
680
  main()
681
 
682
  #########################################################################
683
- # FINAL: sara_v3_interfaz_optimizada.py - DISEÑO NEGRO PROFESIONAL
 
 
 
 
 
 
 
 
 
 
684
  #
685
- # CARACTERÍSTICAS IMPLEMENTADAS:
686
- # FONDO NEGRO PROFESIONAL - Diseño oscuro elegante
687
- # TIPOGRAFÍA INTER - Fuente profesional sin serifa
688
- # ANÁLISIS DETALLADO VISIBLE - Sección dedicada que MUESTRA lo que ve BLIP
689
- # ✅ CSS COMPLETO Y PROFESIONAL - Variables, gradientes, efectos
690
- # ✅ PROMPTS BASADOS EN ANÁLISIS REAL - No plantillas genéricas
691
- # ✅ FUNCIÓN analyze_with_detailed_display() - Muestra análisis completo
692
- # ✅ DISEÑO RESPONSIVE - Se adapta a diferentes tamaños
693
- # ✅ COLORES CODIFICADOS - Cada nivel de prompt tiene su color
694
- # ✅ SCROLLBARS PERSONALIZADAS - Coherentes con el tema
695
- # ✅ EFECTOS HOVER - Interacciones suaves y profesionales
696
  #
697
- # SECCIÓN CLAVE AÑADIDA:
698
- # - analysis_display: Markdown que muestra TODO el análisis de BLIP
699
- # - analyze_with_detailed_display(): Función que extrae y form
 
 
 
 
1
  # sara_v3_interfaz_optimizada.py
2
  # SARA v3 - INTERFAZ GRADIO NEGRA PROFESIONAL COMPLETA
3
+ # Fondo negro, tipografía profesional, análisis visible - PROCESO SEPARADO
4
 
5
  import gradio as gr
6
  import traceback
 
9
  from sara_v3_interfaz_core import sara_optimized
10
 
11
  def create_optimized_interface():
12
+ """Crear interfaz Gradio NEGRA PROFESIONAL - PROCESO SEPARADO"""
13
 
14
  # CSS NEGRO PROFESIONAL
15
  professional_css = """
 
160
  box-shadow: 0 6px 20px rgba(59, 130, 246, 0.4) !important;
161
  }
162
 
163
+ .btn-generate {
164
+ background: linear-gradient(135deg, var(--accent-green) 0%, #059669 100%) !important;
165
+ color: white !important;
166
+ border: none !important;
167
+ border-radius: 8px !important;
168
+ padding: 0.75rem 1.5rem !important;
169
+ font-weight: 600 !important;
170
+ font-size: 1rem !important;
171
+ transition: all 0.2s ease !important;
172
+ box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3) !important;
173
+ }
174
+
175
+ .btn-generate:hover {
176
+ transform: translateY(-1px) !important;
177
+ box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4) !important;
178
+ }
179
+
180
  .btn-secondary {
181
  background: var(--bg-tertiary) !important;
182
  color: var(--text-primary) !important;
 
341
  }
342
  """
343
 
344
+ # VARIABLE GLOBAL PARA ALMACENAR ANÁLISIS
345
+ current_analysis = {"data": None, "image": None}
346
+
347
+ # FUNCIÓN 1: SOLO ANÁLISIS DE IMAGEN
348
+ def analyze_image_only(image):
349
+ """PASO 1: Solo análisis de imagen con BLIP - SIN prompts"""
350
 
351
  if image is None:
352
+ return "❌ Sube una imagen primero", ""
353
 
354
+ # Verificar BLIP
355
  if not sara_optimized.blip_ready:
356
+ return "⚠️ BLIP no está listo. Carga los modelos primero.", ""
357
 
358
  try:
359
+ # ANÁLISIS SOLO CON BLIP
360
+ from sara_v3_parte_6 import analyze_image_with_sara_v3
 
361
 
362
+ analysis = analyze_image_with_sara_v3(image)
363
+ caption = analysis['caption_analysis']['enhanced_caption']
364
+ confidence = analysis['caption_analysis']['confidence_score']
365
+ visual_context = analysis['caption_analysis']['visual_context']
366
+ visual_chars = analysis['image_analysis']['visual_characteristics']
367
+ composition = analysis['image_analysis']['composition_type']
368
+ analysis_time = analysis['total_analysis_time']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
369
 
370
+ # GUARDAR ANÁLISIS PARA USO POSTERIOR
371
+ current_analysis["data"] = analysis
372
+ current_analysis["image"] = image
373
+
374
+ # Extraer características detalladas
375
+ color_info = visual_chars.get('color', {})
376
+ lighting_info = visual_chars.get('lighting', {})
377
+ texture_info = visual_chars.get('texture', {})
378
+
379
+ # CREAR DISPLAY DETALLADO DEL ANÁLISIS
380
+ detailed_analysis = f"""## 🔍 ANÁLISIS COMPLETO DE LA IMAGEN
 
 
 
 
 
 
 
381
 
382
  ### 📝 LO QUE LA IA DETECTA:
383
  **Descripción:** {caption}
 
389
  - Descripción: {visual_context.get('lighting_description', 'Natural')}
390
  - Brillo promedio: {lighting_info.get('avg_brightness', 'N/A')}
391
  - Contraste: {lighting_info.get('contrast_level', 'N/A')}
392
+ - Dirección luz: {lighting_info.get('lighting_direction', 'N/A')}
393
 
394
  **🌈 Análisis de color:**
395
  - Descripción: {visual_context.get('color_description', 'Equilibrados')}
396
  - Temperatura: {color_info.get('temperature', 'N/A')}
397
  - Saturación: {color_info.get('saturation_level', 'N/A')}
398
+ - Colores dominantes: RGB {color_info.get('dominant_rgb', 'N/A')}
399
 
400
  **🎭 Atmósfera:** {visual_context.get('mood_suggestion', 'Neutral')}
401
+ **🖼️ Textura:** {texture_info.get('texture_type', 'N/A')} ({texture_info.get('detail_classification', 'N/A')} detalle)
402
 
403
  ### ⚡ RENDIMIENTO:
404
  **Tiempo:** {analysis_time:.2f}s
405
  **Modelo:** BLIP (análisis de imágenes)
406
+ **Estado:** Análisis completado
407
 
408
+ ### 🎬 SIGUIENTE PASO:
409
+ Usa el botón **"Generar Prompts"** para crear prompts basados en este análisis."""
410
+
411
+ status_msg = f"✅ **Análisis completado en {analysis_time:.2f}s** - Listo para generar prompts"
412
+
413
+ return status_msg, detailed_analysis
 
414
 
415
  except Exception as e:
416
  error_msg = f"❌ Error en análisis: {str(e)}"
417
+ return error_msg, ""
418
+
419
+ # FUNCIÓN 2: SOLO GENERACIÓN DE PROMPTS
420
+ def generate_prompts_only(user_idea=""):
421
+ """PASO 2: Solo generación de prompts basada en análisis previo"""
422
+
423
+ # Verificar que hay análisis previo
424
+ if current_analysis["data"] is None:
425
+ return "⚠️ Primero analiza una imagen usando el botón '🔍 Analizar Imagen'", "", "", "", ""
426
+
427
+ try:
428
+ analysis_data = current_analysis["data"]
429
+ image = current_analysis["image"]
430
+
431
+ # GENERAR PROMPTS CON SARA SI ESTÁ DISPONIBLE
432
+ if sara_optimized.sara_ready:
433
+ try:
434
+ from sara_v3_parte_13 import analyze_image_sara_v3_complete
435
+
436
+ result = analyze_image_sara_v3_complete(image, user_idea)
437
+
438
+ if result['success']:
439
+ prompts = result['prompts']
440
+ generation_time = result['performance']['generation_time']
441
+
442
+ status_msg = f"✅ **Prompts generados en {generation_time:.2f}s** usando SARA-v2"
443
+
444
+ return (
445
+ status_msg,
446
+ prompts.get('basic', ''),
447
+ prompts.get('intermediate', ''),
448
+ prompts.get('advanced', ''),
449
+ prompts.get('experimental', '')
450
+ )
451
+ else:
452
+ return f"❌ Error SARA: {result.get('error', 'Error desconocido')}", "", "", "", ""
453
+
454
+ except ImportError:
455
+ pass
456
+
457
+ # FALLBACK: GENERAR PROMPTS BASADOS EN ANÁLISIS BLIP
458
+ caption = analysis_data['caption_analysis']['enhanced_caption']
459
+ visual_context = analysis_data['caption_analysis']['visual_context']
460
+
461
+ # Determinar sujeto principal
462
+ caption_lower = caption.lower()
463
+ if 'woman' in caption_lower:
464
+ subject = "Woman"
465
+ elif 'man' in caption_lower:
466
+ subject = "Man"
467
+ elif 'person' in caption_lower or 'people' in caption_lower:
468
+ subject = "Person"
469
+ else:
470
+ subject = "Subject"
471
+
472
+ # Extraer contexto
473
+ lighting = visual_context.get('lighting_description', 'soft lighting')
474
+ colors = visual_context.get('color_description', 'balanced colors')
475
+ mood = visual_context.get('mood_suggestion', 'natural atmosphere')
476
+
477
+ # GENERAR PROMPTS BASADOS EN ANÁLISIS REAL
478
+ if user_idea.strip():
479
+ base_action = user_idea.strip()
480
+ prompts = {
481
+ 'basic': f"{subject} {base_action} naturally, {caption.lower()}, {lighting}.",
482
+ 'intermediate': f"{subject} {base_action} expressively while camera follows smoothly, maintaining {caption.lower()} with enhanced depth.",
483
+ 'advanced': f"Cinematic sequence: {subject.lower()} {base_action} professionally, {caption.lower()}, {lighting} creates premium visual aesthetic.",
484
+ 'experimental': f"Artistic interpretation: {subject.lower()} {base_action} transcendentally, {caption.lower()} transforms into ethereal visual poetry."
485
+ }
486
+ else:
487
+ prompts = {
488
+ 'basic': f"{caption}, natural movement with smooth camera work, {lighting}.",
489
+ 'intermediate': f"{subject} moves expressively while camera follows gracefully, {caption.lower()} creates cinematic depth.",
490
+ 'advanced': f"Professional cinematic approach: {caption.lower()}, elegant camera choreography with {lighting} creates premium video aesthetic.",
491
+ 'experimental': f"Artistic vision: {subject.lower()} transcends conventional reality, {caption.lower()} evolves into surreal visual symphony."
492
+ }
493
+
494
+ status_msg = "✅ **Prompts generados** basados en análisis BLIP (SARA no disponible)"
495
+
496
+ return (
497
+ status_msg,
498
+ prompts['basic'],
499
+ prompts['intermediate'],
500
+ prompts['advanced'],
501
+ prompts['experimental']
502
+ )
503
+
504
+ except Exception as e:
505
+ error_msg = f"❌ Error generando prompts: {str(e)}"
506
+ return error_msg, "", "", "", ""
507
 
508
  # Crear interfaz con tema negro
509
  with gr.Blocks(
 
521
  </div>
522
  """)
523
 
524
+ # Instrucciones - PROCESO SEPARADO
525
  with gr.Row():
526
  gr.Markdown("""
527
  <div class="section-container markdown-content">
528
+ <div class="section-title">🚀 Proceso en 2 Pasos</div>
529
+ <p><strong>PASO 1:</strong> 🔍 **Analizar Imagen** - Ver lo que detecta la IA (5-10s)</p>
530
+ <p><strong>PASO 2:</strong> 🎬 **Generar Prompts** - Crear 4 prompts profesionales</p>
531
+ <p><strong>Opcional:</strong> Añadir dirección creativa antes del Paso 2</p>
 
532
  </div>
533
  """)
534
 
535
  # Sección principal
536
  with gr.Row():
537
+ # Columna izquierda - Input y análisis
538
  with gr.Column(scale=1):
539
  gr.HTML('<div class="section-title">📸 Análisis de Imagen</div>')
540
 
 
545
  )
546
  gr.HTML('<div class="description-text">📷 Sube cualquier imagen para análisis completo</div>')
547
 
548
+ # BOTÓN 1: SOLO ANÁLISIS
549
+ analyze_btn = gr.Button(
550
+ "🔍 Analizar Imagen",
551
+ variant="primary",
552
+ size="lg",
553
+ elem_classes="btn-primary"
554
+ )
555
+
556
  user_idea_input = gr.Textbox(
557
  label="💡 Dirección Creativa (Opcional)",
558
  placeholder="ej: 'cámara orbita lentamente', 'iluminación dramática', 'movimiento cinematográfico'",
 
560
  )
561
  gr.HTML('<div class="description-text">🎨 Describe tu visión para el video</div>')
562
 
563
+ # BOTÓN 2: SOLO PROMPTS
564
+ generate_btn = gr.Button(
565
+ "🎬 Generar Prompts",
566
+ variant="secondary",
567
  size="lg",
568
+ elem_classes="btn-generate"
569
  )
570
 
571
+ # Columna derecha - Estado del sistema
572
  with gr.Column(scale=1):
573
  gr.HTML('<div class="section-title">📊 Estado del Sistema</div>')
574
 
575
  status_display = gr.Markdown(
576
+ "ℹ️ **Listo para analizar** - Sube imagen y haz clic en 'Analizar Imagen'",
577
  elem_classes="status-info"
578
  )
579
 
 
601
  gr.HTML('<div class="section-title">🔍 Análisis Detallado de la Imagen</div>')
602
 
603
  analysis_display = gr.Markdown(
604
+ """## 💡 Análisis de imagen aparecerá aquí
605
 
606
+ **PASO 1:** Sube una imagen y haz clic en **"🔍 Analizar Imagen"**
607
+
608
+ Verás exactamente:
609
  - 📝 **Lo que la IA detecta** en tu imagen
610
+ - 🎨 **Características visuales** (colores, iluminación, composición)
611
  - ⚡ **Métricas de rendimiento** y confianza
612
+ - 🎬 **Datos para generar prompts** profesionales
613
+
614
+ **PASO 2:** Usa **"🎬 Generar Prompts"** para crear 4 prompts basados en este análisis""",
615
  elem_classes="analysis-display"
616
  )
617
 
618
+ # STATUS PARA GENERACIÓN
619
+ generate_status = gr.Markdown(
620
+ "ℹ️ **Esperando análisis** - Primero analiza una imagen",
621
+ elem_classes="status-info"
622
+ )
623
+
624
  # Prompts generados
625
  gr.HTML('<div class="section-title">✨ Prompts Generados</div>')
626
 
 
655
  )
656
  gr.HTML('<div class="description-text">🎭 Interpretación artística</div>')
657
 
658
+ # EVENT HANDLERS - PROCESO SEPARADO
659
+
660
+ # PASO 1: Solo análisis
661
  analyze_btn.click(
662
+ fn=analyze_image_only,
663
+ inputs=[image_input],
664
+ outputs=[status_display, analysis_display]
665
+ )
666
+
667
+ # PASO 2: Solo prompts
668
+ generate_btn.click(
669
+ fn=generate_prompts_only,
670
+ inputs=[user_idea_input],
671
+ outputs=[generate_status, basic_output, intermediate_output, advanced_output, experimental_output]
672
  )
673
 
674
+ # Control de modelos (sin cambios)
675
  load_btn.click(
676
  fn=sara_optimized.start_loading,
677
  outputs=model_status
 
685
  # Footer
686
  gr.HTML("""
687
  <div style="margin-top: 2rem; padding: 2rem; background: var(--bg-secondary); border-radius: 12px;">
688
+ <div class="section-title">💡 Proceso Optimizado</div>
689
 
690
  <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1.5rem; margin-top: 1rem;">
691
  <div>
692
+ <h4 style="color: var(--text-primary); margin-bottom: 0.5rem;">🔍 Paso 1: Análisis</h4>
693
  <ul style="color: var(--text-secondary); line-height: 1.8;">
694
+ <li><strong>Rápido:</strong> 5-10 segundos</li>
695
+ <li>👁️ <strong>Ve inmediatamente</strong> lo que detecta BLIP</li>
696
+ <li>🎯 <strong>Decide</strong> si generar prompts o cambiar imagen</li>
697
+ <li>🔧 <strong>Debug fácil:</strong> saber qué ve la IA</li>
 
698
  </ul>
699
  </div>
700
 
701
  <div>
702
+ <h4 style="color: var(--text-primary); margin-bottom: 0.5rem;">🎬 Paso 2: Prompts</h4>
703
  <ul style="color: var(--text-secondary); line-height: 1.8;">
704
+ <li>🎨 <strong>Basados en análisis real</strong> de tu imagen</li>
705
+ <li>💡 <strong>Dirección creativa</strong> opcional</li>
706
+ <li>⚙️ <strong>SARA-v2</strong> si está cargado, sino templates inteligentes</li>
707
+ <li>🚀 <strong>4 niveles:</strong> Básico, Intermedio, Avanzado, Experimental</li>
 
 
708
  </ul>
709
  </div>
710
 
711
  <div>
712
+ <h4 style="color: var(--text-primary); margin-bottom: 0.5rem;">🎬 Ejemplos Creativos</h4>
713
  <ul style="color: var(--text-secondary); line-height: 1.8;">
714
+ <li><code>"cámara orbita lentamente"</code></li>
715
+ <li><code>"iluminación dramática"</code></li>
716
+ <li><code>"movimiento cinematográfico"</code></li>
717
+ <li><code>"estilo documental"</code></li>
718
  </ul>
719
  </div>
720
  </div>
721
 
722
+ <div style="margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid var(--border-color);">
723
+ <h4 style="color: var(--text-primary); margin-bottom: 0.5rem;">🚀 Plataformas Compatibles</h4>
724
+ <p style="color: var(--text-secondary); line-height: 1.6;">
725
+ <strong>RunwayML</strong> Gen-3 • <strong>Pika Labs</strong> • <strong>Stable Video Diffusion</strong> •
726
+ <strong>Luma AI</strong> • <strong>Kling AI</strong> • <strong>Sora</strong> (OpenAI)
727
+ </p>
728
+ </div>
729
+
730
  <div style="text-align: center; margin-top: 2rem; padding-top: 1rem; border-top: 1px solid var(--border-color); color: var(--text-muted);">
731
  🎬 <strong>SARA v3 Professional</strong> | Framework SARA - WGA Registration Number: 2208356
732
  </div>
 
747
  def main():
748
  """Función principal de lanzamiento"""
749
 
750
+ print("⚡ SARA v3 - Interfaz Negra Profesional SEPARADA")
751
+ print("🎨 Fondo negro, tipografía profesional, proceso en 2 pasos")
752
  print("📄 Framework SARA - WGA Registration Number: 2208356")
753
  print("=" * 60)
754
 
755
  try:
756
  interface = create_optimized_interface()
757
 
758
+ print("🌐 Lanzando interfaz profesional con proceso separado...")
759
  print("💡 CARACTERÍSTICAS:")
760
+ print(" ✅ PASO 1: Solo análisis de imagen (5-10s)")
761
+ print(" ✅ PASO 2: Solo generación de prompts")
762
  print(" ✅ Fondo negro profesional")
763
  print(" ✅ Tipografía Inter sin serifa")
764
  print(" ✅ Análisis detallado VISIBLE")
 
765
  print("-" * 60)
766
 
767
  interface.launch(
 
780
  main()
781
 
782
  #########################################################################
783
+ # FINAL: sara_v3_interfaz_optimizada.py - PROCESO SEPARADO EN 2 PASOS
784
+ #
785
+ # CAMBIOS PRINCIPALES:
786
+ # ✅ PROCESO SEPARADO - 2 botones independientes
787
+ # ✅ PASO 1: "🔍 Analizar Imagen" - Solo análisis BLIP (rápido)
788
+ # ✅ PASO 2: "🎬 Generar Prompts" - Solo generación basada en análisis
789
+ # ✅ VARIABLE current_analysis - Almacena análisis entre pasos
790
+ # ✅ FUNCIÓN analyze_image_only() - Solo análisis detallado
791
+ # ✅ FUNCIÓN generate_prompts_only() - Solo prompts basados en análisis
792
+ # ✅ UI MEJORADA - Instrucciones claras del proceso
793
+ # ✅ ESTADO SEPARADO - Status diferentes para cada paso
794
  #
795
+ # FLUJO DE USUARIO:
796
+ # 1. Sube imagen clic "🔍 Analizar Imagen" → ve análisis (10s)
797
+ # 2. (Opcional) Añade dirección creativa
798
+ # 3. Clic "🎬 Generar Prompts" obtiene 4 prompts profesionales
 
 
 
 
 
 
 
799
  #
800
+ # VENTAJAS:
801
+ # - Usuario ve inmediatamente lo que detecta la IA
802
+ # - Control total sobre el proceso
803
+ # - Debug fácil (saber si falla análisis o generación)
804
+ # - Puede ajustar dirección creativa viendo el análisis
805
+ #########################################################################