File size: 6,203 Bytes
44a7ed3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#!/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()