D3V1L1810 commited on
Commit
0b72151
·
verified ·
1 Parent(s): 2e1b199

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -78
app.py CHANGED
@@ -1,109 +1,91 @@
1
  import gradio as gr
2
  from PIL import Image
3
  from ultralytics import YOLO
4
- import requests
 
5
  import json
6
  import logging
7
  import cv2
8
- from numpy import asarray
9
 
10
  logging.basicConfig(level=logging.INFO)
11
 
12
  model_detection = YOLO('./detection_best.pt')
13
  model_classification = YOLO('./classification_best.pt')
14
 
15
- def detect_objects(images):
16
- classes={ 2: "Positive", 1: "Negative"}
17
- names = []
18
- for image in images:
19
- image = asarray(image)
20
- image = cv2.resize(image,(640,640))
21
- results_detection = model_detection(image)
22
- print(results_detection)
23
- # Load the image using OpenCV
24
- # img = cv2.imread(image_path)
25
- # Process each detected object
26
- if results_detection:
27
- for result in results_detection:
28
- for box in result.boxes:
29
- # Get bounding box coordinates (x1, y1, x2, y2)
30
- x1, y1, x2, y2 = map(int, box.xyxy[0])
31
-
32
- # Crop the bounding box from the image
33
- cropped_img = image[y1:y2, x1:x2]
34
-
35
- # Resize the cropped image to 640x640
36
- resized_img = cv2.resize(cropped_img, (640, 640))
37
- resized_img = cv2.cvtColor(resized_img, cv2.COLOR_BGR2RGB)
38
- # Perform inference using the classification model
39
- results_classification = model_classification.predict(resized_img,save = True)
40
-
41
- detected = False
42
- print(results_classification)
43
- # Process classification results
44
- for res in results_classification:
45
- # Get class probabilities and labels
46
- top1_class = res.probs.top1 # Predicted class
47
- top1_confidence = res.probs.top1conf
48
- print(top1_class)
49
- names.append([classes[top1_class]])
50
- else:
51
- names.append(['None'])
52
- # print(names)
53
- return names
54
 
55
  def create_solutions(image_urls, names, file_ids):
56
- solutions = [] #list to store all the objects
57
-
58
- for image_url, class_name, file_id in zip(image_urls, names, file_ids):
59
- obj = {"image": image_url, "answer": [class_name], "qcUserId" : None, "normalfileID" : file_id }
60
- solutions.append(obj)
61
- return solutions
62
-
63
- # def send_results_to_api(data, result_url):
64
- # # Example function to send results to an API
65
- # headers = {"Content-Type": "application/json"}
66
- # response = requests.post(result_url, json=data, headers=headers)
67
- # if response.status_code == 200:
68
- # return response.json() # Return any response from the API if needed
69
- # else:
70
- # return {"error": f"Failed to send results to API: {response.status_code}"}
71
 
72
- def process_images(params):
73
  try:
74
  params = json.loads(params)
75
  except json.JSONDecodeError as e:
76
- logging.error(f"Invalid JSON input: {e.msg} at line {e.lineno} column {e.colno}")
77
- return {"error": f"Invalid JSON input: {e.msg} at line {e.lineno} column {e.colno}"}
78
-
79
  image_urls = params.get("urls", [])
80
- if not params.get("normalfileID",[]):
81
- file_ids = [None]*len(image_urls)
82
- else:
83
- file_ids = params.get("normalfileID",[])
84
- # api = params.get("api", "")
85
- # job_id = params.get("job_id", "")
86
-
87
  if not image_urls:
88
  logging.error("Missing required parameters: 'urls'")
89
  return {"error": "Missing required parameters: 'urls'"}
90
 
91
- try:
92
- images = [Image.open(requests.get(url, stream=True).raw) for url in image_urls] # images from URLs
93
- except Exception as e:
94
- logging.error(f"Error loading images: {e}")
95
- return {"error": f"Error loading images: {str(e)}"}
96
-
97
- names = detect_objects(images) # Perform object detection
98
- solutions = create_solutions(image_urls, names, file_ids) # Create solutions with image URLs and bounding boxes
99
 
100
- # result_url = f"{api}/{job_id}"
101
- # send_results_to_api(solutions, result_url)
 
 
 
 
102
 
103
  return json.dumps({"solutions": solutions})
104
 
 
 
 
105
  inputt = gr.Textbox(label="Parameters (JSON format) Eg. img_url:['','']")
106
  outputs = gr.JSON()
107
 
108
  application = gr.Interface(fn=process_images, inputs=inputt, outputs=outputs, title="ART +ve -ve Detection with API Integration")
109
- application.launch()
 
1
  import gradio as gr
2
  from PIL import Image
3
  from ultralytics import YOLO
4
+ import asyncio
5
+ import aiohttp
6
  import json
7
  import logging
8
  import cv2
9
+ from io import BytesIO
10
 
11
  logging.basicConfig(level=logging.INFO)
12
 
13
  model_detection = YOLO('./detection_best.pt')
14
  model_classification = YOLO('./classification_best.pt')
15
 
16
+ async def fetch_image(url):
17
+ async with aiohttp.ClientSession() as session:
18
+ async with session.get(url) as response:
19
+ if response.status == 200:
20
+ image_data = await response.read()
21
+ return Image.open(BytesIO(image_data))
22
+ else:
23
+ logging.error(f"Failed to load image from {url}")
24
+ return None
25
+
26
+ async def detect_objects(images):
27
+ classes = {2: "Positive", 1: "Negative"}
28
+ results = []
29
+
30
+ processed_images = [cv2.resize(np.array(image), (640, 640)) for image in images]
31
+
32
+ results_detection = model_detection(processed_images)
33
+
34
+ for image, detection in zip(processed_images, results_detection):
35
+ names = []
36
+ if detection:
37
+ for box in detection.boxes:
38
+ x1, y1, x2, y2 = map(int, box.xyxy[0])
39
+ cropped_img = image[y1:y2, x1:x2]
40
+ resized_img = cv2.resize(cropped_img, (640, 640))
41
+ resized_img = cv2.cvtColor(resized_img, cv2.COLOR_BGR2RGB)
42
+
43
+ results_classification = model_classification.predict(resized_img)
44
+
45
+ if results_classification:
46
+ top1_class = results_classification[0].probs.top1
47
+ names.append(classes[top1_class])
48
+ if not names:
49
+ names.append("None")
50
+ results.append(names)
51
+ return results
 
 
 
52
 
53
  def create_solutions(image_urls, names, file_ids):
54
+ return [
55
+ {"image": url, "answer": name, "qcUserId": None, "normalfileID": file_id}
56
+ for url, name, file_id in zip(image_urls, names, file_ids)
57
+ ]
 
 
 
 
 
 
 
 
 
 
 
58
 
59
+ async def process_images_async(params):
60
  try:
61
  params = json.loads(params)
62
  except json.JSONDecodeError as e:
63
+ logging.error(f"Invalid JSON input: {e}")
64
+ return {"error": f"Invalid JSON input: {e}"}
65
+
66
  image_urls = params.get("urls", [])
67
+ file_ids = params.get("normalfileID", [None] * len(image_urls))
68
+
 
 
 
 
 
69
  if not image_urls:
70
  logging.error("Missing required parameters: 'urls'")
71
  return {"error": "Missing required parameters: 'urls'"}
72
 
73
+ images = await asyncio.gather(*[fetch_image(url) for url in image_urls])
 
 
 
 
 
 
 
74
 
75
+ if not any(images):
76
+ logging.error("No valid images were loaded.")
77
+ return {"error": "No valid images were loaded."}
78
+
79
+ names = await detect_objects(images)
80
+ solutions = create_solutions(image_urls, names, file_ids)
81
 
82
  return json.dumps({"solutions": solutions})
83
 
84
+ def process_images(params):
85
+ return asyncio.run(process_images_async(params))
86
+
87
  inputt = gr.Textbox(label="Parameters (JSON format) Eg. img_url:['','']")
88
  outputs = gr.JSON()
89
 
90
  application = gr.Interface(fn=process_images, inputs=inputt, outputs=outputs, title="ART +ve -ve Detection with API Integration")
91
+ application.launch()