Update app.py
Browse files
app.py
CHANGED
@@ -17,7 +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
|
21 |
COUNTGD_API_KEY = os.getenv("COUNTGD_API_KEY")
|
22 |
|
23 |
# Inisialisasi YOLO Model dari Roboflow
|
@@ -25,111 +25,106 @@ rf = Roboflow(api_key=rf_api_key)
|
|
25 |
project = rf.workspace(workspace).project(project_name)
|
26 |
yolo_model = project.version(model_version).model
|
27 |
|
28 |
-
# ========== Fungsi untuk
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
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
|
49 |
yolo_pred = yolo_model.predict(temp_path, confidence=50, overlap=80).json()
|
50 |
-
|
51 |
-
|
52 |
-
|
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 |
-
|
62 |
competitor_boxes = []
|
63 |
COUNTGD_PROMPTS = ["cans", "bottle", "mixed box"]
|
64 |
-
|
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 |
-
|
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 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
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 |
-
|
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),
|
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),
|
125 |
-
|
|
|
126 |
output_path = "/tmp/combined_output.jpg"
|
127 |
cv2.imwrite(output_path, img)
|
128 |
-
return output_path
|
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)
|
|
|
17 |
project_name = os.getenv("ROBOFLOW_PROJECT")
|
18 |
model_version = int(os.getenv("ROBOFLOW_MODEL_VERSION"))
|
19 |
|
20 |
+
# CountGD Config (Replace DINO-X)
|
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 Mengecek Overlap antara YOLO dan CountGD ==========
|
29 |
+
def is_overlap(box1, boxes2, threshold=0.5):
|
30 |
+
"""
|
31 |
+
Mengecek apakah box1 overlap dengan salah satu box di boxes2 berdasarkan IoU.
|
32 |
+
"""
|
33 |
+
x1_min, y1_min, x1_max, y1_max = box1
|
34 |
+
for b2 in boxes2:
|
35 |
+
x_center, y_center, w2, h2 = b2
|
36 |
+
x2_min = x_center - w2 / 2
|
37 |
+
x2_max = x_center + w2 / 2
|
38 |
+
y2_min = y_center - h2 / 2
|
39 |
+
y2_max = y_center + h2 / 2
|
40 |
+
|
41 |
+
dx = min(x1_max, x2_max) - max(x1_min, x2_min)
|
42 |
+
dy = min(y1_max, y2_max) - max(y1_min, y2_min)
|
43 |
+
if dx > 0 and dy > 0:
|
44 |
+
area_overlap = dx * dy
|
45 |
+
area_box1 = (x1_max - x1_min) * (y1_max - y1_min)
|
46 |
+
if area_box1 > 0 and (area_overlap / area_box1) > threshold:
|
47 |
+
return True
|
48 |
+
return False
|
49 |
+
|
50 |
+
# ========== Fungsi untuk Menghitung IoU antar dua bounding box ==========
|
51 |
def iou(boxA, boxB):
|
52 |
+
"""
|
53 |
+
Menghitung Intersection over Union (IoU) antara dua bounding box.
|
54 |
+
"""
|
55 |
xA = max(boxA[0], boxB[0])
|
56 |
yA = max(boxA[1], boxB[1])
|
57 |
xB = min(boxA[2], boxB[2])
|
58 |
yB = min(boxA[3], boxB[3])
|
|
|
59 |
interArea = max(0, xB - xA) * max(0, yB - yA)
|
60 |
boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
|
61 |
boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
|
62 |
+
iou_val = interArea / float(boxAArea + boxBArea - interArea) if (boxAArea + boxBArea - interArea) > 0 else 0
|
63 |
+
return iou_val
|
64 |
|
65 |
# ========== Fungsi Deteksi Kombinasi ==========
|
66 |
def detect_combined(image):
|
67 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
|
68 |
image.save(temp_file, format="JPEG")
|
69 |
temp_path = temp_file.name
|
70 |
+
|
71 |
try:
|
72 |
+
# ===== YOLO Detection =====
|
73 |
yolo_pred = yolo_model.predict(temp_path, confidence=50, overlap=80).json()
|
74 |
+
nestle_boxes = [(pred['x'], pred['y'], pred['width'], pred['height']) for pred in yolo_pred['predictions']]
|
75 |
+
|
76 |
+
# ===== CountGD Detection =====
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
url = "https://api.landing.ai/v1/tools/text-to-object-detection"
|
78 |
+
headers = {"Authorization": f"Basic {COUNTGD_API_KEY}"}
|
79 |
competitor_boxes = []
|
80 |
COUNTGD_PROMPTS = ["cans", "bottle", "mixed box"]
|
81 |
+
|
|
|
82 |
for prompt in COUNTGD_PROMPTS:
|
83 |
with open(temp_path, "rb") as f:
|
84 |
files = {"image": f}
|
85 |
data = {"prompts": [prompt], "model": "countgd"}
|
86 |
response = requests.post(url, files=files, data=data, headers=headers)
|
87 |
result = response.json()
|
88 |
+
|
89 |
if 'data' in result and result['data']:
|
90 |
detections = result['data'][0]
|
91 |
+
for obj in detections:
|
|
|
|
|
92 |
if 'bounding_box' in obj:
|
93 |
x1, y1, x2, y2 = obj['bounding_box']
|
94 |
countgd_box = (x1, y1, x2, y2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
|
96 |
+
if not is_overlap(countgd_box, nestle_boxes, threshold=0.5):
|
97 |
+
duplicate = False
|
98 |
+
for existing_box in competitor_boxes:
|
99 |
+
if iou(countgd_box, existing_box) > 0.4:
|
100 |
+
duplicate = True
|
101 |
+
break
|
102 |
+
if not duplicate:
|
103 |
+
competitor_boxes.append(countgd_box)
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
|
105 |
+
# ===== Visualisasi =====
|
|
|
|
|
|
|
|
|
|
|
106 |
img = cv2.imread(temp_path)
|
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 |
+
|
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)
|
123 |
+
return output_path
|
124 |
+
|
125 |
except Exception as e:
|
126 |
return temp_path, f"Error: {str(e)}"
|
127 |
+
|
128 |
finally:
|
129 |
if os.path.exists(temp_path):
|
130 |
os.remove(temp_path)
|