Spaces:
Sleeping
Sleeping
Download backend/ocr_engine.py from Presight-AI/app: direct link, hf CLI and curl.
- Browser
- Download file 4.08 kB
-
https://huggingface.co/spaces/Presight-AI/app/resolve/main/backend/ocr_engine.py
- Command line
-
hf download hf://spaces/Presight-AI/app/backend/ocr_engine.py
-
curl -L -o ocr_engine.py https://huggingface.co/spaces/Presight-AI/app/resolve/main/backend/ocr_engine.py
4.08 kB
| """ | |
| Advanced OCR Engine for Prescription Text Extraction | |
| Supports both EasyOCR and Tesseract with intelligent preprocessing | |
| """ | |
| try: | |
| import cv2 | |
| except ImportError: | |
| cv2 = None | |
| import numpy as np | |
| from PIL import Image, ImageEnhance, ImageFilter | |
| try: | |
| import easyocr | |
| except ImportError: | |
| easyocr = None | |
| try: | |
| import pytesseract | |
| except ImportError: | |
| pytesseract = None | |
| import logging | |
| from typing import List, Dict, Tuple, Optional | |
| import re | |
| class PrescriptionOCR: | |
| """ | |
| Advanced OCR engine optimized for prescription images | |
| """ | |
| def __init__(self, languages=['en'], use_gpu=False, fallback_to_tesseract=True): | |
| """ | |
| Initialize OCR engines | |
| Args: | |
| languages: List of language codes for OCR | |
| use_gpu: Whether to use GPU for EasyOCR (requires CUDA) | |
| fallback_to_tesseract: Use Tesseract if EasyOCR fails | |
| """ | |
| self.languages = languages | |
| self.fallback_to_tesseract = fallback_to_tesseract | |
| # Initialize EasyOCR | |
| try: | |
| if easyocr: | |
| self.easyocr_reader = easyocr.Reader(languages, gpu=use_gpu) | |
| self.easyocr_available = True | |
| else: | |
| self.easyocr_reader = None | |
| self.easyocr_available = False | |
| except Exception as e: | |
| logging.warning(f"EasyOCR initialization failed: {e}") | |
| self.easyocr_available = False | |
| # Test Tesseract availability | |
| try: | |
| pytesseract.get_tesseract_version() | |
| self.tesseract_available = True | |
| except Exception as e: | |
| logging.warning(f"Tesseract not available: {e}") | |
| self.tesseract_available = False | |
| def extract_text_smart(self, image_path: str) -> Dict: | |
| """ | |
| Smart text extraction using best available method | |
| """ | |
| if self.easyocr_available: | |
| try: | |
| # Use EasyOCR | |
| result = self.easyocr_reader.readtext(image_path, detail=0, paragraph=True) | |
| text = "\n".join(result) | |
| return { | |
| "success": True, | |
| "text": text, | |
| "engine": "EasyOCR", | |
| "avg_confidence": 0.9 # EasyOCR usually has higher accuracy | |
| } | |
| except Exception as e: | |
| logging.warning(f"EasyOCR failed: {e}") | |
| if self.fallback_to_tesseract and self.tesseract_available: | |
| return self.extract_text_tesseract(image_path) | |
| else: | |
| return {"success": False, "error": f"EasyOCR failed and Tesseract unavailable: {e}"} | |
| elif self.tesseract_available: | |
| return self.extract_text_tesseract(image_path) | |
| else: | |
| return {"success": False, "error": "No OCR engines available"} | |
| def extract_text_tesseract(self, image_path: str, psm=6, oem=3) -> Dict: | |
| """ | |
| Extract text using Tesseract OCR | |
| """ | |
| try: | |
| from PIL import Image | |
| # Open image | |
| image = Image.open(image_path) | |
| # Extract text | |
| text = pytesseract.image_to_string(image) | |
| # Clean text | |
| cleaned_text = self._clean_tesseract_text(text) | |
| return { | |
| "success": True, | |
| "text": cleaned_text, | |
| "engine": "Tesseract", | |
| "avg_confidence": 0.8 # Default confidence | |
| } | |
| except Exception as e: | |
| return {"success": False, "error": str(e)} | |
| def _clean_tesseract_text(self, text: str) -> str: | |
| """Clean Tesseract extracted text""" | |
| lines = [line.strip() for line in text.split('\n') if line.strip()] | |
| cleaned = '\n'.join(lines) | |
| cleaned = re.sub(r' +', ' ', cleaned) | |
| return cleaned | |
| def get_text_regions(self, image_path: str) -> List[Dict]: | |
| """Get text regions (basic implementation)""" | |
| return [] | |