Spaces:
Runtime error
Runtime error
Update app.py
Browse files
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 |
-
#
|
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 |
# 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 |
-
|
147 |
-
|
|
|
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 |
-
#
|
175 |
-
#
|
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
|
|
|
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 |
],
|