-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall_facial_recognition.py
More file actions
326 lines (265 loc) · 10.9 KB
/
install_facial_recognition.py
File metadata and controls
326 lines (265 loc) · 10.9 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
#!/usr/bin/env python3
"""
DETECCIÓN_SYX - Instalador de Reconocimiento Facial
Script especializado para instalar dependencias de IA avanzada
"""
import os
import sys
import subprocess
import platform
import time
class Colors:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
BOLD = '\033[1m'
END = '\033[0m'
def print_header():
"""Mostrar header del instalador"""
os.system('cls' if os.name == 'nt' else 'clear')
print(f"{Colors.CYAN}{Colors.BOLD}")
print("╔" + "═" * 78 + "╗")
print("║" + " " * 78 + "║")
print("║" + "DETECCIÓN_SYX - INSTALADOR IA AVANZADA".center(78) + "║")
print("║" + "Reconocimiento Facial Inteligente".center(78) + "║")
print("║" + " " * 78 + "║")
print("╚" + "═" * 78 + "╝")
print(f"{Colors.END}\n")
def log(message, level="INFO"):
"""Logging con colores"""
if level == "INFO":
color = Colors.GREEN
icon = "✅"
elif level == "WARNING":
color = Colors.YELLOW
icon = "⚠️"
elif level == "ERROR":
color = Colors.RED
icon = "❌"
elif level == "PROCESS":
color = Colors.BLUE
icon = "🔄"
else:
color = Colors.WHITE
icon = "📋"
print(f"{color}{icon} {message}{Colors.END}")
def run_command(command, description, timeout=300):
"""Ejecutar comando con timeout"""
log(f"Ejecutando: {description}", "PROCESS")
try:
if isinstance(command, str):
result = subprocess.run(command, shell=True, check=True,
capture_output=True, text=True, timeout=timeout)
else:
result = subprocess.run(command, check=True,
capture_output=True, text=True, timeout=timeout)
log(f"Completado: {description}")
return True, result.stdout
except subprocess.TimeoutExpired:
log(f"Timeout en: {description}", "ERROR")
return False, f"Timeout después de {timeout} segundos"
except subprocess.CalledProcessError as e:
log(f"Error en: {description}", "ERROR")
return False, e.stderr
except Exception as e:
log(f"Error inesperado: {description} - {e}", "ERROR")
return False, str(e)
def check_system_info():
"""Verificar información del sistema"""
log("Verificando sistema...")
system_info = {
'os': platform.system(),
'architecture': platform.machine(),
'python_version': sys.version,
'pip_available': False
}
log(f"Sistema operativo: {system_info['os']}")
log(f"Arquitectura: {system_info['architecture']}")
log(f"Python: {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}")
# Verificar pip
success, _ = run_command([sys.executable, "-m", "pip", "--version"], "Verificar pip", timeout=10)
system_info['pip_available'] = success
return system_info
def install_basic_dependencies():
"""Instalar dependencias básicas"""
log("Instalando dependencias básicas...", "PROCESS")
basic_deps = [
"numpy",
"Pillow",
"opencv-python"
]
for dep in basic_deps:
log(f"Instalando {dep}...")
success, output = run_command(
[sys.executable, "-m", "pip", "install", "--upgrade", dep],
f"Instalar {dep}",
timeout=120
)
if success:
log(f"{dep} instalado correctamente")
else:
log(f"Error instalando {dep}: {output}", "ERROR")
return False
return True
def install_cmake_if_needed():
"""Instalar CMake si es necesario (para dlib)"""
system_os = platform.system()
if system_os == "Windows":
log("En Windows, instala Visual Studio Build Tools si hay errores", "WARNING")
log("Descarga: https://visualstudio.microsoft.com/visual-cpp-build-tools/", "WARNING")
return True
elif system_os == "Darwin": # macOS
log("Verificando CMake en macOS...")
success, _ = run_command(["which", "cmake"], "Verificar CMake", timeout=10)
if not success:
log("CMake no encontrado, intentando instalar...", "WARNING")
# Intentar instalar con brew
success, _ = run_command(["brew", "install", "cmake"], "Instalar CMake", timeout=180)
if not success:
log("No se pudo instalar CMake automáticamente", "WARNING")
log("Instala manualmente: brew install cmake", "WARNING")
return False
log("CMake disponible")
return True
else: # Linux
log("Verificando dependencias de desarrollo en Linux...")
# Detectar distribución
distro_commands = {
'ubuntu': ['sudo', 'apt-get', 'install', '-y', 'build-essential', 'cmake', 'libopenblas-dev', 'liblapack-dev'],
'centos': ['sudo', 'yum', 'install', '-y', 'gcc', 'gcc-c++', 'cmake', 'openblas-devel', 'lapack-devel'],
'fedora': ['sudo', 'dnf', 'install', '-y', 'gcc', 'gcc-c++', 'cmake', 'openblas-devel', 'lapack-devel']
}
log("Si hay errores, instala manualmente:", "WARNING")
log("Ubuntu/Debian: sudo apt-get install build-essential cmake", "WARNING")
log("CentOS/RHEL: sudo yum install gcc gcc-c++ cmake", "WARNING")
return True
def install_dlib():
"""Instalar dlib (requerido para face_recognition)"""
log("Instalando dlib (puede tardar varios minutos)...", "PROCESS")
# Intentar instalar dlib precompilado primero
success, output = run_command(
[sys.executable, "-m", "pip", "install", "--upgrade", "dlib"],
"Instalar dlib precompilado",
timeout=600 # 10 minutos
)
if success:
log("dlib instalado correctamente")
return True
log("Error instalando dlib precompilado, intentando compilar...", "WARNING")
# Si falla, intentar con opciones de compilación
compile_commands = [
[sys.executable, "-m", "pip", "install", "dlib", "--verbose"],
[sys.executable, "-m", "pip", "install", "dlib", "--no-cache-dir"],
[sys.executable, "-m", "pip", "install", "dlib", "--no-binary", ":all:"]
]
for i, cmd in enumerate(compile_commands, 1):
log(f"Intento {i}/3 de compilación...")
success, output = run_command(cmd, f"Compilar dlib (intento {i})", timeout=900)
if success:
log("dlib compilado e instalado correctamente")
return True
log("No se pudo instalar dlib", "ERROR")
return False
def install_face_recognition():
"""Instalar face_recognition"""
log("Instalando face_recognition...", "PROCESS")
success, output = run_command(
[sys.executable, "-m", "pip", "install", "--upgrade", "face_recognition"],
"Instalar face_recognition",
timeout=300
)
if success:
log("face_recognition instalado correctamente")
return True
else:
log(f"Error instalando face_recognition: {output}", "ERROR")
return False
def test_installation():
"""Probar la instalación"""
log("Probando instalación...", "PROCESS")
test_code = '''
import cv2
import face_recognition
import numpy as np
print("✅ Todas las dependencias funcionan correctamente")
print(f"OpenCV: {cv2.__version__}")
print(f"NumPy: {np.__version__}")
print("face_recognition: OK")
'''
try:
exec(test_code)
log("¡Instalación exitosa! Todas las dependencias funcionan")
return True
except Exception as e:
log(f"Error en prueba: {e}", "ERROR")
return False
def show_post_install_instructions():
"""Mostrar instrucciones post-instalación"""
print(f"\n{Colors.GREEN}{Colors.BOLD}🎉 INSTALACIÓN COMPLETADA{Colors.END}")
print(f"\n{Colors.CYAN}📋 PRÓXIMOS PASOS:{Colors.END}")
print(f"1. {Colors.YELLOW}Agregar personas al sistema:{Colors.END}")
print(f" python add_person.py")
print(f"2. {Colors.YELLOW}Ejecutar reconocimiento facial:{Colors.END}")
print(f" python src/main.py")
print(f"3. {Colors.YELLOW}Probar el sistema:{Colors.END}")
print(f" python -c \"from src.services.ai.facial_recognition import test_facial_recognition; test_facial_recognition()\"")
print(f"\n{Colors.MAGENTA}🔧 COMANDOS ÚTILES:{Colors.END}")
print(f" - Agregar persona rápido: {Colors.WHITE}python add_person.py 'Nombre' imagen.jpg{Colors.END}")
print(f" - Ver estadísticas: {Colors.WHITE}python add_person.py{Colors.END} (opción 3)")
print(f"\n{Colors.RED}⚠️ IMPORTANTE:{Colors.END}")
print(f" - Asegúrate de tener una cámara web conectada")
print(f" - Las primeras detecciones pueden ser lentas")
print(f" - Usa fotos claras y bien iluminadas para mejores resultados")
def main():
"""Función principal del instalador"""
print_header()
log("Iniciando instalación de IA avanzada para DETECCIÓN_SYX")
try:
# Verificar sistema
system_info = check_system_info()
if not system_info['pip_available']:
log("pip no está disponible", "ERROR")
return False
# Instalar dependencias básicas
if not install_basic_dependencies():
log("Error instalando dependencias básicas", "ERROR")
return False
# Configurar CMake si es necesario
if not install_cmake_if_needed():
log("Advertencia: Puede haber problemas compilando dlib", "WARNING")
# Instalar dlib
if not install_dlib():
log("Error instalando dlib", "ERROR")
log("Puedes intentar instalarlo manualmente:", "WARNING")
log("conda install -c conda-forge dlib", "WARNING")
return False
# Instalar face_recognition
if not install_face_recognition():
log("Error instalando face_recognition", "ERROR")
return False
# Probar instalación
if not test_installation():
log("Error en prueba final", "ERROR")
return False
# Mostrar instrucciones
show_post_install_instructions()
return True
except KeyboardInterrupt:
log("Instalación cancelada por usuario", "WARNING")
return False
except Exception as e:
log(f"Error inesperado: {e}", "ERROR")
return False
if __name__ == "__main__":
success = main()
if success:
print(f"\n{Colors.GREEN}✅ Instalación completada exitosamente{Colors.END}")
else:
print(f"\n{Colors.RED}❌ Error en la instalación{Colors.END}")
print(f"{Colors.YELLOW}Consulta la documentación para instalación manual{Colors.END}")
input("\nPresiona ENTER para continuar...")
sys.exit(0 if success else 1)