#!/usr/bin/env python3 """ Download real images referenced in X-AIGD real-image metadata. Expected metadata columns: `uid`, `source_dataset`, `image_path`, `format`, `sha256`, and `caption`. What this script does: - saves each image as `.` for deterministic filenames - verifies every output file against the metadata `sha256` - writes logs plus a CSV download report - resumes safely by skipping files that already match the expected hash Supported source groups: 1) SA-1B - `image_path` looks like `sa_000010/sa_120927.jpg` - requires the official index file for download URLs and partitioning - downloads only the required tar parts and extracts only the required images 2) MSCOCO - `image_path` points to a file inside `val2014.zip` - images are re-saved as JPEG with `quality=75, subsampling=2` to match the X-AIGD real images exactly 3) Direct URLs - for sources such as LAION and CC3M Examples: Dry run (validation without downloading): python download_real_images.py --metadata /path/to/real_image_metadata.csv --sa1b-index-file /path/to/sa-1b.txt --output-dir ./real_images --dry-run Download everything: python download_real_images.py --metadata /path/to/real_image_metadata.csv --sa1b-index-file /path/to/sa-1b.txt --output-dir ./real_images Download only direct-URL rows: python download_real_images.py --metadata /path/to/real_image_metadata.csv --source direct --output-dir ./real_images Notes: - The SA-1B index file is not distributed in this repo. Retrieve it from: https://ai.meta.com/datasets/segment-anything-downloads/ - By default, downloaded SA-1B tar files are deleted after extraction to save disk space. Pass `--keep-sa1b-tars` only if you want to keep them. """ from __future__ import annotations import argparse import csv import hashlib import logging import os import re import sys import tarfile import threading import time import zipfile from contextlib import suppress from concurrent.futures import ThreadPoolExecutor, as_completed from dataclasses import dataclass from typing import Dict, Iterable, List, Optional, Tuple try: from PIL import Image # type: ignore[import] except Exception: # pragma: no cover Image = None try: import requests # type: ignore[import] except Exception as e: # pragma: no cover print("This script requires the 'requests' package.") print("Install it with: pip install requests") raise @dataclass class Row: uid: str source_dataset: str image_path: str image_format: str sha256: str @dataclass class Reporter: writer: Optional[csv.writer] lock: threading.Lock def write(self, uid: str, status: str, download_type: str, message: str) -> None: if self.writer is None: return with self.lock: self.writer.writerow((uid, status, download_type, message)) @dataclass(frozen=True) class DownloadConfig: output_dir: str cache_dir: str mscoco_zip: Optional[str] timeout: int retries: int workers_images: int workers_sa1b: int direct_delay: float delete_sa1b_tars: bool headers: Dict[str, str] HTTP_OK = {200, 206} SA1B_PART_RE = re.compile(r"(sa_\d{6})", re.IGNORECASE) URL_RE = re.compile(r"^https?://", re.IGNORECASE) MSCOCO_VAL2014_URL = "http://images.cocodataset.org/zips/val2014.zip" CONTENT_RANGE_RE = re.compile(r"bytes\s+(\d+)-(\d+)/(\d+|\*)", re.IGNORECASE) EXPECTED_METADATA_COLUMNS = [ "uid", "source_dataset", "image_path", "format", "sha256", "caption", ] DIRECT_SOURCE_DATASETS = {"Laion-2B-en-aesthetic", "CC3M"} SUPPORTED_IMAGE_FORMATS = {"jpg", "png"} DEFAULT_OUTPUT_DIR = "./real_images" DEFAULT_CACHE_DIR = "./cache" DEFAULT_TIMEOUT = 30 DEFAULT_RETRIES = 4 DEFAULT_DIRECT_DELAY = 2.0 DEFAULT_DIRECT_WORKERS = 4 DEFAULT_SA1B_WORKERS = 2 SA1B_ESTIMATED_PART_SIZE_GB = 10.9 DEFAULT_USER_AGENT = ( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36" ) def setup_logging(out_dir: str) -> str: log_dir = os.path.join(out_dir, "download_log") os.makedirs(log_dir, exist_ok=True) log_path = os.path.join(log_dir, "download.log") logger = logging.getLogger() logger.setLevel(logging.INFO) # Remove existing handlers if re-run in same process for h in list(logger.handlers): logger.removeHandler(h) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.INFO) ch.setFormatter(logging.Formatter("[%(levelname)s] %(message)s")) fh = logging.FileHandler(log_path, encoding="utf-8") fh.setLevel(logging.INFO) fh.setFormatter(logging.Formatter( fmt="%(asctime)s %(levelname)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S", )) logger.addHandler(ch) logger.addHandler(fh) return log_path def read_metadata(path: str) -> List[Row]: rows: List[Row] = [] with open(path, "r", encoding="utf-8") as f: r = csv.DictReader(f) if r.fieldnames is None: raise ValueError(f"Metadata file is empty: {path}") fieldnames = [name.strip() for name in r.fieldnames] if fieldnames != EXPECTED_METADATA_COLUMNS: raise ValueError( f"Metadata file {path} must have columns exactly " f"{EXPECTED_METADATA_COLUMNS}, got {fieldnames}" ) for row_number, line in enumerate(r, start=2): uid = (line.get("uid") or "").strip() src = (line.get("source_dataset") or "").strip() ipath = (line.get("image_path") or "").strip() image_format = (line.get("format") or "").strip().lower() sha256 = (line.get("sha256") or "").strip().lower() caption = (line.get("caption") or "").strip() if not uid or not src or not ipath or not image_format or not sha256 or not caption: raise ValueError( f"Metadata row {row_number} in {path} contains empty required fields" ) if image_format not in SUPPORTED_IMAGE_FORMATS: raise ValueError( f"Metadata row {row_number} in {path} has unsupported format: {image_format}" ) if not re.fullmatch(r"[0-9a-f]{64}", sha256): raise ValueError( f"Metadata row {row_number} in {path} has invalid sha256: {sha256}" ) rows.append( Row( uid=uid, source_dataset=src, image_path=ipath, image_format=image_format, sha256=sha256, ) ) return rows def parse_sa1b_index(path: str) -> Dict[str, Tuple[str, str]]: """Parse the official SA-1B index (tab-separated) and return mapping: part_id (e.g., 'sa_000020') -> (file_name, url). The index is expected to have headers: 'file_name' and 'cdn_link'. """ if not os.path.exists(path): raise FileNotFoundError(f"SA-1B index file not found: {path}") with open(path, "r", encoding="utf-8") as f: reader = csv.DictReader(f, delimiter="\t") if reader.fieldnames is None or {"file_name", "cdn_link"} - {h.strip() for h in reader.fieldnames}: raise ValueError("SA-1B index must contain 'file_name' and 'cdn_link' headers") mapping: Dict[str, Tuple[str, str]] = {} for line in reader: file_name = (line.get("file_name") or "").strip() url = (line.get("cdn_link") or "").strip() if not file_name or not url: continue part_id = os.path.splitext(file_name)[0].lower() mapping[part_id] = (file_name, url) return mapping def is_url(s: str) -> bool: return bool(URL_RE.match(s)) def ensure_dir(path: str) -> None: os.makedirs(path, exist_ok=True) def compute_sha256(path: str) -> str: digest = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def file_matches_sha256(path: str, expected_sha256: str) -> bool: if not os.path.exists(path): return False try: return compute_sha256(path) == expected_sha256 except OSError: return False def get_output_image_path(uid: str, image_format: str, out_dir: str) -> str: return os.path.join(out_dir, f"{uid}.{image_format}") def recompress_mscoco_image( zip_file: zipfile.ZipFile, info: zipfile.ZipInfo, out_path: str, ) -> None: if Image is None: raise RuntimeError( "MSCOCO extraction requires Pillow. Install it with: pip install pillow" ) tmp_path = f"{out_path}.tmp" with zip_file.open(info, "r") as src: image = Image.open(src) try: image.save(tmp_path, format="JPEG", quality=75, subsampling=2) finally: image.close() os.replace(tmp_path, out_path) def get_row_output_path(row: Row, out_dir: str) -> str: return get_output_image_path(row.uid, row.image_format, out_dir) def select_missing_rows(rows: Iterable[Row], out_dir: str) -> List[Row]: return [ row for row in rows if not file_matches_sha256(get_row_output_path(row, out_dir), row.sha256) ] def format_bytes(num: float) -> str: for unit in ("B", "KB", "MB", "GB", "TB"): if num < 1024 or unit == "TB": if unit == "B": return f"{int(num)} {unit}" return f"{num:.1f} {unit}" num /= 1024 return f"{num:.1f} TB" def safe_wait_futures(futures: List) -> None: """Cancel all pending futures (used on interrupt).""" for fut in futures: try: fut.cancel() except Exception: pass def partition_rows(rows: Iterable[Row]) -> Tuple[List[Row], List[Row], List[Row]]: sa1b_rows: List[Row] = [] mscoco_rows: List[Row] = [] direct_rows: List[Row] = [] for row in rows: if row.source_dataset == "SA-1B": if is_url(row.image_path) or not SA1B_PART_RE.match(row.image_path): raise ValueError( f"Invalid SA-1B image_path for uid {row.uid}: {row.image_path}" ) sa1b_rows.append(row) continue if row.source_dataset == "MSCOCO": if is_url(row.image_path): raise ValueError( f"Invalid MSCOCO image_path for uid {row.uid}: {row.image_path}" ) mscoco_rows.append(row) continue if row.source_dataset in DIRECT_SOURCE_DATASETS: if not is_url(row.image_path): raise ValueError( f"Invalid direct-download URL for uid {row.uid}: {row.image_path}" ) direct_rows.append(row) continue raise ValueError(f"Unsupported source_dataset for uid {row.uid}: {row.source_dataset}") return sa1b_rows, mscoco_rows, direct_rows def apply_source_filter( source: str, sa1b_rows: List[Row], mscoco_rows: List[Row], direct_rows: List[Row], ) -> Tuple[List[Row], List[Row], List[Row]]: if source == "all": return sa1b_rows, mscoco_rows, direct_rows if source == "sa1b": return sa1b_rows, [], [] if source == "mscoco": return [], mscoco_rows, [] if source == "direct": return [], [], direct_rows raise ValueError(f"Unsupported source filter: {source}") class RateLimiter: def __init__(self, delay: float) -> None: self.delay = max(0.0, delay) self._lock = threading.Lock() self._next_time = time.monotonic() def wait(self) -> None: if self.delay <= 0: return while True: with self._lock: now = time.monotonic() wait_for = self._next_time - now if wait_for <= 0: self._next_time = now + self.delay return time.sleep(min(wait_for, self.delay)) def http_download( url: str, dst_path: str, timeout: int, retries: int, backoff: float = 1.5, progress_label: Optional[str] = None, headers: Optional[Dict[str, str]] = None, ) -> bool: """Resumable download to dst_path using Range. Returns True on success.""" tmp_path = dst_path + ".part" attempt = 0 while attempt <= retries: try: resume_pos = 0 if os.path.exists(tmp_path): try: resume_pos = os.path.getsize(tmp_path) except OSError: resume_pos = 0 req_headers: Dict[str, str] = {} if headers: req_headers.update(headers) if resume_pos > 0: req_headers["Range"] = f"bytes={resume_pos}-" with requests.get(url, stream=True, timeout=timeout, headers=req_headers) as r: restart_download = False if resume_pos > 0 and r.status_code == 416: if progress_label: logging.info("%s: received 416 for resume; restarting download", progress_label) with suppress(FileNotFoundError): os.remove(tmp_path) resume_pos = 0 restart_download = True elif r.status_code not in HTTP_OK: raise IOError(f"HTTP status {r.status_code}") content_length = int(r.headers.get("Content-Length") or 0) content_range_hdr = r.headers.get("Content-Range") range_start: Optional[int] = None range_end: Optional[int] = None total_size = 0 if content_range_hdr: match = CONTENT_RANGE_RE.match(content_range_hdr) if match: range_start = int(match.group(1)) range_end = int(match.group(2)) total_str = match.group(3) if total_str != "*": total_size = int(total_str) else: content_range_hdr = None if resume_pos > 0: if r.status_code == 200: if progress_label: logging.info("%s: server ignored Range request; restarting download", progress_label) with suppress(FileNotFoundError): os.remove(tmp_path) resume_pos = 0 restart_download = True elif content_range_hdr is None: if progress_label: logging.info("%s: missing Content-Range header when resuming; restarting download", progress_label) with suppress(FileNotFoundError): os.remove(tmp_path) resume_pos = 0 restart_download = True elif range_start is not None: if range_start > resume_pos: if progress_label: logging.info( "%s: local partial missing %s; restarting download", progress_label, format_bytes(range_start - resume_pos), ) with suppress(FileNotFoundError): os.remove(tmp_path) resume_pos = 0 restart_download = True elif range_start < resume_pos: if progress_label: logging.info( "%s: truncating local partial from %s to %s before resuming", progress_label, format_bytes(resume_pos), format_bytes(range_start), ) with open(tmp_path, "r+b") as adjust: adjust.truncate(range_start) resume_pos = range_start if total_size == 0: if content_length: if r.status_code == 206 and resume_pos > 0: total_size = resume_pos + content_length else: total_size = content_length elif range_end is not None: total_size = range_end + 1 else: if content_length and r.status_code == 206: total_size = max(total_size, resume_pos + content_length) total_size = max(total_size, resume_pos) if total_size and resume_pos > total_size: if progress_label: logging.info( "%s: local partial (%s) exceeds reported size (%s); restarting download", progress_label, format_bytes(resume_pos), format_bytes(total_size), ) with suppress(FileNotFoundError): os.remove(tmp_path) resume_pos = 0 restart_download = True if restart_download: continue mode = "ab" if resume_pos > 0 else "wb" if os.path.exists(tmp_path): try: resume_pos = os.path.getsize(tmp_path) except OSError: resume_pos = 0 mode = "wb" downloaded = resume_pos last_log_time = time.monotonic() last_percent = (downloaded / total_size * 100.0) if total_size else 0.0 last_bytes_logged = downloaded size_mismatch_logged = False if progress_label: if resume_pos and total_size: logging.info( "%s: resuming download at %s of %s", progress_label, format_bytes(downloaded), format_bytes(total_size), ) elif resume_pos: logging.info( "%s: resuming download at %s (total size unknown)", progress_label, format_bytes(downloaded), ) elif total_size: logging.info( "%s: starting download (%s)", progress_label, format_bytes(total_size), ) else: logging.info("%s: starting download (size unknown)", progress_label) with open(tmp_path, mode) as f: for chunk in r.iter_content(chunk_size=1024 * 512): if not chunk: continue f.write(chunk) downloaded += len(chunk) if total_size and downloaded > total_size: if progress_label and not size_mismatch_logged: logging.info( "%s: received more data than expected (%s > %s); treating size as unknown", progress_label, format_bytes(downloaded), format_bytes(total_size), ) total_size = 0 size_mismatch_logged = True last_percent = 0.0 last_bytes_logged = downloaded if progress_label: now = time.monotonic() should_log = False if total_size: percent = min(100.0, 100.0 * downloaded / total_size) if percent - last_percent >= 5.0 or (now - last_log_time) >= 10.0: should_log = True else: if (downloaded - last_bytes_logged) >= 25 * 1024 * 1024 or (now - last_log_time) >= 10.0: should_log = True if should_log: if total_size: logging.info( "%s: %.1f%% (%s / %s)", progress_label, percent, format_bytes(downloaded), format_bytes(total_size), ) last_percent = percent else: logging.info( "%s: %s downloaded", progress_label, format_bytes(downloaded), ) last_bytes_logged = downloaded last_log_time = now os.replace(tmp_path, dst_path) if progress_label: if total_size: logging.info( "%s: download complete (%s)", progress_label, format_bytes(max(downloaded, total_size)), ) else: logging.info( "%s: download complete (%s received)", progress_label, format_bytes(downloaded), ) return True except Exception as e: attempt += 1 if attempt > retries: logging.warning("Download failed for %s: %s", url, e) return False sleep_s = backoff ** attempt + (0.01 * attempt) logging.info("Retrying %s in %.1fs (attempt %d/%d)", url, sleep_s, attempt, retries) time.sleep(sleep_s) return False def download_direct_image( row: Row, out_dir: str, timeout: int, retries: int, rate_limiter: Optional[RateLimiter] = None, headers: Optional[Dict[str, str]] = None, ) -> Tuple[str, bool, str]: out_path = get_row_output_path(row, out_dir) if file_matches_sha256(out_path, row.sha256): return (row.uid, True, "already exists") if rate_limiter is not None: rate_limiter.wait() ok = http_download(row.image_path, out_path, timeout=timeout, retries=retries, headers=headers) if not ok: if os.path.exists(out_path): try: os.remove(out_path) except Exception: pass return (row.uid, False, "download failed") if file_matches_sha256(out_path, row.sha256): return (row.uid, True, "downloaded") else: return (row.uid, False, "sha256 mismatch (file kept)") def build_sa1b_requirements(rows: Iterable[Row]) -> Dict[str, List[Row]]: """Return mapping part_id -> rows required from that SA-1B archive.""" needed: Dict[str, List[Row]] = {} for r in rows: m = SA1B_PART_RE.match(r.image_path) if not m: raise ValueError(f"Invalid SA-1B image_path for uid {r.uid}: {r.image_path}") part_id = m.group(1).lower() needed.setdefault(part_id, []).append(r) return needed def build_sa1b_part_plan( sa1b_needed: Dict[str, List[Row]], part_index: Dict[str, Tuple[str, str]], ) -> List[Tuple[str, str, str]]: missing_parts = [part_id for part_id in sa1b_needed if part_id not in part_index] if missing_parts: raise ValueError( "SA-1B index is missing required parts: " + ", ".join(sorted(missing_parts)[:10]) + (" ..." if len(missing_parts) > 10 else "") ) return [ (part_id, part_index[part_id][0], part_index[part_id][1]) for part_id in sa1b_needed ] def count_missing_sa1b_images( sa1b_needed: Dict[str, List[Row]], out_dir: str, ) -> Tuple[int, int]: missing = 0 existing = 0 for entries in sa1b_needed.values(): for row in entries: out_path = get_row_output_path(row, out_dir) if file_matches_sha256(out_path, row.sha256): existing += 1 else: missing += 1 return missing, existing def select_pending_sa1b_rows( sa1b_needed: Dict[str, List[Row]], out_dir: str, ) -> Dict[str, List[Row]]: pending_parts: Dict[str, List[Row]] = {} for part_id, rows in sa1b_needed.items(): pending_rows = [ row for row in rows if not file_matches_sha256(get_row_output_path(row, out_dir), row.sha256) ] if pending_rows: pending_parts[part_id] = pending_rows return pending_parts def get_cached_sa1b_parts( needed_parts: List[Tuple[str, str, str]], cache_dir: str, ) -> Tuple[Dict[str, str], List[Tuple[str, str, str]]]: cached: Dict[str, str] = {} to_download: List[Tuple[str, str, str]] = [] for part_id, file_name, url in needed_parts: tar_path = os.path.join(cache_dir, file_name) if os.path.exists(tar_path) and os.path.getsize(tar_path) > 0: cached[part_id] = tar_path else: to_download.append((part_id, file_name, url)) return cached, to_download def sa1b_download_part_tar(part_id: str, file_name: str, url: str, cache_dir: str, timeout: int, retries: int, headers: Optional[Dict[str, str]] = None) -> Optional[str]: ensure_dir(cache_dir) tar_path = os.path.join(cache_dir, file_name) if os.path.exists(tar_path) and os.path.getsize(tar_path) > 0: return tar_path logging.info("Downloading SA-1B part %s from %s", part_id, url) ok = http_download( url, tar_path, timeout=timeout, retries=retries, progress_label=f"SA-1B part {part_id}", headers=headers, ) if ok: return tar_path return None def sa1b_extract_required_images( tar_path: str, part_id: str, required: List[Row], out_dir: str, ) -> Tuple[int, int]: """Extract only required images from tar. Returns (num_success, num_skipped) where skipped are already-present valid files. """ success, skipped = 0, 0 pending: Dict[str, Row] = {} for row in required: file_name = os.path.basename(row.image_path) out_path = get_row_output_path(row, out_dir) if file_matches_sha256(out_path, row.sha256): skipped += 1 continue pending[file_name] = row if not pending: return success, skipped total_to_extract = len(pending) if total_to_extract == 0: return success, skipped logging.info("SA-1B part %s: extracting %d file(s)", part_id, total_to_extract) try: with tarfile.open(tar_path, "r:*") as tf: remaining = dict(pending) scanned_members = 0 last_log = time.monotonic() log_interval = 10.0 for member in tf: if not remaining: break if not member.isfile(): continue scanned_members += 1 if log_interval and (time.monotonic() - last_log) >= log_interval: logging.info( "SA-1B part %s: scanned %d entries (%d/%d found)", part_id, scanned_members, total_to_extract - len(remaining), total_to_extract, ) last_log = time.monotonic() file_name = os.path.basename(member.name) row = remaining.get(file_name) if row is None: continue out_path = get_row_output_path(row, out_dir) try: extracted = tf.extractfile(member) if extracted is None: logging.warning("%s: failed to open %s from tar", part_id, file_name) continue with extracted, open(out_path, "wb") as f: while True: chunk = extracted.read(1024 * 512) if not chunk: break f.write(chunk) except Exception as e: logging.warning("%s: extraction failed for %s: %s", part_id, file_name, e) if os.path.exists(out_path): try: os.remove(out_path) except Exception: pass remaining.pop(file_name, None) continue if file_matches_sha256(out_path, row.sha256): success += 1 else: logging.warning("%s: extracted file sha256 mismatch %s", part_id, out_path) remaining.pop(file_name, None) for file_name in remaining: logging.warning("%s: %s not found in %s", part_id, file_name, tar_path) if remaining: logging.info( "SA-1B part %s: finished scan (%d/%d found)", part_id, total_to_extract - len(remaining), total_to_extract, ) else: logging.info( "SA-1B part %s: extraction complete (%d/%d)", part_id, success, total_to_extract, ) except tarfile.ReadError as e: logging.error("Failed to open tar %s: %s", tar_path, e) return success, skipped def ensure_mscoco_zip( zip_path: Optional[str], cache_dir: str, timeout: int, retries: int, headers: Optional[Dict[str, str]] = None, ) -> Optional[str]: """Return path to MSCOCO zip, downloading to cache_dir if needed.""" if zip_path: return zip_path ensure_dir(cache_dir) target_path = os.path.join(cache_dir, "val2014.zip") if os.path.exists(target_path) and os.path.getsize(target_path) > 0: return target_path logging.info("Downloading MSCOCO archive to %s", target_path) ok = http_download( MSCOCO_VAL2014_URL, target_path, timeout=timeout, retries=retries, progress_label="MSCOCO archive", headers=headers, ) if ok: return target_path logging.warning("Failed to download MSCOCO archive from %s", MSCOCO_VAL2014_URL) return None def mscoco_extract_images( rows: Iterable[Row], zip_path: Optional[str], out_dir: str, ) -> Dict[str, Tuple[bool, str]]: """Extract MSCOCO images from a local zip archive. Returns mapping uid -> (success, message). """ results: Dict[str, Tuple[bool, str]] = {} rows = list(rows) if not rows: return results if not zip_path or not os.path.exists(zip_path): msg = "mscoco zip not found" for r in rows: results[r.uid] = (False, msg) logging.warning("%s; expected at %s", msg, zip_path or "") return results try: with zipfile.ZipFile(zip_path, "r") as zf: members = { os.path.basename(info.filename): info for info in zf.infolist() if not info.is_dir() } for r in rows: file_name = os.path.basename(r.image_path) info = members.get(file_name) if not info: msg = "file not found in zip" results[r.uid] = (False, msg) logging.warning("MSCOCO: %s missing from %s", file_name, zip_path) continue out_path = get_row_output_path(r, out_dir) if file_matches_sha256(out_path, r.sha256): results[r.uid] = (True, "already exists") continue try: recompress_mscoco_image(zf, info, out_path) except Exception as e: results[r.uid] = (False, f"extraction failed: {e}") if os.path.exists(out_path): try: os.remove(out_path) except Exception: pass tmp_path = f"{out_path}.tmp" if os.path.exists(tmp_path): try: os.remove(tmp_path) except Exception: pass logging.warning("MSCOCO: extraction failed for %s: %s", file_name, e) continue if file_matches_sha256(out_path, r.sha256): results[r.uid] = (True, "extracted") else: results[r.uid] = (False, "sha256 mismatch (file kept)") logging.warning("MSCOCO: extracted file sha256 mismatch %s", out_path) except zipfile.BadZipFile as e: logging.error("Failed to open MSCOCO zip %s: %s", zip_path, e) for r in rows: results[r.uid] = (False, "mscoco zip unreadable") return results def load_sa1b_index( sa1b_rows: List[Row], sa1b_index_file: Optional[str], dry_run: bool, ) -> Dict[str, Tuple[str, str]]: if not sa1b_rows: return {} if sa1b_index_file: return parse_sa1b_index(sa1b_index_file) if dry_run: return {} raise ValueError( "--sa1b-index-file is required for this metadata because it contains SA-1B images" ) def log_loaded_rows( total_rows: int, sa1b_rows: List[Row], mscoco_rows: List[Row], direct_rows: List[Row], dry_run: bool, log_path: str, report_path: Optional[str], ) -> None: logging.info( "Loaded %d rows (%d SA-1B, %d MSCOCO, %d direct)", total_rows, len(sa1b_rows), len(mscoco_rows), len(direct_rows), ) if not dry_run and report_path is not None: logging.info("Logs: %s | Report: %s", log_path, report_path) def warn_if_keeping_sa1b_tars( sa1b_needed: Dict[str, List[Row]], cache_dir: str, keep_sa1b_tars: bool, ) -> None: if not keep_sa1b_tars or not sa1b_needed: return part_count = len(sa1b_needed) estimated_gb = part_count * SA1B_ESTIMATED_PART_SIZE_GB logging.warning( "Keeping SA-1B tar files may require about %.1f GB (%.2f TB) in %s for %d parts. " "Omit --keep-sa1b-tars to delete each tar after extraction.", estimated_gb, estimated_gb / 1024, cache_dir, part_count, ) def run_dry_run( direct_rows: List[Row], mscoco_rows: List[Row], sa1b_needed: Dict[str, List[Row]], part_index: Dict[str, Tuple[str, str]], config: DownloadConfig, ) -> int: logging.info("Dry run summary:") direct_needed_rows = select_missing_rows(direct_rows, config.output_dir) logging.info( " Direct images needing download: %d (of %d)", len(direct_needed_rows), len(direct_rows), ) mscoco_needed_rows = select_missing_rows(mscoco_rows, config.output_dir) logging.info( " MSCOCO images needing extraction: %d (of %d)", len(mscoco_needed_rows), len(mscoco_rows), ) if mscoco_needed_rows: target_zip = config.mscoco_zip or os.path.join(config.cache_dir, "val2014.zip") if config.mscoco_zip: logging.info(" Using provided MSCOCO archive: %s", config.mscoco_zip) elif os.path.exists(target_zip): logging.info(" MSCOCO archive already cached: %s", target_zip) else: logging.info(" MSCOCO archive will be downloaded to %s", target_zip) parts_to_fetch: Dict[str, List[str]] = {} missing_sa1b_total = 0 for part_id, entries in sa1b_needed.items(): needed_uids: List[str] = [] for row in entries: out_path = get_row_output_path(row, config.output_dir) if not file_matches_sha256(out_path, row.sha256): needed_uids.append(row.uid) if needed_uids: parts_to_fetch[part_id] = needed_uids missing_sa1b_total += len(needed_uids) logging.info( " SA-1B images needing extraction: %d (across %d parts)", missing_sa1b_total, len(parts_to_fetch), ) if parts_to_fetch: missing_index_parts = [part_id for part_id in parts_to_fetch if part_id not in part_index] for part_id, uids in list(parts_to_fetch.items())[:5]: file_name = part_index.get(part_id, (None, None))[0] tar_path = os.path.join(config.cache_dir, file_name) if file_name else None cached = bool(tar_path and os.path.exists(tar_path)) extra = "" if file_name else " (missing index entry)" logging.info( " Part %s: %d image(s) (%s)%s", part_id, len(uids), "cached" if cached else "not cached", extra, ) remaining_parts = len(parts_to_fetch) - min(len(parts_to_fetch), 5) if remaining_parts > 0: logging.info(" ... (%d more parts)", remaining_parts) tar_need_download = [ part_id for part_id in parts_to_fetch if part_id in part_index and not os.path.exists(os.path.join(config.cache_dir, part_index[part_id][0])) ] logging.info( " SA-1B tar files needing download: %d (of %d required parts)", len(tar_need_download), len(parts_to_fetch), ) if missing_index_parts: preview = ", ".join(sorted(missing_index_parts)[:5]) suffix = " ..." if len(missing_index_parts) > 5 else "" logging.info( " WARNING: %d part(s) missing from index: %s%s", len(missing_index_parts), preview, suffix, ) logging.info("Dry run complete. No downloads were performed.") return 0 def process_direct_rows(rows: List[Row], config: DownloadConfig, reporter: Reporter) -> None: needed_rows = select_missing_rows(rows, config.output_dir) if not needed_rows: return rate_limiter = RateLimiter(config.direct_delay) if config.direct_delay > 0 else None if rate_limiter is not None: logging.info("Applying %.2fs delay between direct URL downloads", config.direct_delay) logging.info( "Downloading %d direct images (of %d total) with %d workers", len(needed_rows), len(rows), config.workers_images, ) completed = 0 with ThreadPoolExecutor(max_workers=config.workers_images) as ex: futs = [ ex.submit( download_direct_image, row, config.output_dir, config.timeout, config.retries, rate_limiter, config.headers, ) for row in needed_rows ] try: for fut in as_completed(futs): uid, ok, msg = fut.result() reporter.write(uid, "success" if ok else "failure", "direct", msg) completed += 1 if completed % 25 == 0 or completed == len(needed_rows): logging.info("Direct: %d/%d done", completed, len(needed_rows)) except KeyboardInterrupt: safe_wait_futures(futs) raise def process_mscoco_rows(rows: List[Row], config: DownloadConfig, reporter: Reporter) -> None: if not rows: return needed_rows = select_missing_rows(rows, config.output_dir) if needed_rows: zip_path = ensure_mscoco_zip( config.mscoco_zip, config.cache_dir, config.timeout, config.retries, headers=config.headers, ) logging.info( "Extracting %d MSCOCO images (of %d total) from %s", len(needed_rows), len(rows), zip_path or "", ) results = mscoco_extract_images(needed_rows, zip_path, config.output_dir) else: logging.info("All %d MSCOCO images already present; skipping extraction", len(rows)) results = {} for row in rows: ok, msg = results.get(row.uid, (True, "already exists")) reporter.write(row.uid, "success" if ok else "failure", "mscoco", msg) def process_sa1b_part( part_id: str, rows: List[Row], tar_path: Optional[str], config: DownloadConfig, reporter: Reporter, ) -> Tuple[int, int, Optional[str]]: if not tar_path or not os.path.exists(tar_path): for row in rows: reporter.write(row.uid, "failure", "sa1b", "tar not downloaded") return 0, 0, None ok_count, skipped_count = sa1b_extract_required_images( tar_path, part_id, rows, config.output_dir, ) for row in rows: out_path = get_row_output_path(row, config.output_dir) if file_matches_sha256(out_path, row.sha256): reporter.write(row.uid, "success", "sa1b", "extracted") else: reporter.write(row.uid, "failure", "sa1b", "sha256 mismatch (file kept)") return ok_count, skipped_count, tar_path def process_sa1b_rows( sa1b_needed: Dict[str, List[Row]], part_index: Dict[str, Tuple[str, str]], config: DownloadConfig, reporter: Reporter, ) -> None: pending_sa1b_needed = select_pending_sa1b_rows(sa1b_needed, config.output_dir) missing_images, existing_images = count_missing_sa1b_images(sa1b_needed, config.output_dir) if missing_images > 0: logging.info( "Need to extract %d SA-1B images (of %d total; %d already present) from %d parts", missing_images, missing_images + existing_images, existing_images, len(pending_sa1b_needed), ) elif existing_images > 0: logging.info("All %d SA-1B images already present; skipping extraction", existing_images) return else: logging.info("No SA-1B images to process") return needed_parts = build_sa1b_part_plan(pending_sa1b_needed, part_index) cached_parts, parts_to_download = get_cached_sa1b_parts(needed_parts, config.cache_dir) if parts_to_download: logging.info( "Downloading %d SA-1B tar files (of %d total; %d cached) with %d workers", len(parts_to_download), len(needed_parts), len(cached_parts), config.workers_sa1b, ) elif needed_parts: logging.info("All %d SA-1B tar files already cached", len(needed_parts)) total_rows = sum(len(entries) for entries in pending_sa1b_needed.values()) processed_rows = 0 for part_id, _, _ in needed_parts: if part_id not in cached_parts: continue rows = pending_sa1b_needed[part_id] ok_count, skipped_count, tar_path = process_sa1b_part( part_id, rows, cached_parts[part_id], config, reporter, ) processed_rows += len(rows) logging.info( "SA-1B: %d/%d processed (ok=%d, skipped=%d) for part %s", processed_rows, total_rows, ok_count, skipped_count, part_id, ) if config.delete_sa1b_tars and tar_path: try: os.remove(tar_path) logging.info("SA-1B part %s: deleted tar %s", part_id, tar_path) except OSError as e: logging.warning("SA-1B part %s: failed to delete tar %s: %s", part_id, tar_path, e) if not parts_to_download: return with ThreadPoolExecutor(max_workers=config.workers_sa1b) as ex: futs = [ ex.submit( sa1b_download_part_tar, part_id, file_name, url, config.cache_dir, config.timeout, config.retries, config.headers, ) for part_id, file_name, url in parts_to_download ] future_to_part = { fut: part_id for fut, (part_id, _, _) in zip(futs, parts_to_download) } try: for fut in as_completed(futs): part_id = future_to_part[fut] tar_path = fut.result() rows = pending_sa1b_needed[part_id] ok_count, skipped_count, processed_tar_path = process_sa1b_part( part_id, rows, tar_path, config, reporter, ) processed_rows += len(rows) logging.info( "SA-1B: %d/%d processed (ok=%d, skipped=%d) for part %s", processed_rows, total_rows, ok_count, skipped_count, part_id, ) if config.delete_sa1b_tars and processed_tar_path: try: os.remove(processed_tar_path) logging.info("SA-1B part %s: deleted tar %s", part_id, processed_tar_path) except OSError as e: logging.warning( "SA-1B part %s: failed to delete tar %s: %s", part_id, processed_tar_path, e, ) except KeyboardInterrupt: safe_wait_futures(futs) raise def main(argv: Optional[List[str]] = None) -> int: p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument( "--metadata", type=str, required=True, help="Path to the X-AIGD real-image metadata CSV", ) p.add_argument( "--output-dir", type=str, default=DEFAULT_OUTPUT_DIR, help=f"Directory to save images (default: {DEFAULT_OUTPUT_DIR})", ) p.add_argument("--sa1b-index-file", type=str, default=None, help="Path to sa-1b.txt (download list with URLs)") p.add_argument( "--cache-dir", type=str, default=DEFAULT_CACHE_DIR, help=f"Directory to cache downloaded archives (default: {DEFAULT_CACHE_DIR})", ) p.add_argument( "--source", choices=("all", "direct", "mscoco", "sa1b"), default="all", help="Restrict downloading to one source group (default: all)", ) p.add_argument("--dry-run", action="store_true", help="Print a summary of required downloads without performing them") p.add_argument( "--keep-sa1b-tars", action="store_true", help="Keep downloaded SA-1B tar files in --cache-dir after extraction (default: delete them)", ) args = p.parse_args(argv) report_lock = threading.Lock() report_writer: Optional[csv.writer] report_f: Optional[object] report_path: Optional[str] req_headers: Dict[str, str] = {"User-Agent": DEFAULT_USER_AGENT} if args.dry_run: logging.basicConfig(level=logging.INFO, format="[%(levelname)s] %(message)s") log_path = "" report_path = None report_writer = None report_f = None else: ensure_dir(args.output_dir) log_path = setup_logging(args.output_dir) report_path = os.path.join(args.output_dir, "download_log", "download_report.csv") ensure_dir(os.path.dirname(report_path)) # Append mode: don't overwrite existing report; add header only if file is new report_is_new = not os.path.exists(report_path) report_f = open(report_path, "a", encoding="utf-8", newline="") report_writer = csv.writer(report_f) if report_is_new: report_writer.writerow(["uid", "status", "type", "message"]) # type = sa1b|direct|skip reporter = Reporter(report_writer, report_lock) config = DownloadConfig( output_dir=args.output_dir, cache_dir=args.cache_dir, mscoco_zip=None, timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES, workers_images=DEFAULT_DIRECT_WORKERS, workers_sa1b=DEFAULT_SA1B_WORKERS, direct_delay=DEFAULT_DIRECT_DELAY, delete_sa1b_tars=not args.keep_sa1b_tars, headers=req_headers, ) rows = read_metadata(args.metadata) sa1b_rows, mscoco_rows, direct_rows = partition_rows(rows) sa1b_rows, mscoco_rows, direct_rows = apply_source_filter( args.source, sa1b_rows, mscoco_rows, direct_rows, ) sa1b_needed = build_sa1b_requirements(sa1b_rows) pending_sa1b_needed = select_pending_sa1b_rows(sa1b_needed, args.output_dir) warn_if_keeping_sa1b_tars(pending_sa1b_needed, args.cache_dir, args.keep_sa1b_tars) part_index = load_sa1b_index(sa1b_rows, args.sa1b_index_file, args.dry_run) log_loaded_rows( len(rows), sa1b_rows, mscoco_rows, direct_rows, args.dry_run, log_path, report_path, ) if args.dry_run: return run_dry_run(direct_rows, mscoco_rows, sa1b_needed, part_index, config) ensure_dir(config.cache_dir) try: process_direct_rows(direct_rows, config, reporter) process_mscoco_rows(mscoco_rows, config, reporter) process_sa1b_rows(sa1b_needed, part_index, config, reporter) except KeyboardInterrupt: logging.warning("Interrupted by user (Ctrl+C). Shutting down gracefully...") if report_f: try: report_f.close() except Exception: pass if report_path: logging.info("Partial report saved to %s", report_path) return 1 if report_f: report_f.close() if report_path: logging.info("Done. Report saved to %s", report_path) return 0 if __name__ == "__main__": raise SystemExit(main())