Files
ISSSTELEON/Extraction/extraction/ocr.py
T
2026-11-13 11:53:06 -06:00

104 lines
4.0 KiB
Python

"""Tesseract wrapper that returns positioned lines with a real per-line
confidence (mean of Tesseract's word confidences), not just a string."""
import os
from dataclasses import dataclass
import pytesseract
from PIL import Image
from pytesseract import Output
from extraction.document import BBox, Line, Word
from extraction.errors import ExtractionError
DEFAULT_LANG = os.environ.get("EXTRACTION_OCR_LANG", "spa+eng")
# Below this mean line confidence the page is tried again at the
# orientation Tesseract's OSD detects, for pages scanned rotated.
REORIENT_BELOW = 0.6
@dataclass(frozen=True)
class TesseractOcr:
"""`psm=3` (automatic layout) suits a whole page; `psm=6` (one uniform
block) suits a small crop such as a single form field, where PSM 3
discards short strings like a lone "F" as noise."""
lang: str = DEFAULT_LANG
psm: int = 3
@property
def name(self) -> str:
try:
return f"tesseract-{pytesseract.get_tesseract_version()}"
except Exception:
return "tesseract"
def read_lines(self, image: Image.Image) -> list[Line]:
lines = self._read(image)
if self.psm != 3 or _mean_confidence(lines) >= REORIENT_BELOW:
return lines
rotation = _detected_rotation(image)
if not rotation:
return lines
rotated = self._read(image.rotate(-rotation, expand=True))
return rotated if _mean_confidence(rotated) > _mean_confidence(lines) else lines
def _read(self, image: Image.Image) -> list[Line]:
try:
data = pytesseract.image_to_data(image, output_type=Output.DICT, lang=self.lang, config=f"--psm {self.psm}")
except Exception as exc:
raise ExtractionError(f"OCR failed: {exc}") from exc
width, height = image.size
return [_line(words, width, height) for words in group_words(data)]
def _mean_confidence(lines: list[Line]) -> float:
weights = [len(line.text) for line in lines]
total = sum(weights)
return sum(line.confidence * weight for line, weight in zip(lines, weights)) / total if total else 0.0
def _detected_rotation(image: Image.Image) -> int:
"""Clockwise degrees the page is turned, per Tesseract's OSD; 0 when
OSD can't tell (too little text, no `osd` traineddata)."""
try:
return int(pytesseract.image_to_osd(image, output_type=Output.DICT).get("rotate", 0)) % 360
except Exception:
return 0
def group_words(data: dict[str, list]) -> list[list[dict]]:
"""Words grouped by Tesseract's own (block, paragraph, line) segmentation, left to right."""
grouped: dict[tuple[int, int, int], list[dict]] = {}
for i, raw_text in enumerate(data["text"]):
text = raw_text.strip()
if not text:
continue
key = (data["block_num"][i], data["par_num"][i], data["line_num"][i])
grouped.setdefault(key, []).append(
{
"text": text,
"left": data["left"][i],
"top": data["top"][i],
"width": data["width"][i],
"height": data["height"][i],
"conf": float(data["conf"][i]),
}
)
lines = [sorted(grouped[key], key=lambda w: w["left"]) for key in sorted(grouped)]
return sorted(lines, key=lambda words: min(w["top"] for w in words))
def _line(words: list[dict], width: int, height: int) -> Line:
x0 = min(w["left"] for w in words)
y0 = min(w["top"] for w in words)
x1 = max(w["left"] + w["width"] for w in words)
y1 = max(w["top"] + w["height"] for w in words)
confidences = [w["conf"] for w in words if w["conf"] >= 0]
confidence = (sum(confidences) / len(confidences) / 100) if confidences else 0.0
return Line(
text=" ".join(w["text"] for w in words),
bbox=BBox(x0 / width, y0 / height, x1 / width, y1 / height),
confidence=round(confidence, 4),
words=tuple(Word(w["text"], w["left"] / width, (w["left"] + w["width"]) / width) for w in words),
)