"""What the document extractor should look for to fill a target entity, derived from the entity's import schema: the field's type decides how a value is parsed, its catalog becomes the accepted terms, and the captions and clinical synonyms come from `extraction.nlp.vocabulary`.""" import re import types import typing from datetime import date, datetime from extraction.nlp import FieldKind, FieldSpec from extraction.nlp.vocabulary import ( ANCHORS, CLINICAL_TERMS, FREE_TEXT_FIELDS, NEGATED_VALUES, PATTERNS, SEVERITY, SUBJECTS, UNITS, labels_for, ) from webapi.imports.schemas.registry import EntitySpec # Surrogate keys, stored files and OCR bookkeeping are never read from a document. _NOT_IN_DOCUMENTS = re.compile(r"(_id$|_blob$|_ocr_|_created_at$|_updated_at$|^eeg_estudio$|_pdf_ruta$|_nlp_version$)") _IDENTIFIERS = re.compile(r"(_id_hospital$|_id_registro_laboratorio$)") _LONG_TEXT = re.compile(r"(observaciones|_texto$|interpretacion|descripcion|motivo|interrogatorio|plan_|tratamiento|exploracion|receta|pronostico)") def field_specs_for(entity: EntitySpec, *, key_pattern: str | None = None) -> list[FieldSpec]: specs = [] for name, info in entity.schema.model_fields.items(): if _NOT_IN_DOCUMENTS.search(name): continue kind = _kind(name, info.annotation, entity) choices: dict = {} if kind is FieldKind.CHOICE: catalog = entity.schema.catalog_for(name) if catalog is not None: choices.update(catalog.choices) choices.update(CLINICAL_TERMS.get(name, {})) pattern = PATTERNS.get(name) if key_pattern and name == key_field_for(entity): pattern = key_pattern specs.append( FieldSpec( name=name, kind=kind, labels=labels_for(name, _description(entity, name)), choices=choices, pattern=pattern, scan_free_text=name in FREE_TEXT_FIELDS or (pattern is not None and pattern == key_pattern), multiline=kind is FieldKind.TEXT and bool(_LONG_TEXT.search(name)), required=info.is_required(), anchors=ANCHORS.get(name, ()), severity=SEVERITY.get(name, ()), negated_value=NEGATED_VALUES.get(name), unit=UNITS.get(name), ) ) return specs def subject_for(entity: EntitySpec) -> tuple[str, ...]: """What a document feeding this entity is about (`vocabulary.SUBJECTS`).""" return SUBJECTS.get(entity.model.__table__.name, ()) def foreign_subjects_for(entity: EntitySpec) -> tuple[str, ...]: """What documents feeding other entities are about, less this one's own terms.""" own = set(subject_for(entity)) if not own: return () return tuple(sorted({term for table, terms in SUBJECTS.items() if table != entity.model.__table__.name for term in terms} - own)) def key_field_for(entity: EntitySpec) -> str | None: """The field that identifies whose record a page belongs to.""" fields = entity.schema.model_fields for candidate in ("pac_id_hospital", "eeg_id_registro_laboratorio"): if candidate in fields: return candidate return entity.conflict_fields[0] if entity.conflict_fields else None def _kind(name: str, annotation, entity: EntitySpec) -> FieldKind: if entity.schema.catalog_for(name) is not None or name in CLINICAL_TERMS: return FieldKind.CHOICE if _IDENTIFIERS.search(name): return FieldKind.IDENTIFIER base = _unwrap(annotation) if base in (date, datetime): return FieldKind.DATE if base is bool or base is int: return FieldKind.INTEGER if base is float: return FieldKind.DECIMAL return FieldKind.TEXT def _unwrap(annotation): """`Optional[Annotated[str, ...]]` -> `str`.""" while True: origin = typing.get_origin(annotation) if origin is typing.Annotated: annotation = typing.get_args(annotation)[0] elif origin in (typing.Union, types.UnionType): args = [a for a in typing.get_args(annotation) if a is not type(None)] annotation = args[0] if args else annotation if not args: return annotation else: return annotation def _description(entity: EntitySpec, name: str) -> str | None: field = entity.model.model_fields.get(name) return field.description if field is not None else None