Compare commits
43 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 18b25f0cef | |||
| 041a7997cb | |||
| 268703e272 | |||
| ec6926601d | |||
| e51ce8b71e | |||
| 1bebec7f71 | |||
| 0f6da3d7db | |||
| 175914891a | |||
| 056ce791d8 | |||
| 907a8ce540 | |||
| 621aafb6eb | |||
| 2188d7a5e8 | |||
| d8ff604b6f | |||
| f36b029072 | |||
| 213f5c5bf1 | |||
| df3d902bf3 | |||
| c22648b27a | |||
| 19dfb0c0de | |||
| 3c4ea1a753 | |||
| 85b0834c59 | |||
| eb6e20e3f0 | |||
| 53b7eeefae | |||
| 8d2d6ec1d0 | |||
| 89c366a669 | |||
| 2af9d6df1e | |||
| c0979dd0ed | |||
| 23f529e85c | |||
| 7ea755d3aa | |||
| 8802b804ac | |||
| 3b9099f6bf | |||
| 35bcd2fdcc | |||
| 6f656cec6d | |||
| 0c970b0080 | |||
| f318fb89da | |||
| 6470e99ea5 | |||
| 0351476ec9 | |||
| 444c806d5c | |||
| 7fcc7bdfe9 | |||
| 4ab37f8433 | |||
| 92eae777c9 | |||
| 8b0c0c6733 | |||
| 798ba005cd | |||
| abd056aa8a |
@@ -1,3 +1,4 @@
|
||||
from extraction.nlp.discovery import DiscoveredField, discover_captions
|
||||
from extraction.nlp.extractors import (
|
||||
DEFAULT_EXTRACTORS,
|
||||
FieldExtractor,
|
||||
@@ -11,6 +12,7 @@ from extraction.nlp.fields import Evidence, ExtractedValue, FieldKind, FieldSpec
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_EXTRACTORS",
|
||||
"DiscoveredField",
|
||||
"Evidence",
|
||||
"ExtractedValue",
|
||||
"FieldExtractor",
|
||||
@@ -21,4 +23,5 @@ __all__ = [
|
||||
"PatternExtractor",
|
||||
"RecordExtractor",
|
||||
"SegmentLine",
|
||||
"discover_captions",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Captions a document carries that no registered `FieldSpec` claims.
|
||||
|
||||
`LabeledValueExtractor` only looks for the labels a caller already knows
|
||||
about. A source whose documents carry fields outside today's vocabulary
|
||||
(a hospital's own report layout, a free-form note) still has captions in
|
||||
the `"Campo: valor"` shape; this module finds them so a caller can decide,
|
||||
per caption, whether it matches something in a catalog closely enough to
|
||||
reuse, or is new (see `webapi.imports.schemas.catalog_matching`)."""
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence
|
||||
|
||||
from extraction.nlp.extractors import LabelIndex, SegmentLine
|
||||
from extraction.nlp.fields import Evidence, FieldSpec
|
||||
|
||||
_CAPTION_LINE = re.compile(r"^(?P<caption>[^:=]{2,60}?)\s*[:=]\s*(?P<value>\S.*)$")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiscoveredField:
|
||||
"""One `caption: value` line a known `FieldSpec` didn't already claim."""
|
||||
|
||||
caption: str
|
||||
value: str
|
||||
evidence: Evidence
|
||||
|
||||
|
||||
def discover_captions(lines: Sequence[SegmentLine], specs: Sequence[FieldSpec]) -> list[DiscoveredField]:
|
||||
"""Every undiscovered caption, in line order, duplicates kept (the
|
||||
caller decides how to fold repeats across a record's lines)."""
|
||||
index = LabelIndex(lines, specs)
|
||||
found: list[DiscoveredField] = []
|
||||
for line_index, line in enumerate(lines):
|
||||
if index.hits[line_index]:
|
||||
continue # a known label already explains this line
|
||||
match = _CAPTION_LINE.match(line.text.strip())
|
||||
if not match:
|
||||
continue
|
||||
caption, value = match.group("caption").strip(), match.group("value").strip()
|
||||
if not caption or not value:
|
||||
continue
|
||||
found.append(DiscoveredField(caption, value, line.evidence()))
|
||||
return found
|
||||
@@ -3,15 +3,23 @@ from extraction.errors import ExtractionError
|
||||
from extraction.readers.base import DocumentReader, OcrMode
|
||||
from extraction.readers.image import ImageReader
|
||||
from extraction.readers.pdf import PdfReader, combine_pages
|
||||
from extraction.readers.text import TextReader
|
||||
|
||||
READERS: tuple[type[DocumentReader], ...] = (PdfReader, ImageReader)
|
||||
# Tried only once neither a signature nor the file name picked one of
|
||||
# `READERS`: a SQL column or a plain string that isn't a PDF or an image,
|
||||
# read as text as long as it decodes as one instead of being rejected.
|
||||
FALLBACK_READERS: tuple[type[DocumentReader], ...] = (TextReader,)
|
||||
|
||||
|
||||
def reader_for(name: str, raw: bytes, **options) -> DocumentReader:
|
||||
"""The reader whose signature the bytes carry; the file extension only when none does."""
|
||||
"""The reader whose signature the bytes carry, the file extension when
|
||||
none does, and `FALLBACK_READERS` by content only when neither found one."""
|
||||
head = raw[:16]
|
||||
cls = next((c for c in READERS if c.matches_content(head)), None) or next(
|
||||
(c for c in READERS if c.matches_name(name)), None
|
||||
cls = (
|
||||
next((c for c in READERS if c.matches_content(head)), None)
|
||||
or next((c for c in READERS if c.matches_name(name)), None)
|
||||
or next((c for c in FALLBACK_READERS if c.matches_content(head)), None)
|
||||
)
|
||||
if cls is None:
|
||||
raise ExtractionError(f"unsupported document format: {name!r}")
|
||||
@@ -23,14 +31,16 @@ def read_document(name: str, raw: bytes, *, ocr_mode: OcrMode = "auto") -> Docum
|
||||
|
||||
|
||||
def supported_extensions() -> list[str]:
|
||||
return sorted({extension for cls in READERS for extension in cls.extensions})
|
||||
return sorted({extension for cls in (*READERS, *FALLBACK_READERS) for extension in cls.extensions})
|
||||
|
||||
|
||||
__all__ = [
|
||||
"FALLBACK_READERS",
|
||||
"READERS",
|
||||
"DocumentReader",
|
||||
"ImageReader",
|
||||
"PdfReader",
|
||||
"TextReader",
|
||||
"combine_pages",
|
||||
"read_document",
|
||||
"reader_for",
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import io
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from extraction.document import BBox, Document, Line, Page
|
||||
from extraction.errors import ExtractionError
|
||||
from extraction.readers.base import DocumentReader
|
||||
|
||||
_LINE_HEIGHT_PX = 18
|
||||
|
||||
|
||||
class TextReader(DocumentReader):
|
||||
"""Plain text, one field's content carrying several of its own (a SQL
|
||||
column that isn't a scanned PDF, a note pasted as a string). No OCR: the
|
||||
bytes already are the text, one page, one line per newline.
|
||||
|
||||
The fallback reader, last in `extraction.readers.READERS`: it claims
|
||||
whatever a format-specific reader didn't, as long as it decodes as
|
||||
text, so a source that's neither a PDF nor an image still reaches the
|
||||
same field extraction instead of failing as an unsupported format.
|
||||
"""
|
||||
|
||||
media_type = "text/plain"
|
||||
extensions = ("txt",)
|
||||
|
||||
@classmethod
|
||||
def matches_content(cls, head: bytes) -> bool:
|
||||
"""`head` is only a short prefix (`reader_for` passes 16 bytes), so
|
||||
a multi-byte character can be cut mid-sequence; trimming up to 3
|
||||
trailing bytes covers any such cut without accepting binary data.
|
||||
Printable (plus common whitespace) is required too, so a binary
|
||||
signature that happens to be valid UTF-8 (control bytes are) isn't
|
||||
mistaken for text."""
|
||||
if b"\x00" in head:
|
||||
return False
|
||||
text = None
|
||||
for cut in range(4):
|
||||
trimmed = head[: len(head) - cut] if cut else head
|
||||
if not trimmed:
|
||||
return False
|
||||
try:
|
||||
text = trimmed.decode("utf-8")
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
return text is not None and all(ch.isprintable() or ch in "\t\n\r" for ch in text)
|
||||
|
||||
def read(self, name: str, raw: bytes) -> Document:
|
||||
try:
|
||||
text = raw.decode("utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
raise ExtractionError(f"not valid UTF-8 text: {exc}") from exc
|
||||
rows = text.splitlines() or [""]
|
||||
lines = [
|
||||
Line(text=row, bbox=BBox(0, index / len(rows), 1, (index + 1) / len(rows)))
|
||||
for index, row in enumerate(rows)
|
||||
]
|
||||
return Document(name=name, media_type=self.media_type, pages=[Page(number=1, lines=lines, source="text")], raw=raw)
|
||||
|
||||
def render_page(self, raw: bytes, page_number: int, *, dpi: int = 150) -> bytes:
|
||||
if page_number != 1:
|
||||
raise ExtractionError(f"page {page_number} out of range (1..1)")
|
||||
rows = raw.decode("utf-8", errors="replace").splitlines() or [""]
|
||||
image = Image.new("RGB", (900, max(1, len(rows)) * _LINE_HEIGHT_PX + 20), "white")
|
||||
draw = ImageDraw.Draw(image)
|
||||
for index, row in enumerate(rows):
|
||||
draw.text((10, 10 + index * _LINE_HEIGHT_PX), row, fill="black")
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
@@ -4,6 +4,7 @@ from dataclasses import dataclass, field
|
||||
from typing import Any, Sequence
|
||||
|
||||
from extraction.document import Document, EmbeddedImage
|
||||
from extraction.nlp.discovery import DiscoveredField, discover_captions
|
||||
from extraction.nlp.extractors import DEFAULT_EXTRACTORS, FieldExtractor, RecordExtractor
|
||||
from extraction.nlp.fields import ExtractedValue, FieldSpec
|
||||
from extraction.segmentation import AutoSegmenter, Segment, Segmenter, normalize_key
|
||||
@@ -33,6 +34,10 @@ class ExtractedRecord:
|
||||
images: list[tuple[str, EmbeddedImage]] = field(default_factory=list)
|
||||
key: str | None = None
|
||||
conflicts: list[FieldConflict] = field(default_factory=list)
|
||||
# Captions no known `FieldSpec` claimed (`discover_captions`): what a
|
||||
# source outside today's vocabulary carries, for a caller to match
|
||||
# against a catalog or register as new (catalog_matching, in WebApi).
|
||||
discovered: list[DiscoveredField] = field(default_factory=list)
|
||||
|
||||
def row(self) -> dict[str, Any]:
|
||||
return {name: extracted.value for name, extracted in self.values.items()}
|
||||
@@ -70,6 +75,7 @@ class RecordMerger:
|
||||
target.sources.extend(record.sources)
|
||||
target.images.extend(record.images)
|
||||
target.conflicts.extend(record.conflicts)
|
||||
target.discovered.extend(record.discovered)
|
||||
for name, incoming in record.values.items():
|
||||
current = target.values.get(name)
|
||||
if current is None:
|
||||
@@ -116,7 +122,8 @@ class DocumentExtractor:
|
||||
return self.merger.merge(records) if self.merger else records
|
||||
|
||||
def extract_segment(self, segment: Segment) -> ExtractedRecord:
|
||||
values = self.fields.extract(segment.lines())
|
||||
lines = segment.lines()
|
||||
values = self.fields.extract(lines)
|
||||
key = segment.key
|
||||
if self.key_spec is not None and self.key_spec.name in values:
|
||||
key = normalize_key(values[self.key_spec.name].value)
|
||||
@@ -125,4 +132,5 @@ class DocumentExtractor:
|
||||
sources=[SegmentRef(segment.document.name, list(segment.page_numbers))],
|
||||
images=[(segment.document.name, image) for image in segment.images],
|
||||
key=key,
|
||||
discovered=discover_captions(lines, self.specs),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""`discover_captions`: fails if it stops finding fields a source carries
|
||||
that no registered `FieldSpec` names, or starts re-reporting a field the
|
||||
specs already cover as if it were new."""
|
||||
from extraction.document import BBox, Line
|
||||
from extraction.nlp import FieldKind, FieldSpec, SegmentLine, discover_captions
|
||||
|
||||
EXPEDIENTE = FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))
|
||||
|
||||
|
||||
def lines(*texts: str) -> list[SegmentLine]:
|
||||
return [SegmentLine("doc.pdf", 1, Line(text, BBox(0, i / 10, 1, (i + 1) / 10))) for i, text in enumerate(texts)]
|
||||
|
||||
|
||||
def test_a_caption_outside_the_known_specs_is_discovered():
|
||||
found = discover_captions(lines("Tipo de muestra: Base líquida"), [EXPEDIENTE])
|
||||
assert [(f.caption, f.value) for f in found] == [("Tipo de muestra", "Base líquida")]
|
||||
|
||||
|
||||
def test_a_line_a_known_label_already_claims_is_not_rediscovered():
|
||||
found = discover_captions(lines("Expediente: EXP-0001"), [EXPEDIENTE])
|
||||
assert found == []
|
||||
|
||||
|
||||
def test_a_line_without_the_caption_shape_is_ignored():
|
||||
found = discover_captions(lines("Resultado negativo para lesión intraepitelial"), [EXPEDIENTE])
|
||||
assert found == []
|
||||
|
||||
|
||||
def test_several_undiscovered_captions_come_back_in_line_order():
|
||||
found = discover_captions(lines("Instrumento: ADOS-2", "Módulo: 3", "Expediente: EXP-0001"), [EXPEDIENTE])
|
||||
assert [(f.caption, f.value) for f in found] == [("Instrumento", "ADOS-2"), ("Módulo", "3")]
|
||||
@@ -4,7 +4,7 @@ import pytest
|
||||
|
||||
from extraction.testing import scanned_pdf, text_pdf
|
||||
from extraction import DocumentExtractor, ExtractionError, FieldKind, FieldSpec, make_segmenter, read_document
|
||||
from extraction.readers import ImageReader, PdfReader, combine_pages, reader_for
|
||||
from extraction.readers import ImageReader, PdfReader, TextReader, combine_pages, reader_for
|
||||
|
||||
EXPEDIENTE = FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))
|
||||
NACIMIENTO = FieldSpec("pac_fecha_nacimiento", FieldKind.DATE, labels=("fecha de nacimiento",))
|
||||
@@ -97,6 +97,21 @@ def test_unknown_format_is_rejected():
|
||||
reader_for("notes.docx", b"PK\x03\x04")
|
||||
|
||||
|
||||
def test_plain_text_is_read_as_a_one_page_document():
|
||||
"""Fails if a source whose field bundle is a plain string (not a PDF or
|
||||
an image) stops being readable, falling back to ExtractionError."""
|
||||
document = read_document("fila_42", "Expediente: EXP-0099\nInstrumento: ADOS-2".encode("utf-8"))
|
||||
assert isinstance(reader_for("fila_42", document.raw), TextReader)
|
||||
assert document.page_count == 1
|
||||
assert [line.text for line in document.pages[0].lines] == ["Expediente: EXP-0099", "Instrumento: ADOS-2"]
|
||||
|
||||
|
||||
def test_plain_text_fallback_does_not_steal_a_known_signature_or_extension():
|
||||
"""Fails if `TextReader` starts winning over a real PDF/image match."""
|
||||
assert isinstance(reader_for("reporte.pdf", b"????"), PdfReader)
|
||||
assert isinstance(reader_for("f.png", b"\x89PNG\r\n\x1a\n" + b"\x00" * 8), ImageReader)
|
||||
|
||||
|
||||
def test_combine_pages_from_several_pdfs():
|
||||
from extraction.readers import combine_pages
|
||||
|
||||
|
||||
+1
-1
Submodule WebApi updated: f74ccf5496...102999c8de
+1
-1
Submodule WebApp updated: f4d2a3e85f...c076e1e7a9
+1
-1
Submodule indicadores_kit updated: d1d3b6c694...f4be01b312
+1
-1
Submodule models updated: 5d65730b98...a8bbdc88af
Reference in New Issue
Block a user