kevanme's picture
Update app.py
02789b3 verified
import gradio as gr
import numpy as np
from tensorflow.keras.models import load_model
from PIL import Image
import tensorflow as tf
#Cargar modelo
def euclidean_distance(vects):
x, y = vects
sum_square = tf.reduce_sum(tf.square(x - y), axis=1, keepdims=True)
return tf.sqrt(tf.maximum(sum_square, tf.keras.backend.epsilon()))
model = load_model("mnist_siamese_model.keras", custom_objects={'euclidean_distance': euclidean_distance})
#Preprocesar imágenes
def preprocess(img):
img = img.convert("L").resize((28, 28))
img = np.array(img).astype("float32") / 255.0
img = np.expand_dims(img, axis=-1) # (28, 28, 1)
return img
#Función de predicción
def predict(img1, img2):
img1 = preprocess(img1)
img2 = preprocess(img2)
img1 = np.expand_dims(img1, axis=0)
img2 = np.expand_dims(img2, axis=0)
distance = model.predict([img1, img2])[0][0]
threshold = 0.5
same = distance < threshold
return f"¿Es el mismo dígito? {'Sí' if same else 'No'} (distancia: {distance:.4f})"
#Interfaz Gradio
interface = gr.Interface(
fn=predict,
inputs=[
gr.Image(type="pil", label="Imagen 1"),
gr.Image(type="pil", label="Imagen 2")
],
outputs="text",
title="Modelo Siamese con MNIST",
description="Sube dos imágenes de dígitos para verificar si representan el mismo número."
)
interface.launch()