File size: 12,607 Bytes
5f5554c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#!/usr/bin/env python3
"""Pack GLAMI product images into Hub-ready Parquet shards.

Reads images straight out of glami_images.tar.gz in a single streaming pass --
the 1.3M files are never unpacked onto disk -- and writes

    images/shard-00000.parquet, images/shard-00001.parquet, ...

with the `datasets` Image() feature, so the Hub's Dataset Viewer renders them
and `load_dataset(..., streaming=True)` works without a loading script.

Images are keyed by itemId only. They are deliberately NOT split into
train/test: the splits live in items_train.csv / items_test.csv / *_split.csv,
which reference itemId, so a single image table stays joinable by all of them
and never stores the same picture twice.

Usage:
    python scripts/build_image_shards.py --inspect         # peek inside the tarball first
    python scripts/build_image_shards.py --limit 5000      # small trial run
    python scripts/build_image_shards.py                   # build locally (resumable)
    python scripts/build_image_shards.py \
        --upload-repo zidcenek/GLAMIDuplicationDetection   # build AND upload in one pass

With --upload-repo each batch of shards is pushed and then deleted locally, so
packing 1.3M images needs a couple of GB of free disk rather than ~16GB.

Requires: pip install datasets Pillow   (Pillow is needed to encode the Image feature)
"""

from __future__ import annotations

import argparse
import json
import os
import re
import sys
import tarfile
import time
from array import array
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parent.parent

IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp"}

# Magic bytes, checked on every image. Truncated downloads and HTML error
# pages that got saved with a .jpg name are common in a 1.3M-file crawl and
# would otherwise poison the shard at load time.
MAGIC = (
    (b"\xff\xd8\xff", "jpeg"),
    (b"\x89PNG\r\n\x1a\n", "png"),
    (b"GIF87a", "gif"),
    (b"GIF89a", "gif"),
    (b"BM", "bmp"),
)


def sniff(data: bytes) -> str | None:
    for prefix, kind in MAGIC:
        if data.startswith(prefix):
            return kind
    if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
        return "webp"
    return None


def human(n: float) -> str:
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if n < 1024:
            return f"{n:.1f}{unit}"
        n /= 1024
    return f"{n:.1f}PB"


def iter_members(source: Path):
    """Yield (name, bytes) for every regular file in a tarball or directory."""
    if source.is_dir():
        for path in sorted(source.rglob("*")):
            if path.is_file():
                yield str(path.relative_to(source)), path.read_bytes()
        return

    # "r|gz" is the streaming mode: sequential, no seeking, constant memory.
    with tarfile.open(source, "r|gz") as tar:
        for member in tar:
            if not member.isfile():
                continue
            handle = tar.extractfile(member)
            if handle is None:
                continue
            yield member.name, handle.read()


def make_id_extractor(pattern: str | None):
    """itemId from a filename. Default: the whole stem if numeric, else its last digit run."""
    if pattern:
        rx = re.compile(pattern)

        def extract(stem: str):
            m = rx.search(stem)
            return int(m.group(1)) if m else None

        return extract

    trailing = re.compile(r"(\d+)(?!.*\d)")

    def extract(stem: str):
        if stem.isdigit():
            return int(stem)
        m = trailing.search(stem)
        return int(m.group(1)) if m else None

    return extract


def inspect(source: Path, extract, count: int) -> None:
    print(f"First {count} entries in {source.name}:\n")
    seen = 0
    for name, data in iter_members(source):
        if Path(name).name.startswith("._") or name.startswith("__MACOSX/"):
            continue
        stem = Path(name).stem
        print(
            f"  {name}\n"
            f"      itemId={extract(stem)}  format={sniff(data)}  size={human(len(data))}"
        )
        seen += 1
        if seen >= count:
            break
    print(
        "\nCheck that itemId matches the itemId column in items_train.csv."
        "\nIf it does not, pass --id-regex with a capture group, e.g."
        '\n  --id-regex "item_(\\d+)_thumb"'
    )


def main() -> int:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--source", type=Path, default=REPO_ROOT / "glami_images.tar.gz",
                   help="tarball or already-extracted directory of images")
    p.add_argument("--out", type=Path, default=REPO_ROOT / "images",
                   help="output directory for the parquet shards")
    p.add_argument("--shard-mb", type=int, default=400,
                   help="target uncompressed image bytes per shard (default: 400)")
    p.add_argument("--id-regex", default=None,
                   help="regex with one capture group extracting itemId from the filename stem")
    p.add_argument("--limit", type=int, default=None, help="stop after N images (trial run)")
    p.add_argument("--inspect", nargs="?", type=int, const=15, default=None,
                   help="list the first N tar entries and exit, without writing anything")
    p.add_argument("--allow-duplicates", action="store_true",
                   help="keep repeated itemIds instead of skipping them")
    p.add_argument("--upload-repo", default=None, metavar="REPO_ID",
                   help="upload shards to this Hub dataset as they are built, then delete them "
                        "locally (e.g. zidcenek/GLAMIDuplicationDetection). Keeps peak disk at "
                        "--upload-every-mb instead of the full dataset size.")
    p.add_argument("--upload-every-mb", type=int, default=2000,
                   help="upload once this many MB of shards have accumulated (default: 2000)")
    args = p.parse_args()

    if not args.source.exists():
        sys.exit(f"source not found: {args.source}")
    if args.source.is_file() and args.source.stat().st_size == 0:
        sys.exit(f"{args.source} is empty -- is the download still running?")

    extract = make_id_extractor(args.id_regex)

    if args.inspect is not None:
        inspect(args.source, extract, args.inspect)
        return 0

    from datasets import Dataset, Features, Image, Value  # imported late so --inspect needs no deps
    from datasets.utils.logging import disable_progress_bar

    api = None
    if args.upload_repo:
        from huggingface_hub import HfApi
        from huggingface_hub.utils import HfHubHTTPError

        api = HfApi()
        try:
            print(f"Uploading to {args.upload_repo} as {api.whoami()['name']}.")
        except Exception:
            sys.exit("not authenticated -- run 'hf auth login' (or export HF_TOKEN) first")

    disable_progress_bar()  # one bar per shard is noise across thousands of shards
    features = Features({"itemId": Value("int64"), "image": Image()})
    args.out.mkdir(parents=True, exist_ok=True)
    state_path = args.out / ".build_state.json"

    # Resume support. The gzip stream cannot be seeked, so resuming still has to
    # decompress its way back to where it stopped -- but it does not re-encode
    # or re-upload any shard that already exists.
    state = json.loads(state_path.read_text()) if state_path.exists() else {}
    shard_no = state.get("next_shard", 0)
    resume_from = state.get("images_done", 0)
    skip = resume_from
    # Every packed itemId is appended here as a flat int64 array. Duplicate
    # detection therefore survives both a resume and the shards being deleted
    # after they are uploaded, which is how build_and_upload.py keeps peak disk
    # down to one wave.
    seen_path = args.out / ".seen_ids.bin"
    seen_ids: set[int] = set()
    if resume_from:
        print(f"Resuming: {resume_from:,} images already packed into {shard_no} shard(s).")
        if not args.allow_duplicates and seen_path.exists():
            packed = array("q")
            packed.frombytes(seen_path.read_bytes())
            seen_ids.update(packed)
            print(f"           {len(seen_ids):,} itemIds loaded back for duplicate checking.")

    pending: list[Path] = []
    ids: list[int] = []
    blobs: list[dict] = []
    pending_bytes = 0
    target = args.shard_mb * 1024 * 1024
    done = skipped_nonimage = skipped_noid = skipped_corrupt = skipped_dupe = 0
    started = time.time()

    def flush() -> None:
        nonlocal shard_no, ids, blobs, pending_bytes
        if not ids:
            return
        out = args.out / f"shard-{shard_no:05d}.parquet"
        Dataset.from_dict({"itemId": ids, "image": blobs}, features=features).to_parquet(out)
        if not args.allow_duplicates:
            with open(seen_path, "ab") as fh:
                array("q", ids).tofile(fh)
        shard_no += 1
        rate = done / max(time.time() - started, 1e-9)
        print(f"  wrote {out.name}  {len(ids):,} images  {human(pending_bytes)}  "
              f"[{done:,} packed, {rate:.0f} img/s]", flush=True)
        state_path.write_text(json.dumps({"next_shard": shard_no, "images_done": resume_from + done}))
        pending.append(out)
        ids, blobs, pending_bytes = [], [], 0

    def push() -> None:
        """Upload the shards built since the last push, then delete them locally."""
        nonlocal pending
        if not api or not pending:
            return
        size = sum(f.stat().st_size for f in pending)
        print(f"  uploading {len(pending)} shard(s), {human(size)} ...", flush=True)
        try:
            api.upload_folder(
                repo_id=args.upload_repo,
                repo_type="dataset",
                folder_path=str(args.out),
                path_in_repo="images",
                allow_patterns=["shard-*.parquet"],
                commit_message=f"images: shards through {resume_from + done:,} images",
            )
        except HfHubHTTPError as exc:
            sys.exit(f"upload failed: {exc}\n"
                     "Rerun the same command -- packed shards are on disk and the build resumes.")
        # Only reached on a successful commit. The itemIds survive in
        # .seen_ids.bin, so deleting the shards does not weaken dedup.
        for f in pending:
            f.unlink()
        print(f"  uploaded, freed {human(size)}", flush=True)
        pending = []

    for name, data in iter_members(args.source):
        base = Path(name).name
        # macOS `tar` writes an AppleDouble sidecar next to every file; it shares
        # the real name, so it would otherwise claim the itemId first.
        if base.startswith("._") or name.startswith("__MACOSX/"):
            skipped_nonimage += 1
            continue
        suffix = Path(name).suffix.lower()
        if suffix not in IMAGE_SUFFIXES:
            skipped_nonimage += 1
            continue

        # Everything past here counts as an image, so the resume counter stays
        # aligned with the tar order regardless of what we decide to drop.
        if skip:
            skip -= 1
            continue

        item_id = extract(Path(name).stem)
        if item_id is None:
            skipped_noid += 1
            continue
        if sniff(data) is None:
            skipped_corrupt += 1
            continue
        if not args.allow_duplicates:
            if item_id in seen_ids:
                skipped_dupe += 1
                continue
            seen_ids.add(item_id)

        ids.append(item_id)
        blobs.append({"bytes": data, "path": f"{item_id}{suffix}"})
        pending_bytes += len(data)
        done += 1

        if pending_bytes >= target:
            flush()
            if sum(f.stat().st_size for f in pending) >= args.upload_every_mb * 1024 * 1024:
                push()
        if args.limit and done >= args.limit:
            break

    flush()
    push()

    where = args.upload_repo or f"{args.out}/"
    print(f"\nDone: {done:,} images this run, {shard_no} shard(s) total -> {where}")
    for label, n in (("non-image entries", skipped_nonimage), ("no itemId in filename", skipped_noid),
                     ("corrupt / not an image", skipped_corrupt), ("duplicate itemId", skipped_dupe)):
        if n:
            print(f"  skipped {n:,} -- {label}")
    if skipped_noid or skipped_corrupt:
        print("\nA large skip count usually means --id-regex is wrong or the crawl "
              "saved error pages. Re-check with --inspect before uploading.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())