Spaces:
Sleeping
Sleeping
Download services/ocr_service.py from clabs/learningview: direct link, hf CLI and curl.
- Browser
- Download file 4.31 kB
-
https://huggingface.co/spaces/clabs/learningview/resolve/main/services/ocr_service.py
- Command line
-
hf download hf://spaces/clabs/learningview/services/ocr_service.py
-
curl -L -o ocr_service.py https://huggingface.co/spaces/clabs/learningview/resolve/main/services/ocr_service.py
4.31 kB
| 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]" |