omarhkh commited on
Commit
309b3ae
1 Parent(s): 7fac689

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -1
app.py CHANGED
@@ -1,3 +1,135 @@
 
1
  import gradio as gr
 
 
 
 
 
 
2
 
3
- gr.Interface.load("models/omarhkh/detr-finetuned-omar8").launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, DetrForObjectDetection, YolosForObjectDetection
9
 
10
+ import os
11
+
12
+ # colors for visualization
13
+ COLORS = [
14
+ [0.000, 0.447, 0.741],
15
+ [0.850, 0.325, 0.098],
16
+ [0.929, 0.694, 0.125],
17
+ [0.494, 0.184, 0.556],
18
+ [0.466, 0.674, 0.188],
19
+ [0.301, 0.745, 0.933]
20
+ ]
21
+
22
+ def make_prediction(img, feature_extractor, model):
23
+ inputs = feature_extractor(img, return_tensors="pt")
24
+ outputs = model(**inputs)
25
+ img_size = torch.tensor([tuple(reversed(img.size))])
26
+ processed_outputs = feature_extractor.post_process(outputs, img_size)
27
+ return processed_outputs[0]
28
+
29
+ def fig2img(fig):
30
+ buf = io.BytesIO()
31
+ fig.savefig(buf)
32
+ buf.seek(0)
33
+ img = Image.open(buf)
34
+ return img
35
+
36
+
37
+ def visualize_prediction(pil_img, output_dict, threshold=0.7, id2label=None):
38
+ keep = output_dict["scores"] > threshold
39
+ boxes = output_dict["boxes"][keep].tolist()
40
+ scores = output_dict["scores"][keep].tolist()
41
+ labels = output_dict["labels"][keep].tolist()
42
+ if id2label is not None:
43
+ labels = [id2label[x] for x in labels]
44
+
45
+ plt.figure(figsize=(16, 10))
46
+ plt.imshow(pil_img)
47
+ ax = plt.gca()
48
+ colors = COLORS * 100
49
+ for score, (xmin, ymin, xmax, ymax), label, color in zip(scores, boxes, labels, colors):
50
+ ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=color, linewidth=3))
51
+ ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=15, bbox=dict(facecolor="yellow", alpha=0.5))
52
+ plt.axis("off")
53
+ return fig2img(plt.gcf())
54
+
55
+ def detect_objects(model_name,url_input,image_input,threshold):
56
+
57
+ #Extract model and feature extractor
58
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
59
+
60
+
61
+
62
+ model = DetrForObjectDetection.from_pretrained(model_name)
63
+
64
+
65
+
66
+
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">Object Detection App with DETR and YOLOS</h1>"""
85
+
86
+ description = """
87
+ Links to HuggingFace Models:
88
+ - [facebook/detr-resnet-50](https://huggingface.co/facebook/detr-resnet-50)
89
+ - [facebook/detr-resnet-101](https://huggingface.co/facebook/detr-resnet-101)
90
+ - [hustvl/yolos-small](https://huggingface.co/hustvl/yolos-small)
91
+ - [hustvl/yolos-tiny](https://huggingface.co/hustvl/yolos-tiny)
92
+ """
93
+
94
+ models = ["omarhkh/detr-finetuned-omar8"]
95
+
96
+
97
+ css = '''
98
+ h1#title {
99
+ text-align: center;
100
+ }
101
+ '''
102
+
103
+ demo = gr.Blocks(css=css)
104
+
105
+ with demo:
106
+ gr.Markdown(title)
107
+ gr.Markdown(description)
108
+
109
+ options = gr.Dropdown(choices=models,label='Select Object Detection Model',show_label=True)
110
+ slider_input = gr.Slider(minimum=0.1,maximum=1,value=0.7,label='Prediction Threshold')
111
+
112
+ with gr.Tabs():
113
+
114
+
115
+ with gr.TabItem('Image Upload'):
116
+ with gr.Row():
117
+ img_input = gr.Image(type='pil')
118
+ img_output_from_upload= gr.Image(shape=(650,650))
119
+
120
+ with gr.Row():
121
+ example_images = gr.Dataset(components=[img_input],
122
+ samples=[[path.as_posix()]
123
+ for path in sorted(pathlib.Path('images').rglob('*.JPG'))])
124
+
125
+ img_but = gr.Button('Detect')
126
+
127
+
128
+
129
+ example_images.click(fn=set_example_image,inputs=[example_images],outputs=[img_input])
130
+
131
+
132
+
133
+
134
+
135
+ demo.launch(enable_queue=True)