Eric2983 commited on
Commit
a9de7a2
1 Parent(s): af53fa8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -5
app.py CHANGED
@@ -1,14 +1,118 @@
 
1
  import gradio as gr
2
-
 
 
 
3
  from PIL import Image
4
- import numpy as np
5
  import os
6
 
7
- title = """<h1 id="title">App Detection</h1>"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  models = ["nickmuchi/yolos-small-finetuned-masks","nickmuchi/yolos-base-finetuned-masks"]
10
  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"]
11
 
 
 
 
 
12
  css = '''
13
  h1#title {
14
  text-align: center;
@@ -17,9 +121,12 @@ h1#title {
17
  demo = gr.Blocks(css=css)
18
 
19
  with demo:
 
20
 
21
  gr.Markdown(title)
22
- options = gr.Dropdown(choices=models,label='Detection',show_label=True)
 
 
23
  slider_input = gr.Slider(minimum=0.2,maximum=1,value=0.5,step=0.1,label='Prediction Threshold')
24
 
25
  with gr.Tabs():
@@ -62,4 +169,7 @@ with demo:
62
  example_url.click(fn=set_example_url,inputs=[example_url],outputs=[url_input,original_image])
63
 
64
 
65
- demo.launch(debug=True,enable_queue=True)
 
 
 
 
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
+ pil_img = Image.open(buf)
35
+ basewidth = 750
36
+ wpercent = (basewidth/float(pil_img.size[0]))
37
+ hsize = int((float(pil_img.size[1])*float(wpercent)))
38
+ img = pil_img.resize((basewidth,hsize), Image.Resampling.LANCZOS)
39
+ return img
40
+
41
+
42
+ def visualize_prediction(img, output_dict, threshold=0.5, id2label=None):
43
+ keep = output_dict["scores"] > threshold
44
+ boxes = output_dict["boxes"][keep].tolist()
45
+ scores = output_dict["scores"][keep].tolist()
46
+ labels = output_dict["labels"][keep].tolist()
47
+ if id2label is not None:
48
+ labels = [id2label[x] for x in labels]
49
+
50
+ plt.figure(figsize=(50, 50))
51
+ plt.imshow(img)
52
+ ax = plt.gca()
53
+ colors = COLORS * 100
54
+ for score, (xmin, ymin, xmax, ymax), label, color in zip(scores, boxes, labels, colors):
55
+ ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=color, linewidth=5))
56
+ ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=30, bbox=dict(facecolor="yellow", alpha=0.5))
57
+ plt.axis("off")
58
+ return fig2img(plt.gcf())
59
+
60
+ def get_original_image(url_input):
61
+ if validators.url(url_input):
62
+ image = Image.open(requests.get(url_input, stream=True).raw)
63
+
64
+ return image
65
+
66
+ def detect_objects(model_name,url_input,image_input,webcam_input,threshold):
67
+
68
+ #Extract model and feature extractor
69
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
70
+
71
+ model = YolosForObjectDetection.from_pretrained(model_name)
72
+
73
+
74
+ if validators.url(url_input):
75
+ image = get_original_image(url_input)
76
+
77
+ elif image_input:
78
+ image = image_input
79
+
80
+ elif webcam_input:
81
+ image = webcam_input
82
+
83
+ #Make prediction
84
+ processed_outputs = make_prediction(image, feature_extractor, model)
85
+
86
+ #Visualize prediction
87
+ viz_img = visualize_prediction(image, processed_outputs, threshold, model.config.id2label)
88
+
89
+ return viz_img
90
+
91
+ def set_example_image(example: list) -> dict:
92
+ return gr.Image.update(value=example[0])
93
+
94
+ def set_example_url(example: list) -> dict:
95
+ return gr.Textbox.update(value=example[0]), gr.Image.update(value=get_original_image(example[0]))
96
+
97
+
98
+ title = """<h1 id="title">Face Mask Detection with YOLOS</h1>"""
99
+
100
+ description = """
101
+ 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).
102
+ 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).
103
+ This model was further fine-tuned on the [face mask dataset]("https://www.kaggle.com/datasets/andrewmvd/face-mask-detection") from Kaggle. The dataset consists of 853 images of people with annotations categorised as "with mask","without mask" and "mask not worn correctly". The model was trained for 200 epochs on a single GPU.
104
+ Links to HuggingFace Models:
105
+ - [nickmuchi/yolos-small-finetuned-masks](https://huggingface.co/nickmuchi/yolos-small-finetuned-masks)
106
+ - [hustlv/yolos-small](https://huggingface.co/hustlv/yolos-small)
107
+ """
108
 
109
  models = ["nickmuchi/yolos-small-finetuned-masks","nickmuchi/yolos-base-finetuned-masks"]
110
  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"]
111
 
112
+ twitter_link = """
113
+ [![](https://img.shields.io/twitter/follow/nickmuchi?label=@nickmuchi&style=social)](https://twitter.com/nickmuchi)
114
+ """
115
+
116
  css = '''
117
  h1#title {
118
  text-align: center;
 
121
  demo = gr.Blocks(css=css)
122
 
123
  with demo:
124
+ with gr.Box():
125
 
126
  gr.Markdown(title)
127
+ gr.Markdown(description)
128
+ gr.Markdown(twitter_link)
129
+ options = gr.Dropdown(choices=models,label='Object Detection Model',show_label=True)
130
  slider_input = gr.Slider(minimum=0.2,maximum=1,value=0.5,step=0.1,label='Prediction Threshold')
131
 
132
  with gr.Tabs():
 
169
  example_url.click(fn=set_example_url,inputs=[example_url],outputs=[url_input,original_image])
170
 
171
 
172
+ gr.Markdown("![visitor badge](https://visitor-badge.glitch.me/badge?page_id=nickmuchi-face-mask-detections-with-yolos)")
173
+
174
+
175
+ demo.launch(debug=True,enable_queue=True)