#!/usr/bin/env python3
"""Import every Blastware .MLG under a directory into SFM's DB and waveform store.
import_mlg_dir.py
--db-path P --store-root S [--dry-run] [--not-call-in]
For a copy of an ACH folder (DL2 holds ~86,000). Idempotent: a file already
stored (same name, same bytes) counts as a duplicate. Files with records go
first, then the empty ones, so every unit's serial is known before its empty
files arrive whatever the folder order. Each file's modified time is stored
as its call-in time: copy with robocopy, not a Windows zip, whose dates read
an hour early from March to October.
Operational consequence: writes rows to mlg_files / mlg_records and copies each
original into //mlg/. The dry run writes nothing.
"""
from __future__ import annotations
import argparse
import datetime
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from minimateplus.mlg_file import MLG_PREFIX, MlgFormatError, parse_mlg
from sfm.database import SeismoDb
from sfm.mlg_ingest import ingest_mlg
from sfm.waveform_store import WaveformStore
log = logging.getLogger("import_mlg_dir")
_COUNTS = ("files", "ok", "duplicate", "error", "empty", "unresolved", "inserted", "skipped")
def _mlg_files(root: Path) -> list[Path]:
"""Files with records first, then empty ones; each group oldest first."""
found = [p for p in root.rglob("*") if p.is_file() and p.suffix.upper() == ".MLG"]
key = lambda p: (p.stat().st_size <= len(MLG_PREFIX), p.stat().st_mtime, p.name)
return sorted(found, key=key)
def import_dir(root: Path, db_path: str, store_root: str, *, dry_run: bool = False,
call_in: bool = True) -> dict:
counts = dict.fromkeys(_COUNTS, 0)
db = store = None
if not dry_run:
db, store = SeismoDb(db_path), WaveformStore(store_root)
for path in _mlg_files(root):
counts["files"] += 1
data = path.read_bytes()
if dry_run:
try:
mlg = parse_mlg(data)
except MlgFormatError as exc:
counts["error"] += 1
log.warning("%s: %s", path, exc)
continue
counts["error" if mlg.crc_failures else "ok"] += 1
counts["empty"] += mlg.empty
continue
mtime = datetime.datetime.fromtimestamp(path.stat().st_mtime, datetime.timezone.utc)
res = ingest_mlg(db, store, path.name, data, file_mtime=mtime, call_in=call_in)
counts[res["status"]] += 1
if res["status"] == "error":
log.warning("%s: %s", path, res["detail"])
continue
counts["empty"] += res["empty"]
counts["unresolved"] += res["serial_unresolved"]
counts["inserted"] += res["inserted"]
counts["skipped"] += res["skipped"]
return counts
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("dir")
ap.add_argument("--db-path", required=True)
ap.add_argument("--store-root", required=True)
ap.add_argument("--dry-run", action="store_true", help="parse and check only; write nothing")
ap.add_argument("--not-call-in", action="store_true",
help="these are cable / direct downloads, not call-ins")
a = ap.parse_args(argv)
logging.basicConfig(level=logging.WARNING)
counts = import_dir(Path(a.dir), a.db_path, a.store_root, dry_run=a.dry_run,
call_in=not a.not_call_in)
for key in _COUNTS:
print(f"{key} {counts[key]}")
return 0
if __name__ == "__main__":
raise SystemExit(main())