import os import pdfplumber import pytesseract # 1. Configure Tesseract Path for Windows precisely as requested pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" def extract_text(file_path): """ Extracts text from a given PDF or image file. Image OCR is enhanced manually via OpenCV with graceful fallbacks. """ ext = os.path.splitext(file_path)[1].lower() text = "" if ext == ".pdf": try: with pdfplumber.open(file_path) as pdf: for page in pdf.pages: extracted = page.extract_text() if extracted: text += extracted + "\n" except Exception: raise Exception("PDF Extraction failed.") elif ext in [".png", ".jpg", ".jpeg"]: try: # Inline imports ensure Flask doesn't crash on hot-reload if cv2 isn't installed yet import cv2 import numpy as np # 2. Improve Image OCR (Read via OpenCV) img = cv2.imread(file_path) if img is None: raise Exception("Could not read image file.") # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply thresholding _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) # Pass processed image to pytesseract text = pytesseract.image_to_string(thresh) except ImportError: # Safe Fallback: Process using basic Pillow if OpenCV isn't installed yet from PIL import Image img = Image.open(file_path) try: text = pytesseract.image_to_string(img) except Exception: raise Exception("OCR failed. Please upload a clearer image or use PDF.") except Exception: # 4. Error Handling: Gracefully trigger the expected JSON fail state in app.py raise Exception("OCR failed. Please upload a clearer image or use PDF.") return text