Teacher-AI / app /ocr.py
Moaaz2os's picture
Upload ocr.py
f929840 verified
Raw
History Blame Contribute Delete
1.95 kB
"""
ocr.py — OCR helper for Teacher AI v3.
Uses PaddleOCR (already in requirements.txt) to extract text from images.
"""
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
# Lazy-load so startup is fast; PaddleOCR downloads models on first use.
_ocr_engine = None
def _get_engine():
global _ocr_engine
if _ocr_engine is None:
try:
from paddleocr import PaddleOCR
# use_angle_cls=True handles rotated text; lang="en" for English.
# Set show_log=False to silence PaddlePaddle verbose output.
_ocr_engine = PaddleOCR(use_angle_cls=True, lang="en", show_log=False)
logger.info("PaddleOCR engine initialised.")
except ImportError as exc:
raise RuntimeError(
"paddleocr is not installed. Add 'paddleocr' to requirements.txt."
) from exc
return _ocr_engine
def extract_text(image_path: str) -> str:
"""
Extract text from *image_path* and return it as a single string.
Raises
------
FileNotFoundError
If *image_path* does not exist.
ValueError
If PaddleOCR returns no results at all.
"""
path = Path(image_path)
if not path.exists():
raise FileNotFoundError(f"Image not found: {image_path}")
engine = _get_engine()
result = engine.ocr(str(path), cls=True)
if not result or result == [None]:
raise ValueError("OCR returned no results for the provided image.")
lines = []
for page in result:
if page is None:
continue
for item in page:
# item = [[box], [text, confidence]]
try:
text, confidence = item[1]
if confidence >= 0.5: # discard low-confidence fragments
lines.append(text.strip())
except (IndexError, TypeError):
continue
return "\n".join(lines)