muhammadsalmanalfaridzi commited on
Commit
1f8598c
·
verified ·
1 Parent(s): 49fea9e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +163 -47
app.py CHANGED
@@ -8,7 +8,7 @@ import cv2
8
  import numpy as np
9
  import subprocess
10
 
11
- # ========== Konfigurasi ==========
12
  load_dotenv()
13
 
14
  # Roboflow Config
@@ -17,95 +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
- # Landing AI CountGD Config
21
- COUNTGD_API_KEY = os.getenv("COUNTGD_API_KEY")
22
- COUNTGD_URL = "https://api.landing.ai/v1/tools/text-to-object-detection"
23
- COUNTGD_PROMPT = ["beverage", "bottle", "cans", "mixed box"] # Sesuaikan prompt
24
 
25
- # Inisialisasi Model
26
  rf = Roboflow(api_key=rf_api_key)
27
  project = rf.workspace(workspace).project(project_name)
28
  yolo_model = project.version(model_version).model
29
 
30
- # ========== Fungsi Deteksi Kombinasi ==========
31
  def detect_combined(image):
32
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
33
  image.save(temp_file, format="JPEG")
34
  temp_path = temp_file.name
35
 
36
  try:
37
- # ========== [1] YOLO: Deteksi Produk Nestlé ==========
38
  yolo_pred = yolo_model.predict(temp_path, confidence=50, overlap=80).json()
39
-
 
40
  nestle_class_count = {}
41
  nestle_boxes = []
42
  for pred in yolo_pred['predictions']:
43
  class_name = pred['class']
44
  nestle_class_count[class_name] = nestle_class_count.get(class_name, 0) + 1
45
  nestle_boxes.append((pred['x'], pred['y'], pred['width'], pred['height']))
46
-
47
  total_nestle = sum(nestle_class_count.values())
48
-
49
- # ========== [2] CountGD: Deteksi Kompetitor ==========
50
- with open(temp_path, 'rb') as img_file:
51
- files = {"image": img_file}
52
- data = {"prompts": COUNTGD_PROMPT, "model": "countgd"}
53
- headers = {"Authorization": f"Basic {COUNTGD_API_KEY}"}
54
- response = requests.post(COUNTGD_URL, files=files, data=data, headers=headers)
55
- countgd_pred = response.json()
56
-
 
 
 
 
 
 
57
  competitor_class_count = {}
58
  competitor_boxes = []
59
- for obj in countgd_pred.get("objects", []):
60
- class_name = obj['category'].strip().lower()
61
- competitor_class_count[class_name] = competitor_class_count.get(class_name, 0) + 1
62
- competitor_boxes.append({
63
- "class": class_name,
64
- "box": obj['bbox'],
65
- "confidence": obj['score']
66
- })
67
-
 
 
 
68
  total_competitor = sum(competitor_class_count.values())
69
-
70
- # ========== [3] Format Output ==========
71
- result_text = "Product Nestlé\n\n"
72
  for class_name, count in nestle_class_count.items():
73
  result_text += f"{class_name}: {count}\n"
74
- result_text += f"\nTotal Products Nestlé: {total_nestle}\n\n"
75
-
76
  if competitor_class_count:
77
  result_text += f"Total Unclassified Products: {total_competitor}\n"
78
  else:
79
  result_text += "No Unclassified Products detected\n"
80
-
81
- # ========== [4] Visualisasi ==========
82
  img = cv2.imread(temp_path)
83
-
84
- # Nestlé (Hijau)
85
  for pred in yolo_pred['predictions']:
86
  x, y, w, h = pred['x'], pred['y'], pred['width'], pred['height']
87
- cv2.rectangle(img, (int(x-w/2), int(y-h/2)), (int(x+w/2), int(y+h/2)), (0,255,0), 2)
88
- cv2.putText(img, pred['class'], (int(x-w/2), int(y-h/2-10)),
89
- cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)
90
-
91
- # Kompetitor (Merah)
92
  for comp in competitor_boxes:
93
  x1, y1, x2, y2 = comp['box']
 
 
94
  cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
95
- cv2.putText(img, f"{comp['class']} {comp['confidence']:.2f}",
96
- (int(x1), int(y1-10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
97
-
98
  output_path = "/tmp/combined_output.jpg"
99
  cv2.imwrite(output_path, img)
100
 
101
  return output_path, result_text
102
-
103
  except Exception as e:
104
  return temp_path, f"Error: {str(e)}"
105
  finally:
106
  os.remove(temp_path)
107
 
108
- # ========== Gradio Interface ==========
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", neutral_hue="slate")) as iface:
110
  gr.Markdown("""<div style="text-align: center;"><h1>NESTLE - STOCK COUNTING</h1></div>""")
111
 
@@ -117,4 +227,10 @@ with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", ne
117
  output_text = gr.Textbox(label="Counting Object")
118
  detect_image_button.click(fn=detect_combined, inputs=input_image, outputs=[output_image, output_text])
119
 
 
 
 
 
 
 
120
  iface.launch()
 
8
  import numpy as np
9
  import subprocess
10
 
11
+ # ========== Konfigurasi ==========
12
  load_dotenv()
13
 
14
  # Roboflow Config
 
17
  project_name = os.getenv("ROBOFLOW_PROJECT")
18
  model_version = int(os.getenv("ROBOFLOW_MODEL_VERSION"))
19
 
20
+ # CountGD Config
21
+ # Prompt yang digunakan untuk mendeteksi objek kompetitor
22
+ COUNTGD_PROMPT = "beverage . bottle . cans . mixed box"
 
23
 
24
+ # Inisialisasi Model YOLO dari 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
+ # ========== Fungsi Deteksi Kombinasi ==========
30
  def detect_combined(image):
31
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
32
  image.save(temp_file, format="JPEG")
33
  temp_path = temp_file.name
34
 
35
  try:
36
+ # ========== [1] YOLO: Deteksi Produk Nestlé (Per Class) ==========
37
  yolo_pred = yolo_model.predict(temp_path, confidence=50, overlap=80).json()
38
+
39
+ # Hitung per class Nestlé dan simpan bounding box (format: (x_center, y_center, width, height))
40
  nestle_class_count = {}
41
  nestle_boxes = []
42
  for pred in yolo_pred['predictions']:
43
  class_name = pred['class']
44
  nestle_class_count[class_name] = nestle_class_count.get(class_name, 0) + 1
45
  nestle_boxes.append((pred['x'], pred['y'], pred['width'], pred['height']))
46
+
47
  total_nestle = sum(nestle_class_count.values())
48
+
49
+ # ========== [2] COUNTGD: Deteksi Kompetitor ==========
50
+ # Mengirimkan request ke endpoint CountGD sesuai dokumentasi:
51
+ # https://va.landing.ai/demo/api/Countgd%20Counting
52
+ countgd_url = "https://api.landing.ai/v1/tools/text-to-object-detection"
53
+ with open(temp_path, "rb") as image_file:
54
+ files = {"image": image_file}
55
+ data = {
56
+ "prompts": [COUNTGD_PROMPT],
57
+ "model": "countgd"
58
+ }
59
+ response = requests.post(countgd_url, files=files, data=data)
60
+ # Asumsikan respons JSON mengandung key "predictions" dengan daftar objek
61
+ countgd_pred = response.json()
62
+
63
  competitor_class_count = {}
64
  competitor_boxes = []
65
+ for obj in countgd_pred.get("predictions", []):
66
+ countgd_box = obj["bbox"] # Format: [x1, y1, x2, y2]
67
+ # Filter objek yang sudah terdeteksi oleh YOLO (menghindari duplikasi deteksi)
68
+ if not is_overlap(countgd_box, nestle_boxes):
69
+ class_name = obj["class"].strip().lower()
70
+ competitor_class_count[class_name] = competitor_class_count.get(class_name, 0) + 1
71
+ competitor_boxes.append({
72
+ "class": class_name,
73
+ "box": countgd_box,
74
+ "confidence": obj["score"]
75
+ })
76
+
77
  total_competitor = sum(competitor_class_count.values())
78
+
79
+ # ========== [3] Format Output ==========
80
+ result_text = "Product Nestle\n\n"
81
  for class_name, count in nestle_class_count.items():
82
  result_text += f"{class_name}: {count}\n"
83
+ result_text += f"\nTotal Products Nestle: {total_nestle}\n\n"
84
+
85
  if competitor_class_count:
86
  result_text += f"Total Unclassified Products: {total_competitor}\n"
87
  else:
88
  result_text += "No Unclassified Products detected\n"
89
+
90
+ # ========== [4] Visualisasi ==========
91
  img = cv2.imread(temp_path)
92
+
93
+ # Tandai deteksi produk Nestlé (Hijau)
94
  for pred in yolo_pred['predictions']:
95
  x, y, w, h = pred['x'], pred['y'], pred['width'], pred['height']
96
+ cv2.rectangle(img, (int(x - w/2), int(y - h/2)), (int(x + w/2), int(y + h/2)), (0, 255, 0), 2)
97
+ cv2.putText(img, pred['class'], (int(x - w/2), int(y - h/2 - 10)),
98
+ cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 3)
99
+
100
+ # Tandai deteksi kompetitor (Merah), dengan pengecekan untuk merubah nama kelas menjadi 'unclassified'
101
  for comp in competitor_boxes:
102
  x1, y1, x2, y2 = comp['box']
103
+ unclassified_classes = ["beverage", "cans", "bottle", "mixed box"]
104
+ display_name = "unclassified" if any(c in comp['class'].lower() for c in unclassified_classes) else comp['class']
105
  cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
106
+ cv2.putText(img, f"{display_name} {comp['confidence']:.2f}",
107
+ (int(x1), int(y1 - 10)), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3)
108
+
109
  output_path = "/tmp/combined_output.jpg"
110
  cv2.imwrite(output_path, img)
111
 
112
  return output_path, result_text
113
+
114
  except Exception as e:
115
  return temp_path, f"Error: {str(e)}"
116
  finally:
117
  os.remove(temp_path)
118
 
119
+ def is_overlap(box1, boxes2, threshold=0.3):
120
+ # Fungsi untuk mendeteksi overlap antara bounding box
121
+ x1_min, y1_min, x1_max, y1_max = box1
122
+ for b2 in boxes2:
123
+ x2, y2, w2, h2 = b2
124
+ x2_min = x2 - w2/2
125
+ x2_max = x2 + w2/2
126
+ y2_min = y2 - h2/2
127
+ y2_max = y2 + h2/2
128
+
129
+ dx = min(x1_max, x2_max) - max(x1_min, x2_min)
130
+ dy = min(y1_max, y2_max) - max(y1_min, y2_min)
131
+ if (dx >= 0) and (dy >= 0):
132
+ area_overlap = dx * dy
133
+ area_box1 = (x1_max - x1_min) * (y1_max - y1_min)
134
+ if area_overlap / area_box1 > threshold:
135
+ return True
136
+ return False
137
+
138
+ # ========== Fungsi Deteksi Video (tetap menggunakan YOLO) ==========
139
+ def convert_video_to_mp4(input_path, output_path):
140
+ try:
141
+ subprocess.run(['ffmpeg', '-i', input_path, '-vcodec', 'libx264', '-acodec', 'aac', output_path], check=True)
142
+ return output_path
143
+ except subprocess.CalledProcessError as e:
144
+ return None, f"Error converting video: {e}"
145
+
146
+ def detect_objects_in_video(video_path):
147
+ temp_output_path = "/tmp/output_video.mp4"
148
+ temp_frames_dir = tempfile.mkdtemp()
149
+ frame_count = 0
150
+ previous_detections = {}
151
+
152
+ try:
153
+ if not video_path.endswith(".mp4"):
154
+ video_path, err = convert_video_to_mp4(video_path, temp_output_path)
155
+ if not video_path:
156
+ return None, f"Video conversion error: {err}"
157
+
158
+ video = cv2.VideoCapture(video_path)
159
+ frame_rate = int(video.get(cv2.CAP_PROP_FPS))
160
+ frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
161
+ frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
162
+ frame_size = (frame_width, frame_height)
163
+
164
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
165
+ output_video = cv2.VideoWriter(temp_output_path, fourcc, frame_rate, frame_size)
166
+
167
+ while True:
168
+ ret, frame = video.read()
169
+ if not ret:
170
+ break
171
+
172
+ frame_path = os.path.join(temp_frames_dir, f"frame_{frame_count}.jpg")
173
+ cv2.imwrite(frame_path, frame)
174
+
175
+ predictions = yolo_model.predict(frame_path, confidence=50, overlap=80).json()
176
+
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
+
185
+ cv2.rectangle(frame, (int(x - w/2), int(y - h/2)), (int(x + w/2), int(y + h/2)), (0, 255, 0), 2)
186
+ cv2.putText(frame, class_name, (int(x - w/2), int(y - h/2 - 10)),
187
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
188
+
189
+ object_counts = {}
190
+ for detection_id in current_detections.keys():
191
+ class_name = current_detections[detection_id]
192
+ object_counts[class_name] = object_counts.get(class_name, 0) + 1
193
+
194
+ count_text = ""
195
+ total_product_count = 0
196
+ for class_name, count in object_counts.items():
197
+ count_text += f"{class_name}: {count}\n"
198
+ total_product_count += count
199
+ count_text += f"\nTotal Product: {total_product_count}"
200
+
201
+ y_offset = 20
202
+ for line in count_text.split("\n"):
203
+ cv2.putText(frame, line, (10, y_offset), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
204
+ y_offset += 30
205
+
206
+ output_video.write(frame)
207
+ frame_count += 1
208
+ previous_detections = current_detections
209
+
210
+ video.release()
211
+ output_video.release()
212
+
213
+ return temp_output_path
214
+
215
+ except Exception as e:
216
+ return None, f"An error occurred: {e}"
217
+
218
+ # ========== Gradio Interface ==========
219
  with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", neutral_hue="slate")) as iface:
220
  gr.Markdown("""<div style="text-align: center;"><h1>NESTLE - STOCK COUNTING</h1></div>""")
221
 
 
227
  output_text = gr.Textbox(label="Counting Object")
228
  detect_image_button.click(fn=detect_combined, inputs=input_image, outputs=[output_image, output_text])
229
 
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()