cenekzid commited on
Commit
5f5554c
·
1 Parent(s): 195cad7

dataset: add README, LICENSE, and scripts for uploading

Browse files
Files changed (5) hide show
  1. .gitignore +16 -0
  2. LICENSE +202 -0
  3. README.md +127 -0
  4. scripts/build_image_shards.py +321 -0
  5. scripts/upload_to_hub.py +156 -0
.gitignore ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Raw image crawl and the shards built from it: uploaded over HTTP by
2
+ # scripts/upload_to_hub.py, never committed through git.
3
+ glami_images.tar.gz
4
+ images/
5
+
6
+ # upload_large_folder resume state
7
+ .cache/
8
+
9
+ # macOS
10
+ .DS_Store
11
+
12
+ # local venv for the build/upload scripts
13
+ .venv/
14
+
15
+ # python
16
+ __pycache__/
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 GLAMI
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ task_categories:
4
+ - image-classification
5
+ - zero-shot-image-classification
6
+ language:
7
+ - bg
8
+ - cs
9
+ - el
10
+ - hr
11
+ - hu
12
+ - pl
13
+ - ro
14
+ - sk
15
+ tags:
16
+ - e-commerce
17
+ - duplicate-detection
18
+ - entity-resolution
19
+ - multimodal
20
+ size_categories:
21
+ - 1M<n<10M
22
+ configs:
23
+ - config_name: images
24
+ default: true
25
+ data_files:
26
+ - split: train
27
+ path: images/shard-*.parquet
28
+ - config_name: items
29
+ data_files:
30
+ - split: train
31
+ path: items_train.csv
32
+ - split: test
33
+ path: items_test.csv
34
+ - config_name: splits
35
+ data_files:
36
+ - split: train
37
+ path: train_split.csv
38
+ - split: validation
39
+ path: val_split.csv
40
+ - config_name: groups
41
+ data_files:
42
+ - split: g5
43
+ path: groups_5.csv
44
+ - split: g6
45
+ path: groups_6.csv
46
+ - split: g7
47
+ path: groups_7.csv
48
+ - split: g8
49
+ path: groups_8.csv
50
+ - split: g9
51
+ path: groups_9.csv
52
+ - split: g10
53
+ path: groups_10.csv
54
+ - split: hard_5
55
+ path: groups_hard_5.csv
56
+ - split: category_5
57
+ path: groups_category_5.csv
58
+ ---
59
+
60
+ # GLAMI Duplication Detection
61
+
62
+ Product-duplicate detection over GLAMI e-commerce listings: ~1.3M product
63
+ images plus multilingual titles, descriptions and attributes, with labelled
64
+ groups of items that do or do not refer to the same physical product.
65
+
66
+ Released under the Apache License 2.0 — see [LICENSE](LICENSE).
67
+
68
+ > TODO: describe how the labels were produced.
69
+
70
+ ## Structure
71
+
72
+ | Config | Files | Contents |
73
+ | --- | --- | --- |
74
+ | `images` | `images/shard-*.parquet` | `itemId` → image bytes, one row per product image |
75
+ | `items` | `items_train.csv`, `items_test.csv` | `itemId`, `price`, `colorTagIdsString`, `departmentIds`, `brandEditionTagId`, `title`, `description`, `geo`, and `label` on train |
76
+ | `splits` | `train_split.csv`, `val_split.csv` | train/validation partition of the training items |
77
+ | `groups` | `groups_*.csv` | `item1..itemN`, `label` — candidate groups of 5–10 items, plus `hard_` and `category_` adversarial variants |
78
+
79
+ Images are keyed by `itemId` alone and are not pre-split. Every other file
80
+ references `itemId`, so all of them join against the same image table and no
81
+ picture is stored twice.
82
+
83
+ ## Usage
84
+
85
+ ```python
86
+ from datasets import load_dataset
87
+
88
+ images = load_dataset("zidcenek/GLAMIDuplicationDetection", "images", split="train")
89
+ items = load_dataset("zidcenek/GLAMIDuplicationDetection", "items", split="train")
90
+ groups = load_dataset("zidcenek/GLAMIDuplicationDetection", "groups", split="g5")
91
+
92
+ images[0]["image"] # PIL.Image, decoded lazily
93
+ images[0]["itemId"]
94
+ ```
95
+
96
+ The image config is ~TODO GB, so stream it if you do not want a full local copy:
97
+
98
+ ```python
99
+ images = load_dataset(
100
+ "zidcenek/GLAMIDuplicationDetection", "images", split="train", streaming=True
101
+ )
102
+ ```
103
+
104
+ To attach images to items, build the `itemId` → row-index map once and index into it:
105
+
106
+ ```python
107
+ index = {item_id: i for i, item_id in enumerate(images["itemId"])}
108
+ row = images[index[items[0]["itemId"]]]
109
+ ```
110
+
111
+ ## Reproducing the image shards
112
+
113
+ ```bash
114
+ pip install -U datasets Pillow "huggingface_hub[hf_xet]"
115
+
116
+ python scripts/build_image_shards.py --inspect # check the filename -> itemId mapping
117
+ python scripts/build_image_shards.py # glami_images.tar.gz -> images/shard-*.parquet
118
+ hf auth login
119
+ python scripts/upload_to_hub.py # push to the Hub over HTTP
120
+ ```
121
+
122
+ Both scripts are resumable: rerun the same command after an interruption.
123
+ See the header of each for the full options.
124
+
125
+ ## Citation
126
+
127
+ > TODO
scripts/build_image_shards.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Pack GLAMI product images into Hub-ready Parquet shards.
3
+
4
+ Reads images straight out of glami_images.tar.gz in a single streaming pass --
5
+ the 1.3M files are never unpacked onto disk -- and writes
6
+
7
+ images/shard-00000.parquet, images/shard-00001.parquet, ...
8
+
9
+ with the `datasets` Image() feature, so the Hub's Dataset Viewer renders them
10
+ and `load_dataset(..., streaming=True)` works without a loading script.
11
+
12
+ Images are keyed by itemId only. They are deliberately NOT split into
13
+ train/test: the splits live in items_train.csv / items_test.csv / *_split.csv,
14
+ which reference itemId, so a single image table stays joinable by all of them
15
+ and never stores the same picture twice.
16
+
17
+ Usage:
18
+ python scripts/build_image_shards.py --inspect # peek inside the tarball first
19
+ python scripts/build_image_shards.py --limit 5000 # small trial run
20
+ python scripts/build_image_shards.py # build locally (resumable)
21
+ python scripts/build_image_shards.py \
22
+ --upload-repo zidcenek/GLAMIDuplicationDetection # build AND upload in one pass
23
+
24
+ With --upload-repo each batch of shards is pushed and then deleted locally, so
25
+ packing 1.3M images needs a couple of GB of free disk rather than ~16GB.
26
+
27
+ Requires: pip install datasets Pillow (Pillow is needed to encode the Image feature)
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import json
34
+ import os
35
+ import re
36
+ import sys
37
+ import tarfile
38
+ import time
39
+ from array import array
40
+ from pathlib import Path
41
+
42
+ REPO_ROOT = Path(__file__).resolve().parent.parent
43
+
44
+ IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp"}
45
+
46
+ # Magic bytes, checked on every image. Truncated downloads and HTML error
47
+ # pages that got saved with a .jpg name are common in a 1.3M-file crawl and
48
+ # would otherwise poison the shard at load time.
49
+ MAGIC = (
50
+ (b"\xff\xd8\xff", "jpeg"),
51
+ (b"\x89PNG\r\n\x1a\n", "png"),
52
+ (b"GIF87a", "gif"),
53
+ (b"GIF89a", "gif"),
54
+ (b"BM", "bmp"),
55
+ )
56
+
57
+
58
+ def sniff(data: bytes) -> str | None:
59
+ for prefix, kind in MAGIC:
60
+ if data.startswith(prefix):
61
+ return kind
62
+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
63
+ return "webp"
64
+ return None
65
+
66
+
67
+ def human(n: float) -> str:
68
+ for unit in ("B", "KB", "MB", "GB", "TB"):
69
+ if n < 1024:
70
+ return f"{n:.1f}{unit}"
71
+ n /= 1024
72
+ return f"{n:.1f}PB"
73
+
74
+
75
+ def iter_members(source: Path):
76
+ """Yield (name, bytes) for every regular file in a tarball or directory."""
77
+ if source.is_dir():
78
+ for path in sorted(source.rglob("*")):
79
+ if path.is_file():
80
+ yield str(path.relative_to(source)), path.read_bytes()
81
+ return
82
+
83
+ # "r|gz" is the streaming mode: sequential, no seeking, constant memory.
84
+ with tarfile.open(source, "r|gz") as tar:
85
+ for member in tar:
86
+ if not member.isfile():
87
+ continue
88
+ handle = tar.extractfile(member)
89
+ if handle is None:
90
+ continue
91
+ yield member.name, handle.read()
92
+
93
+
94
+ def make_id_extractor(pattern: str | None):
95
+ """itemId from a filename. Default: the whole stem if numeric, else its last digit run."""
96
+ if pattern:
97
+ rx = re.compile(pattern)
98
+
99
+ def extract(stem: str):
100
+ m = rx.search(stem)
101
+ return int(m.group(1)) if m else None
102
+
103
+ return extract
104
+
105
+ trailing = re.compile(r"(\d+)(?!.*\d)")
106
+
107
+ def extract(stem: str):
108
+ if stem.isdigit():
109
+ return int(stem)
110
+ m = trailing.search(stem)
111
+ return int(m.group(1)) if m else None
112
+
113
+ return extract
114
+
115
+
116
+ def inspect(source: Path, extract, count: int) -> None:
117
+ print(f"First {count} entries in {source.name}:\n")
118
+ seen = 0
119
+ for name, data in iter_members(source):
120
+ if Path(name).name.startswith("._") or name.startswith("__MACOSX/"):
121
+ continue
122
+ stem = Path(name).stem
123
+ print(
124
+ f" {name}\n"
125
+ f" itemId={extract(stem)} format={sniff(data)} size={human(len(data))}"
126
+ )
127
+ seen += 1
128
+ if seen >= count:
129
+ break
130
+ print(
131
+ "\nCheck that itemId matches the itemId column in items_train.csv."
132
+ "\nIf it does not, pass --id-regex with a capture group, e.g."
133
+ '\n --id-regex "item_(\\d+)_thumb"'
134
+ )
135
+
136
+
137
+ def main() -> int:
138
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
139
+ p.add_argument("--source", type=Path, default=REPO_ROOT / "glami_images.tar.gz",
140
+ help="tarball or already-extracted directory of images")
141
+ p.add_argument("--out", type=Path, default=REPO_ROOT / "images",
142
+ help="output directory for the parquet shards")
143
+ p.add_argument("--shard-mb", type=int, default=400,
144
+ help="target uncompressed image bytes per shard (default: 400)")
145
+ p.add_argument("--id-regex", default=None,
146
+ help="regex with one capture group extracting itemId from the filename stem")
147
+ p.add_argument("--limit", type=int, default=None, help="stop after N images (trial run)")
148
+ p.add_argument("--inspect", nargs="?", type=int, const=15, default=None,
149
+ help="list the first N tar entries and exit, without writing anything")
150
+ p.add_argument("--allow-duplicates", action="store_true",
151
+ help="keep repeated itemIds instead of skipping them")
152
+ p.add_argument("--upload-repo", default=None, metavar="REPO_ID",
153
+ help="upload shards to this Hub dataset as they are built, then delete them "
154
+ "locally (e.g. zidcenek/GLAMIDuplicationDetection). Keeps peak disk at "
155
+ "--upload-every-mb instead of the full dataset size.")
156
+ p.add_argument("--upload-every-mb", type=int, default=2000,
157
+ help="upload once this many MB of shards have accumulated (default: 2000)")
158
+ args = p.parse_args()
159
+
160
+ if not args.source.exists():
161
+ sys.exit(f"source not found: {args.source}")
162
+ if args.source.is_file() and args.source.stat().st_size == 0:
163
+ sys.exit(f"{args.source} is empty -- is the download still running?")
164
+
165
+ extract = make_id_extractor(args.id_regex)
166
+
167
+ if args.inspect is not None:
168
+ inspect(args.source, extract, args.inspect)
169
+ return 0
170
+
171
+ from datasets import Dataset, Features, Image, Value # imported late so --inspect needs no deps
172
+ from datasets.utils.logging import disable_progress_bar
173
+
174
+ api = None
175
+ if args.upload_repo:
176
+ from huggingface_hub import HfApi
177
+ from huggingface_hub.utils import HfHubHTTPError
178
+
179
+ api = HfApi()
180
+ try:
181
+ print(f"Uploading to {args.upload_repo} as {api.whoami()['name']}.")
182
+ except Exception:
183
+ sys.exit("not authenticated -- run 'hf auth login' (or export HF_TOKEN) first")
184
+
185
+ disable_progress_bar() # one bar per shard is noise across thousands of shards
186
+ features = Features({"itemId": Value("int64"), "image": Image()})
187
+ args.out.mkdir(parents=True, exist_ok=True)
188
+ state_path = args.out / ".build_state.json"
189
+
190
+ # Resume support. The gzip stream cannot be seeked, so resuming still has to
191
+ # decompress its way back to where it stopped -- but it does not re-encode
192
+ # or re-upload any shard that already exists.
193
+ state = json.loads(state_path.read_text()) if state_path.exists() else {}
194
+ shard_no = state.get("next_shard", 0)
195
+ resume_from = state.get("images_done", 0)
196
+ skip = resume_from
197
+ # Every packed itemId is appended here as a flat int64 array. Duplicate
198
+ # detection therefore survives both a resume and the shards being deleted
199
+ # after they are uploaded, which is how build_and_upload.py keeps peak disk
200
+ # down to one wave.
201
+ seen_path = args.out / ".seen_ids.bin"
202
+ seen_ids: set[int] = set()
203
+ if resume_from:
204
+ print(f"Resuming: {resume_from:,} images already packed into {shard_no} shard(s).")
205
+ if not args.allow_duplicates and seen_path.exists():
206
+ packed = array("q")
207
+ packed.frombytes(seen_path.read_bytes())
208
+ seen_ids.update(packed)
209
+ print(f" {len(seen_ids):,} itemIds loaded back for duplicate checking.")
210
+
211
+ pending: list[Path] = []
212
+ ids: list[int] = []
213
+ blobs: list[dict] = []
214
+ pending_bytes = 0
215
+ target = args.shard_mb * 1024 * 1024
216
+ done = skipped_nonimage = skipped_noid = skipped_corrupt = skipped_dupe = 0
217
+ started = time.time()
218
+
219
+ def flush() -> None:
220
+ nonlocal shard_no, ids, blobs, pending_bytes
221
+ if not ids:
222
+ return
223
+ out = args.out / f"shard-{shard_no:05d}.parquet"
224
+ Dataset.from_dict({"itemId": ids, "image": blobs}, features=features).to_parquet(out)
225
+ if not args.allow_duplicates:
226
+ with open(seen_path, "ab") as fh:
227
+ array("q", ids).tofile(fh)
228
+ shard_no += 1
229
+ rate = done / max(time.time() - started, 1e-9)
230
+ print(f" wrote {out.name} {len(ids):,} images {human(pending_bytes)} "
231
+ f"[{done:,} packed, {rate:.0f} img/s]", flush=True)
232
+ state_path.write_text(json.dumps({"next_shard": shard_no, "images_done": resume_from + done}))
233
+ pending.append(out)
234
+ ids, blobs, pending_bytes = [], [], 0
235
+
236
+ def push() -> None:
237
+ """Upload the shards built since the last push, then delete them locally."""
238
+ nonlocal pending
239
+ if not api or not pending:
240
+ return
241
+ size = sum(f.stat().st_size for f in pending)
242
+ print(f" uploading {len(pending)} shard(s), {human(size)} ...", flush=True)
243
+ try:
244
+ api.upload_folder(
245
+ repo_id=args.upload_repo,
246
+ repo_type="dataset",
247
+ folder_path=str(args.out),
248
+ path_in_repo="images",
249
+ allow_patterns=["shard-*.parquet"],
250
+ commit_message=f"images: shards through {resume_from + done:,} images",
251
+ )
252
+ except HfHubHTTPError as exc:
253
+ sys.exit(f"upload failed: {exc}\n"
254
+ "Rerun the same command -- packed shards are on disk and the build resumes.")
255
+ # Only reached on a successful commit. The itemIds survive in
256
+ # .seen_ids.bin, so deleting the shards does not weaken dedup.
257
+ for f in pending:
258
+ f.unlink()
259
+ print(f" uploaded, freed {human(size)}", flush=True)
260
+ pending = []
261
+
262
+ for name, data in iter_members(args.source):
263
+ base = Path(name).name
264
+ # macOS `tar` writes an AppleDouble sidecar next to every file; it shares
265
+ # the real name, so it would otherwise claim the itemId first.
266
+ if base.startswith("._") or name.startswith("__MACOSX/"):
267
+ skipped_nonimage += 1
268
+ continue
269
+ suffix = Path(name).suffix.lower()
270
+ if suffix not in IMAGE_SUFFIXES:
271
+ skipped_nonimage += 1
272
+ continue
273
+
274
+ # Everything past here counts as an image, so the resume counter stays
275
+ # aligned with the tar order regardless of what we decide to drop.
276
+ if skip:
277
+ skip -= 1
278
+ continue
279
+
280
+ item_id = extract(Path(name).stem)
281
+ if item_id is None:
282
+ skipped_noid += 1
283
+ continue
284
+ if sniff(data) is None:
285
+ skipped_corrupt += 1
286
+ continue
287
+ if not args.allow_duplicates:
288
+ if item_id in seen_ids:
289
+ skipped_dupe += 1
290
+ continue
291
+ seen_ids.add(item_id)
292
+
293
+ ids.append(item_id)
294
+ blobs.append({"bytes": data, "path": f"{item_id}{suffix}"})
295
+ pending_bytes += len(data)
296
+ done += 1
297
+
298
+ if pending_bytes >= target:
299
+ flush()
300
+ if sum(f.stat().st_size for f in pending) >= args.upload_every_mb * 1024 * 1024:
301
+ push()
302
+ if args.limit and done >= args.limit:
303
+ break
304
+
305
+ flush()
306
+ push()
307
+
308
+ where = args.upload_repo or f"{args.out}/"
309
+ print(f"\nDone: {done:,} images this run, {shard_no} shard(s) total -> {where}")
310
+ for label, n in (("non-image entries", skipped_nonimage), ("no itemId in filename", skipped_noid),
311
+ ("corrupt / not an image", skipped_corrupt), ("duplicate itemId", skipped_dupe)):
312
+ if n:
313
+ print(f" skipped {n:,} -- {label}")
314
+ if skipped_noid or skipped_corrupt:
315
+ print("\nA large skip count usually means --id-regex is wrong or the crawl "
316
+ "saved error pages. Re-check with --inspect before uploading.")
317
+ return 0
318
+
319
+
320
+ if __name__ == "__main__":
321
+ raise SystemExit(main())
scripts/upload_to_hub.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Upload this dataset to the Hugging Face Hub over HTTP.
3
+
4
+ Deliberately does not use git. A 100GB+ push through git-lfs stalls, retries
5
+ from zero, and needs a working git-lfs install (this clone does not have one).
6
+ `upload_large_folder` is the Hub's own path for exactly this case: many
7
+ workers, resumable, and it picks up where it left off if you rerun it.
8
+
9
+ Usage:
10
+ hf auth login # once
11
+ python scripts/upload_to_hub.py --dry-run # see what would go up
12
+ python scripts/upload_to_hub.py # upload shards + metadata
13
+ python scripts/upload_to_hub.py --only images # shards alone
14
+
15
+ Requires: pip install -U "huggingface_hub[hf_xet]"
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import sys
22
+ from fnmatch import fnmatch
23
+ from pathlib import Path
24
+
25
+ REPO_ROOT = Path(__file__).resolve().parent.parent
26
+ DEFAULT_REPO = "zidcenek/GLAMIDuplicationDetection"
27
+
28
+ GROUPS = {
29
+ "images": ["images/*.parquet"],
30
+ "metadata": ["*.csv", "README.md", "LICENSE"],
31
+ }
32
+
33
+ # .cache/huggingface holds upload_large_folder's own resume state; .git and the
34
+ # source tarball must never be shipped to the Hub.
35
+ # fnmatch's "*" crosses "/", so an allow pattern like "*.csv" sweeps up every
36
+ # nested CSV as well -- a virtualenv inside the repo is enough to leak numpy's
37
+ # test fixtures into a public dataset. These directories are excluded outright.
38
+ IGNORE = [
39
+ ".git/*", "**/.git/*",
40
+ ".cache/*", "**/.cache/*",
41
+ ".venv/*", "**/.venv/*", "venv/*", "**/venv/*", "**/site-packages/*",
42
+ "*.tar.gz", "scripts/*",
43
+ ".build_state.json", "**/.build_state.json",
44
+ ".seen_ids.bin", "**/.seen_ids.bin",
45
+ ".DS_Store", "**/.DS_Store",
46
+ ]
47
+
48
+
49
+ def human(n: float) -> str:
50
+ for unit in ("B", "KB", "MB", "GB", "TB"):
51
+ if n < 1024:
52
+ return f"{n:.1f}{unit}"
53
+ n /= 1024
54
+ return f"{n:.1f}PB"
55
+
56
+
57
+ def matching_files(root: Path, patterns: list[str]) -> list[Path]:
58
+ hits = []
59
+ for path in root.rglob("*"):
60
+ if not path.is_file():
61
+ continue
62
+ rel = path.relative_to(root).as_posix()
63
+ if any(fnmatch(rel, pat) for pat in IGNORE) or rel.startswith(".git/"):
64
+ continue
65
+ if any(fnmatch(rel, pat) for pat in patterns):
66
+ hits.append(path)
67
+ return sorted(hits)
68
+
69
+
70
+ def main() -> int:
71
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
72
+ p.add_argument("--repo-id", default=DEFAULT_REPO)
73
+ p.add_argument("--root", type=Path, default=REPO_ROOT)
74
+ p.add_argument("--only", choices=sorted(GROUPS), action="append",
75
+ help="upload just one group (repeatable); default is all of them")
76
+ p.add_argument("--workers", type=int, default=8,
77
+ help="parallel upload workers (default: 8; lower it if your uplink saturates)")
78
+ p.add_argument("--dry-run", action="store_true", help="list the files and exit")
79
+ p.add_argument("--yes", "-y", action="store_true", help="skip the confirmation prompt")
80
+ args = p.parse_args()
81
+
82
+ from huggingface_hub import HfApi
83
+ from huggingface_hub.utils import HfHubHTTPError
84
+
85
+ try:
86
+ import hf_xet # noqa: F401
87
+ except ImportError:
88
+ print("note: hf_xet is not installed. Install it -- 'pip install -U \"huggingface_hub[hf_xet]\"' --\n"
89
+ " for chunk-level deduplication, which matters a lot for a near-duplicate image set.\n")
90
+
91
+ patterns = [pat for group in (args.only or sorted(GROUPS)) for pat in GROUPS[group]]
92
+ files = matching_files(args.root, patterns)
93
+ if not files:
94
+ sys.exit(f"nothing matches {patterns} under {args.root} -- build the shards first")
95
+
96
+ suspicious = [f for f in files
97
+ if any(part.startswith(".") or part in {"site-packages", "node_modules"}
98
+ for part in f.relative_to(args.root).parts[:-1])]
99
+ if suspicious:
100
+ print("refusing to upload -- these matched from inside a hidden or vendored directory:")
101
+ for f in suspicious[:10]:
102
+ print(f" {f.relative_to(args.root).as_posix()}")
103
+ sys.exit("widen IGNORE in this script, or move that directory out of the repo")
104
+
105
+ total = sum(f.stat().st_size for f in files)
106
+ print(f"repo {args.repo_id} (dataset)")
107
+ print(f"root {args.root}")
108
+ print(f"files {len(files):,} totalling {human(total)}")
109
+ for f in files[:6]:
110
+ print(f" {f.relative_to(args.root).as_posix()} {human(f.stat().st_size)}")
111
+ if len(files) > 6:
112
+ print(f" ... and {len(files) - 6:,} more")
113
+
114
+ stubs = [f for f in files if f.suffix == ".csv" and f.stat().st_size < 200]
115
+ if stubs:
116
+ print("\nWARNING: these CSVs are 134-byte git-lfs pointer stubs, not real data.")
117
+ for f in stubs:
118
+ print(f" {f.relative_to(args.root).as_posix()}")
119
+ print(" Uploading them would overwrite the real files on the Hub.")
120
+ print(" Install git-lfs and run 'git lfs pull' first, or exclude them.")
121
+ if not args.yes:
122
+ sys.exit("aborting -- rerun with --only images, or fix the stubs")
123
+
124
+ if args.dry_run:
125
+ return 0
126
+
127
+ api = HfApi()
128
+ try:
129
+ who = api.whoami()
130
+ except Exception:
131
+ sys.exit("not authenticated -- run 'hf auth login' first")
132
+ print(f"user {who['name']}")
133
+
134
+ if not args.yes:
135
+ if input("\nupload? [y/N] ").strip().lower() not in {"y", "yes"}:
136
+ return 1
137
+
138
+ try:
139
+ api.upload_large_folder(
140
+ repo_id=args.repo_id,
141
+ repo_type="dataset",
142
+ folder_path=str(args.root),
143
+ allow_patterns=patterns,
144
+ ignore_patterns=IGNORE,
145
+ num_workers=args.workers,
146
+ print_report=True,
147
+ )
148
+ except HfHubHTTPError as exc:
149
+ sys.exit(f"upload failed: {exc}\nRerun the same command -- it resumes from where it stopped.")
150
+
151
+ print(f"\nDone: https://huggingface.co/datasets/{args.repo_id}")
152
+ return 0
153
+
154
+
155
+ if __name__ == "__main__":
156
+ raise SystemExit(main())