muhammadsalmanalfaridzi commited on
Commit
1c1a855
·
verified ·
1 Parent(s): 1e9f7ce

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +252 -0
app.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from dotenv import load_dotenv
3
+ from roboflow import Roboflow
4
+ import tempfile
5
+ import os
6
+ import requests
7
+ import cv2
8
+ import numpy as np
9
+ import subprocess
10
+
11
+ # ========== Konfigurasi ==========
12
+ load_dotenv()
13
+
14
+ # Roboflow Config
15
+ rf_api_key = os.getenv("ROBOFLOW_API_KEY")
16
+ workspace = os.getenv("ROBOFLOW_WORKSPACE")
17
+ project_name = os.getenv("ROBOFLOW_PROJECT")
18
+ model_version = int(os.getenv("ROBOFLOW_MODEL_VERSION"))
19
+
20
+ # OWLv2 Config
21
+ OWLV2_API_KEY = os.getenv("COUNTGD_API_KEY")
22
+ OWLV2_PROMPTS = ["beverage", "bottle", "cans", "boxed milk", "milk"]
23
+
24
+ # Inisialisasi Model YOLO
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
+ # Simpan gambar input ke file sementara
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é (Per Class) ==========
38
+ yolo_pred = yolo_model.predict(temp_path, confidence=50, overlap=80).json()
39
+
40
+ # Hitung per class Nestlé dan simpan bounding box (format: (x_center, y_center, width, height))
41
+ nestle_class_count = {}
42
+ nestle_boxes = []
43
+ for pred in yolo_pred['predictions']:
44
+ class_name = pred['class']
45
+ nestle_class_count[class_name] = nestle_class_count.get(class_name, 0) + 1
46
+ nestle_boxes.append((pred['x'], pred['y'], pred['width'], pred['height']))
47
+
48
+ total_nestle = sum(nestle_class_count.values())
49
+
50
+ # ========== [2] OWLv2: Deteksi Kompetitor ==========
51
+ headers = {
52
+ "Authorization": "Basic " + OWLV2_API_KEY,
53
+ }
54
+ data = {
55
+ "prompts": OWLV2_PROMPTS,
56
+ "model": "owlv2"
57
+ }
58
+ with open(temp_path, "rb") as f:
59
+ files = {"image": f}
60
+ response = requests.post("https://api.landing.ai/v1/tools/text-to-object-detection", files=files, data=data, headers=headers)
61
+ result = response.json()
62
+ owlv2_objects = result['data'][0] if 'data' in result else []
63
+
64
+ competitor_class_count = {}
65
+ competitor_boxes = []
66
+ for obj in owlv2_objects:
67
+ if 'bounding_box' in obj:
68
+ bbox = obj['bounding_box'] # Format: [x1, y1, x2, y2]
69
+ # Filter objek yang sudah terdeteksi oleh YOLO (Overlap detection)
70
+ if not is_overlap(bbox, nestle_boxes):
71
+ class_name = obj.get('label', 'unknown').strip().lower()
72
+ competitor_class_count[class_name] = competitor_class_count.get(class_name, 0) + 1
73
+ competitor_boxes.append({
74
+ "class": class_name,
75
+ "box": bbox,
76
+ "confidence": obj.get("score", 0)
77
+ })
78
+
79
+ total_competitor = sum(competitor_class_count.values())
80
+
81
+ # ========== [3] Format Output ==========
82
+ result_text = "Product Nestle\n\n"
83
+ for class_name, count in nestle_class_count.items():
84
+ result_text += f"{class_name}: {count}\n"
85
+ result_text += f"\nTotal Products Nestle: {total_nestle}\n\n"
86
+ if competitor_class_count:
87
+ result_text += f"Total Unclassified Products: {total_competitor}\n"
88
+ else:
89
+ result_text += "No Unclassified Products detected\n"
90
+
91
+ # ========== [4] Visualisasi ==========
92
+ img = cv2.imread(temp_path)
93
+
94
+ # Gambar bounding box untuk produk Nestlé (Hijau)
95
+ for pred in yolo_pred['predictions']:
96
+ x, y, w, h = pred['x'], pred['y'], pred['width'], pred['height']
97
+ cv2.rectangle(img, (int(x - w/2), int(y - h/2)), (int(x + w/2), int(y + h/2)), (0, 255, 0), 2)
98
+ cv2.putText(img, pred['class'], (int(x - w/2), int(y - h/2 - 10)),
99
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
100
+
101
+ # Gambar bounding box untuk kompetitor (Merah) dengan label 'unclassified' jika sesuai
102
+ for comp in competitor_boxes:
103
+ x1, y1, x2, y2 = comp['box']
104
+ unclassified_classes = ["beverage", "cans", "bottle", "boxed milk", "milk"]
105
+ display_name = "unclassified" if any(cls in comp['class'].lower() for cls in unclassified_classes) else comp['class']
106
+ cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
107
+ cv2.putText(img, f"{display_name} {comp['confidence']:.2f}",
108
+ (int(x1), int(y1 - 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
109
+
110
+ output_path = "/tmp/combined_output.jpg"
111
+ cv2.imwrite(output_path, img)
112
+
113
+ return output_path, result_text
114
+
115
+ except Exception as e:
116
+ return temp_path, f"Error: {str(e)}"
117
+ finally:
118
+ os.remove(temp_path)
119
+
120
+ def is_overlap(box1, boxes2, threshold=0.3):
121
+ """
122
+ Fungsi untuk mendeteksi overlap bounding box.
123
+ Parameter:
124
+ - box1: Bounding box pertama dengan format (x1, y1, x2, y2)
125
+ - boxes2: List bounding box lainnya dengan format (x_center, y_center, width, height)
126
+ """
127
+ x1_min, y1_min, x1_max, y1_max = box1
128
+ for b2 in boxes2:
129
+ x2, y2, w2, h2 = b2
130
+ x2_min = x2 - w2/2
131
+ x2_max = x2 + w2/2
132
+ y2_min = y2 - h2/2
133
+ y2_max = y2 + h2/2
134
+
135
+ dx = min(x1_max, x2_max) - max(x1_min, x2_min)
136
+ dy = min(y1_max, y2_max) - max(y1_min, y2_min)
137
+ if (dx >= 0) and (dy >= 0):
138
+ area_overlap = dx * dy
139
+ area_box1 = (x1_max - x1_min) * (y1_max - y1_min)
140
+ if area_overlap / area_box1 > threshold:
141
+ return True
142
+ return False
143
+
144
+ # ========== Fungsi untuk Deteksi Video ==========
145
+ def convert_video_to_mp4(input_path, output_path):
146
+ try:
147
+ subprocess.run(['ffmpeg', '-i', input_path, '-vcodec', 'libx264', '-acodec', 'aac', output_path], check=True)
148
+ return output_path
149
+ except subprocess.CalledProcessError as e:
150
+ return None, f"Error converting video: {e}"
151
+
152
+ def detect_objects_in_video(video_path):
153
+ temp_output_path = "/tmp/output_video.mp4"
154
+ temp_frames_dir = tempfile.mkdtemp()
155
+ all_class_count = {} # Untuk menyimpan total hitungan objek dari semua frame
156
+ nestle_total = 0
157
+ frame_count = 0
158
+
159
+ try:
160
+ # Convert video ke MP4 jika perlu
161
+ if not video_path.endswith(".mp4"):
162
+ video_path, err = convert_video_to_mp4(video_path, temp_output_path)
163
+ if not video_path:
164
+ return None, f"Video conversion error: {err}"
165
+
166
+ # Membaca dan memproses frame video
167
+ video = cv2.VideoCapture(video_path)
168
+ frame_rate = int(video.get(cv2.CAP_PROP_FPS))
169
+ frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
170
+ frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
171
+ frame_size = (frame_width, frame_height)
172
+
173
+ # VideoWriter untuk output video
174
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
175
+ output_video = cv2.VideoWriter(temp_output_path, fourcc, frame_rate, frame_size)
176
+
177
+ while True:
178
+ ret, frame = video.read()
179
+ if not ret:
180
+ break
181
+
182
+ # Simpan frame untuk prediksi
183
+ frame_path = os.path.join(temp_frames_dir, f"frame_{frame_count}.jpg")
184
+ cv2.imwrite(frame_path, frame)
185
+
186
+ # Proses prediksi untuk frame
187
+ predictions = yolo_model.predict(frame_path, confidence=60, overlap=80).json()
188
+
189
+ # Update hitungan objek untuk frame ini
190
+ frame_class_count = {}
191
+ for prediction in predictions['predictions']:
192
+ class_name = prediction['class']
193
+ frame_class_count[class_name] = frame_class_count.get(class_name, 0) + 1
194
+ cv2.rectangle(frame, (int(prediction['x'] - prediction['width']/2),
195
+ int(prediction['y'] - prediction['height']/2)),
196
+ (int(prediction['x'] + prediction['width']/2),
197
+ int(prediction['y'] + prediction['height']/2)),
198
+ (0, 255, 0), 2)
199
+ cv2.putText(frame, class_name, (int(prediction['x'] - prediction['width']/2),
200
+ int(prediction['y'] - prediction['height']/2 - 10)),
201
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
202
+
203
+ # Update hitungan kumulatif
204
+ for class_name, count in frame_class_count.items():
205
+ all_class_count[class_name] = all_class_count.get(class_name, 0) + count
206
+
207
+ nestle_total = sum(all_class_count.values())
208
+
209
+ # Overlay teks hitungan pada frame
210
+ count_text = "Cumulative Object Counts\n"
211
+ for class_name, count in all_class_count.items():
212
+ count_text += f"{class_name}: {count}\n"
213
+ count_text += f"\nTotal Product Nestlé: {nestle_total}"
214
+
215
+ y_offset = 20
216
+ for line in count_text.split("\n"):
217
+ cv2.putText(frame, line, (10, y_offset), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
218
+ y_offset += 30
219
+
220
+ output_video.write(frame)
221
+ frame_count += 1
222
+
223
+ video.release()
224
+ output_video.release()
225
+
226
+ return temp_output_path
227
+
228
+ except Exception as e:
229
+ return None, f"An error occurred: {e}"
230
+
231
+ # ========== Gradio Interface ==========
232
+ with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", neutral_hue="slate")) as iface:
233
+ gr.Markdown("""<div style="text-align: center;"><h1>NESTLE - STOCK COUNTING</h1></div>""")
234
+ with gr.Row():
235
+ with gr.Column():
236
+ input_image = gr.Image(type="pil", label="Input Image")
237
+ with gr.Column():
238
+ output_image = gr.Image(label="Detect Object")
239
+ with gr.Column():
240
+ output_text = gr.Textbox(label="Counting Object")
241
+
242
+ # Tombol untuk memproses input
243
+ detect_button = gr.Button("Detect")
244
+
245
+ # Hubungkan tombol dengan fungsi deteksi
246
+ detect_button.click(
247
+ fn=detect_combined,
248
+ inputs=input_image,
249
+ outputs=[output_image, output_text]
250
+ )
251
+
252
+ iface.launch()