133 lines
5.3 KiB
Python
133 lines
5.3 KiB
Python
import io
|
|
|
|
import pdfplumber
|
|
import pypdfium2 as pdfium
|
|
|
|
from extraction.document import BBox, Document, EmbeddedImage, Line, Page, Word
|
|
from extraction.errors import ExtractionError
|
|
from extraction.ocr import TesseractOcr
|
|
from extraction.readers.base import DocumentReader
|
|
|
|
# Below this many characters a page is treated as scanned (no usable text layer).
|
|
MIN_TEXT_CHARS = 20
|
|
# A page that is mostly one scanned image is still OCRed unless its text
|
|
# layer has at least this much: a scanner may stamp a header or a page
|
|
# number as text over the image that holds the content.
|
|
MIN_TEXT_CHARS_OVER_SCAN = 200
|
|
# Images smaller than this fraction of the page are bullets, logos or rules.
|
|
MIN_IMAGE_AREA = 0.01
|
|
|
|
|
|
class PdfReader(DocumentReader):
|
|
"""Reads the text layer where there is one and OCRs the pages where
|
|
there isn't, page by page. Hospital exports often mix typed pages with
|
|
scanned attachments."""
|
|
|
|
media_type = "application/pdf"
|
|
extensions = ("pdf",)
|
|
magic = (b"%PDF",)
|
|
|
|
def read(self, name: str, raw: bytes) -> Document:
|
|
pages = []
|
|
with _open(raw) as pdf:
|
|
for plumber_page in pdf.pages:
|
|
pages.append(self._read_page(plumber_page))
|
|
return Document(name=name, media_type=self.media_type, pages=pages, raw=raw)
|
|
|
|
def render_page(self, raw: bytes, page_number: int, *, dpi: int = 150) -> bytes:
|
|
with _open(raw) as pdf:
|
|
if not 1 <= page_number <= len(pdf.pages):
|
|
raise ExtractionError(f"page {page_number} out of range (1..{len(pdf.pages)})")
|
|
image = pdf.pages[page_number - 1].to_image(resolution=dpi).original
|
|
buffer = io.BytesIO()
|
|
image.save(buffer, format="PNG")
|
|
return buffer.getvalue()
|
|
|
|
def _read_page(self, page) -> Page:
|
|
images = _embedded_images(page)
|
|
lines = [] if self.ocr_mode == "always" else _text_layer_lines(page)
|
|
enough = MIN_TEXT_CHARS_OVER_SCAN if any(image.kind == "scan" for image in images) else MIN_TEXT_CHARS
|
|
if self.ocr_mode == "never" or sum(len(line.text) for line in lines) >= enough:
|
|
return Page(number=page.page_number, lines=lines, source="text", images=images)
|
|
rendered = page.to_image(resolution=self.dpi).original
|
|
return Page(number=page.page_number, lines=TesseractOcr().read_lines(rendered), source="ocr", images=images)
|
|
|
|
|
|
def combine_pages(parts: list[tuple[bytes, list[int]]]) -> bytes:
|
|
"""One PDF with the given pages of several PDFs, in order: how a
|
|
patient's pages, spread over several files, become their own document."""
|
|
page_numbers = [numbers for _, numbers in parts]
|
|
try:
|
|
target = pdfium.PdfDocument.new()
|
|
for raw, numbers in parts:
|
|
target.import_pages(pdfium.PdfDocument(raw), [n - 1 for n in numbers])
|
|
buffer = io.BytesIO()
|
|
target.save(buffer)
|
|
return buffer.getvalue()
|
|
except Exception as exc:
|
|
raise ExtractionError(f"could not extract pages {page_numbers}: {exc}") from exc
|
|
|
|
|
|
def _open(raw: bytes):
|
|
try:
|
|
return pdfplumber.open(io.BytesIO(raw))
|
|
except Exception as exc:
|
|
raise ExtractionError(f"could not open PDF: {exc}") from exc
|
|
|
|
|
|
def _text_layer_lines(page) -> list[Line]:
|
|
"""Some generators fake bold by drawing each glyph several times a
|
|
fraction of a point apart, which reads as every letter repeated;
|
|
`dedupe_chars` collapses those before the lines are built."""
|
|
try:
|
|
raw_lines = page.dedupe_chars().extract_text_lines(return_chars=True)
|
|
except Exception:
|
|
return []
|
|
width, height = float(page.width), float(page.height)
|
|
lines = []
|
|
for line in raw_lines:
|
|
text = line.get("text", "").strip()
|
|
if not text:
|
|
continue
|
|
words = _words(text, line.get("chars") or [], width)
|
|
lines.append(
|
|
Line(
|
|
text=" ".join(word.text for word in words) if words else text,
|
|
bbox=BBox(line["x0"] / width, line["top"] / height, line["x1"] / width, line["bottom"] / height),
|
|
words=words,
|
|
)
|
|
)
|
|
return lines
|
|
|
|
|
|
def _words(text: str, chars: list[dict], width: float) -> tuple[Word, ...]:
|
|
"""The line's words with their extent, pairing each word of `text`
|
|
with its glyphs in order; empty when the two don't line up."""
|
|
glyphs = [char for char in chars if char.get("text", "").strip()]
|
|
words: list[Word] = []
|
|
position = 0
|
|
for token in text.split():
|
|
span = glyphs[position : position + len(token)]
|
|
if len(span) != len(token):
|
|
return ()
|
|
words.append(Word(token, span[0]["x0"] / width, span[-1]["x1"] / width))
|
|
position += len(token)
|
|
return tuple(words) if position == len(glyphs) else ()
|
|
|
|
|
|
def _embedded_images(page) -> list[EmbeddedImage]:
|
|
width, height = float(page.width), float(page.height)
|
|
found = []
|
|
for image in page.images:
|
|
bbox = BBox(
|
|
max(0.0, image["x0"] / width),
|
|
max(0.0, image["top"] / height),
|
|
min(1.0, image["x1"] / width),
|
|
min(1.0, image["bottom"] / height),
|
|
)
|
|
if bbox.area < MIN_IMAGE_AREA:
|
|
continue
|
|
src_width, src_height = image.get("srcsize") or (None, None)
|
|
found.append(EmbeddedImage(page_number=page.page_number, bbox=bbox, width_px=src_width, height_px=src_height))
|
|
return found
|