Bmo411 commited on
Commit
3575b55
verified
1 Parent(s): 9d2d3c1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -90
app.py CHANGED
@@ -6,28 +6,11 @@ from huggingface_hub import hf_hub_download
6
  import time
7
  import os
8
 
9
- # Registrar las funciones personalizadas
10
- from tensorflow.keras.saving import register_keras_serializable
11
-
12
- @register_keras_serializable()
13
- def fourier_transform(x):
14
- fourier = tf.signal.fft2d(tf.cast(x, tf.complex64))
15
- fourier = tf.complex(tf.math.real(fourier), tf.math.imag(fourier))
16
- fourier = tf.abs(fourier)
17
- return tf.concat([tf.math.real(fourier), tf.math.imag(fourier)], axis=-1)
18
-
19
- @register_keras_serializable()
20
- def inverse_fourier_transform(x):
21
- real_part, imag_part = tf.split(x, num_or_size_splits=2, axis=-1)
22
- complex_fourier = tf.complex(real_part, imag_part)
23
- return tf.abs(tf.signal.ifft2d(complex_fourier))
24
-
25
  # Configuraci贸n de GPU para TensorFlow
26
  physical_devices = tf.config.list_physical_devices('GPU')
27
  if physical_devices:
28
  print("GPU disponible. Configurando...")
29
  try:
30
- # Permitir crecimiento de memoria seg煤n sea necesario
31
  for gpu in physical_devices:
32
  tf.config.experimental.set_memory_growth(gpu, True)
33
  print("Configuraci贸n de GPU completada")
@@ -36,67 +19,79 @@ if physical_devices:
36
  else:
37
  print("No se detect贸 GPU. El procesamiento ser谩 m谩s lento.")
38
 
39
- # IMPORTANTE: Habilitar deserializaci贸n insegura para capas Lambda
40
- try:
41
- # Para TensorFlow 2.11+
42
- if hasattr(tf.keras.config, 'enable_unsafe_deserialization'):
43
- tf.keras.config.enable_unsafe_deserialization()
44
- print("Deserializaci贸n insegura habilitada mediante tf.keras.config")
45
- # Para versiones antiguas, intentar Keras directamente
46
- elif hasattr(tf.keras.utils, 'enable_unsafe_deserialization'):
47
- tf.keras.utils.enable_unsafe_deserialization()
48
- print("Deserializaci贸n insegura habilitada mediante tf.keras.utils")
49
- else:
50
- print("No se pudo habilitar la deserializaci贸n insegura autom谩ticamente")
51
- except Exception as e:
52
- print(f"Error al configurar deserializaci贸n: {e}")
53
-
54
- # Descargar modelo desde Hugging Face (con cach茅)
55
- cache_dir = os.path.join(os.path.expanduser("~"), ".cache", "huggingface")
56
- model_path = hf_hub_download(
57
- repo_id="Bmo411/DenoisingAutoencoder",
58
- filename="autoencoder_complete_model_Fourier.keras",
59
- cache_dir=cache_dir
60
- )
61
- print(f"Modelo cargado desde: {model_path}")
62
-
63
- # Cargar el modelo con desactivaci贸n de safety
64
- try:
65
- # Intentar cargar con custom_objects para las funciones personalizadas
66
- model = tf.keras.models.load_model(
67
- model_path,
68
- custom_objects={
69
- 'fourier_transform': fourier_transform,
70
- 'inverse_fourier_transform': inverse_fourier_transform
71
- },
72
- compile=False # No compilar el modelo para inferencia m谩s r谩pida
73
- )
74
- print("Modelo cargado correctamente")
75
- except Exception as e:
76
- print(f"Error al cargar el modelo: {e}")
77
- # Alternativa fallback para versiones m谩s recientes de TF
78
- try:
79
- options = tf.saved_model.LoadOptions(
80
- experimental_io_device='/job:localhost'
81
- )
82
- model = tf.keras.models.load_model(
83
- model_path,
84
- custom_objects={
85
- 'fourier_transform': fourier_transform,
86
- 'inverse_fourier_transform': inverse_fourier_transform
87
- },
88
- compile=False,
89
- options=options
90
- )
91
- print("Modelo cargado con opciones alternativas")
92
- except Exception as e2:
93
- print(f"Error al cargar el modelo con opciones alternativas: {e2}")
94
- raise Exception("No se pudo cargar el modelo")
95
-
96
- # Crear versi贸n optimizada para inferencia
97
- @tf.function
98
- def predict_optimized(input_tensor):
99
- return model(input_tensor, training=False)
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
  # Funciones de preprocesamiento optimizadas
102
  def degrade_image(image, downscale_factor=4):
@@ -143,12 +138,13 @@ def preprocess_image(image, std_dev=0.1, downscale_factor=4, target_size=(256, 2
143
 
144
  return noisy_img
145
 
146
- # Variable para medir el tiempo total de la primera ejecuci贸n
147
- first_run = True
 
148
 
 
149
  def Denoiser(imagen):
150
  """Aplica el modelo autoencoder para eliminar ruido de la imagen."""
151
- global first_run
152
 
153
  # Verificar que la imagen no sea None
154
  if imagen is None:
@@ -171,17 +167,12 @@ def Denoiser(imagen):
171
  # Medir el tiempo de la predicci贸n
172
  start_time = time.time()
173
 
174
- # Predecir con el autoencoder
175
- # Usar llamada directa en lugar de predict() para m谩s velocidad
176
  reconstructed = model(noisy_image_input, training=False).numpy()[0]
177
 
178
  prediction_time = time.time() - start_time
179
-
180
- if first_run:
181
- print(f"Primera ejecuci贸n: {prediction_time:.2f} segundos")
182
- first_run = False
183
- else:
184
- print(f"Tiempo de predicci贸n: {prediction_time:.2f} segundos")
185
 
186
  # Asegurarse de que las im谩genes est茅n en el rango [0, 255]
187
  noisy_image = np.uint8(noisy_image * 255)
@@ -202,7 +193,8 @@ demo = gr.Interface(
202
  gr.Image(type="numpy", label="Imagen Restaurada")
203
  ],
204
  title="Autoencoder para Denoising",
205
- description="Este modelo de autoencoder reduce el ruido en im谩genes. Sube una imagen y el modelo generar谩 una versi贸n restaurada.",
 
206
  examples=[
207
  "https://raw.githubusercontent.com/gradio-app/gradio/main/demo/english_htr/images/Create%20a%20free%20Gradio%20account%20to%20access%20our%20most%20powerful%20features.jpeg"
208
  ],
 
6
  import time
7
  import os
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  # Configuraci贸n de GPU para TensorFlow
10
  physical_devices = tf.config.list_physical_devices('GPU')
11
  if physical_devices:
12
  print("GPU disponible. Configurando...")
13
  try:
 
14
  for gpu in physical_devices:
15
  tf.config.experimental.set_memory_growth(gpu, True)
16
  print("Configuraci贸n de GPU completada")
 
19
  else:
20
  print("No se detect贸 GPU. El procesamiento ser谩 m谩s lento.")
21
 
22
+ # Definir funciones personalizadas para las transformadas de Fourier
23
+ def fourier_transform(x):
24
+ fourier = tf.signal.fft2d(tf.cast(x, tf.complex64))
25
+ fourier = tf.complex(tf.math.real(fourier), tf.math.imag(fourier))
26
+ fourier = tf.abs(fourier)
27
+ return tf.concat([tf.math.real(fourier), tf.math.imag(fourier)], axis=-1)
28
+
29
+ def inverse_fourier_transform(x):
30
+ real_part, imag_part = tf.split(x, num_or_size_splits=2, axis=-1)
31
+ complex_fourier = tf.complex(real_part, imag_part)
32
+ return tf.abs(tf.signal.ifft2d(complex_fourier))
33
+
34
+ # Construir modelo manualmente
35
+ def build_autoencoder(input_shape=(256, 256, 3)):
36
+ """Reconstruir el modelo autoencoder manualmente"""
37
+
38
+ # Definir entradas
39
+ inputs = tf.keras.layers.Input(shape=input_shape)
40
+
41
+ # Aplicar transformada de Fourier (opcional)
42
+ # x = tf.keras.layers.Lambda(fourier_transform)(inputs)
43
+ x = inputs # Skip Fourier transform for now
44
+
45
+ # Encoder
46
+ x = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', padding='same')(x)
47
+ x = tf.keras.layers.MaxPooling2D((2, 2), padding='same')(x)
48
+ x = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same')(x)
49
+ x = tf.keras.layers.MaxPooling2D((2, 2), padding='same')(x)
50
+ x = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', padding='same')(x)
51
+ encoded = tf.keras.layers.MaxPooling2D((2, 2), padding='same')(x)
52
+
53
+ # Decoder
54
+ x = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', padding='same')(encoded)
55
+ x = tf.keras.layers.UpSampling2D((2, 2))(x)
56
+ x = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same')(x)
57
+ x = tf.keras.layers.UpSampling2D((2, 2))(x)
58
+ x = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', padding='same')(x)
59
+ x = tf.keras.layers.UpSampling2D((2, 2))(x)
60
+
61
+ # Output
62
+ # x = tf.keras.layers.Lambda(inverse_fourier_transform)(x) # Skip inverse transform
63
+ outputs = tf.keras.layers.Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)
64
+
65
+ # Crear modelo
66
+ model = tf.keras.models.Model(inputs, outputs)
67
+
68
+ return model
69
+
70
+ # Opci贸n alternativa: Crear un modelo simplificado
71
+ def build_simple_autoencoder(input_shape=(256, 256, 3)):
72
+ """Crear un autoencoder simple (sin Fourier)"""
73
+
74
+ inputs = tf.keras.layers.Input(shape=input_shape)
75
+
76
+ # Encoder
77
+ x = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', padding='same')(inputs)
78
+ x = tf.keras.layers.MaxPooling2D((2, 2), padding='same')(x)
79
+ x = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same')(x)
80
+ x = tf.keras.layers.MaxPooling2D((2, 2), padding='same')(x)
81
+
82
+ # Decoder
83
+ x = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same')(x)
84
+ x = tf.keras.layers.UpSampling2D((2, 2))(x)
85
+ x = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', padding='same')(x)
86
+ x = tf.keras.layers.UpSampling2D((2, 2))(x)
87
+
88
+ # Output
89
+ outputs = tf.keras.layers.Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)
90
+
91
+ # Crear modelo
92
+ model = tf.keras.models.Model(inputs, outputs)
93
+
94
+ return model
95
 
96
  # Funciones de preprocesamiento optimizadas
97
  def degrade_image(image, downscale_factor=4):
 
138
 
139
  return noisy_img
140
 
141
+ print("Crear modelo simplificado...")
142
+ model = build_simple_autoencoder()
143
+ print("Modelo creado correctamente")
144
 
145
+ # Funci贸n de denoising
146
  def Denoiser(imagen):
147
  """Aplica el modelo autoencoder para eliminar ruido de la imagen."""
 
148
 
149
  # Verificar que la imagen no sea None
150
  if imagen is None:
 
167
  # Medir el tiempo de la predicci贸n
168
  start_time = time.time()
169
 
170
+ # Para la primera versi贸n usamos el modelo simple sin Fourier
171
+ # Esto resolver谩 el problema de lambda layers
172
  reconstructed = model(noisy_image_input, training=False).numpy()[0]
173
 
174
  prediction_time = time.time() - start_time
175
+ print(f"Tiempo de predicci贸n: {prediction_time:.2f} segundos")
 
 
 
 
 
176
 
177
  # Asegurarse de que las im谩genes est茅n en el rango [0, 255]
178
  noisy_image = np.uint8(noisy_image * 255)
 
193
  gr.Image(type="numpy", label="Imagen Restaurada")
194
  ],
195
  title="Autoencoder para Denoising",
196
+ description="""Este modelo de autoencoder reduce el ruido en im谩genes. Sube una imagen para ver el resultado.
197
+ Nota: Esta es una versi贸n simplificada que no utiliza el modelo pre-entrenado debido a limitaciones t茅cnicas.""",
198
  examples=[
199
  "https://raw.githubusercontent.com/gradio-app/gradio/main/demo/english_htr/images/Create%20a%20free%20Gradio%20account%20to%20access%20our%20most%20powerful%20features.jpeg"
200
  ],