from paddleocr import PaddleOCR
import json
import sys

# =========================
# VALIDASI PARAMETER
# =========================

if len(sys.argv) < 2:
    print(json.dumps({
        "status": "ERROR",
        "message": "File gambar belum diberikan"
    }))
    sys.exit()

image_file = sys.argv[1]

# =========================
# OCR
# =========================

ocr = PaddleOCR(
    use_angle_cls=True,
    lang='en'
)

result = ocr.ocr(
    image_file,
    cls=True
)

# =========================
# HASIL OCR DETAIL
# =========================

ocr_items = []

for line in result[0]:

    box = line[0]
    text = line[1][0]
    score = float(line[1][1])

    x = int(box[0][0])
    y = int(box[0][1])

    item = {
        "text": text,
        "x": x,
        "y": y,
        "score": round(score, 4)
    }

    ocr_items.append(item)

# =========================
# SORTING
# =========================

ocr_items.sort(
    key=lambda r: (r["y"], r["x"])
)

# DEBUG JSON

print(json.dumps(
    ocr_items,
    indent=2
))

# =========================
# TAMPILKAN
# =========================

print("\n===== OCR DETAIL =====\n")

for item in ocr_items:

    print(
        f'({item["x"]:4},{item["y"]:4})  '
        f'{item["score"]:.2f}  '
        f'{item["text"]}'
    )

print("\n======================\n")