nickmuchi commited on
Commit
efd7b02
·
1 Parent(s): dfda1fc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +176 -0
app.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import io
3
+ import gradio as gr
4
+ import matplotlib.pyplot as plt
5
+ import requests, validators
6
+ import torch
7
+ import pathlib
8
+ from PIL import Image
9
+ from transformers import AutoFeatureExtractor, YolosForObjectDetection
10
+ import os
11
+
12
+ os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
13
+
14
+ # colors for visualization
15
+ COLORS = [
16
+ [0.000, 0.447, 0.741],
17
+ [0.850, 0.325, 0.098],
18
+ [0.929, 0.694, 0.125],
19
+ [0.494, 0.184, 0.556],
20
+ [0.466, 0.674, 0.188],
21
+ [0.301, 0.745, 0.933]
22
+ ]
23
+
24
+ def make_prediction(img, feature_extractor, model):
25
+ inputs = feature_extractor(img, return_tensors="pt")
26
+ outputs = model(**inputs)
27
+ img_size = torch.tensor([tuple(reversed(img.size))])
28
+ processed_outputs = feature_extractor.post_process(outputs, img_size)
29
+ return processed_outputs[0]
30
+
31
+ def fig2img(fig):
32
+ buf = io.BytesIO()
33
+ fig.savefig(buf)
34
+ buf.seek(0)
35
+ pil_img = Image.open(buf)
36
+ basewidth = 750
37
+ wpercent = (basewidth/float(pil_img.size[0]))
38
+ hsize = int((float(pil_img.size[1])*float(wpercent)))
39
+ img = pil_img.resize((basewidth,hsize), Image.Resampling.LANCZOS)
40
+ return img
41
+
42
+
43
+ def visualize_prediction(img, output_dict, threshold=0.5, id2label=None):
44
+ keep = output_dict["scores"] > threshold
45
+ boxes = output_dict["boxes"][keep].tolist()
46
+ scores = output_dict["scores"][keep].tolist()
47
+ labels = output_dict["labels"][keep].tolist()
48
+ if id2label is not None:
49
+ labels = [id2label[x] for x in labels]
50
+
51
+ plt.figure(figsize=(50, 50))
52
+ plt.imshow(img)
53
+ ax = plt.gca()
54
+ colors = COLORS * 100
55
+ for score, (xmin, ymin, xmax, ymax), label, color in zip(scores, boxes, labels, colors):
56
+ ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=color, linewidth=5))
57
+ ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=30, bbox=dict(facecolor="yellow", alpha=0.5))
58
+ plt.axis("off")
59
+ return fig2img(plt.gcf())
60
+
61
+ def get_original_image(url_input):
62
+ if validators.url(url_input):
63
+ image = Image.open(requests.get(url_input, stream=True).raw)
64
+
65
+ return image
66
+
67
+ def detect_objects(model_name,url_input,image_input,webcam_input,threshold):
68
+
69
+ #Extract model and feature extractor
70
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
71
+
72
+ model = YolosForObjectDetection.from_pretrained(model_name)
73
+
74
+
75
+ if validators.url(url_input):
76
+ image = get_original_image(url_input)
77
+
78
+ elif image_input:
79
+ image = image_input
80
+
81
+ elif webcam_input:
82
+ image = webcam_input
83
+
84
+ #Make prediction
85
+ processed_outputs = make_prediction(image, feature_extractor, model)
86
+
87
+ #Visualize prediction
88
+ viz_img = visualize_prediction(image, processed_outputs, threshold, model.config.id2label)
89
+
90
+ return viz_img
91
+
92
+ def set_example_image(example: list) -> dict:
93
+ return gr.Image.update(value=example[0])
94
+
95
+ def set_example_url(example: list) -> dict:
96
+ return gr.Textbox.update(value=example[0]), gr.Image.update(value=get_original_image(example[0]))
97
+
98
+
99
+ title = """<h1 id="title">Plant Disease Detection with YOLOS</h1>"""
100
+
101
+ description = """
102
+ YOLOS is a Vision Transformer (ViT) trained using the DETR loss. Despite its simplicity, a base-sized YOLOS model is able to achieve 42 AP on COCO validation 2017 (similar to DETR and more complex frameworks such as Faster R-CNN).
103
+ The YOLOS model was fine-tuned on COCO 2017 object detection (118k annotated images). It was introduced in the paper [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://arxiv.org/abs/2106.00666) by Fang et al. and first released in [this repository](https://github.com/hustvl/YOLOS).
104
+ This model was further fine-tuned on the [Plant Doc Image Dataset]("https://universe.roboflow.com/artificial-intelligence-82oex/detecting-diseases") from Roboflow. The dataset consists of 4700 images of plants with 30 annotations of various diiseases such as "Apple rust leaf","Potato leaf late blight" and "Tomato leaf bacterial spot". The model was trained for 60 epochs on a single GPU.
105
+ Links to HuggingFace Models:
106
+ - [nickmuchi/yolos-small-plant-disease-detection](https://huggingface.co/nickmuchi/yolos-small-plant-disease-detection)
107
+ - [hustlv/yolos-small](https://huggingface.co/hustlv/yolos-small)
108
+ """
109
+
110
+ models = ["nickmuchi/yolos-small-plant-disease-detection"]
111
+ urls = ["https://api.time.com/wp-content/uploads/2020/03/hong-kong-mask-admiralty.jpg","https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ7wiGZhgAFuIpwFJzbpv8kUMM_Q3WaAWYf5NpSJduxvHQ7V2WnqZ0wMWS6cK5gvlfPGxc&usqp=CAU"]
112
+
113
+ twitter_link = """
114
+ [![](https://img.shields.io/twitter/follow/nickmuchi?label=@nickmuchi&style=social)](https://twitter.com/nickmuchi)
115
+ """
116
+
117
+ css = '''
118
+ h1#title {
119
+ text-align: center;
120
+ }
121
+ '''
122
+ demo = gr.Blocks(css=css)
123
+
124
+ with demo:
125
+ with gr.Box():
126
+
127
+ gr.Markdown(title)
128
+ gr.Markdown(description)
129
+ gr.Markdown(twitter_link)
130
+ options = gr.Dropdown(choices=models,label='Object Detection Model',show_label=True)
131
+ slider_input = gr.Slider(minimum=0.2,maximum=1,value=0.5,step=0.1,label='Prediction Threshold')
132
+
133
+ with gr.Tabs():
134
+ with gr.TabItem('Image URL'):
135
+ with gr.Row():
136
+ with gr.Column():
137
+ url_input = gr.Textbox(lines=2,label='Enter valid image URL here..')
138
+ original_image = gr.Image(shape=(750,750))
139
+ with gr.Column():
140
+ img_output_from_url = gr.Image(shape=(750,750))
141
+
142
+ with gr.Row():
143
+ example_url = gr.Dataset(components=[url_input],samples=[[str(url)] for url in urls])
144
+
145
+ url_but = gr.Button('Detect')
146
+
147
+ with gr.TabItem('Image Upload'):
148
+ with gr.Row():
149
+ img_input = gr.Image(type='pil',shape=(750,750))
150
+ img_output_from_upload= gr.Image(shape=(750,750))
151
+
152
+ with gr.Row():
153
+ example_images = gr.Dataset(components=[img_input],
154
+ samples=[[path.as_posix()] for path in sorted(pathlib.Path('images').rglob('*.j*g'))])
155
+
156
+
157
+ img_but = gr.Button('Detect')
158
+
159
+ with gr.TabItem('WebCam'):
160
+ with gr.Row():
161
+ web_input = gr.Image(source='webcam',type='pil',shape=(750,750),streaming=True)
162
+ img_output_from_webcam= gr.Image(shape=(750,750))
163
+
164
+ cam_but = gr.Button('Detect')
165
+
166
+ url_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_url],queue=True)
167
+ img_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_upload],queue=True)
168
+ cam_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_webcam],queue=True)
169
+ example_images.click(fn=set_example_image,inputs=[example_images],outputs=[img_input])
170
+ example_url.click(fn=set_example_url,inputs=[example_url],outputs=[url_input,original_image])
171
+
172
+
173
+ gr.Markdown("![visitor badge](https://visitor-badge.glitch.me/badge?page_id=nickmuchi-plant-disease-detection-with-yolos)")
174
+
175
+
176
+ demo.launch(debug=True,enable_queue=True)