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bbb
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import gradio as gr
from dotenv import load_dotenv
from roboflow import Roboflow
import tempfile
import os
import requests
import cv2
import numpy as np
from dds_cloudapi_sdk import Config, Client
from dds_cloudapi_sdk.tasks.dinox import DinoxTask
from dds_cloudapi_sdk.tasks.types import DetectionTarget
from dds_cloudapi_sdk import TextPrompt
import subprocess

# ========== Konfigurasi ========== 
load_dotenv()

# Roboflow Config
rf_api_key = os.getenv("ROBOFLOW_API_KEY")
workspace = os.getenv("ROBOFLOW_WORKSPACE")
project_name = os.getenv("ROBOFLOW_PROJECT")
model_version = int(os.getenv("ROBOFLOW_MODEL_VERSION"))

# DINO-X Config
DINOX_API_KEY = os.getenv("DINO_X_API_KEY")
DINOX_PROMPT = "beverage . bottle . cans"  # Customize sesuai produk kompetitor : food . drink

# Inisialisasi Model
rf = Roboflow(api_key=rf_api_key)
project = rf.workspace(workspace).project(project_name)
yolo_model = project.version(model_version).model

dinox_config = Config(DINOX_API_KEY)
dinox_client = Client(dinox_config)

# ========== Fungsi Deteksi Kombinasi ========== 
def detect_combined(image):
    with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
        image.save(temp_file, format="JPEG")
        temp_path = temp_file.name

    try:
        # ========== [1] YOLO: Deteksi Produk Nestlé (Per Class) ========== 
        yolo_pred = yolo_model.predict(temp_path, confidence=60, overlap=80).json()

        # Hitung per class Nestlé
        nestle_class_count = {}
        nestle_boxes = []
        for pred in yolo_pred['predictions']:
            class_name = pred['class']
            nestle_class_count[class_name] = nestle_class_count.get(class_name, 0) + 1
            nestle_boxes.append((pred['x'], pred['y'], pred['width'], pred['height']))

        total_nestle = sum(nestle_class_count.values())

        # ========== [2] DINO-X: Deteksi Kompetitor ========== 
        image_url = dinox_client.upload_file(temp_path)
        task = DinoxTask(
            image_url=image_url,
            prompts=[TextPrompt(text=DINOX_PROMPT)],
            bbox_threshold=0.25,
            targets=[DetectionTarget.BBox]
        )
        dinox_client.run_task(task)
        dinox_pred = task.result.objects

        # Filter & Hitung Kompetitor
        competitor_class_count = {}
        competitor_boxes = []
        for obj in dinox_pred:
            dinox_box = obj.bbox
            # Filter objek yang sudah terdeteksi oleh YOLO (Overlap detection)
            if not is_overlap(dinox_box, nestle_boxes):  # Ignore if overlap with YOLO detections
                class_name = obj.category.strip().lower()  # Normalisasi nama kelas
                competitor_class_count[class_name] = competitor_class_count.get(class_name, 0) + 1
                competitor_boxes.append({
                    "class": class_name,
                    "box": dinox_box,
                    "confidence": obj.score
                })

        total_competitor = sum(competitor_class_count.values())

        # ========== [3] Format Output ========== 
        result_text = "Product Nestle\n\n"
        for class_name, count in nestle_class_count.items():
            result_text += f"{class_name}: {count}\n"
        result_text += f"\nTotal Product Nestle: {total_nestle}\n\n"

        result_text += "Competitor Products\n\n"
        if competitor_class_count:
            for class_name, count in competitor_class_count.items():
                result_text += f"{class_name}: {count}\n"
        else:
            result_text += "No competitors detected\n"
        result_text += f"\nTotal Competitor: {total_competitor}"

        # ========== [4] Visualisasi ========== 
        img = cv2.imread(temp_path)

        # Nestlé (Hijau)
        for pred in yolo_pred['predictions']:
            x, y, w, h = pred['x'], pred['y'], pred['width'], pred['height']
            cv2.rectangle(img, (int(x-w/2), int(y-h/2)), (int(x+w/2), int(y+h/2)), (0,255,0), 2)
            cv2.putText(img, pred['class'], (int(x-w/2), int(y-h/2-10)), 
                       cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)

        # Kompetitor (Merah)
        for comp in competitor_boxes:
            x1, y1, x2, y2 = comp['box']
            cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0,0,255), 2)
            cv2.putText(img, f"{comp['class']} {comp['confidence']:.2f}", 
                       (int(x1), int(y1-10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 2)

        output_path = "/tmp/combined_output.jpg"
        cv2.imwrite(output_path, img)

        return output_path, result_text

    except Exception as e:
        return temp_path, f"Error: {str(e)}"
    finally:
        os.remove(temp_path)

def is_overlap(box1, boxes2, threshold=0.3):
    # Fungsi untuk deteksi overlap bounding box
    x1_min, y1_min, x1_max, y1_max = box1
    for b2 in boxes2:
        x2, y2, w2, h2 = b2
        x2_min = x2 - w2/2
        x2_max = x2 + w2/2
        y2_min = y2 - h2/2
        y2_max = y2 + h2/2

        # Hitung area overlap
        dx = min(x1_max, x2_max) - max(x1_min, x2_min)
        dy = min(y1_max, y2_max) - max(y1_min, y2_min)
        if (dx >= 0) and (dy >= 0):
            area_overlap = dx * dy
            area_box1 = (x1_max - x1_min) * (y1_max - y1_min)
            if area_overlap / area_box1 > threshold:
                return True
    return False

# ========== Fungsi untuk Deteksi Video ========== 

def convert_video_to_mp4(input_path, output_path):
    try:
        subprocess.run(['ffmpeg', '-i', input_path, '-vcodec', 'libx264', '-acodec', 'aac', output_path], check=True)
        return output_path
    except subprocess.CalledProcessError as e:
        return None, f"Error converting video: {e}"

def detect_objects_in_video(video_path):
    temp_output_path = "/tmp/output_video.mp4"
    temp_frames_dir = tempfile.mkdtemp()
    all_class_count = {}  # To store cumulative counts for all frames
    nestle_total = 0  # Total Nestlé count
    frame_count = 0

    try:
        # Convert video to MP4 if necessary
        if not video_path.endswith(".mp4"):
            video_path, err = convert_video_to_mp4(video_path, temp_output_path)
            if not video_path:
                return None, f"Video conversion error: {err}"

        # Read video and process frames
        video = cv2.VideoCapture(video_path)
        frame_rate = int(video.get(cv2.CAP_PROP_FPS))
        frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
        frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
        frame_size = (frame_width, frame_height)

        # VideoWriter for output video
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        output_video = cv2.VideoWriter(temp_output_path, fourcc, frame_rate, frame_size)

        while True:
            ret, frame = video.read()
            if not ret:
                break

            # Save frame temporarily for predictions
            frame_path = os.path.join(temp_frames_dir, f"frame_{frame_count}.jpg")
            cv2.imwrite(frame_path, frame)

            # Process predictions for frame
            predictions = yolo_model.predict(frame_path, confidence=60, overlap=80).json()

            # Update class count for this frame
            frame_class_count = {}
            for prediction in predictions['predictions']:
                class_name = prediction['class']
                frame_class_count[class_name] = frame_class_count.get(class_name, 0) + 1
                cv2.rectangle(frame, (int(prediction['x'] - prediction['width']/2), 
                                      int(prediction['y'] - prediction['height']/2)),
                              (int(prediction['x'] + prediction['width']/2), 
                               int(prediction['y'] + prediction['height']/2)),
                              (0, 255, 0), 2)
                cv2.putText(frame, class_name, (int(prediction['x'] - prediction['width']/2),
                                                int(prediction['y'] - prediction['height']/2 - 10)),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

            # Update cumulative count for all frames
            for class_name, count in frame_class_count.items():
                all_class_count[class_name] = all_class_count.get(class_name, 0) + count

            # Update total Nestlé products count
            nestle_total = sum(all_class_count.values())

            # Create a vertical layout for counts (dynamically updated)
            count_text = "Cumulative Object Counts\n"
            for class_name, count in all_class_count.items():
                count_text += f"{class_name}: {count}\n"
            count_text += f"\nTotal Product Nestlé: {nestle_total}"

            # Overlay the counts text onto the frame
            y_offset = 20
            for line in count_text.split("\n"):
                cv2.putText(frame, line, (10, y_offset), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
                y_offset += 30  # Move down for next line

            # Write processed frame to output video
            output_video.write(frame)
            frame_count += 1

        video.release()
        output_video.release()

        return temp_output_path

    except Exception as e:
        return None, f"An error occurred: {e}"

# ========== Gradio Interface ========== 
with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", neutral_hue="slate")) as iface:
    gr.Markdown("""<div style="text-align: center;"><h1>NESTLE - STOCK COUNTING</h1></div>""")
    
    with gr.Row():
        with gr.Column():
            input_image = gr.Image(type="pil", label="Input Image")
            detect_image_button = gr.Button("Detect Image")
            output_image = gr.Image(label="Detect Object")
            output_text = gr.Textbox(label="Counting Object")
            detect_image_button.click(fn=detect_combined, inputs=input_image, outputs=[output_image, output_text])

        with gr.Column():
            input_video = gr.Video(label="Input Video")
            detect_video_button = gr.Button("Detect Video")
            output_video = gr.Video(label="Output Video")
            detect_video_button.click(fn=detect_objects_in_video, inputs=input_video, outputs=[output_video])

iface.launch()