| import os |
| import pdfplumber |
| import pytesseract |
|
|
| |
| 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: |
| |
| import cv2 |
| import numpy as np |
| |
| |
| img = cv2.imread(file_path) |
| |
| if img is None: |
| raise Exception("Could not read image file.") |
| |
| |
| gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) |
| |
| |
| _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) |
| |
| |
| text = pytesseract.image_to_string(thresh) |
| |
| except ImportError: |
| |
| 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: |
| |
| raise Exception("OCR failed. Please upload a clearer image or use PDF.") |
| |
| return text |
|
|