tea_preview job: one file previewed, result as run output
Preview files live in an ephemeral area (DATA_DIR/previews, swept after a day, discarded after the run). The result (EEG verdict, checks, metrics with electrode and zone scores; ADOS-2 items, CSS, warnings) is the step output metadata, served by GET /runs/{id}?outputs=true. The preview check runs inside the existing hospital gate test instead of a second 80-minute load.
Checks: ruff, import-linter, openapi diff, 13 unit tests (sandbox).
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
"""Temporary study files and the result of previewing them."""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
import time
|
||||
from collections.abc import Iterable
|
||||
from datetime import date
|
||||
from fcntl import LOCK_EX, flock
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
from persistance import config
|
||||
|
||||
MAX_AGE_S = 24 * 3600
|
||||
_KEY = re.compile(r"[0-9a-f]{64}")
|
||||
|
||||
|
||||
def area() -> Path:
|
||||
directory = config.DATA_DIR / "previews"
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
return directory
|
||||
|
||||
|
||||
def put(content: bytes) -> str:
|
||||
key = hashlib.sha256(content).hexdigest()
|
||||
directory = area()
|
||||
target = directory / key
|
||||
if target.exists():
|
||||
return key
|
||||
|
||||
with tempfile.NamedTemporaryFile(dir=directory, delete=False) as temporary:
|
||||
path = Path(temporary.name)
|
||||
try:
|
||||
temporary.write(content)
|
||||
temporary.close()
|
||||
# Serialize publication without leaving a lock file in the area.
|
||||
fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
flock(fd, LOCK_EX)
|
||||
if not target.exists():
|
||||
path.rename(target)
|
||||
finally:
|
||||
os.close(fd)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
return key
|
||||
|
||||
|
||||
def get(key: str) -> bytes:
|
||||
if not _KEY.fullmatch(key):
|
||||
raise ValueError(f"invalid preview key {key!r}")
|
||||
try:
|
||||
return (area() / key).read_bytes()
|
||||
except FileNotFoundError as exc:
|
||||
raise LookupError(f"no preview file {key}") from exc
|
||||
|
||||
|
||||
def discard(keys: Iterable[str | None]) -> None:
|
||||
for key in keys:
|
||||
if key is not None and _KEY.fullmatch(key):
|
||||
(area() / key).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def sweep(max_age_s: float = MAX_AGE_S, now: float | None = None) -> int:
|
||||
cutoff = (time.time() if now is None else now) - max_age_s
|
||||
removed = 0
|
||||
for path in area().iterdir():
|
||||
try:
|
||||
if path.is_file() and path.stat().st_mtime < cutoff:
|
||||
path.unlink()
|
||||
removed += 1
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
return removed
|
||||
|
||||
|
||||
class Score(BaseModel):
|
||||
model_config = ConfigDict(ser_json_inf_nan="null")
|
||||
|
||||
z: float | None
|
||||
outside: float | None
|
||||
p5: float | None
|
||||
median: float | None
|
||||
p95: float | None
|
||||
|
||||
|
||||
class Site(BaseModel):
|
||||
model_config = ConfigDict(ser_json_inf_nan="null")
|
||||
|
||||
value: float | None
|
||||
score: Score | None
|
||||
|
||||
|
||||
class PreviewMetric(BaseModel):
|
||||
model_config = ConfigDict(ser_json_inf_nan="null")
|
||||
|
||||
code: str
|
||||
value: float | None
|
||||
score: Score | None
|
||||
model: str | None
|
||||
electrodes: dict[str, Site]
|
||||
zones: dict[str, Site]
|
||||
|
||||
|
||||
class PreviewEeg(BaseModel):
|
||||
model_config = ConfigDict(ser_json_inf_nan="null")
|
||||
|
||||
valid: bool | None
|
||||
level: str
|
||||
recorded_on: date | None
|
||||
age_months: float | None
|
||||
clean_fraction: float | None
|
||||
bad_channels: int | None
|
||||
channels: int | None
|
||||
duration_min: float | None
|
||||
line_noise_db: float | None
|
||||
sleep: bool | None
|
||||
checks: list[dict[str, Any]]
|
||||
metrics: list[PreviewMetric]
|
||||
error: str | None
|
||||
|
||||
|
||||
class PreviewAdos2(BaseModel):
|
||||
model_config = ConfigDict(ser_json_inf_nan="null")
|
||||
|
||||
module: str | None
|
||||
evaluation_date: date | None
|
||||
items: dict[str, float | None]
|
||||
css: int | None
|
||||
classification: str | None
|
||||
read: list[str]
|
||||
|
||||
|
||||
class PreviewResult(BaseModel):
|
||||
model_config = ConfigDict(ser_json_inf_nan="null")
|
||||
|
||||
eeg: PreviewEeg
|
||||
ados2: PreviewAdos2 | None
|
||||
warnings: list[str]
|
||||
+1
-1
Submodule WebApi updated: 3438a3135b...70c9506b97
+1
-1
Submodule WebApp updated: 6732893bcc...b3e5a69783
+1
-1
Submodule models updated: 9ed686e87a...3950b3c1f5
Reference in New Issue
Block a user