Update app.py
Browse files
app.py
CHANGED
@@ -6,13 +6,9 @@ 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 |
-
# ==========
|
16 |
load_dotenv()
|
17 |
|
18 |
# Roboflow Config
|
@@ -21,71 +17,106 @@ 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
|
25 |
-
|
26 |
-
|
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 |
-
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
-
# ==========
|
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 |
-
# YOLO Detection (Nestlé products)
|
44 |
yolo_pred = yolo_model.predict(temp_path, confidence=50, overlap=80).json()
|
45 |
nestle_class_count = {}
|
46 |
-
nestle_boxes = []
|
47 |
for pred in yolo_pred['predictions']:
|
48 |
class_name = pred['class']
|
49 |
nestle_class_count[class_name] = nestle_class_count.get(class_name, 0) + 1
|
50 |
nestle_boxes.append((pred['x'], pred['y'], pred['width'], pred['height']))
|
51 |
total_nestle = sum(nestle_class_count.values())
|
52 |
|
53 |
-
# CountGD Detection (Competitor products)
|
54 |
url = "https://api.landing.ai/v1/tools/text-to-object-detection"
|
55 |
files = {"image": open(temp_path, "rb")}
|
56 |
data = {"prompts": ["mixed box"], "model": "countgd"}
|
57 |
-
headers = {"Authorization": "Basic
|
58 |
response = requests.post(url, files=files, data=data, headers=headers)
|
59 |
result = response.json()
|
60 |
|
61 |
competitor_class_count = {}
|
62 |
-
competitor_boxes = []
|
63 |
if 'data' in result:
|
64 |
for obj in result['data'][0]:
|
65 |
if 'bounding_box' in obj:
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
|
|
|
|
|
|
|
|
70 |
total_competitor = sum(competitor_class_count.values())
|
71 |
|
72 |
-
# Format Output
|
73 |
result_text = "Product Nestlé\n\n"
|
74 |
for class_name, count in nestle_class_count.items():
|
75 |
result_text += f"{class_name}: {count}\n"
|
76 |
result_text += f"\nTotal Products Nestlé: {total_nestle}\n\n"
|
77 |
-
|
|
|
|
|
|
|
78 |
|
79 |
-
# Visualization
|
80 |
img = cv2.imread(temp_path)
|
|
|
81 |
for pred in yolo_pred['predictions']:
|
82 |
x, y, w, h = pred['x'], pred['y'], pred['width'], pred['height']
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
output_path = "/tmp/combined_output.jpg"
|
91 |
cv2.imwrite(output_path, img)
|
@@ -95,30 +126,10 @@ def detect_combined(image):
|
|
95 |
return temp_path, f"Error: {str(e)}"
|
96 |
|
97 |
finally:
|
98 |
-
os.
|
99 |
-
|
100 |
-
def is_overlap(box1, boxes2, threshold=0.3):
|
101 |
-
# Fungsi untuk deteksi overlap bounding box
|
102 |
-
x1_min, y1_min, x1_max, y1_max = box1
|
103 |
-
for b2 in boxes2:
|
104 |
-
x2, y2, w2, h2 = b2
|
105 |
-
x2_min = x2 - w2/2
|
106 |
-
x2_max = x2 + w2/2
|
107 |
-
y2_min = y2 - h2/2
|
108 |
-
y2_max = y2 + h2/2
|
109 |
-
|
110 |
-
# Hitung area overlap
|
111 |
-
dx = min(x1_max, x2_max) - max(x1_min, x2_min)
|
112 |
-
dy = min(y1_max, y2_max) - max(y1_min, y2_min)
|
113 |
-
if (dx >= 0) and (dy >= 0):
|
114 |
-
area_overlap = dx * dy
|
115 |
-
area_box1 = (x1_max - x1_min) * (y1_max - y1_min)
|
116 |
-
if area_overlap / area_box1 > threshold:
|
117 |
-
return True
|
118 |
-
return False
|
119 |
-
|
120 |
-
# ========== Fungsi untuk Deteksi Video ==========
|
121 |
|
|
|
122 |
def convert_video_to_mp4(input_path, output_path):
|
123 |
try:
|
124 |
subprocess.run(['ffmpeg', '-i', input_path, '-vcodec', 'libx264', '-acodec', 'aac', output_path], check=True)
|
@@ -130,7 +141,7 @@ def detect_objects_in_video(video_path):
|
|
130 |
temp_output_path = "/tmp/output_video.mp4"
|
131 |
temp_frames_dir = tempfile.mkdtemp()
|
132 |
frame_count = 0
|
133 |
-
previous_detections = {} # For storing previous frame's
|
134 |
|
135 |
try:
|
136 |
# Convert video to MP4 if necessary
|
@@ -139,14 +150,14 @@ def detect_objects_in_video(video_path):
|
|
139 |
if not video_path:
|
140 |
return None, f"Video conversion error: {err}"
|
141 |
|
142 |
-
#
|
143 |
video = cv2.VideoCapture(video_path)
|
144 |
frame_rate = int(video.get(cv2.CAP_PROP_FPS))
|
145 |
frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
|
146 |
frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
147 |
frame_size = (frame_width, frame_height)
|
148 |
|
149 |
-
# VideoWriter for output
|
150 |
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
151 |
output_video = cv2.VideoWriter(temp_output_path, fourcc, frame_rate, frame_size)
|
152 |
|
@@ -155,54 +166,46 @@ def detect_objects_in_video(video_path):
|
|
155 |
if not ret:
|
156 |
break
|
157 |
|
158 |
-
# Save frame
|
159 |
frame_path = os.path.join(temp_frames_dir, f"frame_{frame_count}.jpg")
|
160 |
cv2.imwrite(frame_path, frame)
|
161 |
|
162 |
-
#
|
163 |
predictions = yolo_model.predict(frame_path, confidence=50, overlap=80).json()
|
164 |
|
165 |
-
#
|
166 |
current_detections = {}
|
167 |
for prediction in predictions['predictions']:
|
168 |
class_name = prediction['class']
|
169 |
x, y, w, h = prediction['x'], prediction['y'], prediction['width'], prediction['height']
|
170 |
-
# Generate a unique ID for each detection based on the bounding box
|
171 |
object_id = f"{class_name}_{x}_{y}_{w}_{h}"
|
172 |
-
|
173 |
-
# Track each detected object individually
|
174 |
if object_id not in current_detections:
|
175 |
current_detections[object_id] = class_name
|
|
|
|
|
|
|
|
|
|
|
176 |
|
177 |
-
|
178 |
-
cv2.rectangle(frame, (int(x-w/2), int(y-h/2)), (int(x+w/2), int(y+h/2)), (0,255,0), 2)
|
179 |
-
cv2.putText(frame, class_name, (int(x-w/2), int(y-h/2-10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)
|
180 |
-
|
181 |
-
# Update counts for objects
|
182 |
object_counts = {}
|
183 |
-
for detection_id in current_detections
|
184 |
-
|
185 |
-
object_counts[
|
186 |
|
187 |
-
# Generate display text for counts
|
188 |
count_text = ""
|
189 |
total_product_count = 0
|
190 |
-
for
|
191 |
-
count_text += f"{
|
192 |
total_product_count += count
|
193 |
count_text += f"\nTotal Product: {total_product_count}"
|
194 |
-
|
195 |
-
# Overlay the counts text onto the frame
|
196 |
y_offset = 20
|
197 |
for line in count_text.split("\n"):
|
198 |
-
cv2.putText(frame, line, (10, y_offset), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255,
|
199 |
-
y_offset += 30
|
200 |
|
201 |
-
# Write processed frame to output video
|
202 |
output_video.write(frame)
|
203 |
frame_count += 1
|
204 |
-
|
205 |
-
# Update previous_detections for the next frame
|
206 |
previous_detections = current_detections
|
207 |
|
208 |
video.release()
|
@@ -213,7 +216,7 @@ def detect_objects_in_video(video_path):
|
|
213 |
except Exception as e:
|
214 |
return None, f"An error occurred: {e}"
|
215 |
|
216 |
-
# ========== Gradio Interface ==========
|
217 |
with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", neutral_hue="slate")) as iface:
|
218 |
gr.Markdown("""<div style="text-align: center;"><h1>NESTLE - STOCK COUNTING</h1></div>""")
|
219 |
|
@@ -224,11 +227,10 @@ with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", ne
|
|
224 |
output_image = gr.Image(label="Detect Object")
|
225 |
output_text = gr.Textbox(label="Counting Object")
|
226 |
detect_image_button.click(fn=detect_combined, inputs=input_image, outputs=[output_image, output_text])
|
227 |
-
|
228 |
with gr.Column():
|
229 |
input_video = gr.Video(label="Input Video")
|
230 |
detect_video_button = gr.Button("Detect Video")
|
231 |
output_video = gr.Video(label="Output Video")
|
232 |
detect_video_button.click(fn=detect_objects_in_video, inputs=input_video, outputs=[output_video])
|
233 |
|
234 |
-
iface.launch()
|
|
|
6 |
import requests
|
7 |
import cv2
|
8 |
import numpy as np
|
|
|
|
|
|
|
|
|
9 |
import subprocess
|
10 |
|
11 |
+
# ========== Load Environment Variables ==========
|
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 (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)
|
|
|
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)
|
|
|
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
|
|
|
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 |
|
|
|
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()
|
|
|
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>""")
|
222 |
|
|
|
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()
|