wait_for_fma_and_prepare.py 1.92 KB
#!/usr/bin/env python3
"""Wait for the FMA archive to finish, then run post-download readiness."""

from __future__ import annotations

import argparse
import json
import subprocess
import time

PYTHON = "/usr/local/miniconda3/bin/python"
INSPECT = [PYTHON, "scripts/prepare_fma_archive.py", "inspect"]
POST = [PYTHON, "scripts/fma_postdownload_ready.py"]


def inspect() -> dict:
    return json.loads(subprocess.check_output(INSPECT, text=True))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--interval", type=float, default=30.0)
    parser.add_argument(
        "--max-cycles",
        type=int,
        default=0,
        help="Number of polling cycles before exiting; 0 means wait indefinitely.",
    )
    args = parser.parse_args()

    snapshots = []
    cycle = 0
    while True:
        cycle += 1
        snap = inspect()
        snapshots.append(snap)
        print(
            json.dumps(
                {
                    "status": "polling",
                    "cycle": cycle,
                    "archive_size": snap.get("archive_size", 0),
                    "archive_bytes_expected": snap.get("archive_bytes_expected", 0),
                    "archive_progress_percent": snap.get("archive_progress_percent", 0.0),
                },
                ensure_ascii=False,
            ),
            flush=True,
        )
        if snap.get("archive_size", 0) >= snap.get("archive_bytes_expected", 0):
            result = json.loads(subprocess.check_output(POST, text=True))
            print(json.dumps({"status": "completed", "snapshots": snapshots, "postdownload": result}, indent=2, ensure_ascii=False), flush=True)
            return
        if args.max_cycles and cycle >= args.max_cycles:
            print(json.dumps({"status": "waiting", "snapshots": snapshots}, indent=2, ensure_ascii=False), flush=True)
            return
        time.sleep(args.interval)


if __name__ == "__main__":
    main()