From c3acdf6c12423a108f1f755372958c03b368cd19 Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 3 Dec 2026 20:41:04 -0600 Subject: [PATCH] F7d: technician notes matched by word start and whole word MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port the reference vocabulary and priority order into NOTE_WORDS triples. Match prefixes at word starts and words at both boundaries, normalize ñ to n after the existing accent normalization, and reject whole-word closing notes. Keep note_intervals, window_note, mask, EXCLUDED and MASKED unchanged. Ported 32 logic cases: 22 recognized texts, nine negative texts and the closing-note interval case. Did not port test_igual_que_la_libreria_eeg, as explicitly required: it imports and compares against the external eeg library rather than testing the local logic. The interval case omits the am.MODULE.version assertion because this implementation has no annotation library MODULE or corresponding version API. Internal choices: - Keep the existing next-with-default expression for first-match selection. - Use the reference ordered list and END, _pattern and PATTERNS structure, compiling one expression per state at module import. - Use Ruff's multiline formatting for the vocabulary and invented fixtures. - Adapt interval fixtures to the existing tuple input/output shapes and calculate the asserted interval end as onset plus duration. Validation from the worktree root with the main checkout's virtualenv: - ruff check models: passed. - ruff format --check models: passed, 54 files already formatted. - lint-imports: passed, two contracts kept and none broken. - pytest models/tests/test_tea_notes.py: 32 passed. - pytest test_eeg_reasons.py, test_tea_training_source.py, test_tea_job.py and test_tea_preview.py under models/tests: 24 passed, seven warnings. This regression run used flock heavy.lock and nice -n 10. - Reference vocabulary and unchanged interval/masking AST checks: passed. - git diff --check: passed. Python checks used PYTHONPATH=Core:Persistance:models:WebApi:synthetic to resolve this worktree instead of the virtualenv's editable main checkout. --- models/tea/eeg/sleep.py | 75 ++++++++++++++++++++++++++++++++--------- tests/test_tea_notes.py | 60 +++++++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+), 15 deletions(-) create mode 100644 tests/test_tea_notes.py diff --git a/models/tea/eeg/sleep.py b/models/tea/eeg/sleep.py index 9d46633..f352128 100644 --- a/models/tea/eeg/sleep.py +++ b/models/tea/eeg/sleep.py @@ -1,4 +1,5 @@ import json +import re import unicodedata from pathlib import Path @@ -8,18 +9,61 @@ from models.tea.eeg import signals from models.tea.eeg.preprocess import WINDOW_S, Prepared REFERENCE = json.loads((Path(__file__).parent / "data" / "hk1k_state.json").read_text()) -NOTE_WORDS = { - "photic": ("fotic", "photic", "flash", "estimulacion luminosa"), - "hyperventilation": ("hv", "hipervent", "hypervent"), - "eyes_open": ("ojos abiertos", "eyes open", "oa"), - "eyes_closed": ("ojos cerrados", "eyes closed", "oc"), - "sleep": ("sueno", "dormido", "sleep", "somnol", "husos", "spindle", "fase i", "fase ii", - "n1", "n2", "n3"), - "awake": ("despierta", "despierto", "arousal", "vigilia"), - "crying": ("llanto", "llora", "cry"), - "movement": ("movimiento", "movement", "artefacto de movimiento"), - "feeding": ("come", "alimenta", "biberon", "lactancia"), -} # fmt: skip +NOTE_WORDS = [ + ("photic", ("fotic", "photic", "flash", "estimulacion luminosa"), ()), + ("hyperventilation", ("hipervent", "hypervent"), ("hv",)), + ( + "eyes_open", + ( + "ojos abiertos", + "eyes open", + "open eyes", + "opens eyes", + "abre ojos", + "abre los ojos", + "abrio ojos", + "abrio los ojos", + "apertura de ojos", + "apertura ocular", + ), + ("oa", "eo"), + ), + ( + "eyes_closed", + ( + "ojos cerrados", + "eyes closed", + "close eyes", + "closes eyes", + "eyes shut", + "cierra ojos", + "cierra los ojos", + "cerro ojos", + "cerro los ojos", + "cierre de ojos", + "cierre ocular", + ), + ("oc", "ec"), + ), + ( + "sleep", + ("sueno", "dormido", "dormida", "sleep", "asleep", "somnol", "husos", "spindle"), + ("fase i", "fase ii", "fase iii", "n1", "n2", "n3"), + ), + ("awake", ("despierta", "despierto", "arousal", "vigilia"), ()), + ("crying", ("llanto", "llora", "cry"), ()), + ("movement", ("movimiento", "movement", "artefacto de movimiento"), ()), + ("feeding", ("alimenta", "biberon", "lactancia"), ("come", "comer", "comio", "comiendo")), +] +END = re.compile(r"\b(off|fin|end|stop)\b") + + +def _pattern(prefixes, words) -> re.Pattern: + parts = [rf"\b{re.escape(k)}" for k in prefixes] + [rf"\b{re.escape(k)}\b" for k in words] + return re.compile("|".join(parts)) + + +PATTERNS = [(state, _pattern(prefixes, words)) for state, prefixes, words in NOTE_WORDS] EXCLUDED = ("crying", "movement", "disconnection") MASKED = (*EXCLUDED, "photic", "hyperventilation") STATES = np.array(["wake", "drowsy", "sleep"], dtype=object) @@ -36,9 +80,10 @@ def note_state(text: str) -> str | None: c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn" ) plain = plain.replace("\0", "ñ").replace("\1", "Ñ").lower().strip() - return next( - (state for state, words in NOTE_WORDS.items() if any(w in plain for w in words)), None - ) + plain = plain.replace("ñ", "n") + if END.search(plain): + return None + return next((state for state, pattern in PATTERNS if pattern.search(plain)), None) def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, str]]: diff --git a/tests/test_tea_notes.py b/tests/test_tea_notes.py new file mode 100644 index 0000000..a0b027b --- /dev/null +++ b/tests/test_tea_notes.py @@ -0,0 +1,60 @@ +import pytest + +from models.tea.eeg.sleep import note_intervals, note_state + +VERDADEROS = [ + ("Ojos cerrados", "eyes_closed"), + ("OC", "eyes_closed"), + ("oc 10 s", "eyes_closed"), + ("Cierra los ojos", "eyes_closed"), + ("Eyes closed", "eyes_closed"), + ("Ojos abiertos", "eyes_open"), + ("OA", "eyes_open"), + ("Sueño", "sleep"), + ("SUEÑO", "sleep"), + ("dormida", "sleep"), + ("Fase II", "sleep"), + ("N2", "sleep"), + ("Asleep", "sleep"), + ("Fótica 6 Hz", "photic"), + ("Photic 12 Hz", "photic"), + ("HV", "hyperventilation"), + ("Hiperventilación", "hyperventilation"), + ("Despierto", "awake"), + ("Llora", "crying"), + ("Movimiento", "movement"), + ("Biberón", "feeding"), + ("come", "feeding"), +] +FALSOS = [ + "foco", + "Boca abierta", + "Mov. local", + "Doctor", + "Toalla", + "comentario del técnico", + "Recolocar electrodo", + "Photic: Off", + "Fin de fótica", +] + + +@pytest.mark.parametrize("texto, estado", VERDADEROS) +def test_estado_reconocido(texto, estado): + assert note_state(texto) == estado + + +@pytest.mark.parametrize("texto", FALSOS) +def test_sin_falso_positivo(texto): + assert note_state(texto) is None + + +def test_intervalos_no_abren_estado_con_nota_de_cierre(): + notas = [ + (0.0, 0.0, "Photic 6 Hz"), + (20.0, 0.0, "Photic: Off"), + (100.0, 0.0, "foco"), + ] + iv = note_intervals(notas, 300.0) + assert [state for _, _, state in iv] == ["photic", "unmarked"] + assert iv[0][0] + iv[0][1] == 60.0