157 lines
7.3 KiB
Python
157 lines
7.3 KiB
Python
"""Auto-match suggestions for the column-mapping UI, based on `rapidfuzz`."""
|
|
|
|
import re
|
|
import unicodedata
|
|
from dataclasses import dataclass
|
|
|
|
from rapidfuzz import fuzz
|
|
|
|
# Keys are target fields; values are normalized source-column names (see
|
|
# `_normalize`: lowercase, no accents, spaces/dashes/dots -> "_").
|
|
SYNONYMS: dict[str, set[str]] = {
|
|
"pac_id_hospital": {
|
|
"id_hospital", "hospital_id", "expediente", "num_expediente", "no_expediente", "numero_expediente",
|
|
"exp", "nss", "id_paciente", "paciente_id", "folio_paciente", "clave_paciente",
|
|
# A source may name the patient column after the entity.
|
|
"paciente",
|
|
},
|
|
"pac_fecha_nacimiento": {"fecha_nacimiento", "dob", "birth_date", "fecha_nac", "fec_nac", "f_nac", "f_nacimiento", "nacimiento"},
|
|
"pac_sexo": {"sexo", "genero", "gender", "sex"},
|
|
"pac_codigo_postal": {"codigo_postal", "cod_postal", "cp", "c_p", "zip", "zip_code"},
|
|
"pac_dependencia": {"dependencia", "tipo_derechohabiente", "derechohabiencia", "afiliacion"},
|
|
"pac_parentesco": {"parentesco", "relacion"},
|
|
"ord_numero_hospital": {"folio", "folio_orden", "numero_orden", "no_orden", "orden", "num_orden"},
|
|
"ord_tipo_estudio": {"estudio", "tipo_estudio", "estudio_solicitado"},
|
|
"ord_medico_solicitante": {"medico", "medico_solicitante", "solicitante"},
|
|
"nm_id_hospital": {"folio_nota", "id_nota", "numero_nota", "no_nota"},
|
|
"nm_fecha": {"fecha", "fecha_consulta", "fecha_nota"},
|
|
"nm_especialidad": {"servicio", "especialidad"},
|
|
"nm_motivo_consulta": {"motivo", "motivo_consulta"},
|
|
"nm_diagnostico_texto": {"dx", "diagnostico"},
|
|
"nm_masa_corporal": {"peso", "peso_kg", "peso_(kg)"},
|
|
"nm_talla": {"talla", "talla_m", "talla_(m)", "estatura"},
|
|
"nm_medico_tratante": {"medico", "medico_tratante"},
|
|
"bx_cin_grado": {"grado_cin", "cin", "resultado_histopatologico", "diagnostico_histopatologico"},
|
|
"bh_fecha": {"fecha", "tomada", "fecha_toma", "fecha_muestra"},
|
|
}
|
|
|
|
# Scores per match kind; the 1:1 assignment takes the best-scoring pairs first.
|
|
_EXACT, _NORMALIZED, _SYNONYM, _UNPREFIXED = 1.0, 0.9, 0.8, 0.75
|
|
_WORD_FLOOR, _FUZZY_CAP = 0.5, 0.7
|
|
# Words that carry no meaning for matching ("Fecha *de* solicitud").
|
|
_STOPWORDS = {"de", "del", "la", "el", "los", "las", "en", "por", "para", "con"}
|
|
_NEAR_WORD = 0.8
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class MatchSuggestion:
|
|
source_column: str
|
|
target_field: str | None
|
|
confidence: float
|
|
reason: str # "exact" | "normalized" | "synonym" | "unprefixed" | "fuzzy" | "none"
|
|
|
|
|
|
def _normalize(name: str) -> str:
|
|
without_accents = "".join(
|
|
c for c in unicodedata.normalize("NFKD", name) if not unicodedata.combining(c)
|
|
)
|
|
cleaned = without_accents.strip().lower()
|
|
for separator in ("-", ".", "/"):
|
|
cleaned = cleaned.replace(separator, " ")
|
|
return "_".join(cleaned.split())
|
|
|
|
|
|
def _words(normalized: str) -> list[str]:
|
|
"""Meaningful words; two letters or fewer are units ("kg") or noise."""
|
|
return [w for w in re.split(r"[^a-z0-9]+", normalized) if len(w) > 2 and w not in _STOPWORDS]
|
|
|
|
|
|
def _word_score(source_words: list[str], target_words: list[str]) -> float:
|
|
"""Word-level similarity: each source word scores its best match among
|
|
the target words (exact 1.0, near-miss spellings ≥0.8, else 0), divided
|
|
by the longer word list. Comparing words rather than whole strings
|
|
rewards shared meaning ("estudio solicitado" ~ "tipo_estudio") instead of
|
|
shared suffixes ("estudio_solicitado" ~ "medico_solicitante")."""
|
|
if not source_words or not target_words:
|
|
return 0.0
|
|
total = 0.0
|
|
for word in source_words:
|
|
best = max(fuzz.ratio(word, other) / 100.0 for other in target_words)
|
|
if best >= _NEAR_WORD:
|
|
total += best
|
|
return total / max(len(source_words), len(target_words))
|
|
|
|
|
|
def _unprefixed(target: str) -> str:
|
|
"""`pac_sexo` -> `sexo`: Core's field names carry a table prefix that
|
|
source systems never use."""
|
|
head, _, rest = target.partition("_")
|
|
return rest if rest else head
|
|
|
|
|
|
def suggest_mapping(source_columns: list[str], target_fields: list[str]) -> list[MatchSuggestion]:
|
|
"""Exact name -> normalized (case/accents/separators) -> static synonym
|
|
table -> name without the table prefix -> word-level similarity -> no
|
|
match.
|
|
|
|
The 1:1 assignment is global: all (source, target) pairs are scored and
|
|
claimed best-first, so a weak fuzzy match early in the file cannot take
|
|
a target from an exact match later in it."""
|
|
candidates: list[tuple[float, int, str, str, str]] = []
|
|
for position, source in enumerate(source_columns):
|
|
for target in target_fields:
|
|
scored = _score(source, target)
|
|
if scored is not None:
|
|
score, reason = scored
|
|
# -position: on equal scores the earlier source column wins.
|
|
candidates.append((score, -position, source, target, reason))
|
|
|
|
claimed_sources: dict[str, MatchSuggestion] = {}
|
|
claimed_targets: set[str] = set()
|
|
for score, _, source, target, reason in sorted(candidates, reverse=True):
|
|
if source in claimed_sources or target in claimed_targets:
|
|
continue
|
|
claimed_sources[source] = MatchSuggestion(source, target, round(score, 2), reason)
|
|
claimed_targets.add(target)
|
|
|
|
return [claimed_sources.get(source, MatchSuggestion(source, None, 0.0, "none")) for source in source_columns]
|
|
|
|
|
|
def _score(source: str, target: str) -> tuple[float, str] | None:
|
|
if source == target:
|
|
return _EXACT, "exact"
|
|
# A dotted (flattened JSON) name also matches by its last segment:
|
|
# "paciente.expediente" is an expediente.
|
|
variants = [source] + ([source.rsplit(".", 1)[-1]] if "." in source else [])
|
|
scored = [s for s in (_score_one(v, target) for v in variants) if s is not None]
|
|
return max(scored, key=lambda s: s[0]) if scored else None
|
|
|
|
|
|
def _score_one(source: str, target: str) -> tuple[float, str] | None:
|
|
normalized_source, normalized_target = _normalize(source), _normalize(target)
|
|
if normalized_source == normalized_target:
|
|
return _NORMALIZED, "normalized"
|
|
if normalized_source in SYNONYMS.get(target, set()):
|
|
return _SYNONYM, "synonym"
|
|
unprefixed_target = _unprefixed(normalized_target)
|
|
if normalized_source == unprefixed_target:
|
|
return _UNPREFIXED, "unprefixed"
|
|
# Words are compared against the full and the unprefixed name, since not every
|
|
# field has a table prefix (`hemoglobina_g_dl`). The prefix itself is shared by
|
|
# every column of the table ("eeg_id" ~ "eeg_estudio"), so it is not evidence.
|
|
unprefixed_target_words = _words(unprefixed_target)
|
|
prefix_token = normalized_target.split("_", 1)[0]
|
|
target_words_full = (
|
|
[w for w in _words(normalized_target) if w != prefix_token]
|
|
if unprefixed_target_words
|
|
else _words(normalized_target)
|
|
)
|
|
source_words = _words(normalized_source)
|
|
words = max(_word_score(source_words, target_words_full), _word_score(source_words, unprefixed_target_words))
|
|
if words >= _WORD_FLOOR:
|
|
# 0.5..0.7 by word overlap, plus a tiny whole-string tiebreak so
|
|
# "fecha_reporte" prefers bx_fecha_reporte over another one-word overlap.
|
|
ratio = fuzz.ratio(normalized_source, unprefixed_target) / 100.0
|
|
return min(0.5 + (words - _WORD_FLOOR) * 0.36 + ratio * 0.02, _FUZZY_CAP), "fuzzy"
|
|
return None
|