muhammadsalmanalfaridzi commited on
Commit
655a65d
·
verified ·
1 Parent(s): 078dc17

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +276 -0
app.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from dds_cloudapi_sdk import Config, Client
10
+ from dds_cloudapi_sdk.tasks.dinox import DinoxTask
11
+ from dds_cloudapi_sdk.tasks.types import DetectionTarget
12
+ from dds_cloudapi_sdk import TextPrompt
13
+ import subprocess
14
+
15
+ # ========== Konfigurasi ==========
16
+ load_dotenv()
17
+
18
+ # Roboflow Config
19
+ rf_api_key = os.getenv("ROBOFLOW_API_KEY")
20
+ workspace = os.getenv("ROBOFLOW_WORKSPACE")
21
+ project_name = os.getenv("ROBOFLOW_PROJECT")
22
+ model_version = int(os.getenv("ROBOFLOW_MODEL_VERSION"))
23
+
24
+ # DINO-X Config
25
+ DINOX_API_KEY = os.getenv("DINO_X_API_KEY")
26
+ DINOX_PROMPT = "beverage . bottle . cans" # Customize sesuai produk kompetitor : food . drink
27
+
28
+ # Inisialisasi Model
29
+ rf = Roboflow(api_key=rf_api_key)
30
+ project = rf.workspace(workspace).project(project_name)
31
+ yolo_model = project.version(model_version).model
32
+
33
+ dinox_config = Config(DINOX_API_KEY)
34
+ dinox_client = Client(dinox_config)
35
+
36
+ # ========== Fungsi Deteksi Kombinasi ==========
37
+ def detect_combined(image):
38
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
39
+ image.save(temp_file, format="JPEG")
40
+ temp_path = temp_file.name
41
+
42
+ try:
43
+ # ========== [1] YOLO: Deteksi Produk Nestlé (Per Class) ==========
44
+ yolo_pred = yolo_model.predict(temp_path, confidence=60, overlap=80).json()
45
+
46
+ # Hitung per class Nestlé
47
+ nestle_class_count = {}
48
+ nestle_boxes = []
49
+ for pred in yolo_pred['predictions']:
50
+ class_name = pred['class']
51
+ nestle_class_count[class_name] = nestle_class_count.get(class_name, 0) + 1
52
+ nestle_boxes.append((pred['x'], pred['y'], pred['width'], pred['height']))
53
+
54
+ total_nestle = sum(nestle_class_count.values())
55
+
56
+ # ========== [2] DINO-X: Deteksi Kompetitor ==========
57
+ image_url = dinox_client.upload_file(temp_path)
58
+ task = DinoxTask(
59
+ image_url=image_url,
60
+ prompts=[TextPrompt(text=DINOX_PROMPT)],
61
+ bbox_threshold=0.25,
62
+ targets=[DetectionTarget.BBox]
63
+ )
64
+ dinox_client.run_task(task)
65
+ dinox_pred = task.result.objects
66
+
67
+ # Filter & Hitung Kompetitor
68
+ competitor_class_count = {}
69
+ competitor_boxes = []
70
+ for obj in dinox_pred:
71
+ dinox_box = obj.bbox
72
+ # Filter objek yang sudah terdeteksi oleh YOLO (Overlap detection)
73
+ if not is_overlap(dinox_box, nestle_boxes): # Ignore if overlap with YOLO detections
74
+ class_name = obj.category.strip().lower() # Normalisasi nama kelas
75
+ competitor_class_count[class_name] = competitor_class_count.get(class_name, 0) + 1
76
+ competitor_boxes.append({
77
+ "class": class_name,
78
+ "box": dinox_box,
79
+ "confidence": obj.score
80
+ })
81
+
82
+ total_competitor = sum(competitor_class_count.values())
83
+
84
+ # ========== [3] Format Output ==========
85
+ result_text = "Product Nestle\n\n"
86
+ for class_name, count in nestle_class_count.items():
87
+ result_text += f"{class_name}: {count}\n"
88
+ result_text += f"\nTotal Products Nestle: {total_nestle}\n\n"
89
+
90
+ #result_text += "Competitor Products\n\n"
91
+ if competitor_class_count:
92
+ result_text += f"Total Unclassified Products: {total_competitor}\n" # Hanya total, tidak per kelas
93
+ else:
94
+ result_text += "No Unclassified Products detected\n"
95
+
96
+ # ========== [4] Visualisasi ==========
97
+ img = cv2.imread(temp_path)
98
+
99
+ # Nestlé (Hijau)
100
+ for pred in yolo_pred['predictions']:
101
+ x, y, w, h = pred['x'], pred['y'], pred['width'], pred['height']
102
+ cv2.rectangle(img, (int(x-w/2), int(y-h/2)), (int(x+w/2), int(y+h/2)), (0,255,0), 2)
103
+ cv2.putText(img, pred['class'], (int(x-w/2), int(y-h/2-10)),
104
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)
105
+
106
+ # Kompetitor (Merah) dengan nama 'unclassified'
107
+ for comp in competitor_boxes:
108
+ x1, y1, x2, y2 = comp['box']
109
+
110
+ # Define a list of target classes to rename
111
+ unclassified_classes = ["beverage", "cans", "bottle"]
112
+
113
+ # Normalize the class name to be case-insensitive and check if it's in the unclassified list
114
+ display_name = "unclassified" if any(class_name in comp['class'].lower() for class_name in unclassified_classes) else comp['class']
115
+
116
+ cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
117
+ cv2.putText(img, f"{display_name} {comp['confidence']:.2f}",
118
+ (int(x1), int(y1-10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
119
+
120
+ output_path = "/tmp/combined_output.jpg"
121
+ cv2.imwrite(output_path, img)
122
+
123
+ return output_path, result_text
124
+
125
+ except Exception as e:
126
+ return temp_path, f"Error: {str(e)}"
127
+ finally:
128
+ os.remove(temp_path)
129
+
130
+ def is_overlap(box1, boxes2, threshold=0.3):
131
+ # Fungsi untuk deteksi overlap bounding box
132
+ x1_min, y1_min, x1_max, y1_max = box1
133
+ for b2 in boxes2:
134
+ x2, y2, w2, h2 = b2
135
+ x2_min = x2 - w2/2
136
+ x2_max = x2 + w2/2
137
+ y2_min = y2 - h2/2
138
+ y2_max = y2 + h2/2
139
+
140
+ # Hitung area overlap
141
+ dx = min(x1_max, x2_max) - max(x1_min, x2_min)
142
+ dy = min(y1_max, y2_max) - max(y1_min, y2_min)
143
+ if (dx >= 0) and (dy >= 0):
144
+ area_overlap = dx * dy
145
+ area_box1 = (x1_max - x1_min) * (y1_max - y1_min)
146
+ if area_overlap / area_box1 > threshold:
147
+ return True
148
+ return False
149
+
150
+ # ========== Fungsi untuk Deteksi Video ==========
151
+
152
+ def convert_video_to_mp4(input_path, output_path):
153
+ try:
154
+ subprocess.run(['ffmpeg', '-i', input_path, '-vcodec', 'libx264', '-acodec', 'aac', output_path], check=True)
155
+ return output_path
156
+ except subprocess.CalledProcessError as e:
157
+ return None, f"Error converting video: {e}"
158
+
159
+ def detect_objects_in_video(video_path):
160
+ temp_output_path = "/tmp/output_video.mp4"
161
+ temp_frames_dir = tempfile.mkdtemp()
162
+ all_class_count = {} # To store cumulative counts for all frames
163
+ nestle_total = 0 # Total Nestlé count
164
+ frame_count = 0
165
+
166
+ try:
167
+ # Convert video to MP4 if necessary
168
+ if not video_path.endswith(".mp4"):
169
+ video_path, err = convert_video_to_mp4(video_path, temp_output_path)
170
+ if not video_path:
171
+ return None, f"Video conversion error: {err}"
172
+
173
+ # Read video and process frames
174
+ video = cv2.VideoCapture(video_path)
175
+ frame_rate = int(video.get(cv2.CAP_PROP_FPS))
176
+ frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
177
+ frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
178
+ frame_size = (frame_width, frame_height)
179
+
180
+ # VideoWriter for output video
181
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
182
+ output_video = cv2.VideoWriter(temp_output_path, fourcc, frame_rate, frame_size)
183
+
184
+ while True:
185
+ ret, frame = video.read()
186
+ if not ret:
187
+ break
188
+
189
+ # Save frame temporarily for predictions
190
+ frame_path = os.path.join(temp_frames_dir, f"frame_{frame_count}.jpg")
191
+ cv2.imwrite(frame_path, frame)
192
+
193
+ # Process predictions for frame
194
+ predictions = yolo_model.predict(frame_path, confidence=60, overlap=80).json()
195
+
196
+ # Update class count for this frame
197
+ frame_class_count = {}
198
+ for prediction in predictions['predictions']:
199
+ class_name = prediction['class']
200
+ frame_class_count[class_name] = frame_class_count.get(class_name, 0) + 1
201
+ cv2.rectangle(frame, (int(prediction['x'] - prediction['width']/2),
202
+ int(prediction['y'] - prediction['height']/2)),
203
+ (int(prediction['x'] + prediction['width']/2),
204
+ int(prediction['y'] + prediction['height']/2)),
205
+ (0, 255, 0), 2)
206
+ cv2.putText(frame, class_name, (int(prediction['x'] - prediction['width']/2),
207
+ int(prediction['y'] - prediction['height']/2 - 10)),
208
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
209
+
210
+ # Update cumulative count for all frames
211
+ for class_name, count in frame_class_count.items():
212
+ all_class_count[class_name] = all_class_count.get(class_name, 0) + count
213
+
214
+ # Update total Nestlé products count
215
+ nestle_total = sum(all_class_count.values())
216
+
217
+ # Create a vertical layout for counts (dynamically updated)
218
+ count_text = "Cumulative Object Counts\n"
219
+ for class_name, count in all_class_count.items():
220
+ count_text += f"{class_name}: {count}\n"
221
+ count_text += f"\nTotal Product Nestlé: {nestle_total}"
222
+
223
+ # Overlay the counts text onto the frame
224
+ y_offset = 20
225
+ for line in count_text.split("\n"):
226
+ cv2.putText(frame, line, (10, y_offset), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
227
+ y_offset += 30 # Move down for next line
228
+
229
+ # Write processed frame to output video
230
+ output_video.write(frame)
231
+ frame_count += 1
232
+
233
+ video.release()
234
+ output_video.release()
235
+
236
+ return temp_output_path
237
+
238
+ except Exception as e:
239
+ return None, f"An error occurred: {e}"
240
+
241
+ # ========== Gradio Interface ==========
242
+ with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", neutral_hue="slate")) as iface:
243
+ gr.Markdown("""<div style="text-align: center;"><h1>NESTLE - STOCK COUNTING</h1></div>""")
244
+ with gr.Row():
245
+ with gr.Column():
246
+ input_image = gr.Image(type="pil", label="Input Image")
247
+ with gr.Column():
248
+ output_image = gr.Image(label="Detect Object")
249
+ with gr.Column():
250
+ output_text = gr.Textbox(label="Counting Object")
251
+
252
+ # Tombol untuk memproses input
253
+ detect_button = gr.Button("Detect")
254
+
255
+ # Hubungkan tombol dengan fungsi deteksi
256
+ detect_button.click(
257
+ fn=detect_objects,
258
+ inputs=input_image,
259
+ outputs=[output_image, output_text]
260
+ )
261
+
262
+ # with gr.Row():
263
+ # with gr.Column():
264
+ # input_image = gr.Image(type="pil", label="Input Image")
265
+ # detect_image_button = gr.Button("Detect Image")
266
+ # output_image = gr.Image(label="Detect Object")
267
+ # output_text = gr.Textbox(label="Counting Object")
268
+ # detect_image_button.click(fn=detect_combined, inputs=input_image, outputs=[output_image, output_text])
269
+
270
+ # with gr.Column():
271
+ # input_video = gr.Video(label="Input Video")
272
+ # detect_video_button = gr.Button("Detect Video")
273
+ # output_video = gr.Video(label="Output Video")
274
+ # detect_video_button.click(fn=detect_objects_in_video, inputs=input_video, outputs=[output_video])
275
+
276
+ iface.launch()