ianhajra commited on
Commit
630b95c
·
verified ·
1 Parent(s): 663d643

Create INRIA-CopyDays.py

Browse files
Files changed (1) hide show
  1. INRIA-CopyDays.py +204 -0
INRIA-CopyDays.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datasets
2
+ import os
3
+ import tarfile
4
+ import shutil
5
+ import subprocess
6
+ import tempfile
7
+
8
+ _VERSION = datasets.Version("1.0.0")
9
+
10
+ _URLS = {
11
+ "copydays_original": {
12
+ "images": [
13
+ "https://dl.fbaipublicfiles.com/vissl/datasets/copydays_original.tar.gz"
14
+ ],
15
+ },
16
+ "copydays_strong": {
17
+ "images": [
18
+ "https://dl.fbaipublicfiles.com/vissl/datasets/copydays_strong.tar.gz"
19
+ ],
20
+ },
21
+ }
22
+
23
+ _DESCRIPTION = (
24
+ "Copydays dataset for copy detection and near-duplicate image retrieval evaluation."
25
+ )
26
+
27
+ _CITATION = """\
28
+ @inproceedings{jegou2008hamming,
29
+ title={Hamming embedding and weak geometric consistency for large scale image search},
30
+ author={Jegou, Herve and Douze, Matthijs and Schmid, Cordelia},
31
+ booktitle={European conference on computer vision},
32
+ pages={304--317},
33
+ year={2008},
34
+ organization={Springer}
35
+ }
36
+ """
37
+
38
+ BUILDER_CONFIGS = [
39
+ datasets.BuilderConfig(
40
+ name="database",
41
+ version=_VERSION,
42
+ description="Copydays original split for copy detection evaluation. Original, unmodified images.",
43
+ ),
44
+ datasets.BuilderConfig(
45
+ name="query",
46
+ version=_VERSION,
47
+ description="Copydays query split for copy detection evaluation. Currently only contains the strong modifications.",
48
+ ),
49
+ ]
50
+
51
+
52
+ class Copydays(datasets.GeneratorBasedBuilder):
53
+ """Copydays copy detection dataset."""
54
+
55
+ BUILDER_CONFIGS = BUILDER_CONFIGS
56
+ DEFAULT_CONFIG_NAME = "database"
57
+
58
+ def _download_and_extract(self, urls, cache_dir):
59
+ """Download archives using wget and extract them."""
60
+ os.makedirs(cache_dir, exist_ok=True)
61
+
62
+ existing_files = [f for f in os.listdir(cache_dir) if f.endswith(".jpg")]
63
+ has_original = any(f.endswith("00") for f in existing_files)
64
+ has_strong = any(
65
+ not f.endswith("00") for f in existing_files if f.endswith(".jpg")
66
+ )
67
+
68
+ if has_original and has_strong:
69
+ print(
70
+ f"Found existing extracted files in {cache_dir}, skipping download..."
71
+ )
72
+ return [cache_dir]
73
+
74
+ for url in urls:
75
+ filename = url.split("/")[-1]
76
+ archive_path = os.path.join(cache_dir, filename)
77
+
78
+ # Download using wget if file doesn't exist
79
+ if not os.path.exists(archive_path):
80
+ print(f"Downloading {url}...")
81
+ result = subprocess.run(
82
+ ["wget", url, "-O", archive_path], capture_output=True, text=True
83
+ )
84
+ if result.returncode != 0:
85
+ raise RuntimeError(f"Failed to download {url}: {result.stderr}")
86
+
87
+ marker_file = os.path.join(cache_dir, f".{filename}.extracted")
88
+ if not os.path.exists(marker_file):
89
+ print(f"Extracting {archive_path}...")
90
+ with tarfile.open(archive_path, "r:gz") as tar:
91
+ tar.extractall(cache_dir)
92
+ with open(marker_file, "w") as f:
93
+ f.write("extracted")
94
+
95
+ return [cache_dir]
96
+
97
+ def _info(self):
98
+ return datasets.DatasetInfo(
99
+ description=_DESCRIPTION,
100
+ features=datasets.Features(
101
+ {
102
+ "image": datasets.Image(),
103
+ "filename": datasets.Value(
104
+ "string"
105
+ ), # ex: "200000.jpg" which is the first db image
106
+ "split_type": datasets.Value("string"), # "original" or "strong"
107
+ "block_id": datasets.Value(
108
+ "int32"
109
+ ), # first 4 digists of filename (ex: 2000)
110
+ "query_id": datasets.Value(
111
+ "int32"
112
+ ), # 1 indexed, digits 5-6 of filename (ex: 01, 02, etc.)
113
+ # query_id is -1 for database split to make it clear it's not a query
114
+ }
115
+ ),
116
+ supervised_keys=None,
117
+ homepage="https://thoth.inrialpes.fr/~jegou/data.php.html#copydays",
118
+ citation=_CITATION,
119
+ )
120
+
121
+ def _split_generators(self, dl_manager):
122
+ # Download both datasets regardless of config (this way we just have to download and cache once)
123
+ all_urls = []
124
+ for dataset_type in _URLS.values():
125
+ all_urls.extend(dataset_type["images"])
126
+
127
+ cache_dir = tempfile.mkdtemp(prefix="copydays_")
128
+
129
+ try:
130
+ # Try HF DownloadManager (this is the preferred method but doesn't work for this dataset)
131
+ archive_paths = dl_manager.download(all_urls)
132
+ extracted_paths = dl_manager.extract(archive_paths)
133
+
134
+ # for type errors
135
+ if not isinstance(extracted_paths, list):
136
+ extracted_paths = [extracted_paths]
137
+ except Exception as e:
138
+ # Download and extract using wget
139
+ print(f"HF download failed: {e}")
140
+ print(
141
+ "Falling back to wget download strategy... This typically works better for this dataset."
142
+ )
143
+ extracted_paths = self._download_and_extract(all_urls, cache_dir)
144
+
145
+ return [
146
+ datasets.SplitGenerator(
147
+ name="queries",
148
+ gen_kwargs={
149
+ "image_dirs": extracted_paths,
150
+ "split_type": "queries",
151
+ "config_name": self.config.name,
152
+ },
153
+ ),
154
+ datasets.SplitGenerator(
155
+ name="database",
156
+ gen_kwargs={
157
+ "image_dirs": extracted_paths,
158
+ "split_type": "database",
159
+ "config_name": self.config.name,
160
+ },
161
+ ),
162
+ ]
163
+
164
+ def _generate_examples(self, image_dirs, split_type, config_name):
165
+ """Generate examples for the dataset."""
166
+ idx = 0
167
+
168
+ for image_dir in image_dirs:
169
+ for root, dirs, files in os.walk(image_dir):
170
+ for file in files:
171
+ if file.lower().endswith((".jpg", ".jpeg", ".png", ".bmp", ".gif")):
172
+ file_path = os.path.join(root, file)
173
+ filename = file
174
+
175
+ # format: "XXXXXX.jpg" where first 4 digits are block_id, next two are query_id
176
+ base_name = os.path.splitext(filename)[0]
177
+ if not base_name.isdigit() or len(base_name) != 6:
178
+ continue
179
+
180
+ block_id = int(base_name[:4])
181
+
182
+ actual_split_type = (
183
+ "original" if split_type == "queries" else "strong"
184
+ )
185
+
186
+ if split_type == "queries":
187
+ if base_name[4:6] == "00":
188
+ query_id = -1
189
+ else:
190
+ continue
191
+ else:
192
+ if base_name[4:6] != "00":
193
+ query_id = int(base_name[4:6])
194
+ else:
195
+ continue
196
+
197
+ yield idx, {
198
+ "image": file_path,
199
+ "filename": filename,
200
+ "split_type": actual_split_type,
201
+ "block_id": block_id,
202
+ "query_id": query_id,
203
+ }
204
+ idx += 1