jarondon82 commited on
Commit
280df10
·
1 Parent(s): 4f233fb

Solución actualizada para compatibilidad con TensorFlow y Keras

Browse files
Files changed (4) hide show
  1. app.py +23 -48
  2. deepface_patch.py +100 -0
  3. packages.txt +4 -1
  4. requirements.txt +2 -1
app.py CHANGED
@@ -9,6 +9,10 @@ except ImportError:
9
  os.system("pip install streamlit>=1.31.0")
10
  import streamlit as st
11
 
 
 
 
 
12
  # Configura mensaje de error personalizado para dlib
13
  try:
14
  import dlib
@@ -17,61 +21,32 @@ except ImportError:
17
  DLIB_AVAILABLE = False
18
  print("Warning: dlib no está disponible. Algunas funciones pueden estar limitadas.")
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  # Asegurar que los archivos necesarios estén disponibles
21
  required_model_files = [
22
  "deploy.prototxt",
23
- "res10_300x300_ssd_iter_140000_fp16.caffemodel"
 
24
  ]
25
 
26
  for model_file in required_model_files:
27
  if not os.path.exists(model_file):
28
- model_dir = "models"
29
- if not os.path.exists(model_dir):
30
- os.makedirs(model_dir)
31
-
32
- if model_file == "deploy.prototxt":
33
- # Crear el archivo deploy.prototxt manualmente
34
- with open(os.path.join(model_dir, model_file), "w") as f:
35
- f.write("""name: "deploy"
36
- input: "data"
37
- input_shape {
38
- dim: 1
39
- dim: 3
40
- dim: 300
41
- dim: 300
42
- }
43
- layer {
44
- name: "conv1_1"
45
- type: "Convolution"
46
- bottom: "data"
47
- top: "conv1_1"
48
- param {
49
- lr_mult: 1
50
- decay_mult: 1
51
- }
52
- param {
53
- lr_mult: 2
54
- decay_mult: 0
55
- }
56
- convolution_param {
57
- num_output: 64
58
- kernel_size: 3
59
- pad: 1
60
- weight_filler {
61
- type: "xavier"
62
- }
63
- bias_filler {
64
- type: "constant"
65
- value: 0
66
- }
67
- }
68
- }
69
- # Continuar con el resto del modelo, pero simplificado por brevedad
70
- """)
71
- print(f"Created {model_file}")
72
- else:
73
- # Para el caffemodel, informamos que se descargará automáticamente mediante DeepFace
74
- print(f"Note: {model_file} will be downloaded automatically when needed")
75
 
76
  # Importa la aplicación principal
77
  from streamlit_app import main
 
9
  os.system("pip install streamlit>=1.31.0")
10
  import streamlit as st
11
 
12
+ # Configura variables de entorno para TensorFlow
13
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Reducir mensajes de TensorFlow
14
+ os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # Forzar CPU para evitar problemas con GPU en entornos cloud
15
+
16
  # Configura mensaje de error personalizado para dlib
17
  try:
18
  import dlib
 
21
  DLIB_AVAILABLE = False
22
  print("Warning: dlib no está disponible. Algunas funciones pueden estar limitadas.")
23
 
24
+ # Verificar TensorFlow y configurar ambiente
25
+ try:
26
+ import tensorflow as tf
27
+ tf_version = tf.__version__
28
+ print(f"TensorFlow version: {tf_version}")
29
+ except Exception as e:
30
+ print(f"Warning: TensorFlow initialization error: {e}")
31
+
32
+ # Aplicar parches para DeepFace y RetinaFace
33
+ try:
34
+ # Intenta importar y aplicar parches
35
+ import deepface_patch
36
+ deepface_patch.apply_patches()
37
+ except Exception as e:
38
+ print(f"Warning: Failed to apply patches: {e}")
39
+
40
  # Asegurar que los archivos necesarios estén disponibles
41
  required_model_files = [
42
  "deploy.prototxt",
43
+ "res10_300x300_ssd_iter_140000.caffemodel",
44
+ "shape_predictor_68_face_landmarks.dat"
45
  ]
46
 
47
  for model_file in required_model_files:
48
  if not os.path.exists(model_file):
49
+ print(f"Note: {model_file} will be downloaded automatically when needed")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
  # Importa la aplicación principal
52
  from streamlit_app import main
deepface_patch.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Módulo para parchear DeepFace y RetinaFace para compatibilidad con diferentes versiones de TensorFlow
3
+ """
4
+ import os
5
+ import sys
6
+ import importlib
7
+ import warnings
8
+
9
+ def patch_retina_face():
10
+ """Parchea RetinaFace para funcionar con Keras independiente o integrado en TensorFlow"""
11
+ try:
12
+ # Verificar si podemos importar retina_face
13
+ import retina_face
14
+
15
+ # Verificar la versión de TensorFlow
16
+ import tensorflow as tf
17
+ tf_version = tf.__version__
18
+
19
+ # Para TF 2.15.x, usamos keras estándar
20
+ if tf_version.startswith('2.15'):
21
+ try:
22
+ import keras
23
+ print(f"Using standard Keras {keras.__version__} with TensorFlow {tf_version}")
24
+
25
+ # Monkeypatch para RetinaFace si es necesario
26
+ try:
27
+ # Intentar importar el módulo que podría usar keras
28
+ from retina_face.commons import postprocess
29
+ if not hasattr(postprocess, '_keras_patched'):
30
+ # Verificar si está usando tf.keras
31
+ if hasattr(postprocess, 'keras') and postprocess.keras.__name__ == 'tensorflow.keras':
32
+ print("Patching RetinaFace to use standard keras instead of tf.keras")
33
+ postprocess.keras = keras
34
+ postprocess._keras_patched = True
35
+ except ImportError:
36
+ pass
37
+ except ImportError:
38
+ print("Standard Keras not found, using tf.keras")
39
+
40
+ # Para TF 2.19.x, necesitamos tf-keras
41
+ elif tf_version.startswith('2.19'):
42
+ try:
43
+ import tf_keras
44
+ print(f"Using tf-keras with TensorFlow {tf_version}")
45
+
46
+ # Monkeypatch para RetinaFace si es necesario
47
+ try:
48
+ from retina_face.commons import postprocess
49
+ if not hasattr(postprocess, '_keras_patched'):
50
+ if hasattr(postprocess, 'keras'):
51
+ print("Patching RetinaFace to use tf-keras")
52
+ postprocess.keras = tf_keras
53
+ postprocess._keras_patched = True
54
+ except ImportError:
55
+ pass
56
+ except ImportError:
57
+ print("Warning: tf-keras not installed. RetinaFace may not work properly.")
58
+
59
+ except ImportError as e:
60
+ print(f"Warning: Could not patch RetinaFace: {e}")
61
+
62
+ def patch_deepface():
63
+ """Parchea DeepFace para funcionar con diferentes versiones de TensorFlow"""
64
+ try:
65
+ import deepface
66
+ import tensorflow as tf
67
+ tf_version = tf.__version__
68
+
69
+ if tf_version.startswith('2.19'):
70
+ try:
71
+ import tf_keras
72
+ # Intentar parchear los módulos relevantes de DeepFace
73
+ deepface_modules = [
74
+ 'deepface.commons.functions',
75
+ 'deepface.detectors.RetinaFaceWrapper',
76
+ 'deepface.detectors.FaceDetector'
77
+ ]
78
+
79
+ for module_name in deepface_modules:
80
+ try:
81
+ module = importlib.import_module(module_name)
82
+ if hasattr(module, 'keras') and module.keras.__name__ == 'tensorflow.keras':
83
+ module.keras = tf_keras
84
+ print(f"Patched {module_name} to use tf-keras")
85
+ except (ImportError, AttributeError):
86
+ pass
87
+ except ImportError:
88
+ print("Warning: tf-keras not installed. DeepFace may not work properly with TF 2.19")
89
+ except ImportError as e:
90
+ print(f"Warning: Could not patch DeepFace: {e}")
91
+
92
+ def apply_patches():
93
+ """Aplica todos los parches necesarios"""
94
+ warnings.filterwarnings('ignore') # Reducir mensajes de advertencia
95
+ patch_retina_face()
96
+ patch_deepface()
97
+ print("Patches applied successfully")
98
+
99
+ if __name__ == "__main__":
100
+ apply_patches()
packages.txt CHANGED
@@ -6,4 +6,7 @@ libxext6
6
  libx11-6
7
  libcairo2
8
  ffmpeg
9
- cmake
 
 
 
 
6
  libx11-6
7
  libcairo2
8
  ffmpeg
9
+ cmake
10
+ libatk1.0-0
11
+ libatk-bridge2.0-0
12
+ libhdf5-dev
requirements.txt CHANGED
@@ -6,7 +6,8 @@ scikit-learn>=1.0.0
6
  matplotlib>=3.5.0
7
  pandas>=1.3.0
8
  deepface>=0.0.79
9
- tensorflow>=2.8.0
 
10
  scipy>=1.7.0
11
  mtcnn>=0.1.0
12
  retina-face>=0.0.1
 
6
  matplotlib>=3.5.0
7
  pandas>=1.3.0
8
  deepface>=0.0.79
9
+ tensorflow==2.15.0
10
+ keras==2.15.0
11
  scipy>=1.7.0
12
  mtcnn>=0.1.0
13
  retina-face>=0.0.1