# ==========================================
# DETECT ROWS
# ==========================================

import cv2
import os

IMAGE_FILE = r"G:\00. PROJECTS\API\Inventory\output\NamaBarang.jpg"

OUTPUT_FILE = r"G:\00. PROJECTS\API\Inventory\output\row_debug.jpg"

# ==========================================
# LOAD
# ==========================================

img = cv2.imread(IMAGE_FILE)

if img is None:

    print("ERROR : Gagal membuka gambar")
    exit()

# ==========================================
# GRAYSCALE
# ==========================================

gray = cv2.cvtColor(
    img,
    cv2.COLOR_BGR2GRAY
)

# ==========================================
# THRESHOLD
# ==========================================

_, thresh = cv2.threshold(
    gray,
    0,
    255,
    cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)

# ==========================================
# PROYEKSI HORIZONTAL
# ==========================================

height, width = thresh.shape

rows = []

for y in range(height):

    count = cv2.countNonZero(
        thresh[y:y+1, :]
    )

    rows.append(count)

# ==========================================
# DETEKSI BLOK TEKS
# ==========================================

inside = False
start_y = 0

row_ranges = []

for y, value in enumerate(rows):

    if value > 5 and not inside:

        start_y = y
        inside = True

    elif value <= 5 and inside:

        end_y = y

        if end_y - start_y > 5:

            row_ranges.append(
                (start_y, end_y)
            )

        inside = False

# ==========================================
# GAMBAR GARIS
# ==========================================

debug_img = img.copy()

for i, (y1, y2) in enumerate(row_ranges, start=1):

    cv2.rectangle(
        debug_img,
        (0, y1),
        (width - 1, y2),
        (0, 0, 255),
        1
    )

    print(
        f"ROW {i}: Y={y1} - {y2}"
    )

# ==========================================
# SAVE
# ==========================================

cv2.imwrite(
    OUTPUT_FILE,
    debug_img
)

cv2.imwrite(
    r"G:\00. PROJECTS\API\Inventory\output\threshold.jpg",
    thresh
)

print("")
print("Saved:")
print(OUTPUT_FILE)