from paddleocr import PaddleOCR
import os

# =====================================
# INISIALISASI OCR
# =====================================

print("Loading PaddleOCR...")

ocr = PaddleOCR(
    use_angle_cls=True,
    lang="en"
)

print("OCR Ready")
print()

# =====================================
# FILE YANG DITES
# =====================================

files = [
    "hasil_stack/001_NamaBarang.jpg",
    "hasil_stack/001_SubTotal.jpg",

    "hasil_stack/002_NamaBarang.jpg",
    "hasil_stack/002_SubTotal.jpg",

    "hasil_stack/003_NamaBarang.jpg",
    "hasil_stack/003_SubTotal.jpg",

    "hasil_stack/004_NamaBarang.jpg",
    "hasil_stack/004_SubTotal.jpg",

    "hasil_stack/005_NamaBarang.jpg",
    "hasil_stack/005_SubTotal.jpg"
]

# =====================================
# OCR LOOP
# =====================================

for fn in files:

    print("=" * 60)
    print(fn)

    if not os.path.exists(fn):

        print("FILE TIDAK DITEMUKAN")
        continue

    try:

        result = ocr.ocr(fn)

    except Exception as ex:

        print("ERROR OCR:")
        print(ex)
        continue

    # -----------------------------
    # Tidak ada hasil
    # -----------------------------

    if result is None:

        print("HASIL = None")
        continue

    if len(result) == 0:

        print("HASIL KOSONG")
        continue

    if result[0] is None:

        print("OCR TIDAK MENEMUKAN TEKS")
        continue

    # -----------------------------
    # Tampilkan hasil
    # -----------------------------

    found = False

    for line in result[0]:

        if line is None:
            continue

        try:

            text = line[1][0]
            conf = line[1][1]

            print(
                f"{conf:.2f}  {text}"
            )

            found = True

        except Exception as ex:

            print("ERROR PARSE:")
            print(ex)

    if not found:

        print("TIDAK ADA TEXT YANG TERBACA")

print()
print("SELESAI")