nickmuchi commited on
Commit
6844550
·
1 Parent(s): 8f9de4b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -0
app.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import gradio as gr
3
+ import matplotlib.pyplot as plt
4
+ import requests, validators
5
+ import torch
6
+ import pathlib
7
+ from PIL import Image
8
+ from transformers import AutoFeatureExtractor, YolosForObjectDetection
9
+ import os
10
+
11
+ os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
12
+
13
+ # colors for visualization
14
+ COLORS = [
15
+ [0.000, 0.447, 0.741],
16
+ [0.850, 0.325, 0.098],
17
+ [0.929, 0.694, 0.125],
18
+ [0.494, 0.184, 0.556],
19
+ [0.466, 0.674, 0.188],
20
+ [0.301, 0.745, 0.933]
21
+ ]
22
+
23
+ def make_prediction(img, feature_extractor, model):
24
+ inputs = feature_extractor(img, return_tensors="pt")
25
+ outputs = model(**inputs)
26
+ img_size = torch.tensor([tuple(reversed(img.size))])
27
+ processed_outputs = feature_extractor.post_process(outputs, img_size)
28
+ return processed_outputs[0]
29
+
30
+ def fig2img(fig):
31
+ buf = io.BytesIO()
32
+ fig.savefig(buf)
33
+ buf.seek(0)
34
+ img = Image.open(buf)
35
+ return img
36
+
37
+
38
+ def visualize_prediction(pil_img, output_dict, threshold=0.7, id2label=None):
39
+ keep = output_dict["scores"] > threshold
40
+ boxes = output_dict["boxes"][keep].tolist()
41
+ scores = output_dict["scores"][keep].tolist()
42
+ labels = output_dict["labels"][keep].tolist()
43
+ if id2label is not None:
44
+ labels = [id2label[x] for x in labels]
45
+
46
+ plt.figure(figsize=(16, 10))
47
+ plt.imshow(pil_img)
48
+ ax = plt.gca()
49
+ colors = COLORS * 100
50
+ for score, (xmin, ymin, xmax, ymax), label, color in zip(scores, boxes, labels, colors):
51
+ ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=color, linewidth=3))
52
+ ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=15, bbox=dict(facecolor="yellow", alpha=0.5))
53
+ plt.axis("off")
54
+ return fig2img(plt.gcf())
55
+
56
+ def detect_objects(model_name,url_input,image_input,threshold):
57
+
58
+ #Extract model and feature extractor
59
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
60
+
61
+ model = YolosForObjectDetection.from_pretrained(model_name)
62
+
63
+ if validators.url(url_input):
64
+ image = Image.open(requests.get(url_input, stream=True).raw)
65
+
66
+ elif image_input:
67
+ image = image_input
68
+
69
+ #Make prediction
70
+ processed_outputs = make_prediction(image, feature_extractor, model)
71
+
72
+ #Visualize prediction
73
+ viz_img = visualize_prediction(image, processed_outputs, threshold, model.config.id2label)
74
+
75
+ return viz_img
76
+
77
+ def set_example_image(example: list) -> dict:
78
+ return gr.Image.update(value=example[0])
79
+
80
+ def set_example_url(example: list) -> dict:
81
+ return gr.Textbox.update(value=example[0])
82
+
83
+
84
+ title = """<h1 id="title">Face Mask Detection App with YOLOS</h1>"""
85
+
86
+ description = """
87
+ Links to HuggingFace Models:
88
+ - [nickmuchi/yolos-small-finetuned-masks](https://huggingface.co/nickmuchi/yolos-small-finetuned-masks)
89
+ """
90
+
91
+ models = ["nickmuchi/yolos-small-finetuned-masks"]
92
+ urls = ["https://drive.google.com/uc?id=1VwYLbGak5c-2P5qdvfWVOeg7DTDYPbro"]
93
+
94
+ twitter_link = """
95
+ [![](https://img.shields.io/twitter/follow/nickmuchi?label=@nickmuchi&style=social)](https://twitter.com/nickmuchi)
96
+ """
97
+
98
+ css = '''
99
+ h1#title {
100
+ text-align: center;
101
+ }
102
+ '''
103
+ demo = gr.Blocks(css=css)
104
+
105
+ with demo:
106
+ gr.Markdown(title)
107
+ gr.Markdown(description)
108
+ gr.Markdown(twitter_link)
109
+ options = gr.Dropdown(choices=models,label='Select Object Detection Model',show_label=True)
110
+ slider_input = gr.Slider(minimum=0.2,maximum=1,value=0.7,label='Prediction Threshold')
111
+
112
+ with gr.Tabs():
113
+ with gr.TabItem('Image URL'):
114
+ with gr.Row():
115
+ url_input = gr.Textbox(lines=2,label='Enter valid image URL here..')
116
+ img_output_from_url = gr.Image(shape=(650,650))
117
+
118
+ with gr.Row():
119
+ example_url = gr.Dataset(components=[url_input],samples=[[str(url)] for url in urls])
120
+
121
+ url_but = gr.Button('Detect')
122
+
123
+ with gr.TabItem('Image Upload'):
124
+ with gr.Row():
125
+ img_input = gr.Image(type='pil')
126
+ img_output_from_upload= gr.Image(shape=(650,650))
127
+
128
+ with gr.Row():
129
+ example_images = gr.Dataset(components=[img_input],
130
+ samples=[[path.as_posix()]
131
+ for path in sorted(pathlib.Path('images').rglob('*.JPG'))])
132
+
133
+ img_but = gr.Button('Detect')
134
+
135
+
136
+ url_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=img_output_from_url,queue=True)
137
+ img_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=img_output_from_upload,queue=True)
138
+ example_images.click(fn=set_example_image,inputs=[example_images],outputs=[img_input])
139
+ example_url.click(fn=set_example_url,inputs=[example_url],outputs=[url_input])
140
+
141
+
142
+ gr.Markdown("![visitor badge](https://visitor-badge.glitch.me/badge?page_id=nickmuchi-face-mask-detection-with-yolos)")
143
+
144
+
145
+ demo.launch(debug=True,enable_queue=True)