File size: 2,211 Bytes
c35855b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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