Update app.py
Browse files
app.py
CHANGED
|
@@ -1,251 +1,71 @@
|
|
| 1 |
-
import io
|
| 2 |
import gradio as gr
|
| 3 |
-
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
#
|
| 14 |
-
|
| 15 |
-
[
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
results = model.predict(image_input)
|
| 75 |
-
|
| 76 |
-
render = render_result(model=model, image=image_input, result=results[0])
|
| 77 |
-
|
| 78 |
-
final_str = ""
|
| 79 |
-
final_str_abv = ""
|
| 80 |
-
final_str_else = ""
|
| 81 |
-
|
| 82 |
-
for result in results:
|
| 83 |
-
boxes = result.boxes.cpu().numpy()
|
| 84 |
-
for i, box in enumerate(boxes):
|
| 85 |
-
# r = box.xyxy[0].astype(int)
|
| 86 |
-
coordinates = box.xyxy[0].astype(int)
|
| 87 |
-
try:
|
| 88 |
-
label = YOLOV8_LABELS[int(box.cls)]
|
| 89 |
-
except:
|
| 90 |
-
label = "ERROR"
|
| 91 |
-
try:
|
| 92 |
-
confi = float(box.conf)
|
| 93 |
-
except:
|
| 94 |
-
confi = 0.0
|
| 95 |
-
# final_str_abv += str() + "__" + str(box.cls) + "__" + str(box.conf) + "__" + str(box) + "\n"
|
| 96 |
-
if confi >= threshold:
|
| 97 |
-
final_str_abv += f"Detected `{label}` with confidence `{confi}` at location `{coordinates}`\n"
|
| 98 |
-
else:
|
| 99 |
-
final_str_else += f"Detected `{label}` with confidence `{confi}` at location `{coordinates}`\n"
|
| 100 |
-
|
| 101 |
-
final_str = "{:*^50}\n".format("ABOVE THRESHOLD OR EQUAL") + final_str_abv + "\n{:*^50}\n".format("BELOW THRESHOLD")+final_str_else
|
| 102 |
-
|
| 103 |
-
return render, final_str
|
| 104 |
-
else:
|
| 105 |
-
|
| 106 |
-
#Extract model and feature extractor
|
| 107 |
-
feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
|
| 108 |
-
if 'detr' in model_name:
|
| 109 |
-
|
| 110 |
-
model = DetrForObjectDetection.from_pretrained(model_name)
|
| 111 |
-
|
| 112 |
-
elif 'yolos' in model_name:
|
| 113 |
-
|
| 114 |
-
model = YolosForObjectDetection.from_pretrained(model_name)
|
| 115 |
-
|
| 116 |
-
tb_label = ""
|
| 117 |
-
if validators.url(url_input):
|
| 118 |
-
image = Image.open(requests.get(url_input, stream=True).raw)
|
| 119 |
-
tb_label = "Confidence Values URL"
|
| 120 |
-
|
| 121 |
-
elif image_input:
|
| 122 |
-
image = image_input
|
| 123 |
-
tb_label = "Confidence Values Upload"
|
| 124 |
-
|
| 125 |
-
#Make prediction
|
| 126 |
-
processed_output_list = make_prediction(image, feature_extractor, model)
|
| 127 |
-
# print("After make_prediction" + str(processed_output_list))
|
| 128 |
-
processed_outputs = processed_output_list[0]
|
| 129 |
-
|
| 130 |
-
#Visualize prediction
|
| 131 |
-
viz_img = visualize_prediction(image, processed_outputs, threshold, model.config.id2label)
|
| 132 |
-
|
| 133 |
-
# return [viz_img, processed_outputs]
|
| 134 |
-
# print(type(viz_img))
|
| 135 |
-
|
| 136 |
-
final_str_abv = ""
|
| 137 |
-
final_str_else = ""
|
| 138 |
-
for score, label, box in sorted(zip(processed_outputs["scores"], processed_outputs["labels"], processed_outputs["boxes"]), key = lambda x: x[0].item(), reverse=True):
|
| 139 |
-
box = [round(i, 2) for i in box.tolist()]
|
| 140 |
-
if score.item() >= threshold:
|
| 141 |
-
final_str_abv += f"Detected `{model.config.id2label[label.item()]}` with confidence `{round(score.item(), 3)}` at location `{box}`\n"
|
| 142 |
-
else:
|
| 143 |
-
final_str_else += f"Detected `{model.config.id2label[label.item()]}` with confidence `{round(score.item(), 3)}` at location `{box}`\n"
|
| 144 |
-
|
| 145 |
-
# https://docs.python.org/3/library/string.html#format-examples
|
| 146 |
-
final_str = "{:*^50}\n".format("ABOVE THRESHOLD OR EQUAL") + final_str_abv + "\n{:*^50}\n".format("BELOW THRESHOLD")+final_str_else
|
| 147 |
-
|
| 148 |
-
return viz_img, final_str
|
| 149 |
-
|
| 150 |
-
def set_example_image(example: list) -> dict:
|
| 151 |
-
return gr.Image(value=example[0]["path"])
|
| 152 |
-
|
| 153 |
-
def set_example_url(example: list) -> dict:
|
| 154 |
-
return gr.Textbox(value=example[0]["path"])
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
title = """<h1 id="title">Object Detection App with DETR and YOLOS</h1>"""
|
| 158 |
-
|
| 159 |
-
description = """
|
| 160 |
-
Links to HuggingFace Models:
|
| 161 |
-
|
| 162 |
-
- [facebook/detr-resnet-50](https://huggingface.co/facebook/detr-resnet-50)
|
| 163 |
-
- [facebook/detr-resnet-101](https://huggingface.co/facebook/detr-resnet-101)
|
| 164 |
-
- [hustvl/yolos-small](https://huggingface.co/hustvl/yolos-small)
|
| 165 |
-
- [hustvl/yolos-tiny](https://huggingface.co/hustvl/yolos-tiny)
|
| 166 |
-
- [facebook/detr-resnet-101-dc5](https://huggingface.co/facebook/detr-resnet-101-dc5)
|
| 167 |
-
- [hustvl/yolos-small-300](https://huggingface.co/hustvl/yolos-small-300)
|
| 168 |
-
- [mshamrai/yolov8x-visdrone](https://huggingface.co/mshamrai/yolov8x-visdrone)
|
| 169 |
-
|
| 170 |
-
"""
|
| 171 |
-
|
| 172 |
-
models = ["facebook/detr-resnet-50","facebook/detr-resnet-101",'hustvl/yolos-small','hustvl/yolos-tiny','facebook/detr-resnet-101-dc5', 'hustvl/yolos-small-300', 'mshamrai/yolov8x-visdrone']
|
| 173 |
-
urls = ["https://c8.alamy.com/comp/J2AB4K/the-new-york-stock-exchange-on-the-wall-street-in-new-york-J2AB4K.jpg"]
|
| 174 |
-
|
| 175 |
-
# twitter_link = """
|
| 176 |
-
# [](https://twitter.com/nickmuchi)
|
| 177 |
-
# """
|
| 178 |
-
|
| 179 |
-
css = '''
|
| 180 |
-
h1#title {
|
| 181 |
-
text-align: center;
|
| 182 |
-
}
|
| 183 |
-
'''
|
| 184 |
-
demo = gr.Blocks(css=css)
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
def changing():
|
| 188 |
-
# https://discuss.huggingface.co/t/how-to-programmatically-enable-or-disable-components/52350/4
|
| 189 |
-
return gr.Button('Detect', interactive=True), gr.Button('Detect', interactive=True)
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
with demo:
|
| 194 |
-
gr.Markdown(title)
|
| 195 |
-
gr.Markdown(description)
|
| 196 |
-
# gr.Markdown(twitter_link)
|
| 197 |
-
options = gr.Dropdown(choices=models,label='Select Object Detection Model',show_label=True)
|
| 198 |
-
|
| 199 |
-
slider_input = gr.Slider(minimum=0.2,maximum=1,value=0.7,label='Prediction Threshold')
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
with gr.Tabs():
|
| 204 |
-
with gr.TabItem('Image URL'):
|
| 205 |
-
with gr.Row():
|
| 206 |
-
url_input = gr.Textbox(lines=2,label='Enter valid image URL here..')
|
| 207 |
-
img_output_from_url = gr.Image(height=650,width=650)
|
| 208 |
-
|
| 209 |
-
with gr.Row():
|
| 210 |
-
example_url = gr.Dataset(components=[url_input],samples=[[str(url)] for url in urls])
|
| 211 |
-
|
| 212 |
-
url_but = gr.Button('Detect', interactive=False)
|
| 213 |
-
|
| 214 |
-
with gr.TabItem('Image Upload'):
|
| 215 |
-
with gr.Row():
|
| 216 |
-
img_input = gr.Image(type='pil')
|
| 217 |
-
img_output_from_upload= gr.Image(height=650,width=650)
|
| 218 |
-
|
| 219 |
-
with gr.Row():
|
| 220 |
-
example_images = gr.Dataset(components=[img_input],
|
| 221 |
-
samples=[[path.as_posix()]
|
| 222 |
-
for path in sorted(pathlib.Path('images').rglob('*.JPG'))]) # Can't get case_sensitive to work
|
| 223 |
-
|
| 224 |
-
img_but = gr.Button('Detect', interactive=False)
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
# output_text1 = gr.outputs.Textbox(label="Confidence Values")
|
| 228 |
-
output_text1 = gr.components.Textbox(label="Confidence Values")
|
| 229 |
-
# https://huggingface.co/spaces/vishnun/CLIPnCROP/blob/main/app.py -- Got .outputs. from this
|
| 230 |
-
|
| 231 |
-
options.change(fn=changing, inputs=[], outputs=[img_but, url_but])
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
url_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=[img_output_from_url, output_text1],queue=True)
|
| 235 |
-
img_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=[img_output_from_upload, output_text1],queue=True)
|
| 236 |
-
# url_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=[img_output_from_url, _],queue=True)
|
| 237 |
-
# img_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=[img_output_from_upload, _],queue=True)
|
| 238 |
-
|
| 239 |
-
# url_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=img_output_from_url,queue=True)
|
| 240 |
-
# img_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=img_output_from_upload,queue=True)
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
example_images.click(fn=set_example_image,inputs=[example_images],outputs=[img_input])
|
| 244 |
-
example_url.click(fn=set_example_url,inputs=[example_url],outputs=[url_input])
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
# gr.Markdown("")
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
# demo.launch(enable_queue=True)
|
| 251 |
-
demo.launch() #removed (share=True)
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 4 |
+
import tempfile
|
| 5 |
+
|
| 6 |
+
# Load the YOLOS object detection model
|
| 7 |
+
detector = pipeline("object-detection", model="hustvl/yolos-small")
|
| 8 |
+
|
| 9 |
+
# Define some colors to differentiate classes
|
| 10 |
+
COLORS = ["red", "blue", "green", "orange", "purple", "yellow", "cyan", "magenta"]
|
| 11 |
+
|
| 12 |
+
# Helper function to assign color per label
|
| 13 |
+
def get_color_for_label(label):
|
| 14 |
+
return COLORS[hash(label) % len(COLORS)]
|
| 15 |
+
|
| 16 |
+
# Main function: detect, draw, and return outputs
|
| 17 |
+
def detect_and_draw(image, threshold):
|
| 18 |
+
results = detector(image)
|
| 19 |
+
image = image.convert("RGB")
|
| 20 |
+
draw = ImageDraw.Draw(image)
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
font = ImageFont.truetype("arial.ttf", 16)
|
| 24 |
+
except:
|
| 25 |
+
font = ImageFont.load_default()
|
| 26 |
+
|
| 27 |
+
annotations = []
|
| 28 |
+
|
| 29 |
+
for obj in results:
|
| 30 |
+
score = obj["score"]
|
| 31 |
+
if score < threshold:
|
| 32 |
+
continue
|
| 33 |
+
|
| 34 |
+
label = f"{obj['label']} ({score:.2f})"
|
| 35 |
+
box = obj["box"]
|
| 36 |
+
color = get_color_for_label(obj["label"])
|
| 37 |
+
|
| 38 |
+
draw.rectangle(
|
| 39 |
+
[(box["xmin"], box["ymin"]), (box["xmax"], box["ymax"])],
|
| 40 |
+
outline=color,
|
| 41 |
+
width=3,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
draw.text((box["xmin"] + 5, box["ymin"] + 5), label, fill=color, font=font)
|
| 45 |
+
|
| 46 |
+
box_coords = (box["xmin"], box["ymin"], box["xmax"], box["ymax"])
|
| 47 |
+
annotations.append((box_coords, label))
|
| 48 |
+
|
| 49 |
+
# Save image for download
|
| 50 |
+
temp_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
|
| 51 |
+
image.save(temp_file.name)
|
| 52 |
+
|
| 53 |
+
# ✅ Return the (image, annotations) tuple and the path to the saved image
|
| 54 |
+
return (image, annotations), temp_file.name
|
| 55 |
+
|
| 56 |
+
# Gradio UI setup
|
| 57 |
+
demo = gr.Interface(
|
| 58 |
+
fn=detect_and_draw,
|
| 59 |
+
inputs=[
|
| 60 |
+
gr.Image(type="pil", label="Upload Image"),
|
| 61 |
+
gr.Slider(minimum=0.1, maximum=1.0, value=0.5, step=0.05, label="Confidence Threshold"),
|
| 62 |
+
],
|
| 63 |
+
outputs=[
|
| 64 |
+
gr.AnnotatedImage(label="Detected Image"),
|
| 65 |
+
gr.File(label="Download Processed Image"),
|
| 66 |
+
],
|
| 67 |
+
title="YOLOS Object Detection",
|
| 68 |
+
description="Upload an image to detect objects using the YOLOS-small model. Adjust the confidence threshold using the slider.",
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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