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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -157
app.py CHANGED
@@ -17,8 +17,7 @@ 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 (Replace DINO-X)
21
- # Pastikan Anda sudah set COUNTGD_API_KEY di .env
22
  COUNTGD_API_KEY = os.getenv("COUNTGD_API_KEY")
23
 
24
  # Inisialisasi YOLO Model dari Roboflow
@@ -26,220 +25,115 @@ 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
- # ========== Fungsi untuk Mengecek Overlap antara YOLO dan CountGD ==========
30
- def is_overlap(box1, boxes2, threshold=0.3):
31
- """
32
- Mengecek apakah box1 (format: (x_min, y_min, x_max, y_max)) overlap dengan salah satu box di boxes2.
33
- boxes2 adalah list bounding box YOLO dengan format (x_center, y_center, width, height).
34
- Mengembalikan True jika rasio overlap melebihi 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
- dx = min(x1_max, x2_max) - max(x1_min, x2_min)
45
- dy = min(y1_max, y2_max) - max(y1_min, y2_min)
46
- if dx > 0 and dy > 0:
47
- area_overlap = dx * dy
48
- area_box1 = (x1_max - x1_min) * (y1_max - y1_min)
49
- if area_box1 > 0 and (area_overlap / area_box1) > threshold:
50
- return True
51
- return False
52
-
53
- # ========== Fungsi untuk Menghitung IoU antar dua bounding box ==========
54
  def iou(boxA, boxB):
55
- """
56
- Menghitung Intersection over Union (IoU) antara dua bounding box.
57
- Masing-masing box dalam format (x_min, y_min, x_max, y_max).
58
- """
59
  xA = max(boxA[0], boxB[0])
60
  yA = max(boxA[1], boxB[1])
61
  xB = min(boxA[2], boxB[2])
62
  yB = min(boxA[3], boxB[3])
 
63
  interArea = max(0, xB - xA) * max(0, yB - yA)
64
  boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
65
  boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
66
- iou_val = interArea / float(boxAArea + boxBArea - interArea) if (boxAArea + boxBArea - interArea) > 0 else 0
67
- return iou_val
68
 
69
  # ========== Fungsi Deteksi Kombinasi ==========
70
  def detect_combined(image):
71
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
72
  image.save(temp_file, format="JPEG")
73
  temp_path = temp_file.name
74
-
75
  try:
76
- # ===== YOLO Detection (Produk Nestlé) =====
77
  yolo_pred = yolo_model.predict(temp_path, confidence=50, overlap=80).json()
78
  nestle_class_count = {}
79
- nestle_boxes = [] # List untuk menyimpan bounding box YOLO (format: x_center, y_center, width, height)
80
  for pred in yolo_pred['predictions']:
81
  class_name = pred['class']
82
  nestle_class_count[class_name] = nestle_class_count.get(class_name, 0) + 1
83
  nestle_boxes.append((pred['x'], pred['y'], pred['width'], pred['height']))
 
84
  total_nestle = sum(nestle_class_count.values())
85
-
86
- # ===== CountGD Detection (Produk Kompetitor) =====
87
  url = "https://api.landing.ai/v1/tools/text-to-object-detection"
88
  competitor_class_count = {}
89
- competitor_boxes = [] # List untuk menyimpan bounding box CountGD (format: x_min, y_min, x_max, y_max)
90
- # Daftar prompt yang akan digunakan
91
  COUNTGD_PROMPTS = ["cans", "bottle", "mixed box"]
92
  headers = {"Authorization": f"Basic {COUNTGD_API_KEY}"}
93
-
94
  for prompt in COUNTGD_PROMPTS:
95
  with open(temp_path, "rb") as f:
96
  files = {"image": f}
97
  data = {"prompts": [prompt], "model": "countgd"}
98
  response = requests.post(url, files=files, data=data, headers=headers)
99
  result = response.json()
 
100
  if 'data' in result and result['data']:
101
  detections = result['data'][0]
102
- for obj in detections:
 
 
103
  if 'bounding_box' in obj:
104
  x1, y1, x2, y2 = obj['bounding_box']
105
  countgd_box = (x1, y1, x2, y2)
106
- # Hanya tambahkan deteksi jika tidak overlap dengan deteksi YOLO
107
- if not is_overlap(countgd_box, nestle_boxes, threshold=0.3):
108
- # Cek duplikasi antar deteksi CountGD menggunakan IoU
109
- duplicate = False
110
- for existing_box in competitor_boxes:
111
- if iou(countgd_box, existing_box) > 0.5:
112
- duplicate = True
113
- break
114
- if not duplicate:
115
- # Gunakan label dari respons jika ada, jika tidak gunakan prompt sebagai default
116
- label = obj.get('label', prompt)
117
- competitor_class_count[label] = competitor_class_count.get(label, 0) + 1
118
- competitor_boxes.append(countgd_box)
 
 
 
 
 
119
  total_competitor = sum(competitor_class_count.values())
120
-
121
- # ===== Format Output Text =====
122
  result_text = "Product Nestlé\n\n"
123
  for class_name, count in nestle_class_count.items():
124
  result_text += f"{class_name}: {count}\n"
125
  result_text += f"\nTotal Products Nestlé: {total_nestle}\n\n"
 
126
  if total_competitor:
127
- #result_text += "Produk Kompetitor (CountGD):\n"
128
- #for label, count in competitor_class_count.items():
129
- # result_text += f"{label}: {count}\n"
130
  result_text += f"\nTotal Unclassified Products: {total_competitor}\n"
131
  else:
132
  result_text += "No Unclassified Products detected\n"
133
-
134
- # ===== Visualisasi =====
135
  img = cv2.imread(temp_path)
136
- # Gambar bounding box YOLO (hijau)
137
  for pred in yolo_pred['predictions']:
138
  x, y, w, h = pred['x'], pred['y'], pred['width'], pred['height']
139
  pt1 = (int(x - w/2), int(y - h/2))
140
  pt2 = (int(x + w/2), int(y + h/2))
141
  cv2.rectangle(img, pt1, pt2, (0, 255, 0), 2)
142
- cv2.putText(img, pred['class'], (pt1[0], pt1[1]-10),
143
- cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,255,0), 3)
144
- # Gambar bounding box CountGD (merah)
145
  for box in competitor_boxes:
146
  x1, y1, x2, y2 = box
147
  cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
148
- cv2.putText(img, "unclassified", (int(x1), int(y1)-10),
149
- cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,0,255), 3)
150
-
151
  output_path = "/tmp/combined_output.jpg"
152
  cv2.imwrite(output_path, img)
153
  return output_path, result_text
154
-
155
  except Exception as e:
156
  return temp_path, f"Error: {str(e)}"
157
-
158
  finally:
159
  if os.path.exists(temp_path):
160
  os.remove(temp_path)
161
 
162
- # ========== Fungsi untuk Deteksi Video ==========
163
- def convert_video_to_mp4(input_path, output_path):
164
- try:
165
- subprocess.run(['ffmpeg', '-i', input_path, '-vcodec', 'libx264', '-acodec', 'aac', output_path], check=True)
166
- return output_path
167
- except subprocess.CalledProcessError as e:
168
- return None, f"Error converting video: {e}"
169
-
170
- def detect_objects_in_video(video_path):
171
- temp_output_path = "/tmp/output_video.mp4"
172
- temp_frames_dir = tempfile.mkdtemp()
173
- frame_count = 0
174
- previous_detections = {} # Untuk menyimpan deteksi frame sebelumnya
175
-
176
- try:
177
- # Konversi video ke MP4 jika perlu
178
- if not video_path.endswith(".mp4"):
179
- video_path, err = convert_video_to_mp4(video_path, temp_output_path)
180
- if not video_path:
181
- return None, f"Video conversion error: {err}"
182
-
183
- video = cv2.VideoCapture(video_path)
184
- frame_rate = int(video.get(cv2.CAP_PROP_FPS))
185
- frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
186
- frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
187
- frame_size = (frame_width, frame_height)
188
-
189
- fourcc = cv2.VideoWriter_fourcc(*'mp4v')
190
- output_video = cv2.VideoWriter(temp_output_path, fourcc, frame_rate, frame_size)
191
-
192
- while True:
193
- ret, frame = video.read()
194
- if not ret:
195
- break
196
-
197
- frame_path = os.path.join(temp_frames_dir, f"frame_{frame_count}.jpg")
198
- cv2.imwrite(frame_path, frame)
199
-
200
- predictions = yolo_model.predict(frame_path, confidence=50, overlap=80).json()
201
-
202
- current_detections = {}
203
- for prediction in predictions['predictions']:
204
- class_name = prediction['class']
205
- x, y, w, h = prediction['x'], prediction['y'], prediction['width'], prediction['height']
206
- object_id = f"{class_name}_{x}_{y}_{w}_{h}"
207
- if object_id not in current_detections:
208
- current_detections[object_id] = class_name
209
- pt1 = (int(x - w/2), int(y - h/2))
210
- pt2 = (int(x + w/2), int(y + h/2))
211
- cv2.rectangle(frame, pt1, pt2, (0,255,0), 2)
212
- cv2.putText(frame, class_name, (pt1[0], pt1[1]-10),
213
- cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)
214
-
215
- object_counts = {}
216
- for detection_id in current_detections:
217
- cls = current_detections[detection_id]
218
- object_counts[cls] = object_counts.get(cls, 0) + 1
219
-
220
- count_text = ""
221
- total_product_count = 0
222
- for cls, count in object_counts.items():
223
- count_text += f"{cls}: {count}\n"
224
- total_product_count += count
225
- count_text += f"\nTotal Product: {total_product_count}"
226
- y_offset = 20
227
- for line in count_text.split("\n"):
228
- cv2.putText(frame, line, (10, y_offset), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255,255,255), 2)
229
- y_offset += 30
230
-
231
- output_video.write(frame)
232
- frame_count += 1
233
- previous_detections = current_detections
234
-
235
- video.release()
236
- output_video.release()
237
-
238
- return temp_output_path
239
-
240
- except Exception as e:
241
- return None, f"An error occurred: {e}"
242
-
243
  # ========== Gradio Interface ==========
244
  with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", neutral_hue="slate")) as iface:
245
  gr.Markdown("""<div style="text-align: center;"><h1>NESTLE - STOCK COUNTING</h1></div>""")
@@ -251,10 +145,5 @@ with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", ne
251
  output_image = gr.Image(label="Detect Object")
252
  output_text = gr.Textbox(label="Counting Object")
253
  detect_image_button.click(fn=detect_combined, inputs=input_image, outputs=[output_image, output_text])
254
- with gr.Column():
255
- input_video = gr.Video(label="Input Video")
256
- detect_video_button = gr.Button("Detect Video")
257
- output_video = gr.Video(label="Output Video")
258
- detect_video_button.click(fn=detect_objects_in_video, inputs=input_video, outputs=[output_video])
259
 
260
  iface.launch()
 
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
 
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
  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()