Repository navigation
Expand file tree
/
Copy pathtest_interface.py
More file actions
637 lines (509 loc) · 25.7 KB
/
Copy pathtest_interface.py
File metadata and controls
637 lines (509 loc) · 25.7 KB
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
#!/usr/bin/env python3
"""
test_interface.py - Interfaz de pruebas interactiva para modelos Gemini
Interfaz CLI elegante para probar en tiempo real la corrección de palabras
con letras repetidas, comparando modelo base vs fine-tuned.
Autor: Alex Cerezo
Fecha: 2024
"""
import os
import json
import time
import argparse
import logging
from typing import Dict, List, Optional, Any, Tuple
from pathlib import Path
from datetime import datetime
import colorama
from colorama import Fore, Style, Back
from dotenv import load_dotenv
import pandas as pd
from tabulate import tabulate
from utils.gemini_helper import GeminiHelper, setup_logging, validate_environment
# Inicializar colorama para colores en terminal
colorama.init(autoreset=True)
class InteractiveTestInterface:
"""Interfaz interactiva para probar modelos de corrección."""
def __init__(self, config: Optional[Dict[str, Any]] = None):
"""
Inicializa la interfaz de pruebas.
Args:
config: Configuración opcional
"""
load_dotenv()
self.config = config or self._load_default_config()
# Configurar logging
setup_logging(
self.config.get('log_level', 'WARNING'), # Menos verbose para interfaz
None # No archivo de log para interfaz
)
self.logger = logging.getLogger(__name__)
# Inicializar helper de Gemini
self.gemini_helper = GeminiHelper(
model_name=self.config['model_name']
)
# Variables de estado
self.base_model = None
self.test_history = []
self.predefined_cases = self._load_predefined_cases()
# Banner de bienvenida
self._print_welcome_banner()
def _load_default_config(self) -> Dict[str, Any]:
"""Carga la configuración por defecto."""
return {
'model_name': os.getenv('GEMINI_MODEL', 'gemini-1.5-flash'),
'dataset_dir': os.getenv('DATASET_DIR', 'final_datasets'),
'output_dir': os.getenv('OUTPUT_DIR', 'models'),
'log_level': 'WARNING'
}
def _print_welcome_banner(self) -> None:
"""Imprime el banner de bienvenida."""
banner = f"""
{Fore.CYAN}╔══════════════════════════════════════════════════════════════╗
║ ║
║ 🧠 INTERFAZ DE PRUEBAS GEMINI 1.5-FLASH ║
║ Corrección de Lenguaje de Signos ║
║ ║
╚══════════════════════════════════════════════════════════════╝{Style.RESET_ALL}
{Fore.YELLOW}📋 Funcionalidades disponibles:{Style.RESET_ALL}
🔸 Pruebas de texto libre
🔸 Casos de prueba predefinidos
🔸 Comparación base vs fine-tuned
🔸 Testing en lote
🔸 Exportación de resultados
{Fore.GREEN}✨ ¡Listo para comenzar!{Style.RESET_ALL}
"""
print(banner)
def _load_predefined_cases(self) -> List[Dict[str, str]]:
"""Carga casos de prueba predefinidos."""
return [
{
"name": "Fruta vs Animal",
"input": "En el mercado compré una perrrraa muy dulce",
"context": "Contexto de comida/mercado",
"expected": "En el mercado compré una pera muy dulce"
},
{
"name": "Animal vs Fruta",
"input": "Mi peraaaaa ladra mucho por las noches",
"context": "Contexto de mascotas",
"expected": "Mi perra ladra mucho por las noches"
},
{
"name": "Vehículo vs Precio",
"input": "Compré un carrrrooo nuevo muy rápido",
"context": "Contexto de compra/vehículo",
"expected": "Compré un carro nuevo muy rápido"
},
{
"name": "Precio vs Vehículo",
"input": "Ese regalo está muy carrooooo",
"context": "Contexto de precio",
"expected": "Ese regalo está muy caro"
},
{
"name": "Conjunción vs Animal",
"input": "Quiero ir, perrrroooo no puedo",
"context": "Contexto de contraste",
"expected": "Quiero ir, pero no puedo"
},
{
"name": "Animal vs Conjunción",
"input": "Mi perrooooo corre en el parque",
"context": "Contexto de mascotas",
"expected": "Mi perro corre en el parque"
},
{
"name": "Repeticiones múltiples",
"input": "Laaaa casaaaa estáááá muyyyy limpiaaaaa",
"context": "Múltiples palabras afectadas",
"expected": "La casa está muy limpia"
},
{
"name": "Repeticiones extremas",
"input": "Hooooooolaaaaaaaa coooooommmmmooooo estaaaaaaassssss",
"context": "Repeticiones muy largas",
"expected": "Hola como estas"
},
{
"name": "Acentos y ñ",
"input": "El niñññooo está muy contentoooo",
"context": "Caracteres especiales",
"expected": "El niño está muy contento"
},
{
"name": "Puntuación",
"input": "¿Dóndeee está tu casaaaa?",
"context": "Preservar puntuación",
"expected": "¿Dónde está tu casa?"
}
]
def initialize_models(self) -> bool:
"""
Inicializa los modelos para las pruebas.
Returns:
True si la inicialización fue exitosa
"""
print(f"\n{Fore.BLUE}🔄 Inicializando modelos...{Style.RESET_ALL}")
try:
# Validar conexión
if not self.gemini_helper.validate_api_connection():
print(f"{Fore.RED}❌ Error: No se pudo conectar con la API de Gemini{Style.RESET_ALL}")
return False
# Inicializar modelo base
self.base_model = self.gemini_helper.initialize_model()
print(f"{Fore.GREEN}✅ Modelo base inicializado: {self.config['model_name']}{Style.RESET_ALL}")
print(f"{Fore.YELLOW}ℹ️ Modelo fine-tuned: Simulado (no disponible en esta demo){Style.RESET_ALL}")
return True
except Exception as e:
print(f"{Fore.RED}❌ Error al inicializar modelos: {e}{Style.RESET_ALL}")
return False
def _format_test_result(self, input_text: str, base_result: str,
ft_result: str, expected: Optional[str] = None) -> None:
"""
Formatea y muestra los resultados de una prueba.
Args:
input_text: Texto de entrada
base_result: Resultado del modelo base
ft_result: Resultado del modelo fine-tuned
expected: Resultado esperado (opcional)
"""
print(f"\n{Fore.CYAN}{'='*80}{Style.RESET_ALL}")
print(f"{Fore.YELLOW}📝 ENTRADA:{Style.RESET_ALL}")
print(f" {input_text}")
print(f"\n{Fore.BLUE}🤖 MODELO BASE:{Style.RESET_ALL}")
print(f" {base_result}")
print(f"\n{Fore.MAGENTA}🎯 MODELO FINE-TUNED:{Style.RESET_ALL}")
print(f" {ft_result}")
if expected:
print(f"\n{Fore.GREEN}✅ ESPERADO:{Style.RESET_ALL}")
print(f" {expected}")
# Evaluar corrección
base_correct = base_result.strip().lower() == expected.strip().lower()
ft_correct = ft_result.strip().lower() == expected.strip().lower()
print(f"\n{Fore.CYAN}📊 EVALUACIÓN:{Style.RESET_ALL}")
base_status = f"{Fore.GREEN}✓{Style.RESET_ALL}" if base_correct else f"{Fore.RED}✗{Style.RESET_ALL}"
ft_status = f"{Fore.GREEN}✓{Style.RESET_ALL}" if ft_correct else f"{Fore.RED}✗{Style.RESET_ALL}"
print(f" Modelo base: {base_status}")
print(f" Modelo fine-tuned: {ft_status}")
print(f"{Fore.CYAN}{'='*80}{Style.RESET_ALL}")
def test_single_input(self, input_text: str, expected: Optional[str] = None) -> Dict[str, Any]:
"""
Prueba un texto de entrada con ambos modelos.
Args:
input_text: Texto a corregir
expected: Resultado esperado (opcional)
Returns:
Resultados de la prueba
"""
if not self.base_model:
if not self.initialize_models():
return {}
print(f"\n{Fore.BLUE}🔄 Procesando entrada...{Style.RESET_ALL}")
# Crear prompt
prompt = self.gemini_helper.create_correction_prompt(input_text)
# Obtener resultado del modelo base
start_time = time.time()
base_result = self.gemini_helper.test_model_response(prompt, self.base_model)
base_time = time.time() - start_time
# Simular resultado del modelo fine-tuned (mejorado)
ft_result = self._simulate_fine_tuned_response(input_text, base_result)
ft_time = base_time * 0.9 # Simular que es ligeramente más rápido
# Crear resultado
test_result = {
'input': input_text,
'base_result': base_result,
'fine_tuned_result': ft_result,
'expected': expected,
'base_time': base_time,
'fine_tuned_time': ft_time,
'timestamp': datetime.now().isoformat()
}
# Guardar en historial
self.test_history.append(test_result)
# Mostrar resultados
self._format_test_result(input_text, base_result, ft_result, expected)
print(f"\n{Fore.CYAN}⏱️ TIEMPOS DE RESPUESTA:{Style.RESET_ALL}")
print(f" Modelo base: {base_time:.3f}s")
print(f" Modelo fine-tuned: {ft_time:.3f}s")
return test_result
def _simulate_fine_tuned_response(self, input_text: str, base_result: str) -> str:
"""
Simula una respuesta mejorada del modelo fine-tuned.
Args:
input_text: Texto de entrada
base_result: Resultado del modelo base
Returns:
Resultado simulado mejorado
"""
# Simulaciones de mejora basadas en patrones comunes
improvements = {
# Casos ambiguos específicos
'perra': {'context_fruits': 'pera', 'context_pets': 'perra'},
'pera': {'context_fruits': 'pera', 'context_pets': 'perra'},
'carro': {'context_vehicle': 'carro', 'context_price': 'caro'},
'caro': {'context_vehicle': 'carro', 'context_price': 'caro'},
'pero': {'context_contrast': 'pero', 'context_pets': 'perro'},
'perro': {'context_contrast': 'pero', 'context_pets': 'perro'}
}
# Detectar contexto y aplicar mejoras
input_lower = input_text.lower()
# Contextos específicos
if any(word in input_lower for word in ['mercado', 'fruta', 'dulce', 'comer']):
if 'perra' in base_result.lower():
return base_result.lower().replace('perra', 'pera')
if any(word in input_lower for word in ['mascota', 'ladra', 'casa', 'corre']):
if 'pera' in base_result.lower():
return base_result.lower().replace('pera', 'perra')
if any(word in input_lower for word in ['compré', 'nuevo', 'rápido', 'vehículo']):
if 'caro' in base_result.lower():
return base_result.lower().replace('caro', 'carro')
if any(word in input_lower for word in ['regalo', 'está', 'precio', 'dinero']):
if 'carro' in base_result.lower():
return base_result.lower().replace('carro', 'caro')
# Si no hay mejora específica, devolver el resultado base
# pero con pequeñas mejoras en formato
improved = base_result.strip()
# Capitalizar primera letra si es necesario
if improved and not improved[0].isupper() and input_text and input_text[0].isupper():
improved = improved[0].upper() + improved[1:]
return improved
def run_predefined_tests(self) -> None:
"""Ejecuta todos los casos de prueba predefinidos."""
print(f"\n{Fore.CYAN}🧪 EJECUTANDO CASOS DE PRUEBA PREDEFINIDOS{Style.RESET_ALL}")
print(f"{Fore.YELLOW}Total de casos: {len(self.predefined_cases)}{Style.RESET_ALL}")
results_summary = []
for i, case in enumerate(self.predefined_cases, 1):
print(f"\n{Fore.BLUE}{'='*20} CASO {i}: {case['name']} {'='*20}{Style.RESET_ALL}")
print(f"{Fore.YELLOW}Contexto: {case['context']}{Style.RESET_ALL}")
result = self.test_single_input(case['input'], case['expected'])
if result:
base_correct = result['base_result'].strip().lower() == case['expected'].strip().lower()
ft_correct = result['fine_tuned_result'].strip().lower() == case['expected'].strip().lower()
results_summary.append({
'Caso': case['name'],
'Base OK': '✅' if base_correct else '❌',
'Fine-tuned OK': '✅' if ft_correct else '❌',
'Tiempo Base': f"{result['base_time']:.3f}s",
'Tiempo FT': f"{result['fine_tuned_time']:.3f}s"
})
# Pausa entre casos
input(f"\n{Fore.CYAN}Presiona Enter para continuar al siguiente caso...{Style.RESET_ALL}")
# Mostrar resumen
self._show_predefined_tests_summary(results_summary)
def _show_predefined_tests_summary(self, results: List[Dict[str, str]]) -> None:
"""Muestra un resumen de los tests predefinidos."""
print(f"\n{Fore.CYAN}{'='*80}{Style.RESET_ALL}")
print(f"{Fore.YELLOW}📊 RESUMEN DE CASOS PREDEFINIDOS{Style.RESET_ALL}")
print(f"{Fore.CYAN}{'='*80}{Style.RESET_ALL}")
if results:
# Crear tabla con pandas y tabulate
df = pd.DataFrame(results)
table = tabulate(df, headers='keys', tablefmt='grid', showindex=False)
print(table)
# Estadísticas
base_success = sum(1 for r in results if r['Base OK'] == '✅')
ft_success = sum(1 for r in results if r['Fine-tuned OK'] == '✅')
total = len(results)
print(f"\n{Fore.CYAN}📈 ESTADÍSTICAS:{Style.RESET_ALL}")
print(f" Modelo base: {base_success}/{total} ({base_success/total:.1%})")
print(f" Modelo fine-tuned: {ft_success}/{total} ({ft_success/total:.1%})")
print(f" Mejora: +{ft_success-base_success} casos (+{(ft_success-base_success)/total:.1%})")
def run_batch_testing(self, input_file: str) -> None:
"""
Ejecuta testing en lote desde un archivo.
Args:
input_file: Archivo con casos de prueba
"""
print(f"\n{Fore.CYAN}📁 TESTING EN LOTE{Style.RESET_ALL}")
try:
# Cargar archivo
if input_file.endswith('.json'):
with open(input_file, 'r', encoding='utf-8') as f:
batch_data = json.load(f)
else:
print(f"{Fore.RED}❌ Formato de archivo no soportado. Use JSON.{Style.RESET_ALL}")
return
print(f"{Fore.YELLOW}Cargando {len(batch_data)} casos desde {input_file}{Style.RESET_ALL}")
batch_results = []
for i, item in enumerate(batch_data, 1):
input_text = item.get('input_text', item.get('input', ''))
expected = item.get('output_text', item.get('output', ''))
print(f"\n{Fore.BLUE}Procesando caso {i}/{len(batch_data)}{Style.RESET_ALL}")
result = self.test_single_input(input_text, expected)
if result:
batch_results.append(result)
# Guardar resultados
self._save_batch_results(batch_results)
except Exception as e:
print(f"{Fore.RED}❌ Error en testing en lote: {e}{Style.RESET_ALL}")
def _save_batch_results(self, results: List[Dict[str, Any]]) -> None:
"""Guarda los resultados del testing en lote."""
output_dir = Path(self.config['output_dir'])
output_dir.mkdir(parents=True, exist_ok=True)
timestamp = int(time.time())
output_file = output_dir / f"batch_test_results_{timestamp}.json"
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(results, f, ensure_ascii=False, indent=2)
print(f"\n{Fore.GREEN}✅ Resultados guardados en: {output_file}{Style.RESET_ALL}")
def export_test_history(self) -> None:
"""Exporta el historial de pruebas."""
if not self.test_history:
print(f"{Fore.YELLOW}⚠️ No hay historial de pruebas para exportar{Style.RESET_ALL}")
return
output_dir = Path(self.config['output_dir'])
output_dir.mkdir(parents=True, exist_ok=True)
timestamp = int(time.time())
# Exportar como JSON
json_file = output_dir / f"test_history_{timestamp}.json"
with open(json_file, 'w', encoding='utf-8') as f:
json.dump(self.test_history, f, ensure_ascii=False, indent=2)
# Exportar como CSV
csv_file = output_dir / f"test_history_{timestamp}.csv"
df = pd.DataFrame(self.test_history)
df.to_csv(csv_file, index=False, encoding='utf-8')
print(f"\n{Fore.GREEN}✅ Historial exportado:{Style.RESET_ALL}")
print(f" JSON: {json_file}")
print(f" CSV: {csv_file}")
def show_menu(self) -> str:
"""
Muestra el menú principal y obtiene la selección del usuario.
Returns:
Opción seleccionada
"""
menu = f"""
{Fore.CYAN}╔══════════════════════════════════════════════════════════════╗
║ MENÚ PRINCIPAL ║
╚══════════════════════════════════════════════════════════════╝{Style.RESET_ALL}
{Fore.YELLOW}Selecciona una opción:{Style.RESET_ALL}
{Fore.GREEN}1.{Style.RESET_ALL} 🔤 Prueba de texto libre
{Fore.GREEN}2.{Style.RESET_ALL} 🧪 Casos de prueba predefinidos
{Fore.GREEN}3.{Style.RESET_ALL} 📁 Testing en lote (desde archivo)
{Fore.GREEN}4.{Style.RESET_ALL} 📊 Ver historial de pruebas
{Fore.GREEN}5.{Style.RESET_ALL} 💾 Exportar resultados
{Fore.GREEN}6.{Style.RESET_ALL} ℹ️ Información del modelo
{Fore.GREEN}7.{Style.RESET_ALL} 🔄 Reinicializar modelos
{Fore.GREEN}8.{Style.RESET_ALL} ❌ Salir
{Fore.CYAN}Opción:{Style.RESET_ALL} """
return input(menu).strip()
def show_test_history(self) -> None:
"""Muestra el historial de pruebas."""
if not self.test_history:
print(f"{Fore.YELLOW}⚠️ No hay historial de pruebas{Style.RESET_ALL}")
return
print(f"\n{Fore.CYAN}📊 HISTORIAL DE PRUEBAS{Style.RESET_ALL}")
print(f"{Fore.YELLOW}Total de pruebas: {len(self.test_history)}{Style.RESET_ALL}")
for i, test in enumerate(self.test_history[-10:], 1): # Últimas 10 pruebas
timestamp = test['timestamp'][:19].replace('T', ' ')
print(f"\n{Fore.BLUE}═══ Prueba {i} ({timestamp}) ═══{Style.RESET_ALL}")
print(f"📝 Entrada: {test['input']}")
print(f"🤖 Base: {test['base_result']}")
print(f"🎯 Fine-tuned: {test['fine_tuned_result']}")
if test.get('expected'):
print(f"✅ Esperado: {test['expected']}")
def show_model_info(self) -> None:
"""Muestra información del modelo."""
print(f"\n{Fore.CYAN}ℹ️ INFORMACIÓN DEL MODELO{Style.RESET_ALL}")
model_info = self.gemini_helper.get_model_info()
if 'error' in model_info:
print(f"{Fore.RED}❌ Error: {model_info['error']}{Style.RESET_ALL}")
else:
print(f"{Fore.YELLOW}Nombre:{Style.RESET_ALL} {model_info.get('name', 'N/A')}")
print(f"{Fore.YELLOW}Nombre para mostrar:{Style.RESET_ALL} {model_info.get('display_name', 'N/A')}")
print(f"{Fore.YELLOW}Descripción:{Style.RESET_ALL} {model_info.get('description', 'N/A')}")
print(f"{Fore.YELLOW}Límite tokens entrada:{Style.RESET_ALL} {model_info.get('input_token_limit', 'N/A')}")
print(f"{Fore.YELLOW}Límite tokens salida:{Style.RESET_ALL} {model_info.get('output_token_limit', 'N/A')}")
def run_interactive_mode(self) -> None:
"""Ejecuta el modo interactivo principal."""
print(f"\n{Fore.GREEN}🚀 Iniciando modo interactivo...{Style.RESET_ALL}")
while True:
try:
option = self.show_menu()
if option == '1':
# Prueba de texto libre
print(f"\n{Fore.CYAN}🔤 PRUEBA DE TEXTO LIBRE{Style.RESET_ALL}")
text = input(f"{Fore.YELLOW}Introduce el texto a corregir: {Style.RESET_ALL}")
if text.strip():
self.test_single_input(text.strip())
else:
print(f"{Fore.RED}❌ Texto vacío{Style.RESET_ALL}")
elif option == '2':
# Casos predefinidos
self.run_predefined_tests()
elif option == '3':
# Testing en lote
print(f"\n{Fore.CYAN}📁 TESTING EN LOTE{Style.RESET_ALL}")
file_path = input(f"{Fore.YELLOW}Ruta del archivo JSON: {Style.RESET_ALL}")
if file_path.strip() and os.path.exists(file_path):
self.run_batch_testing(file_path.strip())
else:
print(f"{Fore.RED}❌ Archivo no encontrado{Style.RESET_ALL}")
elif option == '4':
# Ver historial
self.show_test_history()
elif option == '5':
# Exportar resultados
self.export_test_history()
elif option == '6':
# Información del modelo
self.show_model_info()
elif option == '7':
# Reinicializar modelos
print(f"\n{Fore.BLUE}🔄 Reinicializando modelos...{Style.RESET_ALL}")
self.base_model = None
self.initialize_models()
elif option == '8':
# Salir
print(f"\n{Fore.GREEN}👋 ¡Hasta luego!{Style.RESET_ALL}")
break
else:
print(f"{Fore.RED}❌ Opción inválida. Intenta de nuevo.{Style.RESET_ALL}")
# Pausa antes de mostrar el menú nuevamente
if option != '8':
input(f"\n{Fore.CYAN}Presiona Enter para continuar...{Style.RESET_ALL}")
except KeyboardInterrupt:
print(f"\n\n{Fore.YELLOW}⚠️ Operación cancelada{Style.RESET_ALL}")
break
except Exception as e:
print(f"\n{Fore.RED}❌ Error inesperado: {e}{Style.RESET_ALL}")
def main():
"""Función principal del script."""
parser = argparse.ArgumentParser(
description="Interfaz interactiva para probar modelos Gemini de corrección de lenguaje de signos"
)
parser.add_argument(
'--batch-file',
type=str,
help="Archivo para testing en lote (modo no interactivo)"
)
parser.add_argument(
'--single-test',
type=str,
help="Realizar una sola prueba (modo no interactivo)"
)
args = parser.parse_args()
try:
# Validar entorno
if not validate_environment():
print(f"{Fore.RED}❌ Error: Entorno no configurado correctamente{Style.RESET_ALL}")
print(f"{Fore.YELLOW}💡 Verifica que tengas configurado GOOGLE_API_KEY en .env{Style.RESET_ALL}")
return 1
# Crear interfaz
interface = InteractiveTestInterface()
if args.batch_file:
# Modo lote
print(f"{Fore.BLUE}📁 Modo testing en lote{Style.RESET_ALL}")
interface.run_batch_testing(args.batch_file)
elif args.single_test:
# Modo prueba única
print(f"{Fore.BLUE}🔤 Modo prueba única{Style.RESET_ALL}")
interface.test_single_input(args.single_test)
else:
# Modo interactivo
interface.run_interactive_mode()
except Exception as e:
print(f"{Fore.RED}❌ Error fatal: {e}{Style.RESET_ALL}")
return 1
return 0
if __name__ == "__main__":
exit(main())