#!/usr/bin/env python3 """Download Product1M test/gallery images from official URL metadata.""" from __future__ import annotations import argparse import json import random import sys import time from pathlib import Path try: import requests except ImportError as exc: raise SystemExit("Missing python package: requests (pip install requests)") from exc MAX_RETRIES = 5 MIN_BYTES = 1000 HEADERS = { "User-Agent": ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/119.0.0.0 Safari/537.36" ), "Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", "Referer": "https://www.taobao.com/", } TXT_FILES = { "test": "product1m_test_ossurl_v2.txt", "gallery": "product1m_gallery_ossurl_v2.txt", } def find_txt_dir(root: Path) -> Path: for name in ("Poudct1M", "Product1M"): candidate = root / name if candidate.is_dir(): return candidate raise FileNotFoundError(f"Cannot find Poudct1M/ or Product1M/ under {root}") def load_split(path: Path) -> dict: with open(path, encoding="utf-8") as f: data = json.load(f) for key in ("test", "gallery"): if key not in data: raise KeyError(f"Missing key '{key}' in {path}") return data def read_lines_at(txt_path: Path, line_numbers: list[int]) -> dict[int, str]: wanted = set(line_numbers) max_line = max(line_numbers) found: dict[int, str] = {} with open(txt_path, encoding="utf-8") as f: for lineno, line in enumerate(f, 1): if lineno in wanted: found[lineno] = line.strip() if lineno >= max_line and len(found) == len(wanted): break missing = sorted(wanted - found.keys()) if missing: raise ValueError(f"Missing lines in {txt_path}: {missing[:10]}") return found def parse_record(line: str) -> tuple[str, list[str]]: parts = line.split("#####") if len(parts) < 4: raise ValueError(f"Invalid line with <4 fields: {line[:120]}") image_id = parts[0] urls = [parts[2], parts[3]] return image_id, urls def download_image(session: requests.Session, urls: list[str], out_path: Path) -> str | None: for url in urls: last_error = None for attempt in range(MAX_RETRIES): try: if attempt > 0: time.sleep(random.uniform(1.0, 3.0)) response = session.get(url, timeout=15, allow_redirects=True) if response.status_code == 200 and len(response.content) > MIN_BYTES: out_path.parent.mkdir(parents=True, exist_ok=True) out_path.write_bytes(response.content) return url last_error = f"HTTP {response.status_code}, bytes={len(response.content)}" if response.status_code == 420: time.sleep(random.uniform(2.0, 6.0)) except requests.RequestException as exc: last_error = str(exc) time.sleep(random.uniform(1.0, 2.0)) if last_error: continue return None def download_images( split_json: Path, repo_dir: Path, source_dir: Path, log_file: Path, ) -> None: split = load_split(split_json) txt_dir = find_txt_dir(repo_dir) log_file.parent.mkdir(parents=True, exist_ok=True) session = requests.Session() session.headers.update(HEADERS) total_ok = 0 total_skip = 0 total_fail = 0 with open(log_file, "a", encoding="utf-8") as log_f: for split_name in ("test", "gallery"): entries = split[split_name] line_numbers = [item["line_number"] for item in entries] id_by_line = {item["line_number"]: item["id"] for item in entries} txt_path = txt_dir / TXT_FILES[split_name] lines = read_lines_at(txt_path, line_numbers) out_dir = source_dir / split_name print(f"==> [{split_name}] {len(entries)} images -> {out_dir}") for lineno in sorted(line_numbers): image_id = id_by_line[lineno] out_path = out_dir / f"{image_id}.jpg" if out_path.is_file() and out_path.stat().st_size > MIN_BYTES: total_skip += 1 continue record_id, urls = parse_record(lines[lineno]) if record_id != image_id: raise ValueError( f"ID mismatch at line {lineno}: split={image_id}, txt={record_id}" ) used_url = download_image(session, urls, out_path) if used_url: total_ok += 1 print(f" ok {split_name}/{image_id}.jpg") else: total_fail += 1 msg = ( f"{split_name}; {image_id}; line={lineno}; " f"failed; urls={urls}; retries={MAX_RETRIES}\n" ) log_f.write(msg) print(f" fail {split_name}/{image_id}.jpg (see {log_file})") time.sleep(random.uniform(0.1, 0.5)) print("==> Download summary") print(f" downloaded: {total_ok}") print(f" skipped: {total_skip}") print(f" failed: {total_fail}") print(f" log: {log_file}") if total_fail > 0: raise SystemExit(1) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--split-json", type=Path, required=True) parser.add_argument("--repo-dir", type=Path, required=True) parser.add_argument("--source-dir", type=Path, required=True) parser.add_argument("--log-file", type=Path, required=True) return parser.parse_args() def main() -> None: args = parse_args() download_images( split_json=args.split_json, repo_dir=args.repo_dir, source_dir=args.source_dir, log_file=args.log_file, ) if __name__ == "__main__": main()