Read keeps the file and says its format; extract takes fields from columns; EEG batches carry their recording, on Dask where it is installed
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
"""Where long batches run (the EEG analysis, measuring a reference cohort). Where Dask is
|
||||
installed (the `dask` extra, for testing on a cluster) they run on the scheduler at
|
||||
DASK_SCHEDULER_ADDRESS, or on a Dask cluster of this machine's cores, through joblib's own
|
||||
Dask backend. Without it (the product) joblib runs them on local processes. BATCH_JOBS caps
|
||||
how many run at once (each task carries its recording: a cap paces a slow link)."""
|
||||
|
||||
import os
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from importlib.util import find_spec
|
||||
|
||||
from joblib import parallel_config
|
||||
from joblib.externals.loky import get_reusable_executor
|
||||
|
||||
|
||||
def jobs() -> int:
|
||||
"""How many tasks run at once: BATCH_JOBS, or every core (or worker)."""
|
||||
return int(os.environ.get("BATCH_JOBS", "-1"))
|
||||
|
||||
|
||||
@contextmanager
|
||||
def batch() -> Iterator[None]:
|
||||
if find_spec("distributed") is None:
|
||||
try:
|
||||
yield
|
||||
finally: # the local workers go when the batch is done
|
||||
get_reusable_executor().shutdown(wait=True)
|
||||
return
|
||||
from distributed import Client, LocalCluster
|
||||
|
||||
address = os.environ.get("DASK_SCHEDULER_ADDRESS")
|
||||
# one process per core, no dashboard port to collide with (8787 is often taken)
|
||||
where = address or LocalCluster(threads_per_worker=1, dashboard_address=None)
|
||||
try:
|
||||
with Client(where), parallel_config(backend="dask"):
|
||||
yield
|
||||
finally:
|
||||
if not address:
|
||||
where.close()
|
||||
+33
-4
@@ -50,9 +50,22 @@ READ_COLUMNS = { # declared, so a load where every file read cleanly still has
|
||||
"text": {"data_type": "text", "nullable": True},
|
||||
"ocr": {"data_type": "bool"},
|
||||
"error": {"data_type": "text", "nullable": True},
|
||||
"format": {"data_type": "text", "nullable": True},
|
||||
}
|
||||
|
||||
|
||||
def file_format(content: bytes) -> str:
|
||||
"""What kind of file this is, from its first bytes, so a route can tell a PDF from an
|
||||
EEG recording in the same column: pdf, edf (EDF and EDF+: a fixed ASCII header whose
|
||||
version is "0"), or other (whatever MarkItDown reads)."""
|
||||
if content.startswith(b"%PDF"):
|
||||
return "pdf"
|
||||
head = content[:256]
|
||||
if len(head) == 256 and head[:8] == b"0 " and head[184:192].strip().isdigit():
|
||||
return "edf"
|
||||
return "other"
|
||||
|
||||
|
||||
@cache
|
||||
def _reader() -> MarkItDown:
|
||||
return MarkItDown()
|
||||
@@ -73,7 +86,15 @@ def _text(content: bytes) -> str:
|
||||
|
||||
|
||||
def read_file(content: bytes) -> dict:
|
||||
"""Text of one file, and whether OCR was needed. An unreadable file keeps its error."""
|
||||
"""Text of one file, its format, and whether OCR was needed. An unreadable file keeps
|
||||
its error; a signal recording (EDF) has no text to read."""
|
||||
kind = file_format(content)
|
||||
if kind == "edf":
|
||||
return {"text": None, "ocr": False, "error": None, "format": kind}
|
||||
return {**_read_text(content), "format": kind}
|
||||
|
||||
|
||||
def _read_text(content: bytes) -> dict:
|
||||
try:
|
||||
found = _text(content)
|
||||
ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS
|
||||
@@ -91,12 +112,19 @@ def read_file(content: bytes) -> dict:
|
||||
|
||||
|
||||
def run_read(p: str, node: Read):
|
||||
"""The input's rows with the file column replaced by its text; each file read once."""
|
||||
"""The input's rows with their file's text and format beside the file column (which
|
||||
keeps the file, for a study that takes the file itself: an EEG's recording); each file
|
||||
read once."""
|
||||
rows = list(nodes.rows(p, node.inputs[0]))
|
||||
for row in rows: # the source kept the file; the row carries its hash
|
||||
row["key"] = row.pop(node.column) or None
|
||||
row["key"] = row.get(node.column) or None
|
||||
keys = {r["key"] for r in rows} - {None}
|
||||
found = nodes.cached("read_cache", keys)
|
||||
legacy = [k for k, r in found.items() if r.get("format") is None] # read before formats
|
||||
for k in legacy:
|
||||
found[k]["format"] = file_format(files.content(k) or b"")
|
||||
nodes.remember("read_cache", [{"key": k, **{c: found[k][c] for c in READ_COLUMNS}}
|
||||
for k in legacy], READ_COLUMNS) # fmt: skip
|
||||
new = {k: files.content(k) for k in keys - set(found)}
|
||||
with ProcessPoolExecutor() as pool:
|
||||
read = dict(zip(new, pool.map(read_file, new.values()), strict=True))
|
||||
@@ -191,8 +219,9 @@ def run_extract(p: str, node: Extract):
|
||||
found = apply_patterns(node, text, codes)
|
||||
else:
|
||||
found = [({}, {}, ["no LLM answering and no patterns set"])]
|
||||
taken = {f: row[c] for f, c in node.columns.items() if row.get(c) is not None}
|
||||
for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]):
|
||||
out.append({**values, RECORD: row[RECORD], "_index": index,
|
||||
out.append({**values, **taken, RECORD: row[RECORD], "_index": index,
|
||||
QUOTES: json.dumps(quotes, ensure_ascii=False),
|
||||
HELD: json.dumps(held) if held else None}) # fmt: skip
|
||||
return nodes.write(p, node.id, out)
|
||||
|
||||
+10
-10
@@ -8,12 +8,12 @@ mains, with the table's age) in worker processes; `tables` gives each scenario's
|
||||
from the valid studies.
|
||||
"""
|
||||
|
||||
import multiprocessing
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
from joblib import Parallel, delayed
|
||||
|
||||
from models import cluster
|
||||
from models.tea.eeg.analysis import analyze
|
||||
from models.tea.eeg.curves import SCENARIOS
|
||||
|
||||
@@ -34,9 +34,8 @@ def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path,
|
||||
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
|
||||
|
||||
|
||||
def _one(study: tuple[str, Path, float]) -> dict:
|
||||
key, path, age = study
|
||||
a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=MAINS_HZ)
|
||||
def _one(key: str, edf: bytes, age: float) -> dict:
|
||||
a = analyze(edf, age_months=age, mains_hz=MAINS_HZ)
|
||||
return {
|
||||
"key": key,
|
||||
"age_months": age,
|
||||
@@ -46,11 +45,12 @@ def _one(study: tuple[str, Path, float]) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def measure(studies, workers: int = 4) -> list[dict]:
|
||||
"""Each study's verdict and features, in listing order."""
|
||||
context = multiprocessing.get_context("spawn")
|
||||
with ProcessPoolExecutor(workers, mp_context=context) as pool:
|
||||
return list(pool.map(_one, studies))
|
||||
def measure(studies) -> list[dict]:
|
||||
"""Each study's verdict and features, in listing order, each a task on the cluster
|
||||
(models.cluster)."""
|
||||
with cluster.batch(): # each task carries its recording: workers see no local folder
|
||||
return Parallel(n_jobs=cluster.jobs())(delayed(_one)(key, Path(path).read_bytes(), age)
|
||||
for key, path, age in studies) # fmt: skip
|
||||
|
||||
|
||||
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
|
||||
|
||||
+7
-9
@@ -16,8 +16,8 @@ from pathlib import Path
|
||||
import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
from joblib import Parallel, delayed
|
||||
from joblib.externals.loky import get_reusable_executor
|
||||
|
||||
from models import cluster
|
||||
from models.tea.eeg import analysis, curves, reference
|
||||
from persistance import eeg, registry, silver
|
||||
|
||||
@@ -40,16 +40,14 @@ class Baseline(mlflow.pyfunc.PythonModel):
|
||||
for r in rows]) # fmt: skip
|
||||
|
||||
|
||||
def _analyze(edf: str, birth) -> tuple[str, analysis.Analysis]:
|
||||
return edf, analysis.analyze(eeg.signal(edf), birth)
|
||||
|
||||
|
||||
def analyze() -> int:
|
||||
"""Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt."""
|
||||
pending = eeg.pending()
|
||||
found = dict(Parallel(n_jobs=-1)(delayed(_analyze)(r["edf"], r["birth_date"])
|
||||
for r in pending)) # fmt: skip
|
||||
get_reusable_executor().shutdown(wait=True)
|
||||
with cluster.batch(): # one task per EEG, carrying its recording (models.cluster)
|
||||
tasks = (delayed(analysis.analyze)(eeg.signal(r["edf"]), r["birth_date"])
|
||||
for r in pending) # fmt: skip
|
||||
done = Parallel(n_jobs=cluster.jobs())(tasks)
|
||||
found = dict(zip((r["edf"] for r in pending), done, strict=True))
|
||||
eeg.save_analyses(found)
|
||||
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"])
|
||||
return len(found)
|
||||
@@ -65,7 +63,7 @@ def _reference() -> tuple[str, list[dict]]:
|
||||
path = Path(cache) / f"{reference.NAME}-{digest[:16]}.json" if cache else None
|
||||
if path and path.exists():
|
||||
return digest, json.loads(path.read_text())
|
||||
measured = reference.measure(studies, workers=os.cpu_count() or 4)
|
||||
measured = reference.measure(studies)
|
||||
measured = [{**m, "key": str(m["key"])} for m in measured]
|
||||
if path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
Reference in New Issue
Block a user