#!/usr/bin/env python3 """Shared machinery for ingesting EEG from general-purpose data repositories. Repositories like Zenodo and Dryad publish per-subject archives that are often several gigabytes each, so nothing is ever staged wholesale: one archive is fetched, unpacked, converted and deleted before the next is touched. The readable-signal detection and the give-up rule live here so every repository ingest behaves the same way. """ from __future__ import annotations import json, re, shutil, subprocess, sys, tarfile, time, zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) OUT = ROOT / "data/eegx" # `.mat` is here because EEGLAB writes its `.set` structure as a MATLAB file # and archives routinely publish it under the .mat name instead -- whole # records were converting to nothing for that reason alone. Arbitrary .mat # files that are not EEGLAB structures simply fail to read and are skipped. SIGNAL_EXT = {".edf", ".bdf", ".rec", ".set", ".vhdr", ".fif", ".gdf", ".cnt", ".mff", ".nwb", ".eeg", ".data", ".mat"} # Archives holding stimuli, video, code or documents rather than recordings. # These dominate the byte count of some records -- one carries 36 GB of # narration audio -- and would burn the disk budget for zero hours. SKIP_NAME = re.compile( r"stimul|_audio|video|movie.?file|\bcode\b|script|figure|supplement" r"|readme|licen[cs]e|\.docx?$|\.pdf$|\.csv$|\.xlsx?$|\.wav$|\.mp[34]$" r"|\.avi$|\.mov$|\.png$|\.jpe?g$|\.tiff?$|\.svg$|\.ipynb$|\.m$|\.py$", re.I) # Invasive recordings share the BCI vocabulary that puts them in candidate # lists, but they are not EEG and their spike files convert to nothing. INVASIVE = re.compile(r"intracortic|microelectrode.?array|utah.?array|neuropixel" r"|single.?unit|spiking.?activ|neuroprosthes|implanted.?electrode", re.I) # Synthetic or simulated signals are not recordings of anyone. SYNTHETIC = re.compile(r"\bsimulat|\bsynthetic|\bsurrogate\b|\btoy\b|\bmock\b|\bfake\b", re.I) VOLUME = re.compile(r"^(?P.+?)\.(?:zip\.(?P\d{2,3})|z(?P\d{2})|(?P\d{3}))$", re.I) def log(*a): print(*a, flush=True) def free_gb(path: Path = ROOT) -> float: return shutil.disk_usage(path).free / 1e9 def group_volumes(files: list[dict], key_of=lambda f: f["name"]) -> list[tuple[str, list[dict]]]: """Collapse split archives (foo.zip.001, foo.zip.002, ...) into one unit. Each volume is useless alone, so they have to be fetched together and concatenated before anything can be read out of them. """ units: dict[str, list[dict]] = {} order: list[str] = [] for f in files: name = key_of(f) m = VOLUME.match(name) k = m.group("base") if m else name if k not in units: units[k] = [] order.append(k) units[k].append(f) return [(k, sorted(units[k], key=key_of) if len(units[k]) > 1 else units[k]) for k in order] def download(url: str, dest: Path, headers: dict | None = None, timeout: int = 3600) -> bool: """curl handles redirects, retries and resumes better than urllib.""" dest.parent.mkdir(parents=True, exist_ok=True) cmd = ["curl", "-sSL", "--fail", "--retry", "3", "--retry-delay", "5", "--max-time", str(timeout), "-o", str(dest), url] for k, v in (headers or {}).items(): cmd[1:1] = ["-H", f"{k}: {v}"] rc = subprocess.call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) return rc == 0 and dest.exists() and dest.stat().st_size > 0 def unpack(blob: Path, stage: Path) -> Path | None: """Expand an archive in place, or return the staging dir for a bare file. Returns None when the format has no extractor on this machine, so the caller can journal it as skipped rather than silently finding nothing. """ ex = stage / "x" if zipfile.is_zipfile(blob): with zipfile.ZipFile(blob) as z: z.extractall(ex) blob.unlink() return ex if tarfile.is_tarfile(blob): with tarfile.open(blob) as t: t.extractall(ex, filter="data") blob.unlink() return ex if blob.suffix.lower() == ".7z": try: import py7zr with py7zr.SevenZipFile(blob) as z: z.extractall(ex) blob.unlink() return ex except ImportError: pass if blob.suffix.lower() in (".rar", ".7z"): for tool, args, pos in (("7z", ["x", "-y", f"-o{ex}"], "end"), ("7zz", ["x", "-y", f"-o{ex}"], "end"), ("unar", ["-o", str(ex), "-f"], "end"), ("unrar", ["x", "-y"], "rar")): if shutil.which(tool) is None: continue ex.mkdir(parents=True, exist_ok=True) cmd = ([tool] + args + [str(blob)] if pos == "end" else [tool] + args + [str(blob), str(ex) + "/"]) if subprocess.call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0: blob.unlink() return ex return None return stage def signal_files(root: Path) -> list[Path]: out = [] for p in sorted(root.rglob("*")): if not p.is_file() or p.suffix.lower() not in SIGNAL_EXT: continue # BrainVision: .vhdr is the entry point, .eeg/.data is its payload. stem = p.with_suffix("") if p.suffix.lower() in (".eeg", ".data") and ( stem.with_suffix(".vhdr").exists() or stem.with_suffix(".vhdr").exists()): continue # EEGLAB: .set is the entry point, .fdt holds the samples. out.append(p) return out def recording_hours(recs: list[dict]) -> float: """Wall-clock hours covered by the parts of one source recording. A multi-rate source is split into several EEGX parts covering the same stretch of time, so the recording lasted as long as its longest part and never the sum of them. Every ingest measures hours through here, because when each did its own arithmetic one of them reached for a header key that does not exist and turned every productive unit into a logged failure. """ return max((h["n_samples"] / float(h["sfreq"]) for h in recs), default=0) / 3600 def unreadable_census(root: Path, top: int = 6) -> str: """What a barren archive actually held, by extension and bytes. A unit that yields nothing is otherwise indistinguishable from a unit of documents, and the whole record gets abandoned on the strength of it. This says which formats were passed over, so a real gap in the reader shows up in the log instead of looking like an empty record. """ by_ext: dict[str, list] = {} for p in root.rglob("*"): if not p.is_file(): continue e = p.suffix.lower() or "(none)" v = by_ext.setdefault(e, [0, 0]) v[0] += 1 try: v[1] += p.stat().st_size except OSError: pass ranked = sorted(by_ext.items(), key=lambda kv: -kv[1][1])[:top] return ", ".join(f"{e} x{n} ({b/1e6:.0f} MB)" for e, (n, b) in ranked) or "empty" def convert_tree(ds_name: str, root: Path, prov_base: dict, out_dir: Path = OUT) -> tuple[int, float]: from eegx.convert import convert nfiles = hours = 0 found = signal_files(root) if not found: log(f" (no readable signal; archive holds {unreadable_census(root)})") for i, sf in enumerate(found): rel = str(sf.relative_to(root)) subject = re.sub(r"[^A-Za-z0-9]+", "-", rel.rsplit(".", 1)[0])[:80] or f"f{i}" try: recs = convert(sf, out_dir / ds_name, dataset=ds_name, subject=subject, meta={"source_relpath": rel}, provenance=dict(prov_base, source_file=rel)) except Exception as e: log(f" ! {rel[:60]}: {type(e).__name__}: {str(e)[:90]}") continue nfiles += len(recs) hours += recording_hours(recs) return nfiles, hours class Journal: """Per-unit progress log so an interrupted run never re-downloads.""" def __init__(self, path: Path): self.path = path self.done = set() if path.exists(): for line in path.read_text().splitlines(): try: r = json.loads(line) except Exception: continue if r.get("status") in ("ok", "skip", "empty"): self.done.add((r["record"], r["unit"])) def has(self, record, unit) -> bool: return (str(record), unit) in self.done def write(self, **rec): self.path.parent.mkdir(parents=True, exist_ok=True) with open(self.path, "a") as f: f.write(json.dumps(rec) + "\n") if rec.get("status") in ("ok", "skip", "empty"): self.done.add((str(rec["record"]), rec["unit"]))