from abc import ABC, abstractmethod from typing import ClassVar, Literal from extraction.document import BBox, Document OcrMode = Literal["auto", "always", "never"] class DocumentReader(ABC): """Turns raw bytes of one document format into a `Document`. To support a new format, subclass this, fill in `media_type`, `extensions` and `magic`, and add the class to `extraction.readers.READERS`. """ media_type: ClassVar[str] extensions: ClassVar[tuple[str, ...]] magic: ClassVar[tuple[bytes, ...]] = () def __init__(self, *, ocr_mode: OcrMode = "auto", dpi: int = 200): self.ocr_mode = ocr_mode self.dpi = dpi @classmethod def matches_content(cls, head: bytes) -> bool: return any(head.startswith(signature) for signature in cls.magic) @classmethod def matches_name(cls, name: str) -> bool: return name.lower().rsplit(".", 1)[-1] in cls.extensions @classmethod def accepts(cls, name: str, head: bytes) -> bool: return cls.matches_content(head) or cls.matches_name(name) @abstractmethod def read(self, name: str, raw: bytes) -> Document: ... @abstractmethod def render_page(self, raw: bytes, page_number: int, *, dpi: int = 150) -> bytes: """PNG of one page.""" def render_region(self, raw: bytes, page_number: int, bbox: BBox, *, dpi: int = 150) -> bytes: """PNG of a normalized region of one page (an embedded image, a signature, ...).""" import io from PIL import Image page = Image.open(io.BytesIO(self.render_page(raw, page_number, dpi=dpi))) width, height = page.size crop = page.crop((round(bbox.x0 * width), round(bbox.y0 * height), round(bbox.x1 * width), round(bbox.y1 * height))) buffer = io.BytesIO() crop.save(buffer, format="PNG") return buffer.getvalue()