valmun commited on
Commit
3e8c6dd
1 Parent(s): b66fe8d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -0
app.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import ViTForImageClassification, ViTImageProcessor
3
+ import torch
4
+
5
+ # Define the pretrained model
6
+ model_name = "Treelar/vit-b16-plant_village"
7
+
8
+ # Load the ViT model and the image processor
9
+ model = ViTForImageClassification.from_pretrained(model_name)
10
+ image_processor = ViTImageProcessor.from_pretrained(model_name)
11
+
12
+ def predict(image):
13
+ # Convert the image into the model's required format
14
+ inputs = image_processor(images=image, return_tensors="pt")
15
+
16
+ # Disable gradient calculation to make the process efficient
17
+ with torch.no_grad():
18
+ outputs = model(**inputs) # Gets the model's output for the image
19
+ logits = outputs.logits # Output scores from the model
20
+
21
+ # Convert the logits to a probability using the softmax function
22
+ probability = torch.nn.functional.softmax(logits, dim=1)
23
+ top_probability, top_index = probability.max(1) # Gets the highest probability with its respective index
24
+
25
+ # Gets the disease label from the model using the probability's index
26
+ label_index = top_index.item()
27
+ label = model.config.id2label[label_index]
28
+
29
+ # Split the label into leaf category and disease name
30
+ label_parts = label.split("___")
31
+ leaf_category = label_parts[0]
32
+ disease_name = label_parts[1]
33
+
34
+ # Calculate the percentage breakdown of predicted diseases
35
+ percentage_breakdown = {disease: round(float(probability[0, index]) * 100, 2) for index, disease in enumerate(model.config.label2id)}
36
+
37
+ return leaf_category.capitalize(), disease_name.replace('_', ' ').capitalize(), percentage_breakdown
38
+
39
+ # Gradio interface setup with separate boxes for Leaf Type, Identified Disease, and Percentage Breakdown
40
+ interface = gr.Interface(
41
+ fn=predict,
42
+ inputs=gr.Image(label="Upload the Image"),
43
+ outputs=[
44
+ gr.Textbox(label="Leaf Type:"),
45
+ gr.Textbox(label="Identified Disease:"),
46
+ gr.JSON(label="Percentage Breakdown:")
47
+ ],
48
+ title="Plant Disease Identifier",
49
+ description="Once the image has been uploaded and submitted, the disease of the plant will be determined. The percentage breakdown shows the probability of each disease."
50
+ )
51
+
52
+ interface.launch(debug=True) # Start server and launch the UI