| |
| """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 = ( |
| (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 |
|
|
| |
| 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 |
| 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() |
| features = Features({"itemId": Value("int64"), "image": Image()}) |
| args.out.mkdir(parents=True, exist_ok=True) |
| state_path = args.out / ".build_state.json" |
|
|
| |
| |
| |
| 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 |
| |
| |
| |
| |
| 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.") |
| |
| |
| 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 |
| |
| |
| 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 |
|
|
| |
| |
| 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()) |
|
|