File size: 2,142 Bytes
304ee48
 
 
 
 
 
13ec91a
 
 
304ee48
13ec91a
304ee48
 
13ec91a
304ee48
 
 
 
 
 
 
 
 
 
13ec91a
 
 
 
 
 
 
 
 
 
 
304ee48
 
 
 
 
 
 
13ec91a
304ee48
 
 
 
 
 
 
b686047
 
 
 
954984f
b686047
 
 
75f6396
b686047
 
 
 
13ec91a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
import torch
from torchvision import transforms
import gradio as gr
import timm
from huggingface_hub import hf_hub_download

# Descargar y cargar el checkpoint desde Hugging Face
checkpoint_path = hf_hub_download(repo_id="monabarreiro/ModeloMaiz", filename="best_Model_vit.pt")
checkpoint = torch.load(checkpoint_path, map_location='cpu')

# Crear el modelo con el n煤mero correcto de clases
model = timm.create_model('vit_base_patch16_224', num_classes=len(checkpoint['class_names']))

# Ajustar el state_dict para cargar correctamente los pesos
state_dict = checkpoint['model_state_dict']
new_state_dict = {}
for k, v in state_dict.items():
    if k.startswith('model.'):
        new_state_dict[k[6:]] = v
    else:
        new_state_dict[k] = v
model.load_state_dict(new_state_dict)
model.eval()

# Traducci贸n de clases al espa帽ol
class_names_en = checkpoint['class_names']
class_names_es = {
    "Blight": "Tiz贸n",
    "Common_Rust": "Roya com煤n",
    "Gray_Leaf_Spot": "Mancha gris de la hoja",
    "Healthy": "Sano"
}
class_names = [class_names_es[name] for name in class_names_en]

# Preprocesamiento de im谩genes
preprocess = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

# Funci贸n de predicci贸n
def predict(image):
    img_tensor = preprocess(image).unsqueeze(0)
    with torch.no_grad():
        outputs = model(img_tensor)
        probs = torch.nn.functional.softmax(outputs, dim=1)
    return {class_names[i]: float(probs[0][i]) for i in range(len(class_names))}

with gr.Blocks() as demo:
    gr.Markdown("Clasificador de enfermedades de maiz")
    gr.Markdown("Sube una imagen de una hoja de ma铆z para detectar posibles enfermedades.")
    gr.HTML(""" <a href="http://localhost:8081/enfMaiz" target="_blank">Mostrar Enfermedades</a>""")

    with gr.Row():
        inp = gr.Image(type="pil", label="Sub铆 una imagen")
        out = gr.Textbox(label="Predicci贸n")

    btn = gr.Button("Predecir")
    btn.click(fn=predict, inputs=inp, outputs=out)

demo.launch(debug=True)