# 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)