File size: 4,312 Bytes
408b7e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import os
import requests
import cv2
import numpy as np
from google.cloud import vision
import io
import json
import subprocess
from core.logger import log_debug

class OCRService:
    def __init__(self, provider="google"):
        # Real-time Switch: Set to "google" in Railway Variables
        self.provider = os.getenv("OCR_PROVIDER", provider)
        
        # --- 🔑 CREDENTIALS HANDLING ---
        self.ocr_space_key = os.getenv("OCR_SPACE_KEY", "K89743005188957")
        
        # Railway-Friendly Google Auth
        google_json = os.getenv("GOOGLE_CREDS_JSON")
        if google_json:
            # Create temporary creds file from env var to satisfy Google SDK
            with open("google_ocr_key.json", "w") as f:
                f.write(google_json)
            os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "google_ocr_key.json"
        else:
            # Fallback for local testing
            os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "google_ocr_key.json"

    def extract_text(self, image_path):
        """The central router for all OCR requests."""
        # Step 1: Sanitize (Optimized for Cloud Vision)
        sanitized_path = self._v8_sanitize(image_path)
        
        # Step 2: Route
        if self.provider == "google":
            return self._extract_google_vision(sanitized_path)
        elif self.provider == "ocr_space":
            return self._extract_ocr_space(sanitized_path)
        else:
            # Fallback for local Mac testing only
            if os.name == 'posix' and 'darwin' in os.sys.platform:
                return self._extract_apple_vision(sanitized_path)
            return "[Provider Not Supported on Linux/Railway]"

    def _v8_sanitize(self, path):
        """V8 Pipeline: Clean shadows but preserve stroke gradients for Google."""
        img = cv2.imread(path)
        if img is None: return path
        
        # Convert to grayscale
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        
        # CLAHE (Contrast Limited Adaptive Histogram Equalization) is perfect for 
        # neutralizing shadows on paper
        clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
        res = clahe.apply(gray)
        
        # Denoise to remove paper grain
        denoised = cv2.fastNlMeansDenoising(res, None, 10, 7, 21)
        
        output_path = "sanitized_v8_payload.png"
        cv2.imwrite(output_path, denoised)
        return output_path

    def _extract_google_vision(self, path):
        """Google Vision: High-speed handwriting extraction."""
        try:
            client = vision.ImageAnnotatorClient()
            with io.open(path, 'rb') as image_file:
                content = image_file.read()
            
            image = vision.Image(content=content)
            
            # Use document_text_detection for dense/handwritten text
            response = client.document_text_detection(image=image)
            
            if response.error.message:
                log_debug(f"⚠️ Google API Error: {response.error.message}")
                return "[Google Billing Required]"
                
            text = response.full_text_annotation.text.strip()
            log_debug("Text extracted: "+text)
            return text.replace('\n', ' ') # Flatten to single line for alignment
        except Exception as e:
            log_debug(f"⚠️ Google Vision Failure: {e}")
            return "[Extraction Error]"

    def _extract_ocr_space(self, path):
        """OCR.space Engine 3 Fallback."""
        try:
            with open(path, 'rb') as f:
                r = requests.post(
                    'https://api.ocr.space/parse/image',
                    files={path: f},
                    data={
                        'apikey': self.ocr_space_key, 
                        'language': 'eng', 
                        'ocrengine': 3, 
                        'scale': True
                    },
                    timeout=45 
                )
            result = r.json()
            if result.get('ParsedResults'):
                return result['ParsedResults'][0].get('ParsedText', "").strip()
            return "[OCR Engine Busy]"
        except Exception as e:
            log_debug(f"⚠️ OCR.space Failure: {e}")
            return "[Extraction Timeout]"