muhammadsalmanalfaridzi commited on
Commit
402e547
·
verified ·
1 Parent(s): 15178a8

Delete app-dino.py

Browse files
Files changed (1) hide show
  1. app-dino.py +0 -158
app-dino.py DELETED
@@ -1,158 +0,0 @@
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 supervision as sv
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 . food . drink . bottle" # Customize sesuai produk kompetitor
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
- if not is_overlap(dinox_box, nestle_boxes):
73
- class_name = obj.category.strip().lower() # Normalisasi nama kelas
74
- competitor_class_count[class_name] = competitor_class_count.get(class_name, 0) + 1
75
- competitor_boxes.append({
76
- "class": class_name,
77
- "box": dinox_box,
78
- "confidence": obj.score
79
- })
80
-
81
- total_competitor = sum(competitor_class_count.values())
82
-
83
- # ========== [3] Format Output ==========
84
- result_text = "Product Nestle\n\n"
85
- for class_name, count in nestle_class_count.items():
86
- result_text += f"{class_name}: {count}\n"
87
- result_text += f"\nTotal Product Nestle: {total_nestle}\n\n"
88
-
89
- result_text += "Competitor Products\n\n"
90
- if competitor_class_count:
91
- for class_name, count in competitor_class_count.items():
92
- result_text += f"{class_name}: {count}\n"
93
- else:
94
- result_text += "No competitors detected\n"
95
- result_text += f"\nTotal Competitor: {total_competitor}"
96
-
97
- # ========== [4] Visualisasi ==========
98
- img = cv2.imread(temp_path)
99
-
100
- # Nestlé (Hijau)
101
- for pred in yolo_pred['predictions']:
102
- x, y, w, h = pred['x'], pred['y'], pred['width'], pred['height']
103
- cv2.rectangle(img, (int(x-w/2), int(y-h/2)), (int(x+w/2), int(y+h/2)), (0,255,0), 2)
104
- cv2.putText(img, pred['class'], (int(x-w/2), int(y-h/2-10)),
105
- cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)
106
-
107
- # Kompetitor (Merah)
108
- for comp in competitor_boxes:
109
- x1, y1, x2, y2 = comp['box']
110
- cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0,0,255), 2)
111
- cv2.putText(img, f"{comp['class']} {comp['confidence']:.2f}",
112
- (int(x1), int(y1-10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 2)
113
-
114
- output_path = "/tmp/combined_output.jpg"
115
- cv2.imwrite(output_path, img)
116
-
117
- return output_path, result_text
118
-
119
- except Exception as e:
120
- return temp_path, f"Error: {str(e)}"
121
- finally:
122
- os.remove(temp_path)
123
-
124
- def is_overlap(box1, boxes2, threshold=0.3):
125
- # Fungsi untuk deteksi overlap bounding box
126
- x1_min, y1_min, x1_max, y1_max = box1
127
- for b2 in boxes2:
128
- x2, y2, w2, h2 = b2
129
- x2_min = x2 - w2/2
130
- x2_max = x2 + w2/2
131
- y2_min = y2 - h2/2
132
- y2_max = y2 + h2/2
133
-
134
- # Hitung area overlap
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
- # ========== Gradio Interface ==========
145
- with gr.Blocks() as iface:
146
- with gr.Row():
147
- input_image = gr.Image(type="pil", label="Input Image")
148
- output_image = gr.Image(label="Detection Result")
149
- output_text = gr.Textbox(label="Product Counts")
150
-
151
- detect_button = gr.Button("Detect Products")
152
- detect_button.click(
153
- fn=detect_combined,
154
- inputs=input_image,
155
- outputs=[output_image, output_text]
156
- )
157
-
158
- iface.launch()