Satyacoder commited on
Commit
fa97be6
·
1 Parent(s): 05ca97f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -0
app.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import DetrImageProcessor, DetrForObjectDetection
2
+ import torch
3
+ from PIL import Image
4
+ import requests
5
+ import gradio as gr
6
+
7
+ processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
8
+ model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
9
+
10
+ def predict_bounding_boxes(imageurl:str):
11
+ try:
12
+ response = requests.get(imageurl, stream=True)
13
+ response.raise_for_status() # Raise an exception for HTTP errors
14
+
15
+ image_data = Image.open(response.raw)
16
+ inputs = processor(images=image_data, return_tensors="pt")
17
+ outputs = model(**inputs)
18
+
19
+ target_sizes = torch.tensor([image_data.size[::-1]])
20
+ results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
21
+
22
+ detections = [{"score": score.item(), "label": model.config.id2label[label.item()], "box": box.tolist()} for score, label, box in zip(results["scores"], results["labels"], results["boxes"])]
23
+
24
+ # Wrap detections list inside a dictionary
25
+ return {"detections": detections}
26
+
27
+ except Exception as e:
28
+ # Handle errors gracefully
29
+ return {"error": str(e)}
30
+
31
+ app = gr.Interface(fn=predict_bounding_boxes, inputs="text", outputs="json")
32
+ app.api = True
33
+ app.launch(share=True)