from paddleocr import PaddleOCR
import cv2
import os

ocr = PaddleOCR(
    use_angle_cls=True,
    lang="en"
)

files = [
    "hasil_stack/001_NamaBarang.jpg",
    "hasil_stack/002_NamaBarang.jpg",
    "hasil_stack/003_NamaBarang.jpg",
    "hasil_stack/004_NamaBarang.jpg",
    "hasil_stack/005_NamaBarang.jpg"
]

os.makedirs(
    "hasil_pre",
    exist_ok=True
)

for fn in files:

    print("=" * 60)
    print(fn)

    img = cv2.imread(fn)

    if img is None:
        print("Gagal load")
        continue

    # grayscale
    gray = cv2.cvtColor(
        img,
        cv2.COLOR_BGR2GRAY
    )

    # perbesar 3x
    gray = cv2.resize(
        gray,
        None,
        fx=3,
        fy=3,
        interpolation=cv2.INTER_CUBIC
    )

    # sharpen
    kernel = [
        [-1,-1,-1],
        [-1, 9,-1],
        [-1,-1,-1]
    ]

    import numpy as np

    kernel = np.array(
        kernel,
        dtype=np.float32
    )

    sharp = cv2.filter2D(
        gray,
        -1,
        kernel
    )

    out_file = (
        "hasil_pre/" +
        os.path.basename(fn)
    )

    cv2.imwrite(
        out_file,
        sharp
    )

    result = ocr.ocr(out_file)

    if (
        result is None or
        len(result) == 0 or
        result[0] is None
    ):
        print("Tidak terbaca")
        continue

    for line in result[0]:

        text = line[1][0]
        conf = line[1][1]

        print(
            f"{conf:.2f}  {text}"
        )