Datasets:

ArXiv:
DOI:
License:
File size: 30,866 Bytes
c1dbdc6
 
 
 
 
 
 
 
 
 
 
 
 
 
e88b15e
c1dbdc6
e88b15e
 
 
 
c1dbdc6
 
e88b15e
 
 
 
 
 
 
 
c1dbdc6
 
e88b15e
 
 
c1dbdc6
 
e88b15e
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
 
 
 
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
c1dbdc6
 
e88b15e
 
c1dbdc6
 
e88b15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
 
 
 
 
 
c1dbdc6
e88b15e
 
 
c1dbdc6
e88b15e
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
 
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
c1dbdc6
e88b15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
# Copyright 2022 The HuggingFace Datasets Authors and ProgramComputer.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import csv
import hashlib
import io
import math
import os
import re
import sqlite3
import tarfile
import tempfile
import time
import warnings
from pathlib import Path, PurePosixPath
from typing import Any, Iterable, Mapping
from urllib.parse import urlsplit

import datasets
import requests
from PIL import Image as PILImage
from PIL import UnidentifiedImageError


DEFAULT_REPO_ID = "ProgramComputer/VGGFace2"
DEFAULT_REVISION = "ad5f6b5a5f560621fd7efb9b79c956d27d427a08"
OXFORD_METADATA_REVISION = "921df0a400f599d0b1a201fbfbb9117e6d794e0d"

DEFAULT_CONNECT_TIMEOUT = 10.0
DEFAULT_READ_TIMEOUT = 60.0
DEFAULT_MAX_RETRIES = 3
DEFAULT_BACKOFF_SECONDS = 0.5
DEFAULT_MAX_METADATA_BYTES = 16 * 1024 * 1024
DEFAULT_MAX_METADATA_ENTRIES = 500_000
DEFAULT_MAX_IMAGE_BYTES = 64 * 1024 * 1024
DEFAULT_MAX_IMAGE_PIXELS = 4096 * 4096
DEFAULT_MAX_SCRATCH_BYTES = 512 * 1024 * 1024

_ATTRIBUTE_FILES = {
    "male": "01-Male.txt",
    "black_hair": "02-Black_Hair.txt",
    "brown_hair": "03-Brown_Hair.txt",
    "gray_hair": "04-Gray_Hair.txt",
    "blond_hair": "05-Blond_Hair.txt",
    "long_hair": "06-Long_Hair.txt",
    "mustache_or_beard": "07-Mustache_or_Beard.txt",
    "wearing_hat": "08-Wearing_Hat.txt",
    "eyeglasses": "09-Eyeglasses.txt",
    "sunglasses": "10-Sunglasses.txt",
    "mouth_open": "11-Mouth_Open.txt",
}
_ATTRIBUTE_NAMES = tuple(_ATTRIBUTE_FILES)
_IMAGE_SUFFIXES = {".bmp", ".jpeg", ".jpg", ".png", ".webp"}
_CLASS_ID_PATTERN = re.compile(r"n\d{6}")
_IMAGE_ID_PATTERN = re.compile(r"\d{4}_\d{2}")
_FILENAME_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
_RETRYABLE_STATUS_CODES = {408, 429, 500, 502, 503, 504}

FEATURES = datasets.Features(
    {
        "image": datasets.Image(decode=False),
        "image_key": datasets.Value("string"),
        "filename": datasets.Value("string"),
        "image_id": datasets.Value("string"),
        "class_id": datasets.Value("string"),
        "identity": datasets.Value("string"),
        "split": datasets.Value("string"),
        "gender": datasets.Value("string"),
        "sample_num": datasets.Value("uint64"),
        "flag": datasets.Value("bool"),
        "male": datasets.Value("bool"),
        "black_hair": datasets.Value("bool"),
        "brown_hair": datasets.Value("bool"),
        "gray_hair": datasets.Value("bool"),
        "blond_hair": datasets.Value("bool"),
        "long_hair": datasets.Value("bool"),
        "mustache_or_beard": datasets.Value("bool"),
        "wearing_hat": datasets.Value("bool"),
        "eyeglasses": datasets.Value("bool"),
        "sunglasses": datasets.Value("bool"),
        "mouth_open": datasets.Value("bool"),
    }
)


def _positive_number(value: float, name: str) -> float:
    number = float(value)
    if not math.isfinite(number) or number <= 0:
        raise ValueError(f"{name} must be finite and positive")
    return number


def _positive_integer(value: int, name: str) -> int:
    number = int(value)
    if number <= 0:
        raise ValueError(f"{name} must be positive")
    return number


def _default_cache_dir() -> Path:
    hf_home = os.environ.get("HF_HOME")
    root = Path(hf_home).expanduser() if hf_home else Path.home() / ".cache" / "huggingface"
    return root / "vggface2-streaming"


def _parse_boolean(value: str, source: str) -> bool:
    normalized = value.strip().lower()
    if normalized in {"1", "true"}:
        return True
    if normalized in {"0", "false"}:
        return False
    raise ValueError(f"Expected a boolean value in {source}, got {value!r}")


def _parse_image_path(value: str, source: str) -> tuple[str, str, str, str]:
    if not value or value.startswith(("/", "\\")) or "\\" in value:
        raise ValueError(f"Malformed image path in {source}: {value!r}")
    parts = value.split("/")
    if len(parts) < 2 or any(
        part in {"", ".", ".."} or _FILENAME_PATTERN.fullmatch(part) is None
        for part in parts
    ):
        raise ValueError(f"Malformed image path in {source}: {value!r}")

    class_id, filename = parts[-2:]
    if _CLASS_ID_PATTERN.fullmatch(class_id) is None:
        raise ValueError(
            f"Malformed image path in {source}: expected nNNNNNN/filename, got {value!r}"
        )
    if _FILENAME_PATTERN.fullmatch(filename) is None:
        raise ValueError(f"Malformed image filename in {source}: {filename!r}")

    suffix = Path(filename).suffix.lower()
    if suffix not in _IMAGE_SUFFIXES:
        raise ValueError(f"Unsupported image suffix in {source}: {filename!r}")
    image_id = filename[: -len(suffix)]
    if _IMAGE_ID_PATTERN.fullmatch(image_id) is None:
        raise ValueError(f"Malformed image filename in {source}: {filename!r}")
    return class_id, filename, image_id, f"{class_id}/{image_id}"


def _is_image_path(value: str) -> bool:
    return Path(PurePosixPath(value).name).suffix.lower() in _IMAGE_SUFFIXES


class VGGFace2:
    """Stream VGGFace2 records without extracting or caching either archive."""

    features = FEATURES

    def __init__(
        self,
        *,
        repo_id: str = DEFAULT_REPO_ID,
        revision: str = DEFAULT_REVISION,
        token: str | None = None,
        cache_dir: str | Path | None = None,
        scratch_dir: str | Path | None = None,
        connect_timeout: float = DEFAULT_CONNECT_TIMEOUT,
        read_timeout: float = DEFAULT_READ_TIMEOUT,
        max_retries: int = DEFAULT_MAX_RETRIES,
        backoff_seconds: float = DEFAULT_BACKOFF_SECONDS,
        max_metadata_bytes: int = DEFAULT_MAX_METADATA_BYTES,
        max_metadata_entries: int = DEFAULT_MAX_METADATA_ENTRIES,
        max_image_bytes: int = DEFAULT_MAX_IMAGE_BYTES,
        max_image_pixels: int = DEFAULT_MAX_IMAGE_PIXELS,
        max_scratch_bytes: int = DEFAULT_MAX_SCRATCH_BYTES,
        archive_urls: Mapping[str, str] | None = None,
        identity_url: str | None = None,
        attribute_urls: Mapping[str, str] | None = None,
    ) -> None:
        if not str(repo_id).strip():
            raise ValueError("repo_id must not be empty")
        if re.fullmatch(r"[0-9a-f]{40}", str(revision)) is None:
            raise ValueError("revision must be a 40-character lowercase commit SHA")
        if not 0 <= int(max_retries) <= 10:
            raise ValueError("max_retries must be between 0 and 10")
        if not math.isfinite(float(backoff_seconds)) or float(backoff_seconds) < 0:
            raise ValueError("backoff_seconds must be finite and non-negative")

        self.repo_id = str(repo_id)
        self.revision = str(revision)
        self.token = token
        self.cache_dir = Path(cache_dir).expanduser() if cache_dir else _default_cache_dir()
        self.scratch_dir = (
            Path(scratch_dir).expanduser() if scratch_dir else Path(tempfile.gettempdir())
        )
        self.connect_timeout = _positive_number(connect_timeout, "connect_timeout")
        self.read_timeout = _positive_number(read_timeout, "read_timeout")
        self.max_retries = int(max_retries)
        self.backoff_seconds = float(backoff_seconds)
        self.max_metadata_bytes = _positive_integer(
            max_metadata_bytes, "max_metadata_bytes"
        )
        self.max_metadata_entries = _positive_integer(
            max_metadata_entries, "max_metadata_entries"
        )
        self.max_image_bytes = _positive_integer(max_image_bytes, "max_image_bytes")
        self.max_image_pixels = _positive_integer(max_image_pixels, "max_image_pixels")
        self.max_scratch_bytes = _positive_integer(
            max_scratch_bytes, "max_scratch_bytes"
        )

        default_archives = {
            split: (
                f"https://huggingface.co/datasets/{self.repo_id}/resolve/"
                f"{self.revision}/data/vggface2_{split}.tar.gz"
            )
            for split in ("train", "test")
        }
        self.archive_urls = dict(archive_urls or default_archives)
        if set(self.archive_urls) != {"train", "test"}:
            raise ValueError("archive_urls must contain exactly train and test")

        self.identity_url = identity_url or (
            f"https://huggingface.co/datasets/{self.repo_id}/resolve/"
            f"{self.revision}/meta/identity_meta.csv"
        )
        default_attributes = {
            name: (
                "https://raw.githubusercontent.com/ox-vgg/vgg_face2/"
                f"{OXFORD_METADATA_REVISION}/attributes/{filename}"
            )
            for name, filename in _ATTRIBUTE_FILES.items()
        }
        self.attribute_urls = dict(attribute_urls or default_attributes)
        if set(self.attribute_urls) != set(_ATTRIBUTE_NAMES):
            raise ValueError("attribute_urls must contain all eleven Oxford attributes")

    def _session(self) -> requests.Session:
        session = requests.Session()
        session.headers.update(
            {
                "Accept-Encoding": "identity",
                "User-Agent": "ProgramComputer-VGGFace2-bounded-streaming/2",
            }
        )
        return session

    def _open_response(
        self,
        session: requests.Session,
        url: str,
    ) -> requests.Response:
        attempts = self.max_retries + 1
        last_error: Exception | None = None
        for attempt in range(attempts):
            response: requests.Response | None = None
            try:
                hostname = (urlsplit(url).hostname or "").lower()
                headers = None
                if self.token and (
                    hostname == "huggingface.co" or hostname.endswith(".huggingface.co")
                ):
                    headers = {"Authorization": f"Bearer {self.token}"}
                response = session.get(
                    url,
                    headers=headers,
                    stream=True,
                    timeout=(self.connect_timeout, self.read_timeout),
                )
                if response.status_code in _RETRYABLE_STATUS_CODES:
                    response.close()
                    raise requests.HTTPError(
                        f"HTTP {response.status_code}", response=response
                    )
                response.raise_for_status()
                return response
            except requests.RequestException as exc:
                last_error = exc
                if response is not None:
                    response.close()
                if attempt + 1 >= attempts:
                    break
                delay = min(30.0, self.backoff_seconds * (2**attempt))
                if delay:
                    time.sleep(delay)
        raise RuntimeError(f"Unable to open {url} after {attempts} attempts") from last_error

    def _metadata_cache_path(self, label: str, url: str) -> Path:
        digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:20]
        suffix = Path(PurePosixPath(url.split("?", 1)[0]).name).suffix or ".metadata"
        return self.cache_dir / f"{label}-{digest}{suffix}"

    def _cached_metadata(
        self,
        session: requests.Session,
        label: str,
        url: str,
        remaining_bytes: int,
    ) -> Path:
        target = self._metadata_cache_path(label, url)
        if target.is_file():
            size = target.stat().st_size
            if size <= 0:
                raise ValueError(f"Cached metadata file is empty: {target}")
            if size > remaining_bytes:
                raise ValueError(
                    f"Metadata exceeds max_metadata_bytes while reading {label}: {size} bytes"
                )
            return target

        self.cache_dir.mkdir(parents=True, exist_ok=True)
        response = self._open_response(session, url)
        content_length = response.headers.get("Content-Length")
        if content_length is not None:
            try:
                announced_size = int(content_length)
            except ValueError as exc:
                response.close()
                raise ValueError(f"Invalid Content-Length for {label}: {content_length!r}") from exc
            if announced_size > remaining_bytes:
                response.close()
                raise ValueError(
                    f"Metadata exceeds max_metadata_bytes while reading {label}: "
                    f"{announced_size} bytes"
                )

        handle = tempfile.NamedTemporaryFile(
            mode="wb",
            prefix=f"{target.name}.",
            suffix=".partial",
            dir=self.cache_dir,
            delete=False,
        )
        partial = Path(handle.name)
        total = 0
        try:
            with handle, response:
                for chunk in response.iter_content(chunk_size=64 * 1024):
                    if not chunk:
                        continue
                    total += len(chunk)
                    if total > remaining_bytes:
                        raise ValueError(
                            f"Metadata exceeds max_metadata_bytes while reading {label}: "
                            f"more than {remaining_bytes} bytes"
                        )
                    handle.write(chunk)
                handle.flush()
                os.fsync(handle.fileno())
            if total <= 0:
                raise ValueError(f"Downloaded metadata file is empty: {label}")
            os.replace(partial, target)
        except Exception:
            partial.unlink(missing_ok=True)
            raise
        return target

    def _metadata_paths(self, session: requests.Session) -> dict[str, Path]:
        sources = [("identity", self.identity_url), *self.attribute_urls.items()]
        paths: dict[str, Path] = {}
        used_bytes = 0
        for label, url in sources:
            path = self._cached_metadata(
                session,
                label,
                url,
                remaining_bytes=self.max_metadata_bytes - used_bytes,
            )
            used_bytes += path.stat().st_size
            if used_bytes > self.max_metadata_bytes:
                raise ValueError(
                    f"Metadata exceeds max_metadata_bytes: {used_bytes} bytes"
                )
            paths[label] = path
        return paths

    def _connect_registry(self, database_path: Path) -> sqlite3.Connection:
        connection = sqlite3.connect(database_path)
        connection.execute("PRAGMA journal_mode = OFF")
        connection.execute("PRAGMA synchronous = OFF")
        connection.execute("PRAGMA temp_store = MEMORY")
        connection.execute("PRAGMA cache_size = -4096")
        page_size = int(connection.execute("PRAGMA page_size").fetchone()[0])
        max_pages = max(1, self.max_scratch_bytes // page_size)
        connection.execute(f"PRAGMA max_page_count = {max_pages}")
        connection.execute(
            """
            CREATE TABLE identities (
                class_id TEXT PRIMARY KEY,
                identity TEXT NOT NULL,
                sample_num TEXT NOT NULL,
                flag INTEGER NOT NULL,
                gender TEXT NOT NULL
            ) WITHOUT ROWID
            """
        )
        attribute_columns = ", ".join(f"{name} INTEGER" for name in _ATTRIBUTE_NAMES)
        connection.execute(
            f"CREATE TABLE attributes (image_key TEXT PRIMARY KEY, {attribute_columns}) "
            "WITHOUT ROWID"
        )
        connection.execute(
            "CREATE TABLE seen_images (image_key TEXT PRIMARY KEY) WITHOUT ROWID"
        )
        return connection

    def _check_scratch(self, database_path: Path) -> None:
        size = database_path.stat().st_size if database_path.exists() else 0
        if size > self.max_scratch_bytes:
            raise RuntimeError(
                f"Scratch usage exceeds max_scratch_bytes: {size} > {self.max_scratch_bytes}"
            )

    def _load_identity_metadata(
        self,
        connection: sqlite3.Connection,
        path: Path,
        entry_count: int,
    ) -> int:
        with path.open("r", encoding="utf-8-sig", newline="") as handle:
            reader = csv.reader(handle, skipinitialspace=True)
            try:
                header = [value.strip() for value in next(reader)]
            except StopIteration as exc:
                raise ValueError(f"Identity metadata is empty: {path}") from exc
            expected = ["Class_ID", "Name", "Sample_Num", "Flag", "Gender"]
            if header != expected:
                raise ValueError(f"Unexpected identity metadata header in {path}: {header}")

            for line_number, row in enumerate(reader, start=2):
                if not row or all(not value.strip() for value in row):
                    continue
                entry_count += 1
                if entry_count > self.max_metadata_entries:
                    raise ValueError(
                        f"Metadata exceeds max_metadata_entries: {entry_count}"
                    )
                if len(row) != 5:
                    raise ValueError(
                        f"Malformed identity metadata row {line_number} in {path}: {row!r}"
                    )
                class_id, identity, sample_value, flag_value, gender = (
                    value.strip() for value in row
                )
                if _CLASS_ID_PATTERN.fullmatch(class_id) is None:
                    raise ValueError(
                        f"Malformed class ID at row {line_number} in {path}: {class_id!r}"
                    )
                if not identity:
                    raise ValueError(f"Identity is empty at row {line_number} in {path}")
                try:
                    sample_num = int(sample_value)
                except ValueError as exc:
                    raise ValueError(
                        f"Invalid sample count at row {line_number} in {path}: {sample_value!r}"
                    ) from exc
                if not 0 <= sample_num < 2**64:
                    raise ValueError(
                        f"Invalid sample count at row {line_number} in {path}: {sample_value!r}"
                    )
                flag = _parse_boolean(flag_value, f"row {line_number} of {path}")
                gender = gender.lower()
                if gender not in {"f", "m"}:
                    raise ValueError(
                        f"Invalid gender at row {line_number} in {path}: {gender!r}"
                    )
                try:
                    connection.execute(
                        "INSERT INTO identities VALUES (?, ?, ?, ?, ?)",
                        (class_id, identity, str(sample_num), int(flag), gender),
                    )
                except sqlite3.IntegrityError as exc:
                    raise ValueError(f"Duplicate identity metadata key: {class_id}") from exc
        connection.commit()
        return entry_count

    def _load_attribute_metadata(
        self,
        connection: sqlite3.Connection,
        name: str,
        path: Path,
        entry_count: int,
    ) -> int:
        with path.open("r", encoding="utf-8-sig", newline="") as handle:
            for line_number, line in enumerate(handle, start=1):
                value = line.strip()
                if not value:
                    continue
                entry_count += 1
                if entry_count > self.max_metadata_entries:
                    raise ValueError(
                        f"Metadata exceeds max_metadata_entries: {entry_count}"
                    )
                parts = value.split("\t")
                if len(parts) != 2:
                    raise ValueError(
                        f"Malformed {name} row {line_number} in {path}: {value!r}"
                    )
                image_path, attribute_value = (part.strip() for part in parts)
                _, _, _, image_key = _parse_image_path(
                    image_path, f"row {line_number} of {path}"
                )
                parsed_value = int(
                    _parse_boolean(attribute_value, f"row {line_number} of {path}")
                )
                existing = connection.execute(
                    f"SELECT {name} FROM attributes WHERE image_key = ?", (image_key,)
                ).fetchone()
                if existing is not None and existing[0] is not None:
                    raise ValueError(f"Duplicate {name} metadata key: {image_key}")
                if existing is None:
                    connection.execute(
                        f"INSERT INTO attributes (image_key, {name}) VALUES (?, ?)",
                        (image_key, parsed_value),
                    )
                else:
                    connection.execute(
                        f"UPDATE attributes SET {name} = ? WHERE image_key = ?",
                        (parsed_value, image_key),
                    )
        connection.commit()
        return entry_count

    def _build_metadata_registry(
        self,
        connection: sqlite3.Connection,
        metadata_paths: Mapping[str, Path],
        database_path: Path,
    ) -> None:
        entry_count = self._load_identity_metadata(
            connection, metadata_paths["identity"], entry_count=0
        )
        self._check_scratch(database_path)
        for name in _ATTRIBUTE_NAMES:
            entry_count = self._load_attribute_metadata(
                connection,
                name,
                metadata_paths[name],
                entry_count=entry_count,
            )
            self._check_scratch(database_path)

    def _read_image(self, member: tarfile.TarInfo, archive: tarfile.TarFile) -> bytes:
        if member.size <= 0:
            raise ValueError(f"Image is empty in archive: {member.name}")
        if member.size > self.max_image_bytes:
            raise ValueError(
                f"Image exceeds max_image_bytes in archive: {member.name} "
                f"({member.size} > {self.max_image_bytes})"
            )
        extracted = archive.extractfile(member)
        if extracted is None:
            raise ValueError(f"Unable to read image from archive: {member.name}")
        try:
            data = extracted.read(self.max_image_bytes + 1)
        finally:
            extracted.close()
        if len(data) != member.size:
            raise ValueError(
                f"Truncated image in archive: {member.name} "
                f"({len(data)} of {member.size} bytes)"
            )
        if len(data) > self.max_image_bytes:
            raise ValueError(f"Image exceeds max_image_bytes in archive: {member.name}")

        try:
            with warnings.catch_warnings():
                warnings.simplefilter("error", PILImage.DecompressionBombWarning)
                with PILImage.open(io.BytesIO(data)) as image:
                    width, height = image.size
                    if width <= 0 or height <= 0 or width * height > self.max_image_pixels:
                        raise ValueError(
                            f"Image dimensions exceed max_image_pixels in archive: "
                            f"{member.name} ({width}x{height})"
                        )
                    image.verify()
        except ValueError:
            raise
        except (
            OSError,
            UnidentifiedImageError,
            PILImage.DecompressionBombError,
            PILImage.DecompressionBombWarning,
        ) as exc:
            raise ValueError(f"Corrupt image in archive: {member.name}") from exc
        return data

    def _record(
        self,
        connection: sqlite3.Connection,
        split: str,
        class_id: str,
        filename: str,
        image_id: str,
        image_key: str,
        image_bytes: bytes,
    ) -> dict[str, Any]:
        identity = connection.execute(
            "SELECT identity, sample_num, flag, gender FROM identities WHERE class_id = ?",
            (class_id,),
        ).fetchone()
        if identity is None:
            raise ValueError(f"Identity metadata is missing for image key: {image_key}")
        attributes = connection.execute(
            f"SELECT {', '.join(_ATTRIBUTE_NAMES)} FROM attributes WHERE image_key = ?",
            (image_key,),
        ).fetchone()
        attribute_values = attributes or (None,) * len(_ATTRIBUTE_NAMES)

        record: dict[str, Any] = {
            "image": {"path": f"{class_id}/{filename}", "bytes": image_bytes},
            "image_key": image_key,
            "filename": filename,
            "image_id": image_id,
            "class_id": class_id,
            "identity": str(identity[0]),
            "split": split,
            "gender": str(identity[3]),
            "sample_num": int(identity[1]),
            "flag": bool(identity[2]),
        }
        record.update(
            {
                name: None if value is None else bool(value)
                for name, value in zip(_ATTRIBUTE_NAMES, attribute_values)
            }
        )
        return record

    def _iter_archive(
        self,
        session: requests.Session,
        split: str,
        connection: sqlite3.Connection,
        database_path: Path,
    ) -> Iterable[dict[str, Any]]:
        response = self._open_response(session, self.archive_urls[split])
        archive: tarfile.TarFile | None = None
        yielded = 0
        try:
            response.raw.decode_content = False
            archive = tarfile.open(fileobj=response.raw, mode="r|gz")
            for member in archive:
                if member.name.startswith(("/", "\\")) or "\\" in member.name:
                    raise ValueError(f"Malformed archive member path: {member.name!r}")
                checked_name = (
                    member.name[:-1]
                    if member.isdir() and member.name.endswith("/")
                    else member.name
                )
                path_parts = checked_name.split("/")
                if any(part in {"", ".", ".."} for part in path_parts):
                    raise ValueError(f"Malformed archive member path: {member.name!r}")
                if member.isdir():
                    continue
                if not member.isfile():
                    raise ValueError(f"Unsupported archive member type: {member.name!r}")
                if not _is_image_path(member.name):
                    continue

                class_id, filename, image_id, image_key = _parse_image_path(
                    member.name, "VGGFace2 archive"
                )
                try:
                    connection.execute(
                        "INSERT INTO seen_images VALUES (?)", (image_key,)
                    )
                except sqlite3.IntegrityError as exc:
                    raise ValueError(f"Duplicate canonical image key: {image_key}") from exc
                except sqlite3.OperationalError as exc:
                    if "full" not in str(exc).lower():
                        raise
                    raise RuntimeError(
                        "Scratch registry reached max_scratch_bytes"
                    ) from exc
                if yielded % 1024 == 0:
                    try:
                        connection.commit()
                    except sqlite3.OperationalError as exc:
                        raise RuntimeError(
                            "Scratch registry reached max_scratch_bytes"
                        ) from exc
                    self._check_scratch(database_path)

                image_bytes = self._read_image(member, archive)
                yield self._record(
                    connection,
                    split,
                    class_id,
                    filename,
                    image_id,
                    image_key,
                    image_bytes,
                )
                yielded += 1
            try:
                connection.commit()
            except sqlite3.OperationalError as exc:
                raise RuntimeError("Scratch registry reached max_scratch_bytes") from exc
            self._check_scratch(database_path)
        except tarfile.TarError as exc:
            raise RuntimeError(f"Unable to stream {split} tar archive") from exc
        finally:
            if archive is not None:
                archive.close()
            response.close()

    def iter_split(self, split: str) -> Iterable[dict[str, Any]]:
        """Iterate one pinned source archive in its original member order."""
        normalized_split = str(split)
        if normalized_split not in {"train", "test"}:
            raise ValueError("split must be train or test")

        self.scratch_dir.mkdir(parents=True, exist_ok=True)
        with tempfile.TemporaryDirectory(
            prefix="vggface2-stream-", dir=self.scratch_dir
        ) as temporary:
            database_path = Path(temporary) / "registry.sqlite3"
            connection: sqlite3.Connection | None = None
            with self._session() as session:
                try:
                    metadata_paths = self._metadata_paths(session)
                    connection = self._connect_registry(database_path)
                    self._build_metadata_registry(
                        connection, metadata_paths, database_path
                    )
                    yield from self._iter_archive(
                        session,
                        normalized_split,
                        connection,
                        database_path,
                    )
                finally:
                    if connection is not None:
                        connection.close()

    def as_dataset(self, split: str) -> datasets.IterableDataset:
        """Return the supported Hugging Face streaming entry point."""
        normalized_split = str(split)
        if normalized_split not in {"train", "test"}:
            raise ValueError("split must be train or test")
        return datasets.IterableDataset.from_generator(
            _iter_loader,
            features=self.features,
            gen_kwargs={"loader": self, "split": normalized_split},
            split=normalized_split,
        )


def _iter_loader(loader: VGGFace2, split: str) -> Iterable[dict[str, Any]]:
    yield from loader.iter_split(split)


def load_streaming(split: str, **loader_kwargs: Any) -> datasets.IterableDataset:
    """Load a bounded project-side stream from the pinned VGGFace2 revision."""
    return VGGFace2(**loader_kwargs).as_dataset(split)