# ==========================================
# OCR NAMABARANG ROWS
# ==========================================

import os
import cv2

from paddleocr import PaddleOCR

ROWS_DIR = r"G:\00. PROJECTS\API\Inventory\output\rows"

print("Loading PaddleOCR...")

ocr = PaddleOCR(
    use_angle_cls=True,
    lang="en"
)

print("Ready")
print("")

for i in range(1, 100):

    file_name = os.path.join(
        ROWS_DIR,
        f"NamaBarang_{i:03d}.jpg"
    )

    if not os.path.exists(file_name):
        break

    img = cv2.imread(file_name)

    if img is None:
        continue

    # ==================================
    # UPSCALE BESAR
    # ==================================

    img = cv2.resize(
        img,
        None,
        fx=6,
        fy=6,
        interpolation=cv2.INTER_CUBIC
    )

    # ==================================
    # GRAYSCALE
    # ==================================

    gray = cv2.cvtColor(
        img,
        cv2.COLOR_BGR2GRAY
    )

    # ==================================
    # OTSU
    # ==================================

    _, thresh = cv2.threshold(
        gray,
        0,
        255,
        cv2.THRESH_BINARY + cv2.THRESH_OTSU
    )

    # ==================================
    # DEBUG SAVE
    # ==================================

    debug_file = os.path.join(
        ROWS_DIR,
        f"DEBUG_{i:03d}.jpg"
    )

    cv2.imwrite(
        debug_file,
        thresh
    )

    # ==================================
    # OCR
    # ==================================

    result = ocr.ocr(
        thresh,
        cls=True
    )

    text = ""

    if result and result[0]:

        texts = []

        for line in result[0]:

            texts.append(
                line[1][0]
            )

        text = " ".join(texts)

    print(
        f"{i:03d} = {text}"
    )

print("")
print("SELESAI")