legacy.validation: director's validation behind the Validator protocol
The director's scripts (biomarcadores-tea/preproceso @ 7dfc641) are vendored unchanged except imports by tools/vendor_legacy.py, one copy per legacy module; --check re-derives them from the pinned submodule. LegacyValidation runs steps 1-4 of un_estudio.procesar for an EDF (edf_convert, lote.excluidos_para_qc + qc_estudio + veredicto, triaje.triar, 60% clean windows) plus preproceso.MIN_CUERO, and returns an R4B FHIR Bundle and 0/1. Tests: identical to the submodule on a synthetic EDF, contract suite, not-valid case, vendor check.
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Copy the director's code into tea_modulo.legacy, unchanged except imports.
|
||||
|
||||
python tools/vendor_legacy.py # (re)write every legacy _director/ folder
|
||||
python tools/vendor_legacy.py --check # exit 1 if any copy differs from the source
|
||||
|
||||
Each legacy module gets its OWN copy of every file it needs (the import
|
||||
closure of its roots), so legacy modules stay independent like the modern
|
||||
ones. The only changes to a copied file:
|
||||
|
||||
- the line `sys.path.insert(0, str(Path(__file__).resolve().parent))` is removed;
|
||||
- imports of sibling scripts become relative (`import eeg_io` ->
|
||||
`from . import eeg_io`; `from validacion import X` -> `from .validacion import X`);
|
||||
- a header comment records the source path, commit and SHA-256.
|
||||
|
||||
`--check` re-applies the same transformation to the pinned submodule and
|
||||
compares, so an edit to a legacy copy is caught (tests/legacy/test_vendor.py).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LEGACY = ROOT / "src" / "tea_modulo" / "legacy"
|
||||
SOURCES = {
|
||||
"preproceso": ROOT / "biomarcadores-tea" / "preproceso",
|
||||
}
|
||||
PINNED = {"biomarcadores-tea": "7dfc641"}
|
||||
|
||||
# legacy module -> (source tree, root scripts). The closure is computed.
|
||||
MANIFEST: dict[str, tuple[str, tuple[str, ...]]] = {
|
||||
"validation": ("preproceso", ("edf_convert", "lote", "triaje", "preproceso")),
|
||||
"preprocessing": ("preproceso", ("edf_convert", "lote", "preproceso")),
|
||||
}
|
||||
|
||||
SYS_PATH_LINE = "sys.path.insert(0, str(Path(__file__).resolve().parent))"
|
||||
_IMPORT = re.compile(r"^(?P<ind>\s*)import (?P<mod>[A-Za-z_][A-Za-z_0-9]*)(?P<rest>(\s+as\s+\w+)?\s*(#.*)?)$")
|
||||
_FROM = re.compile(r"^(?P<ind>\s*)from (?P<mod>[A-Za-z_][A-Za-z_0-9]*) import (?P<rest>.*)$")
|
||||
|
||||
|
||||
def local_names(src: Path) -> set[str]:
|
||||
return {p.stem for p in src.glob("*.py")}
|
||||
|
||||
|
||||
def deps_of(path: Path, local: set[str]) -> set[str]:
|
||||
out = set()
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
m = _IMPORT.match(line) or _FROM.match(line)
|
||||
if m and m.group("mod") in local and m.group("mod") != path.stem:
|
||||
out.add(m.group("mod"))
|
||||
return out
|
||||
|
||||
|
||||
def closure(src: Path, roots) -> list[str]:
|
||||
local = local_names(src)
|
||||
todo, seen = list(roots), set()
|
||||
while todo:
|
||||
m = todo.pop()
|
||||
if m in seen:
|
||||
continue
|
||||
seen.add(m)
|
||||
todo += sorted(deps_of(src / f"{m}.py", local) - seen)
|
||||
return sorted(seen)
|
||||
|
||||
|
||||
def transform(text: str, local: set[str]) -> str:
|
||||
out = []
|
||||
for line in text.splitlines(keepends=True):
|
||||
body = line.rstrip("\n")
|
||||
if body.strip() == SYS_PATH_LINE:
|
||||
continue
|
||||
m = _IMPORT.match(body)
|
||||
if m and m.group("mod") in local:
|
||||
out.append(f"{m.group('ind')}from . import {m.group('mod')}{m.group('rest')}\n")
|
||||
continue
|
||||
m = _FROM.match(body)
|
||||
if m and m.group("mod") in local:
|
||||
out.append(f"{m.group('ind')}from .{m.group('mod')} import {m.group('rest')}\n")
|
||||
continue
|
||||
out.append(line)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def header(src_name: str, rel: str, sha: str, commit: str) -> str:
|
||||
return (f"# Vendored by tools/vendor_legacy.py from {src_name}/{rel} @ {commit}\n"
|
||||
f"# source sha256 {sha}. Do not edit: changed only in imports.\n")
|
||||
|
||||
|
||||
def submodule_commit() -> str:
|
||||
r = subprocess.run(["git", "-C", str(ROOT / "biomarcadores-tea"), "rev-parse", "--short", "HEAD"],
|
||||
capture_output=True, text=True, check=True)
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
def expected_files(module: str) -> dict[str, str]:
|
||||
"""{file name: expected content} for one legacy module's _director folder."""
|
||||
src_name, roots = MANIFEST[module]
|
||||
src = SOURCES[src_name]
|
||||
local = local_names(src)
|
||||
commit = PINNED["biomarcadores-tea"]
|
||||
files = {"__init__.py": f'"""Director code vendored from {src_name} @ {commit} (see tools/vendor_legacy.py)."""\n'}
|
||||
for name in closure(src, roots):
|
||||
raw = (src / f"{name}.py").read_text(encoding="utf-8")
|
||||
sha = hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
||||
files[f"{name}.py"] = header(src_name, f"{name}.py", sha, commit) + transform(raw, local)
|
||||
return files
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--check", action="store_true")
|
||||
args = ap.parse_args(argv)
|
||||
commit = submodule_commit()
|
||||
if commit != PINNED["biomarcadores-tea"]:
|
||||
print(f"biomarcadores-tea is at {commit}, legacy is pinned to "
|
||||
f"{PINNED['biomarcadores-tea']}: check out the pinned commit first", file=sys.stderr)
|
||||
return 2
|
||||
bad = 0
|
||||
for module in MANIFEST:
|
||||
folder = LEGACY / Path(*module.split("/")) / "_director"
|
||||
want = expected_files(module)
|
||||
if args.check:
|
||||
have = {p.name for p in folder.glob("*.py")} if folder.exists() else set()
|
||||
for name in sorted(set(want) | have):
|
||||
p = folder / name
|
||||
if name not in want or not p.exists() or p.read_text(encoding="utf-8") != want[name]:
|
||||
print(f"differs: {p.relative_to(ROOT)}")
|
||||
bad += 1
|
||||
else:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
for old in folder.glob("*.py"):
|
||||
if old.name not in want:
|
||||
old.unlink()
|
||||
for name, text in want.items():
|
||||
(folder / name).write_text(text, encoding="utf-8")
|
||||
print(f"{module}: {len(want) - 1} files")
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user