Files
codigo/PROGRAMAS/test_acentos.py
2026-11-17 10:47:00 -06:00

230 lines
9.0 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_acentos.py — Prueba de extremo a extremo con acentos, ñ y diéresis.
Construye un estudio sintético donde TODO lleva caracteres no ASCII:
nombre de carpeta, nombre de archivo, nombre del paciente dentro de la
cabecera binaria, y anotaciones del .ent escritas en cp1252 (como las escribe
NeuroWorks en Windows). Luego recorre la cadena completa —conversión,
metadatos, microvoltios, carga, auditoría, informe de cohorte— y comprueba
que ningún paso falla y que los acentos llegan intactos hasta el final.
python test_acentos.py
"""
import json
import shutil
import struct
import sys
import tempfile
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import test_roundtrip as tr # noqa: E402
import texto as txt # noqa: E402
import xltek_convert as xc # noqa: E402
import eeg_io # noqa: E402
PACIENTE = "MUÑOZ PEÑA"
NOMBRE = "JOSÉ ANDRÉS"
CARPETA = "eeg_012_MUÑOZ_PEÑA_señal"
NOTAS = [
'Detección de electrodo: DESACT. (no admitido por la caja de conexión)',
'Fotoestimulación a 10 Hz — configuración estándar',
'Hiperventilación: niño de 3 años, colaboración regular',
'Vigilia con ojos cerrados; artefacto de máscara y sueño ligero',
'Impedancias sin verificación posible (headbox)',
'Ünlaut de prueba: Müller, güero, pingüino',
]
_E = {"ok": 0, "fallo": 0}
def check(nombre, cond, extra=""):
_E["ok" if cond else "fallo"] += 1
print(("[ok] " if cond else "[FALLO] ") + nombre
+ (f" {extra}" if extra else ""))
def construir(raiz: Path):
"""Estudio KTLX con texto acentuado en cabecera y en el .ent (cp1252)."""
carpeta = raiz / CARPETA
carpeta.mkdir(parents=True)
stem = f"{PACIENTE}, {NOMBRE}_señal-abc123"
total = 900
data = tr.make_signal(total)
eventos = np.zeros(total, dtype=np.uint8)
for k in range(20):
eventos[100 + int(k * tr.FS / 10)] = 1
blob = bytearray(tr.erd_header())
# nombre del paciente en la cabecera, en cp1252 como hace NeuroWorks
blob[32:32 + len(PACIENTE)] = PACIENTE.encode("cp1252")
blob[112:112 + len(NOMBRE)] = NOMBRE.encode("cp1252")
etc_rows = []
for a, n in ((0, 450), (450, 450)):
off = len(blob)
blob += xc.encode_packet(data[a:a + n], eventos[a:a + n], tr.N_CHAN)
etc_rows.append((off, a, n, n, 0))
(carpeta / f"{stem}.erd").write_bytes(bytes(blob))
eb = bytearray(tr.generic_header(9))
for row in etc_rows:
eb += struct.pack("<iiihh", *row)
(carpeta / f"{stem}.etc").write_bytes(bytes(eb))
sb = bytearray(tr.generic_header(9))
sb += struct.pack("<ii", 1, 1) + b"\x00" * 48
sb += stem.encode("cp1252").ljust(256, b"\x00")
sb += struct.pack("<iiii", 0, total, total, total)
(carpeta / f"{stem}.stc").write_bytes(bytes(sb))
nb = bytearray(tr.generic_header(9))
ft0 = xc.EPOCH_AS_FILETIME + 1_600_000_000 * xc.HUNDREDS_OF_NS
nb += struct.pack("<iq", 0, ft0)
nb += struct.pack("<iq", total,
int(ft0 + total / tr.FS * xc.HUNDREDS_OF_NS))
(carpeta / f"{stem}.snc").write_bytes(bytes(nb))
# .ent con las notas en cp1252, sintaxis real de NeuroWorks
ent = bytearray(tr.generic_header(9))
montaje = ('(.(."ChanNames", (' + ", ".join(f'"{c}"' for c in tr.CHAN_NAMES)
+ ')), (."Stamp", 0))')
payloads = [montaje]
for i, n in enumerate(NOTAS):
payloads.append(
f'(.(."Comment", "Configuración"), (."Stamp", {100 + i * 50}), '
f'(."Text", "{n}"), (."Data", (.(."User", "Téc. Muñoz"))), '
f'(."Type", "Annotation"))')
for pl in payloads:
b = pl.encode("cp1252") + b"\x00\x00"
ent += struct.pack("<4i", 1, 16 + len(b), 0, 0) + b
ent += struct.pack("<4i", 0, 0, 0, 0)
(carpeta / f"{stem}.ent").write_bytes(bytes(ent))
return carpeta
def main():
tmp = Path(tempfile.mkdtemp(prefix="acentos_"))
try:
raiz = tmp / "Pediátricos año 2025"
carpeta = construir(raiz)
salida = tmp / "convertidos ñ"
print("--- 1. helpers de texto ---")
p = tmp / "prueba.json"
p.write_bytes(json.dumps({"n": PACIENTE}, ensure_ascii=False)
.encode("cp1252"))
check("lee JSON escrito en cp1252",
txt.leer_json(p)["n"] == PACIENTE, txt.leer_json(p)["n"])
txt.escribir_json(p, {"n": PACIENTE, "u": "pingüino", "t": "José"})
check("escribe y relee en utf-8",
txt.leer_json(p)["u"] == "pingüino")
check("el archivo escrito ES utf-8 válido",
json.loads(p.read_text(encoding="utf-8"))["t"] == "José")
check("normalizar quita tildes y conserva la ñ",
txt.normalizar("Fotoestimulación AÑO Müller")
== "fotoestimulacion año muller",
txt.normalizar("Fotoestimulación AÑO Müller"))
check("nombre_seguro conserva acentos",
txt.nombre_seguro("señal/año:2025") == "señal_año_2025",
txt.nombre_seguro("señal/año:2025"))
print("\n--- 2. lectura del estudio ---")
st = xc.KtlxStudy(carpeta)
check("carpeta con ñ y tilde localizada", st.n_samples == 900)
check("paciente con Ñ desde la cabecera binaria",
st.hdr["pat_last_name"] == PACIENTE, st.hdr["pat_last_name"])
check("nombre con tilde", st.hdr["pat_first_name"] == NOMBRE,
st.hdr["pat_first_name"])
textos = [xc.parse_note(n["text"]).get("texto") for n in st.notes]
textos = [t for t in textos if t]
check("anotación con tilde y guión largo",
any("Fotoestimulación a 10 Hz" in t for t in textos),
next((t for t in textos if "Foto" in t), "—"))
check("anotación con diéresis",
any("pingüino" in t for t in textos))
check("usuario con tilde y punto",
any(xc.parse_note(n["text"]).get("usuario") == "Téc. Muñoz"
for n in st.notes))
print("\n--- 3. conversión y metadatos ---")
class A:
pass
a = A()
a.channels = None
a.calibration = None
a.uv_per_lsb = 5000.0 / (2 ** 21 - 0.5) * 2 ** st.hdr["discardbits"]
a.assume_standard_scale = False
a.format = "npz"
a.gzip = 4
a.out = str(salida)
a.prefix = CARPETA
a.keep_phi = True
a.hash_all = False
sp, mp = xc.convert(st, a)
check("archivos escritos", Path(sp).exists() and Path(mp).exists())
crudo = Path(mp).read_bytes()
check("el metadata.json es utf-8 estricto",
b"\xd1" not in crudo or crudo.decode("utf-8", errors="strict"))
md = txt.leer_json(mp)
check("apellido con Ñ en el JSON",
md["paciente"]["apellido"] == PACIENTE,
md["paciente"]["apellido"])
ev = [e.get("texto") for e in md["eventos"] if e.get("texto")]
check("eventos con acentos en el JSON",
any("Hiperventilación" in str(e) for e in ev))
print("\n--- 4. carga y auditoría ---")
est = eeg_io.Estudio(sp, mp)
check("Estudio carga el JSON acentuado",
est.md["paciente"]["apellido"] == PACIENTE)
df = est.eventos(patron="fotoestimulacion")
check("búsqueda sin acentos encuentra el evento acentuado",
len(df) >= 1, f"{len(df)} coincidencias")
df2 = est.eventos(patron="hiperventilación")
check("búsqueda CON acentos también encuentra", len(df2) >= 1)
print("\n--- 5. microvoltios y lote ---")
import a_microvolts
a_microvolts.main([str(sp), "--formato", "npz"])
uv = Path(str(sp).replace("_signals.npz", "_signals_uV.npz"))
check("archivo en µV escrito", uv.exists())
proc = json.loads(str(np.load(uv, allow_pickle=False)["procedencia"]))
check("procedencia legible", proc["unidad"] == "uV")
import lote
salida2 = tmp / "lote ñ"
rc = lote.main([str(raiz), "-o", str(salida2)])
qc = salida2 / "cohorte_qc.csv"
check("informe de cohorte escrito", qc.exists())
if qc.exists():
b = qc.read_bytes()
check("CSV con BOM utf-8-sig (Excel en español)",
b.startswith(b"\xef\xbb\xbf"))
import pandas as pd
t = pd.read_csv(qc, encoding="utf-8-sig")
check("nombre de estudio con Ñ en el CSV",
any("Ñ" in str(v) for v in t.estudio.values),
str(list(t.estudio.values)))
j = salida2 / "cohorte_qc.json"
check("cohorte_qc.json es utf-8 estricto",
j.exists() and j.read_bytes().decode("utf-8") is not None)
finally:
shutil.rmtree(tmp, ignore_errors=True)
print(f"\nOK: {_E['ok']} FALLOS: {_E['fallo']}")
if _E["fallo"]:
print("Hay fallos: los acentos aún rompen algo.")
return 1
print("La cadena completa resiste acentos, ñ y diéresis.")
return 0
if __name__ == "__main__":
sys.exit(main())