from paddleocr import PaddleOCR
import cv2
import sys


# ==========================================
# PARAMETER
# ==========================================

if len(sys.argv) < 2:

    print("Pemakaian:")
    print("python ocr_header.py sample.jpg")
    sys.exit()

image_file = sys.argv[1]


# ==========================================
# LOAD IMAGE
# ==========================================

img = cv2.imread(image_file)

if img is None:

    print("Gagal membuka gambar")
    sys.exit()

h, w = img.shape[:2]


# ==========================================
# CROP HEADER
# ==========================================

crop = img[0:int(h * 0.65), :]

header_file = "header.jpg"

cv2.imwrite(
    header_file,
    crop
)

print("HEADER =", header_file)


# ==========================================
# OCR
# ==========================================

ocr = PaddleOCR(
    use_angle_cls=True,
    lang="en"
)

raw = ocr.ocr(
    header_file,
    cls=True
)


# ==========================================
# OUTPUT
# ==========================================

print("\n===== HEADER OCR =====\n")

for line in raw[0]:

    text = line[1][0]
    score = line[1][1]

    print(
        f"{score:.2f}  {text}"
    )

print("\n======================\n")