F7d: technician notes matched by word start and whole word

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.
This commit is contained in:
2026-12-03 20:41:04 -06:00
parent cb1c6bc7ee
commit c3acdf6c12
2 changed files with 120 additions and 15 deletions
+60 -15
View File
@@ -1,4 +1,5 @@
import json import json
import re
import unicodedata import unicodedata
from pathlib import Path from pathlib import Path
@@ -8,18 +9,61 @@ from models.tea.eeg import signals
from models.tea.eeg.preprocess import WINDOW_S, Prepared from models.tea.eeg.preprocess import WINDOW_S, Prepared
REFERENCE = json.loads((Path(__file__).parent / "data" / "hk1k_state.json").read_text()) REFERENCE = json.loads((Path(__file__).parent / "data" / "hk1k_state.json").read_text())
NOTE_WORDS = { NOTE_WORDS = [
"photic": ("fotic", "photic", "flash", "estimulacion luminosa"), ("photic", ("fotic", "photic", "flash", "estimulacion luminosa"), ()),
"hyperventilation": ("hv", "hipervent", "hypervent"), ("hyperventilation", ("hipervent", "hypervent"), ("hv",)),
"eyes_open": ("ojos abiertos", "eyes open", "oa"), (
"eyes_closed": ("ojos cerrados", "eyes closed", "oc"), "eyes_open",
"sleep": ("sueno", "dormido", "sleep", "somnol", "husos", "spindle", "fase i", "fase ii", (
"n1", "n2", "n3"), "ojos abiertos",
"awake": ("despierta", "despierto", "arousal", "vigilia"), "eyes open",
"crying": ("llanto", "llora", "cry"), "open eyes",
"movement": ("movimiento", "movement", "artefacto de movimiento"), "opens eyes",
"feeding": ("come", "alimenta", "biberon", "lactancia"), "abre ojos",
} # fmt: skip "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") EXCLUDED = ("crying", "movement", "disconnection")
MASKED = (*EXCLUDED, "photic", "hyperventilation") MASKED = (*EXCLUDED, "photic", "hyperventilation")
STATES = np.array(["wake", "drowsy", "sleep"], dtype=object) 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" c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn"
) )
plain = plain.replace("\0", "ñ").replace("\1", "Ñ").lower().strip() plain = plain.replace("\0", "ñ").replace("\1", "Ñ").lower().strip()
return next( plain = plain.replace("ñ", "n")
(state for state, words in NOTE_WORDS.items() if any(w in plain for w in words)), None 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]]: def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, str]]:
+60
View File
@@ -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