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

187 lines
7.1 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Spanish clinical text normalization and value parsing.
`fold` maps every character to exactly one character (uppercase, without
accents), so a match found in folded text points at the same span in the
original text.
"""
import re
import unicodedata
from datetime import date
_PUNCT_EQUIVALENTS = {"–": "-", "—": "-", "·": ".", "’": "'", " ": " "}
def fold_char(ch: str) -> str:
ch = _PUNCT_EQUIVALENTS.get(ch, ch)
base = unicodedata.normalize("NFKD", ch)[:1] or ch
upper = base.upper()
return upper[:1] if upper else base
def fold(text: str) -> str:
return "".join(fold_char(ch) for ch in text)
# Characters OCR confuses with each other, mapped to one representative.
# Digits only count as letters inside a word, so `NIC 1` and `10.-` keep theirs.
_OCR_LETTERS = {"L": "I", "!": "I", "|": "I", "J": "I"}
_OCR_DIGITS = {"1": "I", "0": "O", "5": "S", "8": "B"}
def ocr_fold(text: str) -> str:
"""`fold`, then OCR look-alikes collapsed (`DLAGNOSTLCO`, `COND!LOMA`,
`NAC1MIENTO`), keeping the length. Both sides of a comparison go
through it, so a confusion matches whichever way it went."""
folded = fold(text)
out = []
for i, ch in enumerate(folded):
if ch in _OCR_LETTERS:
ch = _OCR_LETTERS[ch]
elif ch in _OCR_DIGITS:
before = folded[i - 1] if i else " "
after = folded[i + 1] if i + 1 < len(folded) else " "
if before.isalpha() or after.isalpha():
ch = _OCR_DIGITS[ch]
out.append(ch)
return "".join(out)
# Words a caption may drop without changing what it names.
_CONNECTORS = frozenset({"DE", "DEL", "LA", "EL", "LOS", "LAS", "EN", "PARA", "POR", "AL", "Y"})
_LABEL_SEPARATOR = r"[\s.\-_/]*"
# A date caption may also announce the time: `FECHA/HORA DE REPORTE`, `FECHA Y HORA DE...`.
_TIME_QUALIFIER = r"(?:(?:Y\s+)?HORA[\s.\-_/]*)?"
# Shortest abbreviation of a caption word: `NAC.` for `NACIMIENTO`.
MIN_ABBREVIATION = 3
def label_pattern(label: str) -> re.Pattern:
"""`"fecha de nacimiento"` -> a pattern matching `FECHA DE NACIMIENTO`,
`Fecha de nacimiento`, `F.DE NACIMIENTO` style spacing/punctuation
variants, on word boundaries. Long words may be abbreviated with a
period (`FECH. NAC.`), connectors between words left out
(`FECHA NACIMIENTO`) and a date caption may name the time too
(`FECHA/HORA DE NACIMIENTO`)."""
tokens = re.findall(r"[A-Z0-9]+", fold(label))
parts = []
for position, token in enumerate(tokens):
last = position == len(tokens) - 1
word = _abbreviable(token) + ("" if last else _LABEL_SEPARATOR)
optional = token in _CONNECTORS and 0 < position and not last
parts.append(f"(?:{word})?" if optional else word)
if token == "FECHA" and not last:
parts.append(_TIME_QUALIFIER)
return re.compile(rf"(?<![A-Z0-9]){''.join(parts)}\.?(?![A-Z0-9])")
def _abbreviable(token: str) -> str:
if len(token) <= MIN_ABBREVIATION + 1 or not token.isalpha():
return re.escape(token)
head, rest = token[:MIN_ABBREVIATION], token[MIN_ABBREVIATION:-1]
nested = ""
for char in reversed(rest):
nested = f"(?:{re.escape(char)}{nested})?"
return f"(?:{re.escape(token)}|{re.escape(head)}{nested}\\.)"
SEPARATOR = re.compile(r"^[\s.:\-=#•|)]*")
MONTHS = {
"ENERO": 1, "ENE": 1, "JAN": 1, "JANUARY": 1,
"FEBRERO": 2, "FEB": 2, "FEBRUARY": 2,
"MARZO": 3, "MAR": 3, "MARCH": 3,
"ABRIL": 4, "ABR": 4, "APR": 4, "APRIL": 4,
"MAYO": 5, "MAY": 5,
"JUNIO": 6, "JUN": 6, "JUNE": 6,
"JULIO": 7, "JUL": 7, "JULY": 7,
"AGOSTO": 8, "AGO": 8, "AUG": 8, "AUGUST": 8,
"SEPTIEMBRE": 9, "SETIEMBRE": 9, "SEP": 9, "SEPT": 9, "SET": 9, "SEPTEMBER": 9,
"OCTUBRE": 10, "OCT": 10, "OCTOBER": 10,
"NOVIEMBRE": 11, "NOV": 11, "NOVEMBER": 11,
"DICIEMBRE": 12, "DIC": 12, "DEC": 12, "DECEMBER": 12,
}
_MONTH_NAMES = "|".join(sorted(MONTHS, key=len, reverse=True))
_DATE_PATTERNS = (
# 2024-01-15
(re.compile(r"(?<!\d)(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})(?!\d)"), ("y", "m", "d")),
# 15/01/2024, 15-01-24 (day first: how dates are written in Mexico)
(re.compile(r"(?<!\d)(\d{1,2})[-/.](\d{1,2})[-/.](\d{4}|\d{2})(?!\d)"), ("d", "m", "y")),
# 15 de enero de 2024, 15-ENE-2024, 15 ene. 2024
(re.compile(rf"(?<!\d)(\d{{1,2}})[\s.\-/]*(?:DE[\s]+)?({_MONTH_NAMES})\.?[\s.\-/,]*(?:DE(?:L)?[\s]+)?(\d{{4}}|\d{{2}})(?!\d)"), ("d", "M", "y")),
# enero 15, 2024
(re.compile(rf"(?<![A-Z])({_MONTH_NAMES})\.?\s+(\d{{1,2}}),?\s+(\d{{4}})(?!\d)"), ("M", "d", "y")),
)
def find_date(text: str) -> tuple[date, tuple[int, int]] | None:
"""First valid date in `text` and its span."""
folded = fold(text)
best: tuple[date, tuple[int, int]] | None = None
for pattern, order in _DATE_PATTERNS:
for match in pattern.finditer(folded):
parts = dict(zip(order, match.groups()))
parsed = _build_date(parts)
if parsed and (best is None or match.start() < best[1][0]):
best = (parsed, match.span())
break
return best
def _build_date(parts: dict[str, str]) -> date | None:
try:
month = MONTHS[parts["M"]] if "M" in parts else int(parts["m"])
year = int(parts["y"])
if year < 100:
year += 2000 if year <= date.today().year % 100 else 1900
return date(year, month, int(parts["d"]))
except (KeyError, ValueError):
return None
_NUMBER = re.compile(r"(?<![\w.])[-+]?\d{1,3}(?:[,\s]\d{3})*(?:[.,]\d+)?(?![\w])|(?<![\w.])[-+]?\d+(?:[.,]\d+)?(?![\w])")
_INTEGER = re.compile(r"(?<![\w.,])[-+]?\d+(?!\w)(?![.,]\d)")
_IDENTIFIER = re.compile(r"[A-Z0-9][A-Z0-9\-/._]*\d[A-Z0-9\-/._]*|\d+[A-Z][A-Z0-9\-]*")
def find_decimal(text: str) -> tuple[float, tuple[int, int]] | None:
match = _NUMBER.search(text)
if not match:
return None
raw = match.group().replace(" ", "")
if "," in raw and "." in raw:
raw = raw.replace(",", "")
elif "," in raw:
whole, _, frac = raw.rpartition(",")
raw = f"{whole}.{frac}" if len(frac) != 3 else raw.replace(",", "")
try:
return float(raw), match.span()
except ValueError:
return None
def find_integer(text: str) -> tuple[int, tuple[int, int]] | None:
match = _INTEGER.search(text)
return (int(match.group()), match.span()) if match else None
def find_identifier(text: str, pattern: str | None = None) -> tuple[str, tuple[int, int]] | None:
folded = fold(text)
regex = re.compile(pattern, re.I) if pattern else _IDENTIFIER
match = regex.search(folded if not pattern else text)
if not match:
return None
return text[match.start() : match.end()].strip(" .,;:"), match.span()
_NEGATION_TRIGGERS = re.compile(
r"(?<![A-Z])(NO|SIN|NI|NUNCA|NIEGA|NEGATIVO (?:PARA|A)|AUSENCIA DE|DESCARTA(?:DO|R)?|NO SE OBSERVA(?:N)?|NO HAY|LIBRE DE)(?![A-Z])[^.;:]{0,30}$"
)
def is_negated(folded_text: str, start: int) -> bool:
"""NegEx-style check: does a negation trigger precede position `start`
within the same clause?"""
window = folded_text[max(0, start - 45) : start]
return bool(_NEGATION_TRIGGERS.search(window))