Datasets:

ArXiv:
DOI:
License:
ProgramComputer commited on
Commit
e88b15e
·
verified ·
1 Parent(s): ad5f6b5

Repair VGGFace2 streaming loader

Browse files
Files changed (2) hide show
  1. README.md +26 -1
  2. VGGFace2.py +720 -145
README.md CHANGED
@@ -3,6 +3,31 @@ license: cc-by-nc-4.0
3
  paperswithcode_id: vggface2
4
  pretty_name: vggface2
5
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  ```
7
  @article{DBLP:journals/corr/abs-1710-08092,
8
  author = {Qiong Cao and
@@ -21,4 +46,4 @@ pretty_name: vggface2
21
  biburl = {https://dblp.org/rec/journals/corr/abs-1710-08092.bib},
22
  bibsource = {dblp computer science bibliography, https://dblp.org}
23
  }
24
- ```
 
3
  paperswithcode_id: vggface2
4
  pretty_name: vggface2
5
  ---
6
+
7
+ ## Bounded streaming
8
+
9
+ `datasets==5.0.0` does not execute this repository's remote Python loader
10
+ through `load_dataset()`. Clone code and metadata without downloading Git LFS
11
+ objects, then use the project-side module directly:
12
+
13
+ ```shell
14
+ GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/datasets/ProgramComputer/VGGFace2
15
+ ```
16
+
17
+ Archive bytes are read sequentially and are not extracted or cached.
18
+
19
+ ```python
20
+ from VGGFace2 import load_streaming
21
+
22
+ dataset = load_streaming(
23
+ split="train",
24
+ revision="ad5f6b5a5f560621fd7efb9b79c956d27d427a08",
25
+ cache_dir="./metadata-cache",
26
+ scratch_dir="./stream-scratch",
27
+ )
28
+ first_hundred = list(dataset.take(100))
29
+ ```
30
+
31
  ```
32
  @article{DBLP:journals/corr/abs-1710-08092,
33
  author = {Qiong Cao and
 
46
  biburl = {https://dblp.org/rec/journals/corr/abs-1710-08092.bib},
47
  bibsource = {dblp computer science bibliography, https://dblp.org}
48
  }
49
+ ```
VGGFace2.py CHANGED
@@ -1,4 +1,3 @@
1
- # coding=utf-8
2
  # Copyright 2022 The HuggingFace Datasets Authors and ProgramComputer.
3
  #
4
  # Licensed under the Apache License, Version 2.0 (the "License");
@@ -13,174 +12,750 @@
13
  # See the License for the specific language governing permissions and
14
  # limitations under the License.
15
 
16
- # Lint as: python3
17
- """VGGFace2 audio-visual human speech dataset."""
18
 
19
- import json
 
 
 
20
  import os
21
  import re
22
- from urllib.parse import urlparse, parse_qs
23
- from getpass import getpass
24
- from hashlib import sha256
25
- from itertools import repeat
26
- from multiprocessing import Manager, Pool, Process
27
- from pathlib import Path
28
- from shutil import copyfileobj
29
- from warnings import catch_warnings, filterwarnings
30
- from urllib3.exceptions import InsecureRequestWarning
31
-
32
- import pandas as pd
33
- import requests
34
 
35
  import datasets
 
 
 
36
 
37
- _DESCRIPTION = "VGGFace2 is a large-scale face recognition dataset. Images are downloaded from Google Image Search and have large variations in pose, age, illumination, ethnicity and profession."
38
- _CITATION = """\
39
- @article{DBLP:journals/corr/abs-1710-08092,
40
- author = {Qiong Cao and
41
- Li Shen and
42
- Weidi Xie and
43
- Omkar M. Parkhi and
44
- Andrew Zisserman},
45
- title = {VGGFace2: {A} dataset for recognising faces across pose and age},
46
- journal = {CoRR},
47
- volume = {abs/1710.08092},
48
- year = {2017},
49
- url = {http://arxiv.org/abs/1710.08092},
50
- eprinttype = {arXiv},
51
- eprint = {1710.08092},
52
- timestamp = {Wed, 04 Aug 2021 07:50:14 +0200},
53
- biburl = {https://dblp.org/rec/journals/corr/abs-1710-08092.bib},
54
- bibsource = {dblp computer science bibliography, https://dblp.org}
55
- }
56
- """
57
 
 
 
 
58
 
 
 
 
 
 
 
 
 
 
59
 
60
- _URLS = {
61
- "default": {
62
- "train": "https://huggingface.co/datasets/ProgramComputer/VGGFace2/resolve/main/data/vggface2_train.tar.gz",
63
- "test": "https://huggingface.co/datasets/ProgramComputer/VGGFace2/resolve/main/data/vggface2_test.tar.gz",
64
- }
 
 
 
 
 
 
 
65
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
 
 
 
 
 
 
 
67
 
68
 
69
- class VGGFace2(datasets.GeneratorBasedBuilder):
70
- """VGGFace2 is dataset contains faces from Google Search"""
71
 
72
- VERSION = datasets.Version("1.0.0")
73
 
74
- BUILDER_CONFIGS = [
75
- datasets.BuilderConfig( version=VERSION
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  )
77
- ]
78
-
79
- def _info(self):
80
- features = {
81
- "image": datasets.Image(),
82
- "image_id": datasets.Value("string"),
83
- "class_id": datasets.Value("string"),
84
- "identity": datasets.Value("string"),
85
- 'gender': datasets.Value("string"),
86
- 'sample_num':datasets.Value("uint64"),
87
- 'flag':datasets.Value("bool"),
88
- "male": datasets.Value("bool"),
89
- "black_hair": datasets.Value("bool"),
90
- "gray_hair": datasets.Value("bool"),
91
- "blond_hair": datasets.Value("bool"),
92
- "long_hair": datasets.Value("bool"),
93
- "mustache_or_beard": datasets.Value("bool"),
94
- "wearing_hat": datasets.Value("bool"),
95
- "eyeglasses": datasets.Value("bool"),
96
- "sunglasses": datasets.Value("bool"),
97
- "mouth_open": datasets.Value("bool"),
98
  }
 
 
 
99
 
100
- return datasets.DatasetInfo(
101
- description=_DESCRIPTION,
102
- supervised_keys=datasets.info.SupervisedKeysData("file", "class_id"),
103
- features=datasets.Features(features),
104
- citation=_CITATION,
105
  )
 
 
 
 
 
 
 
 
 
 
106
 
107
- def _split_generators(self, dl_manager):
108
- targets = (
109
- ["01-Male.txt", "02-Black_Hair.txt","03-Brown_Hair.txt","04-Gray_Hair.txt","05-Blond_Hair.txt","06-Long_Hair.txt","07-Mustache_or_Beard.txt","08-Wearing_Hat.txt","09-Eyeglasses.txt","10-Sunglasses.txt","11-Mouth_Open.txt"]
 
 
 
 
110
  )
111
- target_dict = dict(
112
- (
113
- re.sub(r"^\d+-|\.txt$","",target),
114
- f"https://raw.githubusercontent.com/ox-vgg/vgg_face2/master/attributes/{target}",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  )
116
- for target in targets
117
- )
118
- target_dict['identity'] = "https://huggingface.co/datasets/ProgramComputer/VGGFace2/raw/main/meta/identity_meta.csv"
119
- metadata = dl_manager.download(
120
- target_dict
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- mapped_paths_train = dl_manager.iter_archive(
124
- _URLS["default"]["train"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  )
126
- mapped_paths_test = dl_manager.iter_archive(
127
- _URLS["default"]["test"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  )
129
- return [
130
- datasets.SplitGenerator(
131
- name="train",
132
- gen_kwargs={
133
- "paths": mapped_paths_train,
134
- "meta_paths": metadata,
135
- },
136
- ),
137
- datasets.SplitGenerator(
138
- name="test",
139
- gen_kwargs={
140
- "paths": mapped_paths_test,
141
- "meta_paths": metadata,
142
- },
143
- ),
144
- ]
145
-
146
- def _generate_examples(self, paths, meta_paths):
147
- key = 0
148
- meta = pd.read_csv(
149
- meta_paths["identity"],
150
- sep=", "
151
  )
152
- for key,conf in [(k,v) for (k,v) in meta_paths.items() if k != "identity"]:
153
-
154
- temp = pd.read_csv(conf,sep='\t', header=None)
155
- temp.columns = ['Image_Path', key]
156
-
157
- temp['Class_ID'] = temp['Image_Path'].str.split('/').str[0]
158
- #temp['Image_Name'] = temp['Image_Path'].str.split('/').str[1]
159
-
160
- temp.drop(columns=['Image_Path'], inplace=True)
161
-
162
- meta = meta.merge(temp, on='Class_ID', how='left')
163
- for file_path, file_obj in paths:
164
-
165
- label = file_path.split("/")[2]
166
- yield file_path, {
167
- "image": {"path": file_path, "bytes": file_obj.read()},
168
- # "image_id": datasets.Value("string"),
169
- # "class_id": datasets.Value("string"),
170
- # "identity": datasets.Value("string"),
171
- # 'gender': dataset.Value("string"),
172
- # 'sample_num':dataset.Value("uint64"),
173
- # 'flag':dataset.Value("bool"),
174
- # "male": datasets.Value("bool"),
175
- # "black_hair": datasets.Value("bool"),
176
- # "gray_hair": datasets.Value("bool"),
177
- # "blond_hair": datasets.Value("bool"),
178
- # "long_hair": datasets.Value("bool"),
179
- # "mustache_or_beard": datasets.Value("bool"),
180
- # "wearing_hat": datasets.Value("bool"),
181
- # "eyeglasses": datasets.Value("bool"),
182
- # "sunglasses": datasets.Value("bool"),
183
- #"mouth_open": datasets.Value("bool")
184
- }
185
- key+= 1
186
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # Copyright 2022 The HuggingFace Datasets Authors and ProgramComputer.
2
  #
3
  # Licensed under the Apache License, Version 2.0 (the "License");
 
12
  # See the License for the specific language governing permissions and
13
  # limitations under the License.
14
 
15
+ from __future__ import annotations
 
16
 
17
+ import csv
18
+ import hashlib
19
+ import io
20
+ import math
21
  import os
22
  import re
23
+ import sqlite3
24
+ import tarfile
25
+ import tempfile
26
+ import time
27
+ import warnings
28
+ from pathlib import Path, PurePosixPath
29
+ from typing import Any, Iterable, Mapping
30
+ from urllib.parse import urlsplit
 
 
 
 
31
 
32
  import datasets
33
+ import requests
34
+ from PIL import Image as PILImage
35
+ from PIL import UnidentifiedImageError
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
+ DEFAULT_REPO_ID = "ProgramComputer/VGGFace2"
39
+ DEFAULT_REVISION = "ad5f6b5a5f560621fd7efb9b79c956d27d427a08"
40
+ OXFORD_METADATA_REVISION = "921df0a400f599d0b1a201fbfbb9117e6d794e0d"
41
 
42
+ DEFAULT_CONNECT_TIMEOUT = 10.0
43
+ DEFAULT_READ_TIMEOUT = 60.0
44
+ DEFAULT_MAX_RETRIES = 3
45
+ DEFAULT_BACKOFF_SECONDS = 0.5
46
+ DEFAULT_MAX_METADATA_BYTES = 16 * 1024 * 1024
47
+ DEFAULT_MAX_METADATA_ENTRIES = 500_000
48
+ DEFAULT_MAX_IMAGE_BYTES = 64 * 1024 * 1024
49
+ DEFAULT_MAX_IMAGE_PIXELS = 4096 * 4096
50
+ DEFAULT_MAX_SCRATCH_BYTES = 512 * 1024 * 1024
51
 
52
+ _ATTRIBUTE_FILES = {
53
+ "male": "01-Male.txt",
54
+ "black_hair": "02-Black_Hair.txt",
55
+ "brown_hair": "03-Brown_Hair.txt",
56
+ "gray_hair": "04-Gray_Hair.txt",
57
+ "blond_hair": "05-Blond_Hair.txt",
58
+ "long_hair": "06-Long_Hair.txt",
59
+ "mustache_or_beard": "07-Mustache_or_Beard.txt",
60
+ "wearing_hat": "08-Wearing_Hat.txt",
61
+ "eyeglasses": "09-Eyeglasses.txt",
62
+ "sunglasses": "10-Sunglasses.txt",
63
+ "mouth_open": "11-Mouth_Open.txt",
64
  }
65
+ _ATTRIBUTE_NAMES = tuple(_ATTRIBUTE_FILES)
66
+ _IMAGE_SUFFIXES = {".bmp", ".jpeg", ".jpg", ".png", ".webp"}
67
+ _CLASS_ID_PATTERN = re.compile(r"n\d{6}")
68
+ _IMAGE_ID_PATTERN = re.compile(r"\d{4}_\d{2}")
69
+ _FILENAME_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
70
+ _RETRYABLE_STATUS_CODES = {408, 429, 500, 502, 503, 504}
71
+
72
+ FEATURES = datasets.Features(
73
+ {
74
+ "image": datasets.Image(decode=False),
75
+ "image_key": datasets.Value("string"),
76
+ "filename": datasets.Value("string"),
77
+ "image_id": datasets.Value("string"),
78
+ "class_id": datasets.Value("string"),
79
+ "identity": datasets.Value("string"),
80
+ "split": datasets.Value("string"),
81
+ "gender": datasets.Value("string"),
82
+ "sample_num": datasets.Value("uint64"),
83
+ "flag": datasets.Value("bool"),
84
+ "male": datasets.Value("bool"),
85
+ "black_hair": datasets.Value("bool"),
86
+ "brown_hair": datasets.Value("bool"),
87
+ "gray_hair": datasets.Value("bool"),
88
+ "blond_hair": datasets.Value("bool"),
89
+ "long_hair": datasets.Value("bool"),
90
+ "mustache_or_beard": datasets.Value("bool"),
91
+ "wearing_hat": datasets.Value("bool"),
92
+ "eyeglasses": datasets.Value("bool"),
93
+ "sunglasses": datasets.Value("bool"),
94
+ "mouth_open": datasets.Value("bool"),
95
+ }
96
+ )
97
+
98
+
99
+ def _positive_number(value: float, name: str) -> float:
100
+ number = float(value)
101
+ if not math.isfinite(number) or number <= 0:
102
+ raise ValueError(f"{name} must be finite and positive")
103
+ return number
104
+
105
+
106
+ def _positive_integer(value: int, name: str) -> int:
107
+ number = int(value)
108
+ if number <= 0:
109
+ raise ValueError(f"{name} must be positive")
110
+ return number
111
+
112
+
113
+ def _default_cache_dir() -> Path:
114
+ hf_home = os.environ.get("HF_HOME")
115
+ root = Path(hf_home).expanduser() if hf_home else Path.home() / ".cache" / "huggingface"
116
+ return root / "vggface2-streaming"
117
+
118
+
119
+ def _parse_boolean(value: str, source: str) -> bool:
120
+ normalized = value.strip().lower()
121
+ if normalized in {"1", "true"}:
122
+ return True
123
+ if normalized in {"0", "false"}:
124
+ return False
125
+ raise ValueError(f"Expected a boolean value in {source}, got {value!r}")
126
+
127
+
128
+ def _parse_image_path(value: str, source: str) -> tuple[str, str, str, str]:
129
+ if not value or value.startswith(("/", "\\")) or "\\" in value:
130
+ raise ValueError(f"Malformed image path in {source}: {value!r}")
131
+ parts = value.split("/")
132
+ if len(parts) < 2 or any(
133
+ part in {"", ".", ".."} or _FILENAME_PATTERN.fullmatch(part) is None
134
+ for part in parts
135
+ ):
136
+ raise ValueError(f"Malformed image path in {source}: {value!r}")
137
+
138
+ class_id, filename = parts[-2:]
139
+ if _CLASS_ID_PATTERN.fullmatch(class_id) is None:
140
+ raise ValueError(
141
+ f"Malformed image path in {source}: expected nNNNNNN/filename, got {value!r}"
142
+ )
143
+ if _FILENAME_PATTERN.fullmatch(filename) is None:
144
+ raise ValueError(f"Malformed image filename in {source}: {filename!r}")
145
 
146
+ suffix = Path(filename).suffix.lower()
147
+ if suffix not in _IMAGE_SUFFIXES:
148
+ raise ValueError(f"Unsupported image suffix in {source}: {filename!r}")
149
+ image_id = filename[: -len(suffix)]
150
+ if _IMAGE_ID_PATTERN.fullmatch(image_id) is None:
151
+ raise ValueError(f"Malformed image filename in {source}: {filename!r}")
152
+ return class_id, filename, image_id, f"{class_id}/{image_id}"
153
 
154
 
155
+ def _is_image_path(value: str) -> bool:
156
+ return Path(PurePosixPath(value).name).suffix.lower() in _IMAGE_SUFFIXES
157
 
 
158
 
159
+ class VGGFace2:
160
+ """Stream VGGFace2 records without extracting or caching either archive."""
161
+
162
+ features = FEATURES
163
+
164
+ def __init__(
165
+ self,
166
+ *,
167
+ repo_id: str = DEFAULT_REPO_ID,
168
+ revision: str = DEFAULT_REVISION,
169
+ token: str | None = None,
170
+ cache_dir: str | Path | None = None,
171
+ scratch_dir: str | Path | None = None,
172
+ connect_timeout: float = DEFAULT_CONNECT_TIMEOUT,
173
+ read_timeout: float = DEFAULT_READ_TIMEOUT,
174
+ max_retries: int = DEFAULT_MAX_RETRIES,
175
+ backoff_seconds: float = DEFAULT_BACKOFF_SECONDS,
176
+ max_metadata_bytes: int = DEFAULT_MAX_METADATA_BYTES,
177
+ max_metadata_entries: int = DEFAULT_MAX_METADATA_ENTRIES,
178
+ max_image_bytes: int = DEFAULT_MAX_IMAGE_BYTES,
179
+ max_image_pixels: int = DEFAULT_MAX_IMAGE_PIXELS,
180
+ max_scratch_bytes: int = DEFAULT_MAX_SCRATCH_BYTES,
181
+ archive_urls: Mapping[str, str] | None = None,
182
+ identity_url: str | None = None,
183
+ attribute_urls: Mapping[str, str] | None = None,
184
+ ) -> None:
185
+ if not str(repo_id).strip():
186
+ raise ValueError("repo_id must not be empty")
187
+ if re.fullmatch(r"[0-9a-f]{40}", str(revision)) is None:
188
+ raise ValueError("revision must be a 40-character lowercase commit SHA")
189
+ if not 0 <= int(max_retries) <= 10:
190
+ raise ValueError("max_retries must be between 0 and 10")
191
+ if not math.isfinite(float(backoff_seconds)) or float(backoff_seconds) < 0:
192
+ raise ValueError("backoff_seconds must be finite and non-negative")
193
+
194
+ self.repo_id = str(repo_id)
195
+ self.revision = str(revision)
196
+ self.token = token
197
+ self.cache_dir = Path(cache_dir).expanduser() if cache_dir else _default_cache_dir()
198
+ self.scratch_dir = (
199
+ Path(scratch_dir).expanduser() if scratch_dir else Path(tempfile.gettempdir())
200
+ )
201
+ self.connect_timeout = _positive_number(connect_timeout, "connect_timeout")
202
+ self.read_timeout = _positive_number(read_timeout, "read_timeout")
203
+ self.max_retries = int(max_retries)
204
+ self.backoff_seconds = float(backoff_seconds)
205
+ self.max_metadata_bytes = _positive_integer(
206
+ max_metadata_bytes, "max_metadata_bytes"
207
+ )
208
+ self.max_metadata_entries = _positive_integer(
209
+ max_metadata_entries, "max_metadata_entries"
210
  )
211
+ self.max_image_bytes = _positive_integer(max_image_bytes, "max_image_bytes")
212
+ self.max_image_pixels = _positive_integer(max_image_pixels, "max_image_pixels")
213
+ self.max_scratch_bytes = _positive_integer(
214
+ max_scratch_bytes, "max_scratch_bytes"
215
+ )
216
+
217
+ default_archives = {
218
+ split: (
219
+ f"https://huggingface.co/datasets/{self.repo_id}/resolve/"
220
+ f"{self.revision}/data/vggface2_{split}.tar.gz"
221
+ )
222
+ for split in ("train", "test")
 
 
 
 
 
 
 
 
 
223
  }
224
+ self.archive_urls = dict(archive_urls or default_archives)
225
+ if set(self.archive_urls) != {"train", "test"}:
226
+ raise ValueError("archive_urls must contain exactly train and test")
227
 
228
+ self.identity_url = identity_url or (
229
+ f"https://huggingface.co/datasets/{self.repo_id}/resolve/"
230
+ f"{self.revision}/meta/identity_meta.csv"
 
 
231
  )
232
+ default_attributes = {
233
+ name: (
234
+ "https://raw.githubusercontent.com/ox-vgg/vgg_face2/"
235
+ f"{OXFORD_METADATA_REVISION}/attributes/{filename}"
236
+ )
237
+ for name, filename in _ATTRIBUTE_FILES.items()
238
+ }
239
+ self.attribute_urls = dict(attribute_urls or default_attributes)
240
+ if set(self.attribute_urls) != set(_ATTRIBUTE_NAMES):
241
+ raise ValueError("attribute_urls must contain all eleven Oxford attributes")
242
 
243
+ def _session(self) -> requests.Session:
244
+ session = requests.Session()
245
+ session.headers.update(
246
+ {
247
+ "Accept-Encoding": "identity",
248
+ "User-Agent": "ProgramComputer-VGGFace2-bounded-streaming/2",
249
+ }
250
  )
251
+ return session
252
+
253
+ def _open_response(
254
+ self,
255
+ session: requests.Session,
256
+ url: str,
257
+ ) -> requests.Response:
258
+ attempts = self.max_retries + 1
259
+ last_error: Exception | None = None
260
+ for attempt in range(attempts):
261
+ response: requests.Response | None = None
262
+ try:
263
+ hostname = (urlsplit(url).hostname or "").lower()
264
+ headers = None
265
+ if self.token and (
266
+ hostname == "huggingface.co" or hostname.endswith(".huggingface.co")
267
+ ):
268
+ headers = {"Authorization": f"Bearer {self.token}"}
269
+ response = session.get(
270
+ url,
271
+ headers=headers,
272
+ stream=True,
273
+ timeout=(self.connect_timeout, self.read_timeout),
274
  )
275
+ if response.status_code in _RETRYABLE_STATUS_CODES:
276
+ response.close()
277
+ raise requests.HTTPError(
278
+ f"HTTP {response.status_code}", response=response
279
+ )
280
+ response.raise_for_status()
281
+ return response
282
+ except requests.RequestException as exc:
283
+ last_error = exc
284
+ if response is not None:
285
+ response.close()
286
+ if attempt + 1 >= attempts:
287
+ break
288
+ delay = min(30.0, self.backoff_seconds * (2**attempt))
289
+ if delay:
290
+ time.sleep(delay)
291
+ raise RuntimeError(f"Unable to open {url} after {attempts} attempts") from last_error
292
+
293
+ def _metadata_cache_path(self, label: str, url: str) -> Path:
294
+ digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:20]
295
+ suffix = Path(PurePosixPath(url.split("?", 1)[0]).name).suffix or ".metadata"
296
+ return self.cache_dir / f"{label}-{digest}{suffix}"
297
+
298
+ def _cached_metadata(
299
+ self,
300
+ session: requests.Session,
301
+ label: str,
302
+ url: str,
303
+ remaining_bytes: int,
304
+ ) -> Path:
305
+ target = self._metadata_cache_path(label, url)
306
+ if target.is_file():
307
+ size = target.stat().st_size
308
+ if size <= 0:
309
+ raise ValueError(f"Cached metadata file is empty: {target}")
310
+ if size > remaining_bytes:
311
+ raise ValueError(
312
+ f"Metadata exceeds max_metadata_bytes while reading {label}: {size} bytes"
313
+ )
314
+ return target
315
+
316
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
317
+ response = self._open_response(session, url)
318
+ content_length = response.headers.get("Content-Length")
319
+ if content_length is not None:
320
+ try:
321
+ announced_size = int(content_length)
322
+ except ValueError as exc:
323
+ response.close()
324
+ raise ValueError(f"Invalid Content-Length for {label}: {content_length!r}") from exc
325
+ if announced_size > remaining_bytes:
326
+ response.close()
327
+ raise ValueError(
328
+ f"Metadata exceeds max_metadata_bytes while reading {label}: "
329
+ f"{announced_size} bytes"
330
+ )
331
+
332
+ handle = tempfile.NamedTemporaryFile(
333
+ mode="wb",
334
+ prefix=f"{target.name}.",
335
+ suffix=".partial",
336
+ dir=self.cache_dir,
337
+ delete=False,
338
  )
339
+ partial = Path(handle.name)
340
+ total = 0
341
+ try:
342
+ with handle, response:
343
+ for chunk in response.iter_content(chunk_size=64 * 1024):
344
+ if not chunk:
345
+ continue
346
+ total += len(chunk)
347
+ if total > remaining_bytes:
348
+ raise ValueError(
349
+ f"Metadata exceeds max_metadata_bytes while reading {label}: "
350
+ f"more than {remaining_bytes} bytes"
351
+ )
352
+ handle.write(chunk)
353
+ handle.flush()
354
+ os.fsync(handle.fileno())
355
+ if total <= 0:
356
+ raise ValueError(f"Downloaded metadata file is empty: {label}")
357
+ os.replace(partial, target)
358
+ except Exception:
359
+ partial.unlink(missing_ok=True)
360
+ raise
361
+ return target
362
 
363
+ def _metadata_paths(self, session: requests.Session) -> dict[str, Path]:
364
+ sources = [("identity", self.identity_url), *self.attribute_urls.items()]
365
+ paths: dict[str, Path] = {}
366
+ used_bytes = 0
367
+ for label, url in sources:
368
+ path = self._cached_metadata(
369
+ session,
370
+ label,
371
+ url,
372
+ remaining_bytes=self.max_metadata_bytes - used_bytes,
373
+ )
374
+ used_bytes += path.stat().st_size
375
+ if used_bytes > self.max_metadata_bytes:
376
+ raise ValueError(
377
+ f"Metadata exceeds max_metadata_bytes: {used_bytes} bytes"
378
+ )
379
+ paths[label] = path
380
+ return paths
381
+
382
+ def _connect_registry(self, database_path: Path) -> sqlite3.Connection:
383
+ connection = sqlite3.connect(database_path)
384
+ connection.execute("PRAGMA journal_mode = OFF")
385
+ connection.execute("PRAGMA synchronous = OFF")
386
+ connection.execute("PRAGMA temp_store = MEMORY")
387
+ connection.execute("PRAGMA cache_size = -4096")
388
+ page_size = int(connection.execute("PRAGMA page_size").fetchone()[0])
389
+ max_pages = max(1, self.max_scratch_bytes // page_size)
390
+ connection.execute(f"PRAGMA max_page_count = {max_pages}")
391
+ connection.execute(
392
+ """
393
+ CREATE TABLE identities (
394
+ class_id TEXT PRIMARY KEY,
395
+ identity TEXT NOT NULL,
396
+ sample_num TEXT NOT NULL,
397
+ flag INTEGER NOT NULL,
398
+ gender TEXT NOT NULL
399
+ ) WITHOUT ROWID
400
+ """
401
+ )
402
+ attribute_columns = ", ".join(f"{name} INTEGER" for name in _ATTRIBUTE_NAMES)
403
+ connection.execute(
404
+ f"CREATE TABLE attributes (image_key TEXT PRIMARY KEY, {attribute_columns}) "
405
+ "WITHOUT ROWID"
406
+ )
407
+ connection.execute(
408
+ "CREATE TABLE seen_images (image_key TEXT PRIMARY KEY) WITHOUT ROWID"
409
  )
410
+ return connection
411
+
412
+ def _check_scratch(self, database_path: Path) -> None:
413
+ size = database_path.stat().st_size if database_path.exists() else 0
414
+ if size > self.max_scratch_bytes:
415
+ raise RuntimeError(
416
+ f"Scratch usage exceeds max_scratch_bytes: {size} > {self.max_scratch_bytes}"
417
+ )
418
+
419
+ def _load_identity_metadata(
420
+ self,
421
+ connection: sqlite3.Connection,
422
+ path: Path,
423
+ entry_count: int,
424
+ ) -> int:
425
+ with path.open("r", encoding="utf-8-sig", newline="") as handle:
426
+ reader = csv.reader(handle, skipinitialspace=True)
427
+ try:
428
+ header = [value.strip() for value in next(reader)]
429
+ except StopIteration as exc:
430
+ raise ValueError(f"Identity metadata is empty: {path}") from exc
431
+ expected = ["Class_ID", "Name", "Sample_Num", "Flag", "Gender"]
432
+ if header != expected:
433
+ raise ValueError(f"Unexpected identity metadata header in {path}: {header}")
434
+
435
+ for line_number, row in enumerate(reader, start=2):
436
+ if not row or all(not value.strip() for value in row):
437
+ continue
438
+ entry_count += 1
439
+ if entry_count > self.max_metadata_entries:
440
+ raise ValueError(
441
+ f"Metadata exceeds max_metadata_entries: {entry_count}"
442
+ )
443
+ if len(row) != 5:
444
+ raise ValueError(
445
+ f"Malformed identity metadata row {line_number} in {path}: {row!r}"
446
+ )
447
+ class_id, identity, sample_value, flag_value, gender = (
448
+ value.strip() for value in row
449
+ )
450
+ if _CLASS_ID_PATTERN.fullmatch(class_id) is None:
451
+ raise ValueError(
452
+ f"Malformed class ID at row {line_number} in {path}: {class_id!r}"
453
+ )
454
+ if not identity:
455
+ raise ValueError(f"Identity is empty at row {line_number} in {path}")
456
+ try:
457
+ sample_num = int(sample_value)
458
+ except ValueError as exc:
459
+ raise ValueError(
460
+ f"Invalid sample count at row {line_number} in {path}: {sample_value!r}"
461
+ ) from exc
462
+ if not 0 <= sample_num < 2**64:
463
+ raise ValueError(
464
+ f"Invalid sample count at row {line_number} in {path}: {sample_value!r}"
465
+ )
466
+ flag = _parse_boolean(flag_value, f"row {line_number} of {path}")
467
+ gender = gender.lower()
468
+ if gender not in {"f", "m"}:
469
+ raise ValueError(
470
+ f"Invalid gender at row {line_number} in {path}: {gender!r}"
471
+ )
472
+ try:
473
+ connection.execute(
474
+ "INSERT INTO identities VALUES (?, ?, ?, ?, ?)",
475
+ (class_id, identity, str(sample_num), int(flag), gender),
476
+ )
477
+ except sqlite3.IntegrityError as exc:
478
+ raise ValueError(f"Duplicate identity metadata key: {class_id}") from exc
479
+ connection.commit()
480
+ return entry_count
481
+
482
+ def _load_attribute_metadata(
483
+ self,
484
+ connection: sqlite3.Connection,
485
+ name: str,
486
+ path: Path,
487
+ entry_count: int,
488
+ ) -> int:
489
+ with path.open("r", encoding="utf-8-sig", newline="") as handle:
490
+ for line_number, line in enumerate(handle, start=1):
491
+ value = line.strip()
492
+ if not value:
493
+ continue
494
+ entry_count += 1
495
+ if entry_count > self.max_metadata_entries:
496
+ raise ValueError(
497
+ f"Metadata exceeds max_metadata_entries: {entry_count}"
498
+ )
499
+ parts = value.split("\t")
500
+ if len(parts) != 2:
501
+ raise ValueError(
502
+ f"Malformed {name} row {line_number} in {path}: {value!r}"
503
+ )
504
+ image_path, attribute_value = (part.strip() for part in parts)
505
+ _, _, _, image_key = _parse_image_path(
506
+ image_path, f"row {line_number} of {path}"
507
+ )
508
+ parsed_value = int(
509
+ _parse_boolean(attribute_value, f"row {line_number} of {path}")
510
+ )
511
+ existing = connection.execute(
512
+ f"SELECT {name} FROM attributes WHERE image_key = ?", (image_key,)
513
+ ).fetchone()
514
+ if existing is not None and existing[0] is not None:
515
+ raise ValueError(f"Duplicate {name} metadata key: {image_key}")
516
+ if existing is None:
517
+ connection.execute(
518
+ f"INSERT INTO attributes (image_key, {name}) VALUES (?, ?)",
519
+ (image_key, parsed_value),
520
+ )
521
+ else:
522
+ connection.execute(
523
+ f"UPDATE attributes SET {name} = ? WHERE image_key = ?",
524
+ (parsed_value, image_key),
525
+ )
526
+ connection.commit()
527
+ return entry_count
528
+
529
+ def _build_metadata_registry(
530
+ self,
531
+ connection: sqlite3.Connection,
532
+ metadata_paths: Mapping[str, Path],
533
+ database_path: Path,
534
+ ) -> None:
535
+ entry_count = self._load_identity_metadata(
536
+ connection, metadata_paths["identity"], entry_count=0
537
  )
538
+ self._check_scratch(database_path)
539
+ for name in _ATTRIBUTE_NAMES:
540
+ entry_count = self._load_attribute_metadata(
541
+ connection,
542
+ name,
543
+ metadata_paths[name],
544
+ entry_count=entry_count,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
545
  )
546
+ self._check_scratch(database_path)
547
+
548
+ def _read_image(self, member: tarfile.TarInfo, archive: tarfile.TarFile) -> bytes:
549
+ if member.size <= 0:
550
+ raise ValueError(f"Image is empty in archive: {member.name}")
551
+ if member.size > self.max_image_bytes:
552
+ raise ValueError(
553
+ f"Image exceeds max_image_bytes in archive: {member.name} "
554
+ f"({member.size} > {self.max_image_bytes})"
555
+ )
556
+ extracted = archive.extractfile(member)
557
+ if extracted is None:
558
+ raise ValueError(f"Unable to read image from archive: {member.name}")
559
+ try:
560
+ data = extracted.read(self.max_image_bytes + 1)
561
+ finally:
562
+ extracted.close()
563
+ if len(data) != member.size:
564
+ raise ValueError(
565
+ f"Truncated image in archive: {member.name} "
566
+ f"({len(data)} of {member.size} bytes)"
567
+ )
568
+ if len(data) > self.max_image_bytes:
569
+ raise ValueError(f"Image exceeds max_image_bytes in archive: {member.name}")
570
+
571
+ try:
572
+ with warnings.catch_warnings():
573
+ warnings.simplefilter("error", PILImage.DecompressionBombWarning)
574
+ with PILImage.open(io.BytesIO(data)) as image:
575
+ width, height = image.size
576
+ if width <= 0 or height <= 0 or width * height > self.max_image_pixels:
577
+ raise ValueError(
578
+ f"Image dimensions exceed max_image_pixels in archive: "
579
+ f"{member.name} ({width}x{height})"
580
+ )
581
+ image.verify()
582
+ except ValueError:
583
+ raise
584
+ except (
585
+ OSError,
586
+ UnidentifiedImageError,
587
+ PILImage.DecompressionBombError,
588
+ PILImage.DecompressionBombWarning,
589
+ ) as exc:
590
+ raise ValueError(f"Corrupt image in archive: {member.name}") from exc
591
+ return data
592
+
593
+ def _record(
594
+ self,
595
+ connection: sqlite3.Connection,
596
+ split: str,
597
+ class_id: str,
598
+ filename: str,
599
+ image_id: str,
600
+ image_key: str,
601
+ image_bytes: bytes,
602
+ ) -> dict[str, Any]:
603
+ identity = connection.execute(
604
+ "SELECT identity, sample_num, flag, gender FROM identities WHERE class_id = ?",
605
+ (class_id,),
606
+ ).fetchone()
607
+ if identity is None:
608
+ raise ValueError(f"Identity metadata is missing for image key: {image_key}")
609
+ attributes = connection.execute(
610
+ f"SELECT {', '.join(_ATTRIBUTE_NAMES)} FROM attributes WHERE image_key = ?",
611
+ (image_key,),
612
+ ).fetchone()
613
+ attribute_values = attributes or (None,) * len(_ATTRIBUTE_NAMES)
614
+
615
+ record: dict[str, Any] = {
616
+ "image": {"path": f"{class_id}/{filename}", "bytes": image_bytes},
617
+ "image_key": image_key,
618
+ "filename": filename,
619
+ "image_id": image_id,
620
+ "class_id": class_id,
621
+ "identity": str(identity[0]),
622
+ "split": split,
623
+ "gender": str(identity[3]),
624
+ "sample_num": int(identity[1]),
625
+ "flag": bool(identity[2]),
626
+ }
627
+ record.update(
628
+ {
629
+ name: None if value is None else bool(value)
630
+ for name, value in zip(_ATTRIBUTE_NAMES, attribute_values)
631
+ }
632
+ )
633
+ return record
634
+
635
+ def _iter_archive(
636
+ self,
637
+ session: requests.Session,
638
+ split: str,
639
+ connection: sqlite3.Connection,
640
+ database_path: Path,
641
+ ) -> Iterable[dict[str, Any]]:
642
+ response = self._open_response(session, self.archive_urls[split])
643
+ archive: tarfile.TarFile | None = None
644
+ yielded = 0
645
+ try:
646
+ response.raw.decode_content = False
647
+ archive = tarfile.open(fileobj=response.raw, mode="r|gz")
648
+ for member in archive:
649
+ if member.name.startswith(("/", "\\")) or "\\" in member.name:
650
+ raise ValueError(f"Malformed archive member path: {member.name!r}")
651
+ checked_name = (
652
+ member.name[:-1]
653
+ if member.isdir() and member.name.endswith("/")
654
+ else member.name
655
+ )
656
+ path_parts = checked_name.split("/")
657
+ if any(part in {"", ".", ".."} for part in path_parts):
658
+ raise ValueError(f"Malformed archive member path: {member.name!r}")
659
+ if member.isdir():
660
+ continue
661
+ if not member.isfile():
662
+ raise ValueError(f"Unsupported archive member type: {member.name!r}")
663
+ if not _is_image_path(member.name):
664
+ continue
665
+
666
+ class_id, filename, image_id, image_key = _parse_image_path(
667
+ member.name, "VGGFace2 archive"
668
+ )
669
+ try:
670
+ connection.execute(
671
+ "INSERT INTO seen_images VALUES (?)", (image_key,)
672
+ )
673
+ except sqlite3.IntegrityError as exc:
674
+ raise ValueError(f"Duplicate canonical image key: {image_key}") from exc
675
+ except sqlite3.OperationalError as exc:
676
+ if "full" not in str(exc).lower():
677
+ raise
678
+ raise RuntimeError(
679
+ "Scratch registry reached max_scratch_bytes"
680
+ ) from exc
681
+ if yielded % 1024 == 0:
682
+ try:
683
+ connection.commit()
684
+ except sqlite3.OperationalError as exc:
685
+ raise RuntimeError(
686
+ "Scratch registry reached max_scratch_bytes"
687
+ ) from exc
688
+ self._check_scratch(database_path)
689
+
690
+ image_bytes = self._read_image(member, archive)
691
+ yield self._record(
692
+ connection,
693
+ split,
694
+ class_id,
695
+ filename,
696
+ image_id,
697
+ image_key,
698
+ image_bytes,
699
+ )
700
+ yielded += 1
701
+ try:
702
+ connection.commit()
703
+ except sqlite3.OperationalError as exc:
704
+ raise RuntimeError("Scratch registry reached max_scratch_bytes") from exc
705
+ self._check_scratch(database_path)
706
+ except tarfile.TarError as exc:
707
+ raise RuntimeError(f"Unable to stream {split} tar archive") from exc
708
+ finally:
709
+ if archive is not None:
710
+ archive.close()
711
+ response.close()
712
+
713
+ def iter_split(self, split: str) -> Iterable[dict[str, Any]]:
714
+ """Iterate one pinned source archive in its original member order."""
715
+ normalized_split = str(split)
716
+ if normalized_split not in {"train", "test"}:
717
+ raise ValueError("split must be train or test")
718
+
719
+ self.scratch_dir.mkdir(parents=True, exist_ok=True)
720
+ with tempfile.TemporaryDirectory(
721
+ prefix="vggface2-stream-", dir=self.scratch_dir
722
+ ) as temporary:
723
+ database_path = Path(temporary) / "registry.sqlite3"
724
+ connection: sqlite3.Connection | None = None
725
+ with self._session() as session:
726
+ try:
727
+ metadata_paths = self._metadata_paths(session)
728
+ connection = self._connect_registry(database_path)
729
+ self._build_metadata_registry(
730
+ connection, metadata_paths, database_path
731
+ )
732
+ yield from self._iter_archive(
733
+ session,
734
+ normalized_split,
735
+ connection,
736
+ database_path,
737
+ )
738
+ finally:
739
+ if connection is not None:
740
+ connection.close()
741
+
742
+ def as_dataset(self, split: str) -> datasets.IterableDataset:
743
+ """Return the supported Hugging Face streaming entry point."""
744
+ normalized_split = str(split)
745
+ if normalized_split not in {"train", "test"}:
746
+ raise ValueError("split must be train or test")
747
+ return datasets.IterableDataset.from_generator(
748
+ _iter_loader,
749
+ features=self.features,
750
+ gen_kwargs={"loader": self, "split": normalized_split},
751
+ split=normalized_split,
752
+ )
753
+
754
+
755
+ def _iter_loader(loader: VGGFace2, split: str) -> Iterable[dict[str, Any]]:
756
+ yield from loader.iter_split(split)
757
+
758
+
759
+ def load_streaming(split: str, **loader_kwargs: Any) -> datasets.IterableDataset:
760
+ """Load a bounded project-side stream from the pinned VGGFace2 revision."""
761
+ return VGGFace2(**loader_kwargs).as_dataset(split)