import pdfplumber import pytesseract from PIL import Image import io def extract_pdf_text(file_bytes: bytes): """Extracts text page-wise from PDF, falls back to OCR if needed.""" pages_text = [] with pdfplumber.open(io.BytesIO(file_bytes)) as pdf: for page in pdf.pages: text = page.extract_text() if not text: # fallback to OCR pil_img = page.to_image(resolution=300).original text = pytesseract.image_to_string(pil_img) pages_text.append(text.strip() if text else "") return pages_text