muhammadsalmanalfaridzi commited on
Commit
0aa4aac
·
verified ·
1 Parent(s): 8b978f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -70
app.py CHANGED
@@ -17,123 +17,205 @@ workspace = os.getenv("ROBOFLOW_WORKSPACE")
17
  project_name = os.getenv("ROBOFLOW_PROJECT")
18
  model_version = int(os.getenv("ROBOFLOW_MODEL_VERSION"))
19
 
20
- # CountGD Config
 
21
  COUNTGD_API_KEY = os.getenv("COUNTGD_API_KEY")
22
 
23
- # Inisialisasi YOLO Model dari Roboflow
24
  rf = Roboflow(api_key=rf_api_key)
25
  project = rf.workspace(workspace).project(project_name)
26
  yolo_model = project.version(model_version).model
27
 
28
- # ========== Fungsi untuk Menghitung IoU ==========
29
- def iou(boxA, boxB):
30
- xA = max(boxA[0], boxB[0])
31
- yA = max(boxA[1], boxB[1])
32
- xB = min(boxA[2], boxB[2])
33
- yB = min(boxA[3], boxB[3])
34
-
35
- interArea = max(0, xB - xA) * max(0, yB - yA)
36
- boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
37
- boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
38
-
39
- return interArea / float(boxAArea + boxBArea - interArea) if (boxAArea + boxBArea - interArea) > 0 else 0
40
-
41
- # ========== Fungsi Deteksi Kombinasi ==========
 
 
 
 
 
 
 
 
 
 
 
 
42
  def detect_combined(image):
43
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
44
  image.save(temp_file, format="JPEG")
45
  temp_path = temp_file.name
46
-
47
  try:
48
- # YOLO Detection (Produk Nestlé)
49
  yolo_pred = yolo_model.predict(temp_path, confidence=50, overlap=80).json()
50
  nestle_class_count = {}
51
- nestle_boxes = [] # (x_center, y_center, width, height)
52
  for pred in yolo_pred['predictions']:
53
  class_name = pred['class']
54
  nestle_class_count[class_name] = nestle_class_count.get(class_name, 0) + 1
55
  nestle_boxes.append((pred['x'], pred['y'], pred['width'], pred['height']))
56
-
57
  total_nestle = sum(nestle_class_count.values())
58
-
59
- # CountGD Detection (Produk Kompetitor)
60
  url = "https://api.landing.ai/v1/tools/text-to-object-detection"
61
- competitor_class_count = {}
62
- competitor_boxes = []
63
- COUNTGD_PROMPTS = ["cans", "bottle", "mixed box"]
64
  headers = {"Authorization": f"Basic {COUNTGD_API_KEY}"}
65
-
66
- for prompt in COUNTGD_PROMPTS:
67
- with open(temp_path, "rb") as f:
68
- files = {"image": f}
69
- data = {"prompts": [prompt], "model": "countgd"}
70
- response = requests.post(url, files=files, data=data, headers=headers)
71
- result = response.json()
72
-
73
- if 'data' in result and result['data']:
74
- detections = result['data'][0]
75
- detections_sorted = sorted(detections, key=lambda obj: obj.get('confidence', 0), reverse=True)
76
-
77
- for obj in detections_sorted:
78
- if 'bounding_box' in obj:
79
- x1, y1, x2, y2 = obj['bounding_box']
80
- countgd_box = (x1, y1, x2, y2)
81
-
82
- # Hapus duplikasi dengan deteksi YOLO
83
- if any(iou(countgd_box, yolo_box) > 0.3 for yolo_box in nestle_boxes):
84
- continue
85
-
86
- # Hapus duplikasi antar deteksi CountGD
87
- if any(iou(countgd_box, existing_box) > 0.3 for existing_box in competitor_boxes):
88
- continue
89
-
90
- label = obj.get('label', prompt)
91
-
92
- # Hapus "mixed box" jika ada "cans" atau "bottle" yang lebih spesifik
93
- if label == "mixed box" and ("cans" in competitor_class_count or "bottle" in competitor_class_count):
94
- continue
95
-
96
- competitor_class_count[label] = competitor_class_count.get(label, 0) + 1
97
  competitor_boxes.append(countgd_box)
98
-
99
  total_competitor = sum(competitor_class_count.values())
100
-
101
- # Format Output Text
102
  result_text = "Product Nestlé\n\n"
103
  for class_name, count in nestle_class_count.items():
104
  result_text += f"{class_name}: {count}\n"
105
  result_text += f"\nTotal Products Nestlé: {total_nestle}\n\n"
106
-
107
  if total_competitor:
108
- result_text += f"\nTotal Unclassified Products: {total_competitor}\n"
109
  else:
110
  result_text += "No Unclassified Products detected\n"
111
-
112
- # Visualisasi Bounding Box
113
  img = cv2.imread(temp_path)
 
114
  for pred in yolo_pred['predictions']:
115
  x, y, w, h = pred['x'], pred['y'], pred['width'], pred['height']
116
  pt1 = (int(x - w/2), int(y - h/2))
117
  pt2 = (int(x + w/2), int(y + h/2))
118
  cv2.rectangle(img, pt1, pt2, (0, 255, 0), 2)
119
- cv2.putText(img, pred['class'], (pt1[0], pt1[1]-10), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,255,0), 3)
120
-
 
121
  for box in competitor_boxes:
122
  x1, y1, x2, y2 = box
123
  cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
124
- cv2.putText(img, "unclassified", (int(x1), int(y1)-10), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,0,255), 3)
125
-
 
126
  output_path = "/tmp/combined_output.jpg"
127
  cv2.imwrite(output_path, img)
128
  return output_path, result_text
129
-
130
  except Exception as e:
131
  return temp_path, f"Error: {str(e)}"
132
-
133
  finally:
134
  if os.path.exists(temp_path):
135
  os.remove(temp_path)
136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  # ========== Gradio Interface ==========
138
  with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", neutral_hue="slate")) as iface:
139
  gr.Markdown("""<div style="text-align: center;"><h1>NESTLE - STOCK COUNTING</h1></div>""")
@@ -145,5 +227,10 @@ with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", ne
145
  output_image = gr.Image(label="Detect Object")
146
  output_text = gr.Textbox(label="Counting Object")
147
  detect_image_button.click(fn=detect_combined, inputs=input_image, outputs=[output_image, output_text])
 
 
 
 
 
148
 
149
  iface.launch()
 
17
  project_name = os.getenv("ROBOFLOW_PROJECT")
18
  model_version = int(os.getenv("ROBOFLOW_MODEL_VERSION"))
19
 
20
+ # CountGD Config (Replace DINO-X)
21
+ # Set your CountGD API key in your .env file (e.g., COUNTGD_API_KEY=YourEncodedAPIKey)
22
  COUNTGD_API_KEY = os.getenv("COUNTGD_API_KEY")
23
 
24
+ # Inisialisasi YOLO Model from Roboflow
25
  rf = Roboflow(api_key=rf_api_key)
26
  project = rf.workspace(workspace).project(project_name)
27
  yolo_model = project.version(model_version).model
28
 
29
+ # ========== Function to Check Overlap ==========
30
+ def is_overlap(box1, boxes2, threshold=0.3):
31
+ """
32
+ Checks if box1 (format: (x_min, y_min, x_max, y_max)) overlaps with any boxes in boxes2.
33
+ boxes2 is a list of YOLO bounding boxes in the format (x_center, y_center, width, height).
34
+ Returns True if the overlap ratio of box1 is greater than the threshold.
35
+ """
36
+ x1_min, y1_min, x1_max, y1_max = box1
37
+ for b2 in boxes2:
38
+ x_center, y_center, w2, h2 = b2
39
+ x2_min = x_center - w2 / 2
40
+ x2_max = x_center + w2 / 2
41
+ y2_min = y_center - h2 / 2
42
+ y2_max = y_center + h2 / 2
43
+
44
+ # Calculate overlap area
45
+ dx = min(x1_max, x2_max) - max(x1_min, x2_min)
46
+ dy = min(y1_max, y2_max) - max(y1_min, y2_min)
47
+ if dx > 0 and dy > 0:
48
+ area_overlap = dx * dy
49
+ area_box1 = (x1_max - x1_min) * (y1_max - y1_min)
50
+ if area_box1 > 0 and (area_overlap / area_box1) > threshold:
51
+ return True
52
+ return False
53
+
54
+ # ========== Combined Object Detection Function ==========
55
  def detect_combined(image):
56
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
57
  image.save(temp_file, format="JPEG")
58
  temp_path = temp_file.name
59
+
60
  try:
61
+ # ===== YOLO Detection (Nestlé products) =====
62
  yolo_pred = yolo_model.predict(temp_path, confidence=50, overlap=80).json()
63
  nestle_class_count = {}
64
+ nestle_boxes = [] # List to hold YOLO bounding boxes (format: x_center, y_center, width, height)
65
  for pred in yolo_pred['predictions']:
66
  class_name = pred['class']
67
  nestle_class_count[class_name] = nestle_class_count.get(class_name, 0) + 1
68
  nestle_boxes.append((pred['x'], pred['y'], pred['width'], pred['height']))
 
69
  total_nestle = sum(nestle_class_count.values())
70
+
71
+ # ===== CountGD Detection (Competitor products) =====
72
  url = "https://api.landing.ai/v1/tools/text-to-object-detection"
73
+ files = {"image": open(temp_path, "rb")}
74
+ data = {"prompts": ["mixed box"], "model": "countgd"}
 
75
  headers = {"Authorization": f"Basic {COUNTGD_API_KEY}"}
76
+ response = requests.post(url, files=files, data=data, headers=headers)
77
+ result = response.json()
78
+
79
+ competitor_class_count = {}
80
+ competitor_boxes = [] # List to hold CountGD bounding boxes (format: x_min, y_min, x_max, y_max)
81
+ if 'data' in result:
82
+ for obj in result['data'][0]:
83
+ if 'bounding_box' in obj:
84
+ # CountGD returns bounding_box as [x_min, y_min, x_max, y_max]
85
+ x1, y1, x2, y2 = obj['bounding_box']
86
+ countgd_box = (x1, y1, x2, y2)
87
+ # Only add CountGD detection if it does NOT significantly overlap with any YOLO detection
88
+ if not is_overlap(countgd_box, nestle_boxes, threshold=0.3):
89
+ class_name = "unclassified" # Generic label for competitor objects
90
+ competitor_class_count[class_name] = competitor_class_count.get(class_name, 0) + 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  competitor_boxes.append(countgd_box)
 
92
  total_competitor = sum(competitor_class_count.values())
93
+
94
+ # ===== Format Output Text =====
95
  result_text = "Product Nestlé\n\n"
96
  for class_name, count in nestle_class_count.items():
97
  result_text += f"{class_name}: {count}\n"
98
  result_text += f"\nTotal Products Nestlé: {total_nestle}\n\n"
 
99
  if total_competitor:
100
+ result_text += f"Total Unclassified Products: {total_competitor}\n"
101
  else:
102
  result_text += "No Unclassified Products detected\n"
103
+
104
+ # ===== Visualization =====
105
  img = cv2.imread(temp_path)
106
+ # Draw YOLO boxes in green
107
  for pred in yolo_pred['predictions']:
108
  x, y, w, h = pred['x'], pred['y'], pred['width'], pred['height']
109
  pt1 = (int(x - w/2), int(y - h/2))
110
  pt2 = (int(x + w/2), int(y + h/2))
111
  cv2.rectangle(img, pt1, pt2, (0, 255, 0), 2)
112
+ cv2.putText(img, pred['class'], (pt1[0], pt1[1]-10),
113
+ cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,255,0), 3)
114
+ # Draw CountGD boxes in red
115
  for box in competitor_boxes:
116
  x1, y1, x2, y2 = box
117
  cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
118
+ cv2.putText(img, "unclassified", (int(x1), int(y1)-10),
119
+ cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,0,255), 3)
120
+
121
  output_path = "/tmp/combined_output.jpg"
122
  cv2.imwrite(output_path, img)
123
  return output_path, result_text
124
+
125
  except Exception as e:
126
  return temp_path, f"Error: {str(e)}"
127
+
128
  finally:
129
  if os.path.exists(temp_path):
130
  os.remove(temp_path)
131
 
132
+ # ========== Video Detection Functions ==========
133
+ def convert_video_to_mp4(input_path, output_path):
134
+ try:
135
+ subprocess.run(['ffmpeg', '-i', input_path, '-vcodec', 'libx264', '-acodec', 'aac', output_path], check=True)
136
+ return output_path
137
+ except subprocess.CalledProcessError as e:
138
+ return None, f"Error converting video: {e}"
139
+
140
+ def detect_objects_in_video(video_path):
141
+ temp_output_path = "/tmp/output_video.mp4"
142
+ temp_frames_dir = tempfile.mkdtemp()
143
+ frame_count = 0
144
+ previous_detections = {} # For storing previous frame's detections
145
+
146
+ try:
147
+ # Convert video to MP4 if necessary
148
+ if not video_path.endswith(".mp4"):
149
+ video_path, err = convert_video_to_mp4(video_path, temp_output_path)
150
+ if not video_path:
151
+ return None, f"Video conversion error: {err}"
152
+
153
+ # Open video for processing
154
+ video = cv2.VideoCapture(video_path)
155
+ frame_rate = int(video.get(cv2.CAP_PROP_FPS))
156
+ frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
157
+ frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
158
+ frame_size = (frame_width, frame_height)
159
+
160
+ # Setup VideoWriter for output
161
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
162
+ output_video = cv2.VideoWriter(temp_output_path, fourcc, frame_rate, frame_size)
163
+
164
+ while True:
165
+ ret, frame = video.read()
166
+ if not ret:
167
+ break
168
+
169
+ # Save frame for YOLO detection
170
+ frame_path = os.path.join(temp_frames_dir, f"frame_{frame_count}.jpg")
171
+ cv2.imwrite(frame_path, frame)
172
+
173
+ # YOLO detection on the frame
174
+ predictions = yolo_model.predict(frame_path, confidence=50, overlap=80).json()
175
+
176
+ # Draw YOLO detections on the frame
177
+ current_detections = {}
178
+ for prediction in predictions['predictions']:
179
+ class_name = prediction['class']
180
+ x, y, w, h = prediction['x'], prediction['y'], prediction['width'], prediction['height']
181
+ object_id = f"{class_name}_{x}_{y}_{w}_{h}"
182
+ if object_id not in current_detections:
183
+ current_detections[object_id] = class_name
184
+ pt1 = (int(x - w/2), int(y - h/2))
185
+ pt2 = (int(x + w/2), int(y + h/2))
186
+ cv2.rectangle(frame, pt1, pt2, (0,255,0), 2)
187
+ cv2.putText(frame, class_name, (pt1[0], pt1[1]-10),
188
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)
189
+
190
+ # Count objects and overlay text
191
+ object_counts = {}
192
+ for detection_id in current_detections:
193
+ cls = current_detections[detection_id]
194
+ object_counts[cls] = object_counts.get(cls, 0) + 1
195
+
196
+ count_text = ""
197
+ total_product_count = 0
198
+ for cls, count in object_counts.items():
199
+ count_text += f"{cls}: {count}\n"
200
+ total_product_count += count
201
+ count_text += f"\nTotal Product: {total_product_count}"
202
+ y_offset = 20
203
+ for line in count_text.split("\n"):
204
+ cv2.putText(frame, line, (10, y_offset), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255,255,255), 2)
205
+ y_offset += 30
206
+
207
+ output_video.write(frame)
208
+ frame_count += 1
209
+ previous_detections = current_detections
210
+
211
+ video.release()
212
+ output_video.release()
213
+
214
+ return temp_output_path
215
+
216
+ except Exception as e:
217
+ return None, f"An error occurred: {e}"
218
+
219
  # ========== Gradio Interface ==========
220
  with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", neutral_hue="slate")) as iface:
221
  gr.Markdown("""<div style="text-align: center;"><h1>NESTLE - STOCK COUNTING</h1></div>""")
 
227
  output_image = gr.Image(label="Detect Object")
228
  output_text = gr.Textbox(label="Counting Object")
229
  detect_image_button.click(fn=detect_combined, inputs=input_image, outputs=[output_image, output_text])
230
+ with gr.Column():
231
+ input_video = gr.Video(label="Input Video")
232
+ detect_video_button = gr.Button("Detect Video")
233
+ output_video = gr.Video(label="Output Video")
234
+ detect_video_button.click(fn=detect_objects_in_video, inputs=input_video, outputs=[output_video])
235
 
236
  iface.launch()