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

97 lines
3.6 KiB
Python

"""Lines that belong to a document's template, not to its record.
A letterhead or a footer carries the issuer's own name, address, phone
and postal code, printed the same on every document it issues. Read as
fields, they would give every patient the issuer's address. A line counts
as template when it sits in the page's top or bottom margin and repeats,
give or take OCR noise, on the documents of at least two different
patients; a header that repeats only across one patient's own pages or
studies (her name, her file number) is hers and stays.
"""
import re
from collections import defaultdict
from typing import Hashable, Iterable
from rapidfuzz import fuzz
from rapidfuzz.process import cdist
from extraction.document import Line
from extraction.nlp.text import fold
# Fraction of the page from the top and from the bottom treated as margins.
HEADER_BAND = 0.16
FOOTER_BAND = 0.12
# Two margin lines are the same line when their digits are identical and
# their normalized texts this similar (0..100): OCR rarely reads the same
# letterhead twice identically, but a line whose numbers differ (an id, a
# date) is a different line.
SAME_LINE_SCORE = 94
MIN_LINE_LENGTH = 8
# Above this many distinct margin lines, only exact repeats are compared.
MAX_FUZZY_LINES = 4000
def in_margin(line: Line) -> bool:
return line.bbox.y0 < HEADER_BAND or line.bbox.y1 > 1 - FOOTER_BAND
def normalized(line: Line) -> str:
return re.sub(r"[^A-Z0-9]", "", fold(line.text))
def template_lines(lines_by_owner: Iterable[tuple[Hashable, Iterable[Line]]]) -> set[str]:
"""The normalized texts of margin lines shared by two or more owners
(patients). `lines_by_owner` pairs an owner with the lines of one of
their documents or segments; owners that are `None` are skipped, since
a line can't be told apart from its owner's data without knowing who
the owner is."""
owners: dict[str, set[Hashable]] = defaultdict(set)
for owner, lines in lines_by_owner:
if owner is None:
continue
for line in lines:
text = normalized(line)
if in_margin(line) and len(text) >= MIN_LINE_LENGTH:
owners[text].add(owner)
texts = list(owners)
groups = _similar_groups(texts) if len(texts) <= MAX_FUZZY_LINES else [[i] for i in range(len(texts))]
shared: set[str] = set()
for group in groups:
members = [texts[i] for i in group]
if len(set().union(*(owners[text] for text in members))) >= 2:
shared.update(members)
return shared
def _similar_groups(texts: list[str]) -> list[list[int]]:
"""Indices of `texts` grouped by similarity (connected components),
only ever joining texts with the same digits."""
by_digits: dict[str, list[int]] = defaultdict(list)
for i, text in enumerate(texts):
by_digits[re.sub(r"\D", "", text)].append(i)
groups: list[list[int]] = []
for indices in by_digits.values():
groups.extend([[indices[i] for i in group] for group in _components([texts[i] for i in indices])])
return groups
def _components(texts: list[str]) -> list[list[int]]:
if len(texts) == 1:
return [[0]]
scores = cdist(texts, texts, scorer=fuzz.ratio, score_cutoff=SAME_LINE_SCORE, workers=-1)
parent = list(range(len(texts)))
def root(i: int) -> int:
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i
for i, j in zip(*scores.nonzero()):
if i < j:
parent[root(i)] = root(j)
components: dict[int, list[int]] = defaultdict(list)
for i in range(len(texts)):
components[root(i)].append(i)
return list(components.values())