Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Define el modelo y carga los pesos guardados
|
| 2 |
+
model = efficientnet_b0(weights=EfficientNet_B0_Weights.DEFAULT)
|
| 3 |
+
model.classifier[1] = torch.nn.Linear(in_features=1280, out_features=101)
|
| 4 |
+
model.load_state_dict(torch.load('./Model_Food_ProyectoIA'))
|
| 5 |
+
|
| 6 |
+
model.eval() # Poner el modelo en modo evaluaci贸n
|
| 7 |
+
|
| 8 |
+
# Mueve el modelo a la GPU si est谩 disponible
|
| 9 |
+
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
| 10 |
+
model.to(device)
|
| 11 |
+
|
| 12 |
+
# Define las transformaciones
|
| 13 |
+
transform_preprocess = transforms.Compose([
|
| 14 |
+
transforms.Resize(256, interpolation=InterpolationMode.BICUBIC),
|
| 15 |
+
transforms.CenterCrop(224),
|
| 16 |
+
transforms.ToTensor(),
|
| 17 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 18 |
+
])
|
| 19 |
+
|
| 20 |
+
# Cargar el conjunto de datos Food-101 para obtener la lista de clases
|
| 21 |
+
image_path = '../../compartida/vision-project/'
|
| 22 |
+
food101_dataset = datasets.Food101(image_path, split='train')
|
| 23 |
+
classes = food101_dataset.classes
|
| 24 |
+
|
| 25 |
+
# Funci贸n para predecir la clase de una nueva imagen
|
| 26 |
+
def predict_image(image):
|
| 27 |
+
image = Image.fromarray(image).convert('RGB') # Convertir la imagen cargada a PIL
|
| 28 |
+
image = transform_preprocess(image).unsqueeze(0) # Preprocesar y a帽adir dimensi贸n de batch
|
| 29 |
+
image = image.to(device) # Mover la imagen a la GPU si est谩 disponible
|
| 30 |
+
|
| 31 |
+
with torch.no_grad():
|
| 32 |
+
output = model(image) # Realizar la predicci贸n
|
| 33 |
+
prediction = torch.nn.functional.softmax(output[0], dim=0) # Aplicar softmax para obtener probabilidades
|
| 34 |
+
confidences = {classes[i]: float(prediction[i]) for i in range(101)} # Crear diccionario de clases y probabilidades
|
| 35 |
+
|
| 36 |
+
return confidences # Devolver las probabilidades de cada clase
|
| 37 |
+
|
| 38 |
+
# Crear la interfaz de Gradio
|
| 39 |
+
interface = gr.Interface(
|
| 40 |
+
fn=predict_image,
|
| 41 |
+
inputs=gr.Image(type="numpy"),
|
| 42 |
+
outputs=gr.Label(num_top_classes=3),
|
| 43 |
+
title="Food101 Classifier",
|
| 44 |
+
description="Sube una imagen de comida y el modelo clasificar谩 la imagen.",
|
| 45 |
+
examples=["../../Alan/Proyecto_Food_101/hamb.jpg"] # Reemplaza con rutas de ejemplo
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# Iniciar la interfaz
|
| 49 |
+
interface.launch(share=True)
|