import io import zipfile from collections.abc import Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Union import datasets if TYPE_CHECKING: import numpy as np import PIL.Image logger = datasets.utils.logging.get_logger(__name__) @dataclass class Comic(datasets.Image): """Comic feature that extends Image feature for CBZ files.""" def encode_example( self, value: Sequence[Union[str, bytes, dict, "np.ndarray", "PIL.Image.Image"]] ) -> dict: """Encode example into a format for Arrow. Args: value (`Sequence` of `str`, `bytes`, `dict`, `np.ndarray`, or `PIL.Image.Image`): Sequence of data passed as input to Comic feature. Each element can be: - A path to a local image file - Raw bytes of an image file - A dictionary containing image data - A numpy array representing an image - A PIL Image object Returns: `dict` with "path" and "bytes" fields for each image in the sequence """ return [super().encode_example(img) for img in value] def decode_example( self, value: dict, token_per_repo_id=None ) -> list["PIL.Image.Image"]: """Decode example CBZ file into image data. Args: value (`str` or `dict`): Either a string with absolute path to CBZ file, or a dictionary with keys: - `path`: String with absolute path to CBZ file. - `bytes`: The bytes of the CBZ file. token_per_repo_id (`dict`, *optional*): To access and decode files from private repositories on the Hub. Returns: `List[PIL.Image.Image]`: List of images from CBZ """ if isinstance(value, str): zip_file = value else: zip_file = ( io.BytesIO(value["bytes"]) if value.get("bytes") else value["path"] ) with zipfile.ZipFile(zip_file, "r") as zip_ref: return [ super().decode_example(img_file) for img_file in sorted(zip_ref.namelist()) ] class NhentaiConfig(datasets.folder_based_builder.FolderBasedBuilderConfig): """BuilderConfig for ImageFolder.""" drop_labels: bool = None drop_metadata: bool = None def __post_init__(self): super().__post_init__() class Nhentai(datasets.folder_based_builder.FolderBasedBuilder): BASE_COLUMN_NAME = "comic" BASE_FEATURE = Comic BUILDER_CONFIG_CLASS = NhentaiConfig BUILDER_CONFIGS = [ NhentaiConfig( name="nhentai", description="Default configuration for nhentai dataset", drop_labels=False, drop_metadata=False, ) ] DEFAULT_CONFIG_NAME = "nhentai" EXTENSIONS: list[str] = [".cbz"] VERSION = datasets.Version("1.0.0") def _info(self): """Returns the dataset metadata.""" return datasets.DatasetInfo( description="Dataset of comic books in CBZ format", features=datasets.Features( { "comic": Comic(), "title": datasets.Value("string"), "media_id": datasets.Value("int64"), "num_favorites": datasets.Value("int64"), "tag": datasets.Sequence(datasets.Value("string")), "language": datasets.Sequence(datasets.Value("string")), "artist": datasets.Sequence(datasets.Value("string")), "category": datasets.Sequence(datasets.Value("string")), "num_pages": datasets.Value("int64"), "scanlator": datasets.Value("string"), "group": datasets.Sequence(datasets.Value("string")), "parody": datasets.Sequence(datasets.Value("string")), "character": datasets.Sequence(datasets.Value("string")), "epos": datasets.Value("int64"), "file_name": datasets.Value("string"), } ), supervised_keys=None, homepage="https://nhentai.net/", )