muhammadsalmanalfaridzi's picture
Update app.py
f280e18 verified
raw
history blame
10.7 kB
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
import subprocess
# ========== Load Environment Variables ==========
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"))
# CountGD Config (Replace DINO-X)
# Pastikan Anda sudah set COUNTGD_API_KEY di .env
COUNTGD_API_KEY = os.getenv("COUNTGD_API_KEY")
# Inisialisasi YOLO Model dari Roboflow
rf = Roboflow(api_key=rf_api_key)
project = rf.workspace(workspace).project(project_name)
yolo_model = project.version(model_version).model
# ========== Fungsi untuk Mengecek Overlap ==========
def is_overlap(box1, boxes2, threshold=0.3):
"""
Mengecek apakah box1 (format: (x_min, y_min, x_max, y_max)) overlap dengan salah satu box di boxes2.
boxes2 adalah list bounding box YOLO dengan format (x_center, y_center, width, height).
Mengembalikan True jika rasio overlap melebihi threshold.
"""
x1_min, y1_min, x1_max, y1_max = box1
for b2 in boxes2:
x_center, y_center, w2, h2 = b2
x2_min = x_center - w2 / 2
x2_max = x_center + w2 / 2
y2_min = y_center - h2 / 2
y2_max = y_center + h2 / 2
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_box1 > 0 and (area_overlap / area_box1) > threshold:
return True
return False
# ========== Fungsi Deteksi Kombinasi ==========
def detect_combined(image):
# Simpan image ke file sementara
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
image.save(temp_file, format="JPEG")
temp_path = temp_file.name
try:
# ===== YOLO Detection (Produk Nestlé) =====
yolo_pred = yolo_model.predict(temp_path, confidence=50, overlap=80).json()
nestle_class_count = {}
nestle_boxes = [] # Menyimpan bounding box YOLO (format: x_center, y_center, width, height)
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())
# ===== CountGD Detection (Produk Kompetitor) =====
url = "https://api.landing.ai/v1/tools/text-to-object-detection"
competitor_class_count = {}
competitor_boxes = [] # Menyimpan bounding box CountGD (format: x_min, y_min, x_max, y_max)
# Daftar prompt yang akan digunakan
COUNTGD_PROMPTS = ["cans", "bottle", "mixed box"]
headers = {"Authorization": f"Basic {COUNTGD_API_KEY}"}
for prompt in COUNTGD_PROMPTS:
# Untuk setiap prompt, buka file gambar dan kirim request
with open(temp_path, "rb") as f:
files = {"image": f}
data = {"prompts": [prompt], "model": "countgd"}
response = requests.post(url, files=files, data=data, headers=headers)
result = response.json()
# Cek apakah API mengembalikan data
if 'data' in result and result['data']:
detections = result['data'][0]
for obj in detections:
if 'bounding_box' in obj:
x1, y1, x2, y2 = obj['bounding_box']
countgd_box = (x1, y1, x2, y2)
# Hanya tambahkan deteksi jika tidak overlap signifikan dengan YOLO
if not is_overlap(countgd_box, nestle_boxes, threshold=0.3):
# Gunakan label dari respons jika ada, jika tidak gunakan prompt sebagai default
label = obj.get('label', prompt)
competitor_class_count[label] = competitor_class_count.get(label, 0) + 1
competitor_boxes.append(countgd_box)
total_competitor = sum(competitor_class_count.values())
# ===== Format Output Text =====
result_text = "Product Nestlé\n\n"
for class_name, count in nestle_class_count.items():
result_text += f"{class_name}: {count}\n"
result_text += f"\nTotal Products Nestlé: {total_nestle}\n\n"
if total_competitor:
result_text += "Produk Kompetitor (CountGD):\n"
for label, count in competitor_class_count.items():
result_text += f"{label}: {count}\n"
result_text += f"\nTotal Produk Kompetitor: {total_competitor}\n"
else:
result_text += "No Unclassified Products detected\n"
# ===== Visualisasi =====
img = cv2.imread(temp_path)
# Gambar bounding box YOLO (hijau)
for pred in yolo_pred['predictions']:
x, y, w, h = pred['x'], pred['y'], pred['width'], pred['height']
pt1 = (int(x - w/2), int(y - h/2))
pt2 = (int(x + w/2), int(y + h/2))
cv2.rectangle(img, pt1, pt2, (0, 255, 0), 2)
cv2.putText(img, pred['class'], (pt1[0], pt1[1]-10),
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,255,0), 3)
# Gambar bounding box CountGD (merah)
for box in competitor_boxes:
x1, y1, x2, y2 = box
cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
cv2.putText(img, "unclassified", (int(x1), int(y1)-10),
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,0,255), 3)
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:
if os.path.exists(temp_path):
os.remove(temp_path)
# ========== 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()
frame_count = 0
previous_detections = {} # Untuk menyimpan deteksi frame sebelumnya
try:
# Konversi video ke MP4 jika perlu
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}"
# Buka video untuk diproses
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)
# Setup VideoWriter untuk output
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
# Simpan frame untuk deteksi YOLO
frame_path = os.path.join(temp_frames_dir, f"frame_{frame_count}.jpg")
cv2.imwrite(frame_path, frame)
# YOLO detection pada frame
predictions = yolo_model.predict(frame_path, confidence=50, overlap=80).json()
# Gambar deteksi YOLO pada frame
current_detections = {}
for prediction in predictions['predictions']:
class_name = prediction['class']
x, y, w, h = prediction['x'], prediction['y'], prediction['width'], prediction['height']
object_id = f"{class_name}_{x}_{y}_{w}_{h}"
if object_id not in current_detections:
current_detections[object_id] = class_name
pt1 = (int(x - w/2), int(y - h/2))
pt2 = (int(x + w/2), int(y + h/2))
cv2.rectangle(frame, pt1, pt2, (0,255,0), 2)
cv2.putText(frame, class_name, (pt1[0], pt1[1]-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)
# Hitung dan tampilkan jumlah deteksi pada frame
object_counts = {}
for detection_id in current_detections:
cls = current_detections[detection_id]
object_counts[cls] = object_counts.get(cls, 0) + 1
count_text = ""
total_product_count = 0
for cls, count in object_counts.items():
count_text += f"{cls}: {count}\n"
total_product_count += count
count_text += f"\nTotal Product: {total_product_count}"
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
output_video.write(frame)
frame_count += 1
previous_detections = current_detections
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()