134 lines
4.9 KiB
Python
134 lines
4.9 KiB
Python
"""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)
|
||
|
||
|
||
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."""
|
||
tokens = re.findall(r"[A-Z0-9]+", fold(label))
|
||
body = r"[\s.\-_/]*".join(re.escape(token) for token in tokens)
|
||
return re.compile(rf"(?<![A-Z0-9]){body}\.?(?![A-Z0-9])")
|
||
|
||
|
||
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))
|