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
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
# coding=utf-8
# 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.

"""VGGFace2-HQ bounded streaming dataset loader."""

from __future__ import annotations

import csv
import io
import math
import os
import re
import shutil
import sqlite3
import tempfile
import warnings
import zipfile
from collections import OrderedDict
from dataclasses import dataclass
from hashlib import sha256
from pathlib import Path, PurePosixPath
from typing import Any, BinaryIO, Iterator, Mapping
from urllib.parse import urlparse

import datasets
import requests
from requests.auth import AuthBase
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry


DEFAULT_REVISION = "ee41c3e64981063524744286b468e739190cfbed"
DEFAULT_RAW_REVISION = "ad5f6b5a5f560621fd7efb9b79c956d27d427a08"
OXFORD_METADATA_REVISION = "921df0a400f599d0b1a201fbfbb9117e6d794e0d"
DEFAULT_MAX_SHARD_BYTES = 10_100_000_000
DEFAULT_MAX_SCRATCH_BYTES = 10_500_000_000
DEFAULT_MAX_IMAGE_BYTES = 32 * 1024 * 1024
DEFAULT_MAX_IMAGE_PIXELS = 4096 * 4096
DEFAULT_MAX_METADATA_BYTES = 64 * 1024 * 1024
DEFAULT_MAX_METADATA_ENTRIES = 400_000
DEFAULT_RANGE_BLOCK_BYTES = 1024 * 1024
DEFAULT_RANGE_CACHE_BYTES = 8 * 1024 * 1024
_CLASS_ID_PATTERN = re.compile(r"n\d{6}")
_IMAGE_ID_PATTERN = re.compile(r"\d{4}_\d{2}")
_SAFE_PATH_PART_PATTERN = re.compile(r"[A-Za-z0-9._-]+")
_IMAGE_SUFFIXES = {".jpeg", ".jpg", ".png"}
_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)

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"),
        **{name: datasets.Value("bool") for name in _ATTRIBUTE_NAMES},
    }
)


class RangeUnavailableError(RuntimeError):
    """Raised when a remote ZIP cannot be read through HTTP ranges."""


class _HuggingFaceTokenAuth(AuthBase):
    def __init__(self, token: str) -> None:
        self._token = token

    def __call__(self, request: requests.PreparedRequest) -> requests.PreparedRequest:
        hostname = (urlparse(request.url).hostname or "").lower()
        if hostname == "huggingface.co" or hostname.endswith(".huggingface.co"):
            request.headers["Authorization"] = f"Bearer {self._token}"
        return request


@dataclass(frozen=True)
class ImagePath:
    canonical_path: str
    image_key: str
    filename: str
    image_id: str
    class_id: str


@dataclass(frozen=True)
class IdentityMetadata:
    identity: str
    sample_num: int
    flag: bool
    gender: str


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


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


def _parse_image_path(value: str, *, context: str) -> ImagePath:
    normalized = str(value)
    if "\\" in normalized:
        raise ValueError(f"Malformed image path in {context}: {value!r}")
    raw_parts = normalized.split("/")
    if (
        not normalized
        or normalized.startswith("/")
        or any(
            part in {"", ".", ".."} or not _SAFE_PATH_PART_PATTERN.fullmatch(part)
            for part in raw_parts
        )
    ):
        raise ValueError(f"Malformed image path in {context}: {value!r}")
    path = PurePosixPath(*raw_parts)
    if len(path.parts) < 2:
        raise ValueError(f"Malformed image path in {context}: {value!r}")

    class_id = path.parts[-2]
    filename = path.parts[-1]
    suffix = PurePosixPath(filename).suffix.lower()
    image_id = PurePosixPath(filename).stem
    if not _CLASS_ID_PATTERN.fullmatch(class_id):
        raise ValueError(f"Malformed class ID in {context}: {value!r}")
    if not _IMAGE_ID_PATTERN.fullmatch(image_id) or suffix not in _IMAGE_SUFFIXES:
        raise ValueError(f"Malformed image filename in {context}: {value!r}")

    canonical_path = f"{class_id}/{filename}"
    return ImagePath(
        canonical_path=canonical_path,
        image_key=f"{class_id}/{image_id}",
        filename=filename,
        image_id=image_id,
        class_id=class_id,
    )


def _build_session(
    *,
    token: str | None,
    max_retries: int,
    retry_backoff_seconds: float,
) -> requests.Session:
    if max_retries < 0 or max_retries > 10:
        raise ValueError("max_retries must be between 0 and 10")
    if (
        not math.isfinite(float(retry_backoff_seconds))
        or float(retry_backoff_seconds) < 0
    ):
        raise ValueError("retry_backoff_seconds must be finite and non-negative")

    retry = Retry(
        total=max_retries,
        connect=max_retries,
        read=max_retries,
        status=max_retries,
        backoff_factor=float(retry_backoff_seconds),
        status_forcelist=(429, 500, 502, 503, 504),
        allowed_methods=frozenset({"GET", "HEAD"}),
        respect_retry_after_header=False,
    )
    session = requests.Session()
    session.headers.update(
        {
            "Accept-Encoding": "identity",
            "User-Agent": "ProgramComputer-VGGFace2-HQ-bounded-loader/2.0",
        }
    )
    if token:
        session.auth = _HuggingFaceTokenAuth(token)
    adapter = HTTPAdapter(max_retries=retry)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    return session


def _timeout(connect_timeout_seconds: float, read_timeout_seconds: float) -> tuple[float, float]:
    connect_timeout = float(connect_timeout_seconds)
    read_timeout = float(read_timeout_seconds)
    if (
        not math.isfinite(connect_timeout)
        or not math.isfinite(read_timeout)
        or connect_timeout <= 0
        or read_timeout <= 0
    ):
        raise ValueError("connect/read timeouts must be finite and positive")
    return connect_timeout, read_timeout


def _read_response_bytes(
    session: requests.Session,
    url: str,
    *,
    timeout: tuple[float, float],
    max_bytes: int,
) -> bytes:
    with session.get(url, stream=True, timeout=timeout) as response:
        response.raise_for_status()
        content_length = response.headers.get("Content-Length")
        if content_length is not None and int(content_length) > max_bytes:
            raise ValueError(f"Remote file exceeds {max_bytes} bytes: {url}")
        payload = bytearray()
        for chunk in response.iter_content(chunk_size=1024 * 1024):
            if not chunk:
                continue
            payload.extend(chunk)
            if len(payload) > max_bytes:
                raise ValueError(f"Remote file exceeds {max_bytes} bytes: {url}")
    return bytes(payload)


class _MetadataReader:
    def __init__(
        self,
        session: requests.Session,
        *,
        cache_dir: Path | None,
        timeout: tuple[float, float],
        max_bytes: int,
    ) -> None:
        self._session = session
        self._cache_dir = cache_dir
        self._timeout = timeout
        self._max_bytes = _positive_int(max_bytes, "max_metadata_bytes")
        self._bytes_read = 0

    def read_text(self, url: str) -> str:
        cache_path = None
        if self._cache_dir is not None:
            self._cache_dir.mkdir(parents=True, exist_ok=True)
            suffix = Path(url.split("?", 1)[0]).suffix or ".txt"
            cache_path = self._cache_dir / f"{sha256(url.encode('utf-8')).hexdigest()}{suffix}"

        remaining = self._max_bytes - self._bytes_read
        if remaining <= 0:
            raise ValueError(f"Metadata exceeds {self._max_bytes} bytes")

        if cache_path is not None and cache_path.is_file():
            cached_size = cache_path.stat().st_size
            if cached_size <= 0:
                raise ValueError(f"Cached metadata file is empty: {cache_path}")
            if cached_size > remaining:
                raise ValueError(f"Metadata exceeds {self._max_bytes} bytes")
            payload = cache_path.read_bytes()
        else:
            payload = _read_response_bytes(
                self._session,
                url,
                timeout=self._timeout,
                max_bytes=remaining,
            )
            if cache_path is not None:
                partial = cache_path.with_name(cache_path.name + ".partial")
                partial.write_bytes(payload)
                os.replace(partial, cache_path)

        self._bytes_read += len(payload)
        if self._bytes_read > self._max_bytes:
            raise ValueError(f"Metadata exceeds {self._max_bytes} bytes")
        try:
            return payload.decode("utf-8-sig")
        except UnicodeDecodeError as exc:
            raise ValueError(f"Metadata is not UTF-8: {url}") from exc


class _KeyRegistry:
    def __init__(self, path: Path, *, max_scratch_bytes: int) -> None:
        self._path = path
        self._max_scratch_bytes = _positive_int(max_scratch_bytes, "max_scratch_bytes")
        self._connection = sqlite3.connect(path, isolation_level=None)
        self._connection.execute("PRAGMA journal_mode=OFF")
        self._connection.execute("PRAGMA synchronous=OFF")
        page_size = int(self._connection.execute("PRAGMA page_size").fetchone()[0])
        max_pages = max(1, self._max_scratch_bytes // page_size)
        self._connection.execute(f"PRAGMA max_page_count={max_pages}")
        self._connection.execute("CREATE TABLE image_keys (value TEXT PRIMARY KEY) WITHOUT ROWID")

    def add(self, image_key: str, *, context: str) -> None:
        try:
            self._connection.execute("INSERT INTO image_keys(value) VALUES (?)", (image_key,))
        except sqlite3.IntegrityError as exc:
            raise ValueError(f"Duplicate image key {image_key!r} in {context}") from exc
        except sqlite3.OperationalError as exc:
            if "full" not in str(exc).lower():
                raise
            raise ValueError(
                f"Duplicate-key registry exceeds max_scratch_bytes={self._max_scratch_bytes}"
            ) from exc

    def close(self) -> None:
        self._connection.close()


class _HTTPRangeReader(io.RawIOBase):
    def __init__(
        self,
        session: requests.Session,
        url: str,
        *,
        timeout: tuple[float, float],
        block_bytes: int,
        cache_bytes: int,
    ) -> None:
        super().__init__()
        self._session = session
        self._url = url
        self._timeout = timeout
        self._block_bytes = _positive_int(block_bytes, "range_block_bytes")
        self._cache_bytes = _positive_int(cache_bytes, "range_cache_bytes")
        if self._cache_bytes < self._block_bytes:
            raise ValueError("range_cache_bytes must be at least range_block_bytes")
        self._max_blocks = self._cache_bytes // self._block_bytes
        self._blocks: OrderedDict[int, bytes] = OrderedDict()
        self._position = 0
        self._size = self._probe_size()

    @property
    def size(self) -> int:
        return self._size

    def _probe_size(self) -> int:
        headers = {"Range": "bytes=0-0"}
        with self._session.get(
            self._url,
            headers=headers,
            stream=True,
            timeout=self._timeout,
        ) as response:
            if response.status_code == 200:
                raise RangeUnavailableError(f"Server ignored an HTTP range request: {self._url}")
            if response.status_code != 206:
                response.raise_for_status()
                raise RangeUnavailableError(
                    f"Server returned HTTP {response.status_code} for an HTTP range request: "
                    f"{self._url}"
                )
            content_range = response.headers.get("Content-Range", "")
            match = re.fullmatch(r"bytes 0-0/(\d+)", content_range)
            if match is None:
                raise RangeUnavailableError(
                    f"Server returned an invalid Content-Range {content_range!r}: {self._url}"
                )
            first_byte = response.raw.read(2)
            if len(first_byte) != 1:
                raise RangeUnavailableError(f"Server returned an invalid range body: {self._url}")
            return _positive_int(int(match.group(1)), "remote ZIP size")

    def _fetch_block(self, block_index: int) -> bytes:
        cached = self._blocks.pop(block_index, None)
        if cached is not None:
            self._blocks[block_index] = cached
            return cached

        start = block_index * self._block_bytes
        end = min(self._size, start + self._block_bytes) - 1
        with self._session.get(
            self._url,
            headers={"Range": f"bytes={start}-{end}"},
            stream=True,
            timeout=self._timeout,
        ) as response:
            if response.status_code != 206:
                if response.status_code == 200:
                    raise RangeUnavailableError(
                        f"Server stopped honoring HTTP ranges for {self._url}"
                    )
                response.raise_for_status()
                raise RangeUnavailableError(
                    f"Server returned HTTP {response.status_code} for bytes {start}-{end}: "
                    f"{self._url}"
                )
            expected_range = f"bytes {start}-{end}/{self._size}"
            if response.headers.get("Content-Range") != expected_range:
                raise RangeUnavailableError(
                    f"Unexpected Content-Range for {self._url}: "
                    f"{response.headers.get('Content-Range')!r}"
                )
            data = response.raw.read(end - start + 2)
        if len(data) != end - start + 1:
            raise OSError(f"Short HTTP range read for bytes {start}-{end}: {self._url}")

        self._blocks[block_index] = data
        while len(self._blocks) > self._max_blocks:
            self._blocks.popitem(last=False)
        return data

    def readable(self) -> bool:
        return True

    def seekable(self) -> bool:
        return True

    def tell(self) -> int:
        return self._position

    def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
        if whence == io.SEEK_SET:
            position = int(offset)
        elif whence == io.SEEK_CUR:
            position = self._position + int(offset)
        elif whence == io.SEEK_END:
            position = self._size + int(offset)
        else:
            raise ValueError(f"Unsupported seek mode: {whence}")
        if position < 0:
            raise ValueError("Negative seek position")
        self._position = position
        return position

    def read(self, size: int = -1) -> bytes:
        if self._position >= self._size:
            return b""
        if size is None or size < 0:
            size = self._size - self._position
        if size == 0:
            return b""

        stop = min(self._size, self._position + int(size))
        chunks: list[bytes] = []
        while self._position < stop:
            block_index = self._position // self._block_bytes
            block = self._fetch_block(block_index)
            block_offset = self._position % self._block_bytes
            take = min(stop - self._position, len(block) - block_offset)
            chunks.append(block[block_offset : block_offset + take])
            self._position += take
        return b"".join(chunks)

    def close(self) -> None:
        self._blocks.clear()
        super().close()


def _parse_flag(value: str, *, context: str) -> bool:
    normalized = str(value).strip()
    if normalized not in {"0", "1"}:
        raise ValueError(f"Expected 0 or 1 in {context}, got {value!r}")
    return normalized == "1"


def _parse_identities(text: str, *, source: str) -> dict[str, IdentityMetadata]:
    rows = csv.DictReader(io.StringIO(text), skipinitialspace=True)
    if rows.fieldnames is None:
        raise ValueError(f"Identity metadata has no header: {source}")
    rows.fieldnames = [name.strip() for name in rows.fieldnames]
    expected = {"Class_ID", "Name", "Sample_Num", "Flag", "Gender"}
    if set(rows.fieldnames) != expected:
        raise ValueError(f"Unexpected identity metadata columns in {source}: {rows.fieldnames}")

    identities: dict[str, IdentityMetadata] = {}
    for line_number, row in enumerate(rows, start=2):
        class_id = str(row["Class_ID"]).strip()
        if not _CLASS_ID_PATTERN.fullmatch(class_id):
            raise ValueError(f"Malformed class ID at {source}:{line_number}: {class_id!r}")
        if class_id in identities:
            raise ValueError(f"Duplicate class ID at {source}:{line_number}: {class_id!r}")
        try:
            sample_num = int(str(row["Sample_Num"]).strip())
        except ValueError as exc:
            raise ValueError(
                f"Invalid sample count at {source}:{line_number}: {row['Sample_Num']!r}"
            ) from exc
        if not 0 <= sample_num < 2**64:
            raise ValueError(
                f"Sample count is outside uint64 range at {source}:{line_number}: "
                f"{sample_num}"
            )
        identity = str(row["Name"]).strip()
        gender = str(row["Gender"]).strip().lower()
        if not identity or gender not in {"f", "m"}:
            raise ValueError(f"Invalid identity metadata at {source}:{line_number}")
        identities[class_id] = IdentityMetadata(
            identity=identity,
            sample_num=sample_num,
            flag=_parse_flag(row["Flag"], context=f"{source}:{line_number}"),
            gender=gender,
        )
    return identities


def _parse_attribute(
    text: str,
    *,
    name: str,
    source: str,
) -> dict[str, bool]:
    values: dict[str, bool] = {}
    for line_number, line in enumerate(io.StringIO(text), start=1):
        stripped = line.strip()
        if not stripped:
            continue
        columns = stripped.split("\t")
        if len(columns) != 2:
            raise ValueError(f"Malformed attribute row at {source}:{line_number}")
        image_path = _parse_image_path(columns[0], context=f"{source}:{line_number}")
        if image_path.image_key in values:
            raise ValueError(
                f"Duplicate image key {image_path.image_key!r} at {source}:{line_number}"
            )
        values[image_path.image_key] = _parse_flag(
            columns[1],
            context=f"{name} at {source}:{line_number}",
        )
    return values


def _read_member(handle: BinaryIO, *, max_bytes: int, context: str) -> bytes:
    payload = bytearray()
    while True:
        chunk = handle.read(min(1024 * 1024, max_bytes - len(payload) + 1))
        if not chunk:
            break
        payload.extend(chunk)
        if len(payload) > max_bytes:
            raise ValueError(f"Image exceeds max_image_bytes={max_bytes}: {context}")
    return bytes(payload)


def _verify_image(data: bytes, *, context: str, max_pixels: int) -> None:
    try:
        from PIL import Image, UnidentifiedImageError
    except Exception as exc:
        raise ImportError("Pillow is required to validate streamed images") from exc

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


class VGGFace2HQ:
    """Stream VGGFace2-HQ one ZIP shard and one image at a time."""

    features = FEATURES

    def __init__(
        self,
        *,
        revision: str = DEFAULT_REVISION,
        raw_revision: str = DEFAULT_RAW_REVISION,
        token: str | None = None,
        cache_dir: str | Path | None = None,
        scratch_dir: str | Path | None = None,
        connect_timeout_seconds: float = 15.0,
        read_timeout_seconds: float = 60.0,
        max_retries: int = 3,
        retry_backoff_seconds: float = 0.5,
        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,
        range_block_bytes: int = DEFAULT_RANGE_BLOCK_BYTES,
        range_cache_bytes: int = DEFAULT_RANGE_CACHE_BYTES,
        allow_full_shard_fallback: bool = False,
        max_shard_bytes: int = DEFAULT_MAX_SHARD_BYTES,
        max_scratch_bytes: int = DEFAULT_MAX_SCRATCH_BYTES,
        archive_urls: Mapping[str, tuple[str, ...]] | None = None,
        identity_url: str | None = None,
        attribute_urls: Mapping[str, str] | None = None,
    ) -> None:
        if not re.fullmatch(r"[0-9a-f]{40}", revision):
            raise ValueError("revision must be a 40-character lowercase commit SHA")
        if not re.fullmatch(r"[0-9a-f]{40}", raw_revision):
            raise ValueError("raw_revision must be a 40-character lowercase commit SHA")
        self.revision = revision
        self.raw_revision = raw_revision
        self.token = token
        self.cache_dir = Path(cache_dir).resolve() if cache_dir is not None else None
        self.scratch_dir = Path(scratch_dir).resolve() if scratch_dir is not None else None
        self.timeout = _timeout(connect_timeout_seconds, read_timeout_seconds)
        self.max_retries = _non_negative_int(max_retries, "max_retries")
        self.retry_backoff_seconds = float(retry_backoff_seconds)
        self.max_metadata_bytes = _positive_int(max_metadata_bytes, "max_metadata_bytes")
        self.max_metadata_entries = _positive_int(max_metadata_entries, "max_metadata_entries")
        self.max_image_bytes = _positive_int(max_image_bytes, "max_image_bytes")
        self.max_image_pixels = _positive_int(max_image_pixels, "max_image_pixels")
        self.range_block_bytes = _positive_int(range_block_bytes, "range_block_bytes")
        self.range_cache_bytes = _positive_int(range_cache_bytes, "range_cache_bytes")
        self.allow_full_shard_fallback = bool(allow_full_shard_fallback)
        self.max_shard_bytes = _positive_int(max_shard_bytes, "max_shard_bytes")
        self.max_scratch_bytes = _positive_int(max_scratch_bytes, "max_scratch_bytes")

        base_url = (
            "https://huggingface.co/datasets/ProgramComputer/VGGFace2-HQ/resolve/"
            f"{revision}"
        )
        self.archive_urls = dict(
            archive_urls
            or {
                "train": tuple(
                    f"{base_url}/train/VGGFac{index:02d}.zip"
                    for index in range(1, 11)
                ),
                "test": (f"{base_url}/test/test.zip",),
            }
        )
        self.identity_url = identity_url or (
            "https://huggingface.co/datasets/ProgramComputer/VGGFace2/resolve/"
            f"{raw_revision}/meta/identity_meta.csv"
        )
        self.attribute_urls = dict(
            attribute_urls
            or {
                name: (
                    "https://raw.githubusercontent.com/ox-vgg/vgg_face2/"
                    f"{OXFORD_METADATA_REVISION}/attributes/{filename}"
                )
                for name, filename in _ATTRIBUTE_FILES.items()
            }
        )

    def _load_metadata(
        self,
        session: requests.Session,
    ) -> tuple[dict[str, IdentityMetadata], dict[str, dict[str, bool]]]:
        reader = _MetadataReader(
            session,
            cache_dir=self.cache_dir,
            timeout=self.timeout,
            max_bytes=self.max_metadata_bytes,
        )
        identities = _parse_identities(
            reader.read_text(self.identity_url),
            source=self.identity_url,
        )
        if len(identities) > self.max_metadata_entries:
            raise ValueError(
                f"Metadata exceeds max_metadata_entries={self.max_metadata_entries}"
            )

        attributes: dict[str, dict[str, bool]] = {}
        assignments = len(identities)
        for name in _ATTRIBUTE_NAMES:
            url = self.attribute_urls.get(name)
            if url is None:
                raise ValueError(f"Missing attribute URL for {name}")
            values = _parse_attribute(reader.read_text(url), name=name, source=url)
            assignments += len(values)
            if assignments > self.max_metadata_entries:
                raise ValueError(
                    f"Metadata exceeds max_metadata_entries={self.max_metadata_entries}"
                )
            attributes[name] = values
        return identities, attributes

    def _record(
        self,
        image_path: ImagePath,
        image_bytes: bytes,
        *,
        split: str,
        identities: Mapping[str, IdentityMetadata],
        attributes: Mapping[str, Mapping[str, bool]],
        context: str,
    ) -> dict[str, Any]:
        identity = identities.get(image_path.class_id)
        if identity is None:
            raise ValueError(
                f"Missing identity metadata for {image_path.class_id!r} in {context}"
            )
        record: dict[str, Any] = {
            "image": {"path": image_path.canonical_path, "bytes": image_bytes},
            "image_key": image_path.image_key,
            "filename": image_path.filename,
            "image_id": image_path.image_id,
            "class_id": image_path.class_id,
            "identity": identity.identity,
            "split": split,
            "gender": identity.gender,
            "sample_num": identity.sample_num,
            "flag": identity.flag,
        }
        for name in _ATTRIBUTE_NAMES:
            record[name] = attributes[name].get(image_path.image_key)
        return record

    def _iter_zip(
        self,
        archive: zipfile.ZipFile,
        *,
        split: str,
        archive_name: str,
        identities: Mapping[str, IdentityMetadata],
        attributes: Mapping[str, Mapping[str, bool]],
        registry: _KeyRegistry,
    ) -> Iterator[dict[str, Any]]:
        for info in archive.infolist():
            if info.is_dir():
                continue
            context = f"{archive_name}:{info.filename}"
            image_path = _parse_image_path(info.filename, context=context)
            registry.add(image_path.image_key, context=context)
            if info.file_size > self.max_image_bytes:
                raise ValueError(
                    f"Image exceeds max_image_bytes={self.max_image_bytes}: {context}"
                )
            if info.compress_size > self.max_image_bytes:
                raise ValueError(
                    f"Compressed image exceeds max_image_bytes={self.max_image_bytes}: {context}"
                )
            with archive.open(info, "r") as handle:
                image_bytes = _read_member(
                    handle,
                    max_bytes=self.max_image_bytes,
                    context=context,
                )
            _verify_image(
                image_bytes,
                context=context,
                max_pixels=self.max_image_pixels,
            )
            yield self._record(
                image_path,
                image_bytes,
                split=split,
                identities=identities,
                attributes=attributes,
                context=context,
            )

    def _download_shard(
        self,
        session: requests.Session,
        url: str,
        target: Path,
    ) -> None:
        existing_bytes = sum(
            path.stat().st_size for path in target.parent.iterdir() if path.is_file()
        )
        scratch_remaining = self.max_scratch_bytes - existing_bytes
        if scratch_remaining <= 0:
            raise ValueError(
                f"Scratch usage already reaches max_scratch_bytes={self.max_scratch_bytes}: "
                f"{target.parent}"
            )
        limit = min(self.max_shard_bytes, scratch_remaining)
        free_bytes = shutil.disk_usage(target.parent).free
        if free_bytes < limit:
            raise OSError(
                f"Scratch directory has {free_bytes} free bytes; fallback limit is {limit}: "
                f"{target.parent}"
            )
        with session.get(url, stream=True, timeout=self.timeout) as response:
            response.raise_for_status()
            content_length = response.headers.get("Content-Length")
            if content_length is not None and int(content_length) > limit:
                raise ValueError(f"ZIP shard exceeds fallback byte limit {limit}: {url}")
            written = 0
            partial = target.with_name(target.name + ".partial")
            try:
                with partial.open("wb") as handle:
                    for chunk in response.iter_content(chunk_size=1024 * 1024):
                        if not chunk:
                            continue
                        written += len(chunk)
                        if written > limit:
                            raise ValueError(
                                f"ZIP shard exceeds fallback byte limit {limit}: {url}"
                            )
                        handle.write(chunk)
                os.replace(partial, target)
            finally:
                partial.unlink(missing_ok=True)

    def _iter_archive(
        self,
        session: requests.Session,
        url: str,
        *,
        split: str,
        identities: Mapping[str, IdentityMetadata],
        attributes: Mapping[str, Mapping[str, bool]],
        registry: _KeyRegistry,
        work_dir: Path,
    ) -> Iterator[dict[str, Any]]:
        range_reader: _HTTPRangeReader | None = None
        archive: zipfile.ZipFile | None = None
        try:
            range_reader = _HTTPRangeReader(
                session,
                url,
                timeout=self.timeout,
                block_bytes=self.range_block_bytes,
                cache_bytes=self.range_cache_bytes,
            )
            if range_reader.size > self.max_shard_bytes:
                range_reader.close()
                raise ValueError(
                    f"ZIP shard exceeds max_shard_bytes={self.max_shard_bytes}: "
                    f"{url} ({range_reader.size} bytes)"
                )
            try:
                archive = zipfile.ZipFile(range_reader, "r")
            except Exception:
                range_reader.close()
                raise
        except RangeUnavailableError:
            if archive is not None:
                archive.close()
            if range_reader is not None:
                range_reader.close()
            if not self.allow_full_shard_fallback:
                raise RuntimeError(
                    "HTTP range access is unavailable. Set allow_full_shard_fallback=True "
                    "with explicit max_shard_bytes and max_scratch_bytes to download one shard."
                ) from None
            warnings.warn(
                f"HTTP range access is unavailable for {url}; "
                "downloading one bounded shard to scratch",
                RuntimeWarning,
                stacklevel=2,
            )
            target = work_dir / "current-shard.zip"
            try:
                self._download_shard(session, url, target)
                with zipfile.ZipFile(target, "r") as archive:
                    yield from self._iter_zip(
                        archive,
                        split=split,
                        archive_name=url,
                        identities=identities,
                        attributes=attributes,
                        registry=registry,
                    )
            finally:
                target.unlink(missing_ok=True)
            return

        if range_reader is None or archive is None:
            raise RuntimeError(f"Unable to open ranged ZIP shard: {url}")
        with range_reader, archive:
            yield from self._iter_zip(
                archive,
                split=split,
                archive_name=url,
                identities=identities,
                attributes=attributes,
                registry=registry,
            )

    def iter_split(self, split: str) -> Iterator[dict[str, Any]]:
        """Yield one complete record at a time in pinned shard/member order."""
        if split not in {"train", "test"}:
            raise ValueError("split must be train or test")
        urls = self.archive_urls.get(split)
        expected_shards = 10 if split == "train" else 1
        if urls is None or len(urls) != expected_shards:
            raise ValueError(
                f"{split} must define exactly {expected_shards} ZIP shard URL(s)"
            )

        scratch_parent = self.scratch_dir or Path(tempfile.gettempdir())
        scratch_parent.mkdir(parents=True, exist_ok=True)
        session = _build_session(
            token=self.token,
            max_retries=self.max_retries,
            retry_backoff_seconds=self.retry_backoff_seconds,
        )
        try:
            identities, attributes = self._load_metadata(session)
            with tempfile.TemporaryDirectory(
                prefix="vggface2-hq-",
                dir=scratch_parent,
            ) as temporary_dir:
                work_dir = Path(temporary_dir)
                registry_budget = self.max_scratch_bytes
                if self.allow_full_shard_fallback:
                    registry_budget -= self.max_shard_bytes
                    if registry_budget <= 0:
                        raise ValueError(
                            "max_scratch_bytes must exceed max_shard_bytes when "
                            "allow_full_shard_fallback=True"
                        )
                registry = _KeyRegistry(
                    work_dir / "image-keys.sqlite3",
                    max_scratch_bytes=registry_budget,
                )
                try:
                    for url in urls:
                        yield from self._iter_archive(
                            session,
                            url,
                            split=split,
                            identities=identities,
                            attributes=attributes,
                            registry=registry,
                            work_dir=work_dir,
                        )
                finally:
                    registry.close()
        finally:
            session.close()

    def as_dataset(self, split: str) -> datasets.IterableDataset:
        """Return the current supported project-side datasets entry point."""
        if split not in {"train", "test"}:
            raise ValueError("split must be train or test")
        return datasets.IterableDataset.from_generator(
            self.iter_split,
            gen_kwargs={"split": split},
            features=self.features,
            split=split,
        )


def load_streaming(split: str, **loader_kwargs: Any) -> datasets.IterableDataset:
    """Build a bounded IterableDataset without executing remote code."""
    return VGGFace2HQ(**loader_kwargs).as_dataset(split)