""" Download MIMIC-CXR images required by qa.json from PhysioNet. Prerequisites: 1. Create a PhysioNet account at https://physionet.org/ 2. Complete the required CITI training course 3. Sign the data use agreement for MIMIC-CXR-JPG v2.1.0 https://physionet.org/content/mimic-cxr-jpg/2.1.0/ Usage: python download_mimic.py --user --password """ import argparse import json import os import subprocess import sys BASE_URL = "https://physionet.org/files/mimic-cxr-jpg/2.1.0/files" def get_required_images(qa_path: str) -> list[str]: """Extract unique MIMIC image paths from qa.json.""" with open(qa_path) as f: data = json.load(f) images = set() for entry in data: for key in ("image_1", "image_2"): path = entry.get(key, "") if path.startswith("images/mimic/"): images.add(path) return sorted(images) def download_images(images: list[str], user: str, password: str, root_dir: str): """Download images from PhysioNet and place them at the expected paths.""" total = len(images) print(f"Found {total} MIMIC-CXR images to download.\n") skipped = 0 downloaded = 0 failed = 0 for i, image_path in enumerate(images, 1): dest = os.path.join(root_dir, image_path) if os.path.exists(dest): skipped += 1 continue # images/mimic/p15/p15592981/s55194630/xxx.jpg -> p15/p15592981/s55194630/xxx.jpg physionet_path = image_path.removeprefix("images/mimic/") url = f"{BASE_URL}/{physionet_path}" os.makedirs(os.path.dirname(dest), exist_ok=True) print(f"[{i}/{total}] Downloading {physionet_path} ...") result = subprocess.run( [ "wget", "-q", "-O", dest, "--user", user, "--password", password, url, ], capture_output=True, text=True, ) if result.returncode != 0: failed += 1 print(f" FAILED: {result.stderr.strip()}") # Remove empty file on failure if os.path.exists(dest) and os.path.getsize(dest) == 0: os.remove(dest) else: downloaded += 1 print(f"\nDone: {downloaded} downloaded, {skipped} skipped (already exist), {failed} failed.") if failed > 0: print("Re-run the script to retry failed downloads.") def main(): parser = argparse.ArgumentParser(description="Download MIMIC-CXR images for VLM-SubtleBench.") parser.add_argument("--user", required=True, help="PhysioNet username") parser.add_argument("--password", required=True, help="PhysioNet password") parser.add_argument("--qa-path", default=None, help="Path to qa.json (default: qa.json in the same directory as this script)") args = parser.parse_args() root_dir = os.path.dirname(os.path.abspath(__file__)) qa_path = args.qa_path or os.path.join(root_dir, "qa.json") if not os.path.exists(qa_path): print(f"Error: qa.json not found at {qa_path}", file=sys.stderr) sys.exit(1) images = get_required_images(qa_path) if not images: print("No MIMIC-CXR images found in qa.json.") sys.exit(0) download_images(images, args.user, args.password, root_dir) if __name__ == "__main__": main()