Download app.py from PaaPnchos/Floetry: direct link, hf CLI and curl.
- Browser
- Download file 1.73 kB
-
https://huggingface.co/spaces/PaaPnchos/Floetry/resolve/main/app.py
- Command line
-
hf download hf://spaces/PaaPnchos/Floetry/app.py
-
curl -L -o app.py https://huggingface.co/spaces/PaaPnchos/Floetry/resolve/main/app.py
1.73 kB
| import torch | |
| import torch.nn as nn | |
| from torchvision import models, transforms | |
| from PIL import Image | |
| import numpy as np | |
| import gradio as gr | |
| class_labels = ['daisy', 'dandelion', 'rose', 'sunflower', 'tulip', 'unknown'] | |
| def load_model(path='model.pth'): | |
| model = models.resnet50(weights='IMAGENET1K_V1') | |
| model.fc = nn.Linear(model.fc.in_features, len(class_labels) - 1) | |
| model.load_state_dict(torch.load(path, map_location=torch.device('cpu'))) | |
| model.eval() | |
| return model | |
| model = load_model() | |
| val_transform = transforms.Compose([ | |
| transforms.Resize(256), | |
| transforms.CenterCrop(224), | |
| transforms.ToTensor(), | |
| transforms.Normalize([0.485, 0.456, 0.406], | |
| [0.229, 0.224, 0.225]) | |
| ]) | |
| def predict(image): | |
| image = Image.fromarray(image.astype('uint8'), 'RGB') | |
| input_tensor = val_transform(image).unsqueeze(0) | |
| with torch.no_grad(): | |
| outputs = model(input_tensor) | |
| probs = torch.nn.functional.softmax(outputs[0], dim=0) | |
| confidence, predicted_idx = torch.max(probs, dim=0) | |
| if confidence.item() < 0.85: | |
| return f"No registrado (Confianza: {confidence:.2f})" | |
| else: | |
| return f"{class_labels[predicted_idx]} (Confianza: {confidence:.2f})" | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# Floetry") | |
| gr.Markdown("Clasificador de especies de flores con aprendizaje profundo.") | |
| with gr.Row(): | |
| image_input = gr.Image(label="Sube una imagen", type="numpy") | |
| output_box = gr.Textbox(label="Predicción", placeholder="Aquí aparecerá el resultado") | |
| submit_button = gr.Button("Clasificar") | |
| submit_button.click(fn=predict, inputs=image_input, outputs=output_box) | |
| demo.launch() |