File size: 1,498 Bytes
a3730f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from PIL import Image
import torch
from transformers import AutoImageProcessor, AutoModelForImageClassification


# Load model and processor
MODEL_NAME = "nexusbert/resnet50-cassava-finetuned"

processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
model = AutoModelForImageClassification.from_pretrained(MODEL_NAME)
id2label = model.config.id2label


def predict(image: Image.Image):
    """
    Run inference on a single image and return class probabilities.
    Gradio's Label component expects a dict: {label: probability}.
    """
    inputs = processor(images=image, return_tensors="pt")

    with torch.no_grad():
        outputs = model(**inputs)
        probs = torch.nn.functional.softmax(outputs.logits, dim=-1)[0]

    # Map class indices to human-readable labels and probabilities (as floats)
    result = {
        id2label[i]: float(probs[i])
        for i in range(len(probs))
    }
    return result


demo = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="pil", label="Upload cassava leaf image"),
    outputs=gr.Label(num_top_classes=3, label="Predicted classes"),
    title="Cassava Leaf Disease Classifier",
    description=(
        "Upload an image of a cassava leaf and this app will predict the most likely disease class "
        "using the `nexusbert/resnet50-cassava-finetuned` model from Hugging Face."
    ),
    examples=None,
)


if __name__ == "__main__":
    # Set share=True if you want a public shareable link
    demo.launch()