from pdf2image import convert_from_path
import pytesseract
import cv2
import numpy as np
import re

PDF = "/var/www/html/land-ocr/input_pdfs/261__BRAHMANBAHARA__MAYURESWAR-2.pdf"
DPI = 400

BN_TO_EN = str.maketrans("০১২৩৪৫৬৭৮৯", "0123456789")

def normalize(text):
    text = text.translate(BN_TO_EN)
    text = re.sub(r"\s+", " ", text)
    return text

images = convert_from_path(PDF, dpi=DPI)

for i, img in enumerate(images, start=1):
    img = np.array(img)

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.equalizeHist(gray)

    text = pytesseract.image_to_string(
        gray,
        lang="ben+eng",
        config="--psm 6 -c tessedit_char_whitelist=0123456789০১২৩৪৫৬৭৮৯"
    )

    text = normalize(text)

    print(f"\n--- PAGE {i} OCR OUTPUT (normalized) ---")
    print(text[:500])   # print first 500 chars
