janasumit2911 commited on
Commit
3ac154d
·
verified ·
1 Parent(s): f33eba9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -0
app.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image
3
+ from ultralytics import YOLO
4
+ import requests
5
+ import json
6
+
7
+ # Load the pretrained YOLO model
8
+ model = YOLO("Single_Object_BB_Detection_v1.pt")
9
+
10
+
11
+ Api = "myapi" # API endpoint
12
+
13
+ def detect_objects(images):
14
+ results = model(images, max_det=1)
15
+ all_bboxes = []
16
+ all_bboxes2 = []
17
+ for result in results:
18
+ boxes = result.boxes.xywhn.tolist()
19
+ boxes2 = result.boxes.xywh.tolist()
20
+ all_bboxes.append(boxes)
21
+ all_bboxes2.append(boxes2)
22
+ return all_bboxes, all_bboxes2
23
+
24
+
25
+ def create_solutions(image_urls, all_bboxes, all_bboxes2):
26
+ solutions = []
27
+ img_id = 1
28
+ box_id = 1
29
+ category_id = 1
30
+ for image_url, bboxes, bboxes2 in zip(image_urls, all_bboxes, all_bboxes2):
31
+ for box, box2 in zip(bboxes, bboxes2):
32
+ if isinstance(box2[0], list):
33
+ w = box2[0][2]
34
+ h = box2[0][3]
35
+ else:
36
+ w = box2[2]
37
+ h = box2[3]
38
+
39
+ area = w * h
40
+ seg = [[]]
41
+
42
+ ans = {
43
+ "segmentation": seg,
44
+ "area": area,
45
+ "iscrowd": 0,
46
+ "image_id": img_id,
47
+ "bbox": box,
48
+ "category_id": category_id,
49
+ "id": box_id
50
+ }
51
+ obj = {"url": image_url, "answer": [ans]}
52
+ solutions.append(obj)
53
+
54
+ box_id += 1
55
+ img_id += 1
56
+ return solutions
57
+
58
+
59
+ def process_images(params):
60
+ image_urls = params.get("image_urls", [])
61
+ api = params.get("api", "")
62
+ job_id = params.get("job_id", "")
63
+
64
+ images = [Image.open(requests.get(url, stream=True).raw) for url in image_urls] # images from URLs
65
+
66
+ all_bboxes, all_bboxes2 = detect_objects(images) # Perform object detection
67
+ solutions = create_solutions(image_urls, all_bboxes, all_bboxes2) # Createing solutions with image URLs and bounding boxes
68
+
69
+ result_url = Api + f"{api}/{job_id}"
70
+ # send_results_to_api(solutions, result_url)
71
+
72
+ return json.dumps({"result_url": result_url, "solutions": solutions}, indent=4)
73
+
74
+ # def send_results_to_api(data, result_url):
75
+ # response = requests.post(result_url, json=data)
76
+ # if response.status_code == 200:
77
+ # return response.json()
78
+ # else:
79
+ # return {"error": "Failed to send results to API"}
80
+
81
+ #interface
82
+ chatbox = gr.Textbox(default="Enter parameters here...", label="Parameters (JSON format)")
83
+ outputs = gr.JSON()
84
+
85
+ application = gr.Interface(fn=process_images, inputs=chatbox, outputs=outputs, title="Image Detection with API Integration")
86
+ application.launch()