janasumit2911 commited on
Commit
9972c0a
·
verified ·
1 Parent(s): 3fef183

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -0
app.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image
3
+ from ultralytics import YOLO
4
+ import requests
5
+ import json
6
+
7
+ model = YOLO("Multiple_Object_BB_Detection_v1.pt")
8
+
9
+ def detect_objects(images):
10
+ results = model(images)
11
+ all_bboxes = []
12
+ all_bboxes2 = []
13
+ for result in results:
14
+ boxes = result.boxes.xywhn.tolist()
15
+ boxes2 = result.boxes.xywh.tolist()
16
+ all_bboxes.append(boxes)
17
+ all_bboxes2.append(boxes2)
18
+ return all_bboxes, all_bboxes2
19
+
20
+ def create_solutions(image_urls, all_bboxes, all_bboxes2):
21
+ solutions = []
22
+ img_id =1
23
+ box_id =1
24
+ cat_id =1
25
+ for image_url, bbox, bbox2 in zip(images, bboxes, bboxes2): # Loop through each image ID and its corresponding prediction
26
+
27
+ for subbox, subbox2 in zip(bbox, bbox2):
28
+
29
+ w = subbox2[2]
30
+ h = subbox2[3]
31
+ area = w*h
32
+ seg=[[]]
33
+ ans = {"segmentation":seg, "area":area, 'iscrowd':0, "image_id":img_id, "bbox": subbox, "category_id":cat_id, "id":box_id }
34
+ ansx=[]
35
+ ansx.append(ans)
36
+ obj = {"image_url": image_url, 'answer':ansx}
37
+ box_id +=1
38
+ solutions.append(obj)
39
+ img_id +=1
40
+ return solutions
41
+
42
+ def send_results_to_api(data, result_url):
43
+ # Example function to send results to an API
44
+ headers = {"Content-Type": "application/json"}
45
+ response = requests.post(result_url, json=data, headers=headers)
46
+ if response.status_code == 200:
47
+ return response.json() # Return any response from the API if needed
48
+ else:
49
+ return {"error": f"Failed to send results to API: {response.status_code}"}
50
+
51
+ def process_images(params):
52
+ # Parse the JSON string into a dictionary
53
+ params = json.loads(params)
54
+
55
+ image_urls = params.get("image_urls", [])
56
+ api = params.get("api", "")
57
+ job_id = params.get("job_id", "")
58
+
59
+ images = [Image.open(requests.get(url, stream=True).raw) for url in image_urls] # images from URLs
60
+
61
+ all_bboxes, all_bboxes2 = detect_objects(images) # Perform object detection
62
+ solutions = create_solutions(image_urls, all_bboxes, all_bboxes2) # Create solutions with image URLs and bounding boxes
63
+
64
+ result_url = f"{api}/{job_id}"
65
+ # send_results_to_api(solutions, result_url)
66
+
67
+ return json.dumps({"solutions": solutions}, indent=4)
68
+
69
+
70
+ inputt = gr.Textbox(label="Parameters (JSON format)")
71
+ outputs = gr.JSON()
72
+
73
+ application = gr.Interface(fn=process_images, inputs=inputt, outputs=outputs, title="Multiple Object Detection with API Integration")
74
+ application.launch()