Repository navigation
Expand file tree
/
Copy pathsetup_environment.py
More file actions
514 lines (408 loc) · 17.6 KB
/
Copy pathsetup_environment.py
File metadata and controls
514 lines (408 loc) · 17.6 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
#!/usr/bin/env python3
"""
setup_environment.py - Script de configuración inicial del entorno
Configura el entorno de desarrollo para fine-tuning de Gemini,
valida dependencias, y prepara la configuración inicial.
Autor: Alex Cerezo
Fecha: 2024
"""
import os
import sys
import json
import shutil
import subprocess
from pathlib import Path
from typing import List, Dict, Any, Optional
import colorama
from colorama import Fore, Style
# Inicializar colorama
colorama.init(autoreset=True)
class EnvironmentSetup:
"""Configurador del entorno de desarrollo."""
def __init__(self):
"""Inicializa el configurador."""
self.project_root = Path.cwd()
self.errors = []
self.warnings = []
print(f"""
{Fore.CYAN}╔══════════════════════════════════════════════════════════════╗
║ ║
║ 🛠️ CONFIGURACIÓN DEL ENTORNO GEMINI ║
║ Fine-tuning Sign Language ║
║ ║
╚══════════════════════════════════════════════════════════════╝{Style.RESET_ALL}
""")
def check_python_version(self) -> bool:
"""
Verifica que la versión de Python sea compatible.
Returns:
True si la versión es compatible
"""
print(f"{Fore.BLUE}🔍 Verificando versión de Python...{Style.RESET_ALL}")
version = sys.version_info
required_major, required_minor = 3, 8
if version.major >= required_major and version.minor >= required_minor:
print(f"{Fore.GREEN}✅ Python {version.major}.{version.minor}.{version.micro} es compatible{Style.RESET_ALL}")
return True
else:
error_msg = f"Python {version.major}.{version.minor} no es compatible. Se requiere Python {required_major}.{required_minor}+"
self.errors.append(error_msg)
print(f"{Fore.RED}❌ {error_msg}{Style.RESET_ALL}")
return False
def check_dependencies(self) -> bool:
"""
Verifica e instala las dependencias requeridas.
Returns:
True si todas las dependencias están disponibles
"""
print(f"{Fore.BLUE}📦 Verificando dependencias...{Style.RESET_ALL}")
requirements_file = self.project_root / "requirements.txt"
if not requirements_file.exists():
error_msg = "Archivo requirements.txt no encontrado"
self.errors.append(error_msg)
print(f"{Fore.RED}❌ {error_msg}{Style.RESET_ALL}")
return False
try:
# Instalar dependencias
print(f"{Fore.YELLOW}📥 Instalando dependencias...{Style.RESET_ALL}")
result = subprocess.run(
[sys.executable, "-m", "pip", "install", "-r", str(requirements_file)],
capture_output=True,
text=True,
check=True
)
print(f"{Fore.GREEN}✅ Dependencias instaladas correctamente{Style.RESET_ALL}")
return True
except subprocess.CalledProcessError as e:
error_msg = f"Error al instalar dependencias: {e.stderr}"
self.errors.append(error_msg)
print(f"{Fore.RED}❌ {error_msg}{Style.RESET_ALL}")
return False
def setup_environment_file(self) -> bool:
"""
Configura el archivo .env si no existe.
Returns:
True si la configuración fue exitosa
"""
print(f"{Fore.BLUE}⚙️ Configurando archivo de entorno...{Style.RESET_ALL}")
env_file = self.project_root / ".env"
env_example = self.project_root / ".env.example"
if env_file.exists():
print(f"{Fore.YELLOW}⚠️ El archivo .env ya existe{Style.RESET_ALL}")
return True
if not env_example.exists():
warning_msg = "Archivo .env.example no encontrado"
self.warnings.append(warning_msg)
print(f"{Fore.YELLOW}⚠️ {warning_msg}{Style.RESET_ALL}")
# Crear .env básico
self._create_basic_env_file(env_file)
else:
# Copiar desde .env.example
shutil.copy2(env_example, env_file)
print(f"{Fore.GREEN}✅ Archivo .env creado desde .env.example{Style.RESET_ALL}")
# Solicitar API key si no está configurada
self._configure_api_key(env_file)
return True
def _create_basic_env_file(self, env_file: Path) -> None:
"""
Crea un archivo .env básico.
Args:
env_file: Ruta del archivo .env
"""
basic_config = """# Google Generative AI Configuration
GOOGLE_API_KEY=your_api_key_here
# Fine-tuning Configuration
GEMINI_MODEL=gemini-1.5-flash
DATASET_DIR=final_datasets
OUTPUT_DIR=models
# Training Parameters
EPOCHS=3
BATCH_SIZE=32
LEARNING_RATE=auto
# Logging Configuration
LOG_LEVEL=INFO
LOG_FILE=fine_tuning.log
# Evaluation Configuration
EVAL_THRESHOLD=0.8
EVAL_SAMPLE_SIZE=100
"""
with open(env_file, 'w', encoding='utf-8') as f:
f.write(basic_config)
print(f"{Fore.GREEN}✅ Archivo .env básico creado{Style.RESET_ALL}")
def _configure_api_key(self, env_file: Path) -> None:
"""
Configura la API key de Google si no está presente.
Args:
env_file: Ruta del archivo .env
"""
# Leer archivo actual
with open(env_file, 'r', encoding='utf-8') as f:
content = f.read()
# Verificar si ya tiene una API key válida
if 'GOOGLE_API_KEY=' in content:
lines = content.split('\n')
for line in lines:
if line.startswith('GOOGLE_API_KEY='):
api_key = line.split('=', 1)[1].strip()
if api_key and api_key != 'your_api_key_here' and len(api_key) > 30:
print(f"{Fore.GREEN}✅ API key ya configurada{Style.RESET_ALL}")
return
# Solicitar API key
print(f"\n{Fore.YELLOW}🔑 Configuración de API Key de Google{Style.RESET_ALL}")
print(f"{Fore.CYAN}Para obtener tu API key:{Style.RESET_ALL}")
print(f" 1. Visita: https://aistudio.google.com/app/apikey")
print(f" 2. Crea una nueva API key")
print(f" 3. Copia la key generada")
api_key = input(f"\n{Fore.YELLOW}Introduce tu API key de Google (o presiona Enter para omitir): {Style.RESET_ALL}").strip()
if api_key:
# Actualizar archivo .env
updated_content = content.replace(
'GOOGLE_API_KEY=your_api_key_here',
f'GOOGLE_API_KEY={api_key}'
)
# Si no encontró la línea, agregarla
if 'your_api_key_here' not in content:
if 'GOOGLE_API_KEY=' in content:
import re
updated_content = re.sub(
r'GOOGLE_API_KEY=.*',
f'GOOGLE_API_KEY={api_key}',
content
)
else:
updated_content = f'GOOGLE_API_KEY={api_key}\n' + content
with open(env_file, 'w', encoding='utf-8') as f:
f.write(updated_content)
print(f"{Fore.GREEN}✅ API key configurada{Style.RESET_ALL}")
else:
warning_msg = "API key no configurada. Configúrala manualmente en .env"
self.warnings.append(warning_msg)
print(f"{Fore.YELLOW}⚠️ {warning_msg}{Style.RESET_ALL}")
def validate_project_structure(self) -> bool:
"""
Valida que la estructura del proyecto sea correcta.
Returns:
True si la estructura es válida
"""
print(f"{Fore.BLUE}📁 Validando estructura del proyecto...{Style.RESET_ALL}")
required_files = [
"fine_tune_gemini.py",
"evaluate_model.py",
"test_interface.py",
"utils/gemini_helper.py",
"requirements.txt"
]
required_dirs = [
"utils",
"final_datasets",
"models"
]
missing_files = []
missing_dirs = []
# Verificar archivos
for file_path in required_files:
full_path = self.project_root / file_path
if not full_path.exists():
missing_files.append(file_path)
# Verificar directorios
for dir_path in required_dirs:
full_path = self.project_root / dir_path
if not full_path.exists():
missing_dirs.append(dir_path)
# Crear directorio si es necesario
full_path.mkdir(parents=True, exist_ok=True)
print(f"{Fore.YELLOW}📁 Directorio creado: {dir_path}{Style.RESET_ALL}")
# Reportar archivos faltantes
if missing_files:
for file_path in missing_files:
error_msg = f"Archivo requerido no encontrado: {file_path}"
self.errors.append(error_msg)
print(f"{Fore.RED}❌ {error_msg}{Style.RESET_ALL}")
# Verificar datasets
self._validate_datasets()
return len(missing_files) == 0
def _validate_datasets(self) -> None:
"""Valida que los datasets estén presentes."""
dataset_dir = self.project_root / "final_datasets"
required_datasets = ["train.json", "validation.json", "test.json"]
for dataset in required_datasets:
dataset_path = dataset_dir / dataset
if dataset_path.exists():
print(f"{Fore.GREEN}✅ Dataset encontrado: {dataset}{Style.RESET_ALL}")
else:
warning_msg = f"Dataset no encontrado: {dataset}"
self.warnings.append(warning_msg)
print(f"{Fore.YELLOW}⚠️ {warning_msg}{Style.RESET_ALL}")
def test_api_connection(self) -> bool:
"""
Prueba la conexión con la API de Gemini.
Returns:
True si la conexión es exitosa
"""
print(f"{Fore.BLUE}🌐 Probando conexión con API de Gemini...{Style.RESET_ALL}")
try:
# Importar y probar helper
from utils.gemini_helper import validate_environment, GeminiHelper
if not validate_environment():
error_msg = "Validación del entorno falló"
self.errors.append(error_msg)
print(f"{Fore.RED}❌ {error_msg}{Style.RESET_ALL}")
return False
# Probar conexión
helper = GeminiHelper()
if helper.validate_api_connection():
print(f"{Fore.GREEN}✅ Conexión con API exitosa{Style.RESET_ALL}")
return True
else:
error_msg = "No se pudo conectar con la API de Gemini"
self.errors.append(error_msg)
print(f"{Fore.RED}❌ {error_msg}{Style.RESET_ALL}")
return False
except Exception as e:
error_msg = f"Error al probar conexión: {e}"
self.errors.append(error_msg)
print(f"{Fore.RED}❌ {error_msg}{Style.RESET_ALL}")
return False
def create_usage_guide(self) -> None:
"""Crea una guía de uso rápida."""
guide_content = """# 🚀 Guía de Uso Rápida
## Configuración Inicial
1. **Verificar configuración**:
```bash
python setup_environment.py
```
2. **Configurar API Key** (si no se hizo automáticamente):
- Edita el archivo `.env`
- Cambia `GOOGLE_API_KEY=your_api_key_here` por tu API key real
## Uso Principal
### 1. Fine-tuning del Modelo
```bash
# Fine-tuning completo
python fine_tune_gemini.py
# Solo evaluación del modelo base
python fine_tune_gemini.py --eval-only
```
### 2. Evaluación Detallada
```bash
# Evaluación completa
python evaluate_model.py
# Evaluación con muestra específica
python evaluate_model.py --sample-size 50
```
### 3. Interfaz de Pruebas
```bash
# Modo interactivo
python test_interface.py
# Prueba única
python test_interface.py --single-test "Texto con repeticionesss"
# Testing en lote
python test_interface.py --batch-file datos/test.json
```
## Estructura de Archivos
- `fine_tune_gemini.py` - Script principal de fine-tuning
- `evaluate_model.py` - Sistema de evaluación
- `test_interface.py` - Interfaz interactiva de pruebas
- `utils/gemini_helper.py` - Utilidades para API de Gemini
- `final_datasets/` - Datasets de entrenamiento
- `models/` - Modelos y resultados
## Configuración Avanzada
Edita el archivo `.env` para personalizar:
- Número de epochs
- Tamaño de batch
- Directorios de entrada y salida
- Nivel de logging
## Troubleshooting
### Error de API Key
- Verifica que tu API key sea válida
- Asegúrate de tener créditos en Google AI Studio
### Error de Dependencias
```bash
pip install -r requirements.txt
```
### Datasets No Encontrados
- Verifica que existan los archivos en `final_datasets/`
- Ejecuta `python data_generator.py` si es necesario
"""
guide_file = self.project_root / "QUICK_START.md"
with open(guide_file, 'w', encoding='utf-8') as f:
f.write(guide_content)
print(f"{Fore.GREEN}✅ Guía de uso creada: QUICK_START.md{Style.RESET_ALL}")
def run_setup(self) -> bool:
"""
Ejecuta la configuración completa del entorno.
Returns:
True si la configuración fue exitosa
"""
print(f"{Fore.CYAN}🚀 Iniciando configuración del entorno...{Style.RESET_ALL}\n")
steps = [
("Verificar Python", self.check_python_version),
("Instalar dependencias", self.check_dependencies),
("Configurar entorno", self.setup_environment_file),
("Validar estructura", self.validate_project_structure),
("Probar API", self.test_api_connection)
]
success_count = 0
for step_name, step_func in steps:
print(f"\n{Fore.BLUE}{'='*60}{Style.RESET_ALL}")
print(f"{Fore.BLUE}🔧 {step_name}...{Style.RESET_ALL}")
print(f"{Fore.BLUE}{'='*60}{Style.RESET_ALL}")
try:
if step_func():
success_count += 1
print(f"{Fore.GREEN}✅ {step_name} completado{Style.RESET_ALL}")
else:
print(f"{Fore.RED}❌ {step_name} falló{Style.RESET_ALL}")
except Exception as e:
error_msg = f"Error en {step_name}: {e}"
self.errors.append(error_msg)
print(f"{Fore.RED}❌ {error_msg}{Style.RESET_ALL}")
# Crear guía de uso
print(f"\n{Fore.BLUE}{'='*60}{Style.RESET_ALL}")
print(f"{Fore.BLUE}🔧 Creando guía de uso...{Style.RESET_ALL}")
print(f"{Fore.BLUE}{'='*60}{Style.RESET_ALL}")
self.create_usage_guide()
# Mostrar resumen
self._show_setup_summary(success_count, len(steps))
return success_count == len(steps) and len(self.errors) == 0
def _show_setup_summary(self, success_count: int, total_steps: int) -> None:
"""
Muestra un resumen de la configuración.
Args:
success_count: Número de pasos exitosos
total_steps: Total de pasos
"""
print(f"\n{Fore.CYAN}{'='*80}{Style.RESET_ALL}")
print(f"{Fore.CYAN}📊 RESUMEN DE CONFIGURACIÓN{Style.RESET_ALL}")
print(f"{Fore.CYAN}{'='*80}{Style.RESET_ALL}")
print(f"{Fore.YELLOW}Pasos completados: {success_count}/{total_steps}{Style.RESET_ALL}")
if self.errors:
print(f"\n{Fore.RED}❌ ERRORES ENCONTRADOS:{Style.RESET_ALL}")
for error in self.errors:
print(f" • {error}")
if self.warnings:
print(f"\n{Fore.YELLOW}⚠️ ADVERTENCIAS:{Style.RESET_ALL}")
for warning in self.warnings:
print(f" • {warning}")
if success_count == total_steps and not self.errors:
print(f"\n{Fore.GREEN}🎉 ¡CONFIGURACIÓN COMPLETADA EXITOSAMENTE!{Style.RESET_ALL}")
print(f"\n{Fore.CYAN}🚀 Próximos pasos:{Style.RESET_ALL}")
print(f" 1. Revisa el archivo QUICK_START.md")
print(f" 2. Ejecuta: python fine_tune_gemini.py --eval-only")
print(f" 3. Prueba la interfaz: python test_interface.py")
else:
print(f"\n{Fore.RED}⚠️ CONFIGURACIÓN INCOMPLETA{Style.RESET_ALL}")
print(f"{Fore.YELLOW}Revisa los errores y ejecuta el script nuevamente{Style.RESET_ALL}")
def main():
"""Función principal del script."""
try:
setup = EnvironmentSetup()
success = setup.run_setup()
return 0 if success else 1
except KeyboardInterrupt:
print(f"\n\n{Fore.YELLOW}⚠️ Configuración cancelada por el usuario{Style.RESET_ALL}")
return 1
except Exception as e:
print(f"\n{Fore.RED}❌ Error fatal durante la configuración: {e}{Style.RESET_ALL}")
return 1
if __name__ == "__main__":
exit(main())