fmagot01's picture
Update app.py
dec0f7f
import gradio as gr
import torch
from transformers import pipeline
from timeit import default_timer as timer
username = "fmagot01" ## Complete your username
model_id = f"{username}/vit-base-beans"
device = "cuda:0" if torch.cuda.is_available() else "cpu"
pipe = pipeline("image-classification", model=model_id, device=device)
# def predict_trunc(filepath):
# preprocessed = pipe.preprocess(filepath)
# truncated = pipe.feature_extractor.pad(preprocessed,truncation=True, max_length = 16_000*30)
# model_outputs = pipe.forward(truncated)
# outputs = pipe.postprocess(model_outputs)
# return outputs
def classify_image(filepath):
"""
Goes from
[{'score': 0.8339303731918335, 'label': 'healthy'},
{'score': 0.11914275586605072, 'label': 'bean_rust'},]
to
{"health": 0.8339303731918335, "bean_rust":0.11914275586605072}
"""
start_time = timer()
preds = pipe(filepath)
outputs = {}
pred_time = round(timer() - start_time, 5)
for p in preds:
outputs[p["label"]] = p["score"]
return outputs, pred_time
title = "Classifier of Leaf Images"
description = """
This demo shows the application of the fintuned image classification model using [Beans](https://huggingface.co/datasets/beans). You can upload your own image or select an image from the examples below.
It will output 3 different labels: Healthy, Bean Rust and Angular leaf Spot. Bean rust is a type of disease that leaves can get. Angular leaf spot refers to irregular spots that a leaf can get (not a disease) and healthy leaves do not have any of these.
"""
filenames = ['leaftest1.jpeg', "leaftest2.jpeg", "leaftest3.jpeg"]
filenames = [[f"./{f}"] for f in filenames]
demo = gr.Interface(
fn=classify_image,
inputs=gr.Image(type="filepath"),
outputs=[gr.outputs.Label(label="Predictions"),
gr.Number(label="Prediction time (s)")
],
title=title,
description=description,
examples=filenames,
)
demo.launch()