import fitz  # pymupdf
import pytesseract
from PIL import Image
import io
import os

files = [
    "/home/z/my-project/upload/Company registration.pdf",
    "/home/z/my-project/upload/prabandha.pdf",
]

outdir = "/home/z/my-project/scripts/pdf_images"
os.makedirs(outdir, exist_ok=True)

for f in files:
    print("=" * 80)
    print("FILE:", os.path.basename(f))
    print("=" * 80)
    try:
        doc = fitz.open(f)
        print(f"Number of pages: {len(doc)}")
        for i, page in enumerate(doc):
            # Render at high resolution for better OCR
            mat = fitz.Matrix(3, 3)  # 3x zoom
            pix = page.get_pixmap(matrix=mat)
            img_bytes = pix.tobytes("png")
            img = Image.open(io.BytesIO(img_bytes))
            base = os.path.splitext(os.path.basename(f))[0].replace(" ", "_")
            imgpath = f"{outdir}/{base}_p{i+1}.png"
            img.save(imgpath)
            print(f"\n----- PAGE {i+1} (saved {imgpath}) -----")
            # OCR
            text = pytesseract.image_to_string(img, lang='eng')
            print(text)
        doc.close()
    except Exception as e:
        print("ERROR:", e)
    print()
