Dataset Viewer
Auto-converted to Parquet Duplicate
The dataset viewer is not available for this split.
Parquet error: Scan size limit exceeded: attempted to read 1083818434 bytes, limit is 300000000 bytes Make sure that 1. the Parquet files contain a page index to enable random access without loading entire row groups2. otherwise use smaller row-group sizes when serializing the Parquet files
Error code:   TooBigContentError

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

Curated Danbooru Streaming Dataset

A large-scale, high-performance curated dataset of ~330,000 (330K) high-quality anime illustrations designed for training Diffusion Transformers (DiT), Latent Diffusion Models (LDM), and text-to-image generative models focused on the anime domain.

This dataset is focused on specific curated characters and high-ranking artists using knowledge base lists (characters_list.txt and artists_list.txt). Prompt sequence lengths and bucket tiers (77, 152, 227) are calculated using the standard CLIP tokenizer to eliminate sequence padding waste. All samples undergo multi-metric aesthetic classification, rule-validated prompt upsampling, and serialization into sharded Parquet files with embedded AVIF binaries for high-throughput network streaming.

Highlights & Features

  • ~330K Curated Illustrations: Filtered from millions of Danbooru posts, targeting popular characters and high-ranking illustrators from the included knowledge base lists. Each shard contains 10K images.
  • CLIP Tokenizer-Calibrated Length Tiers: Prompt token lengths are pre-calculated using the CLIP tokenizer into discrete tiers (77, 152, 227), enabling dynamic sequence batching with zero padding overhead.
  • Curated Knowledge Base: Focused on curated popular anime characters and high-tier illustrative artists. Full text lists (artists_list.txt and characters_list.txt) are provided in the repository for fine-tuning control and dataset transparency.
  • AVIF Binary Encoding: Images are compressed in AVIF format and stored as raw binary within Parquet files, saving substantial bandwidth while preserving fine high-frequency lines.
  • Two-Phase Aesthetic Tiering: Classified into 4 discrete quality tiers (0: worse_score, 1: bad_score, 2: good_score, 3: masterpiece) using Danbooru scores, favorite counts, positive/negative tag heuristics, and a SwinV2 neural classifier with "Veto and Rescue" logic.
  • Validated Prompt Upsampling: Prompts are upsampled using a WD-SwinV2 tagger and sanitized with structural conflict heuristics (preventing attribute clashes in hair length, eye color, and clothing).
  • Aspect Ratio & Sequence Length Bucketing: Includes precomputed target dimensions (target_width, target_height, bucket_idx) and token length tiers (77, 152, 227) to eliminate padding waste and aspect distortion during training.
  • Dynamic Loss Tag Weighting: Every sample includes a precomputed tag_weight reflecting tag rarity across general, character, and artist categories to counter frequency imbalance.
  • No Natural Language: Prompts combine original danbooru tags and upsampled tags. However the prompts have not been upsampled using Natural Language.

Dataset Structure & Parquet Schema

The dataset is partitioned into sequential Parquet shards (data_shard_00000.parquet, data_shard_00001.parquet, etc.) accompanied by a root metadata.json.

Apache Arrow / Parquet Schema

Column Name Type Description
booru_id string Unique Danbooru post identifier.
image binary Raw AVIF-compressed image byte stream.
prompt string Structured, sanitized, and upsampled caption tag string.
bucket_idx int32 Index of the pre-calculated aspect ratio resolution bucket.
target_width int32 Target width in pixels for aspect ratio bucketing.
target_height int32 Target height in pixels for aspect ratio bucketing.
original_width int32 Original scraped image width.
original_height int32 Original scraped image height.
aspect_ratio float32 Precomputed aspect ratio ( Width / Height ).
tier int32 Token length tier limit (77, 152, 227) for sequence packing.
aesthetic_tier int32 Final quality tier index (0: Worse, 1: Bad, 2: Good, 3: Masterpiece).
tag_weight float32 Caption importance weight based on category-wise tag rarity.

Prompt Structure

Prompts are assembled following a structured order optimized for custom tag dropping and tag shuffling:

[person count], [character], [copyright/series], [content rating], [artist], [aesthetic tier], [quality tags], [year modifier], [general tags], [upsampled tags]

Example Prompt

1girl, souryuu asuka langley, neon genesis evangelion, sensitive, torino aqua, masterpiece, best quality, very aesthetic, newest, year 2023, looking at viewer, solo, blue eyes, orage hair, plugsuit, red plugsuit

Quality Tiers & Classification Logic

Samples are categorized into four aesthetic tiers:

Tier ID Tier Name Description Selection Criteria
3 masterpiece Elite illustrative art Score β‰₯p92\ge p_{92}, Favs β‰₯p92\ge p_{92}, Aesthetic Score β‰₯p50\ge p_{50}, ≀1\le 1 negative tag, validated by SwinV2 classifier.
2 good_score High-quality illustrations Score β‰₯p60\ge p_{60}, Favs β‰₯p60\ge p_{60}, Aesthetic Score β‰₯p38\ge p_{38}, ≀2\le 2 negative tags.
1 bad_score Average/sketch quality Default baseline tier; also acts as the protected floor for curated artist samples.
0 worse_score Poor quality / noisy Score <p20< p_{20}, Favs <p20< p_{20}, Aesthetic Score <p25< p_{25}, or β‰₯2\ge 2 negative defect tags.

Veto and Rescue Mechanism

  • Veto (Demotion): An image with high Booru metrics that is predicted as worst by the SwinV2 neural classifier is demoted to worse_score (unless it belongs to a protected artist, where it is assigned to bad_score).
  • Rescue (Promotion): An undiscovered illustration with low metric counts that is predicted as best by the classifier is promoted directly to good_score or masterpiece.

Dataset Creation Pipeline

  1. Targeted Scraping: Metadata and 1MP-resolution images were retrieved from Danbooru using targeted character and artist lists.
  2. Missing Metric Imputation: Posts with missing metrics were imputed using a hierarchical fallback scheme (Artist Mean β†’\rightarrow Character Mean β†’\rightarrow Global Mean).
  3. Perceptual Deduplication: Visual near-duplicates were detected using perceptual hashing (cv2.img_hash.PHash), indexed via Faiss (IndexBinaryFlat), and grouped with Disjoint Set Union (DSU) clustering. The item with the longest prompt and highest score in each cluster was retained.
  4. Unified Tagging & Aesthetic Inference: Images were processed through a SwinV2 feature extractor to jointly predict aesthetic tiers and missing tag descriptors.
  5. Conflict Filtering: Upsampled tags were filtered against ground truth character counts (e.g., restricting hair lengths and eye colors to character quantity) and clothing conflict tables.
  6. Tag Weighting: Loss weights were assigned per sample by calculating the inverse frequencies across tag categories. Curated artist and character tags receive priority multipliers (1.55x and \1.15x respectively):

Weight=exp⁑(1∣Cβˆ£βˆ‘c∈Clog⁑μc) \text{Weight} = \exp\left(\frac{1}{|\mathcal{C}|} \sum_{c \in \mathcal{C}} \log \mu_c\right)

  1. Parquet Serialization: Images were compressed into AVIF and serialized alongside bucketing coordinates into Parquet shards.

How to Use

Installation

Pillow 12 already supports AVIF images natively, however for older versions ensure you have pillow-heif installed to decode the AVIF image streams:

pip install datasets pillow pillow-heif pyarrow torch torchvision

1. Streaming with Hugging Face datasets

import io
from PIL import Image
from datasets import load_dataset


# Load dataset in streaming mode
dataset = load_dataset(
    "aipracticecafe/curated-danbooru-2026",
    split="train",
    streaming=True
)

for sample in dataset:
    booru_id = sample["booru_id"]
    prompt = sample["prompt"]
    tag_weight = sample["tag_weight"]
    aesthetic_tier = sample["aesthetic_tier"]
    
    # Decode AVIF binary bytes to PIL Image
    image = Image.open(io.BytesIO(sample["image"])).convert("RGB")
    
    print(f"ID: {booru_id} | Tier: {aesthetic_tier} | Size: {image.size} | Weight: {tag_weight:.2f}")
    print(f"Prompt: {prompt[:80]}...\n")
    break

2. PyTorch Training Loop (Filtering by Aesthetic Tier)

import io
import torch
from torch.utils.data import IterableDataset, DataLoader
from datasets import load_dataset
from PIL import Image


class AnimeDiffusionStreamDataset(IterableDataset):
    def __init__(
        self,
        hf_dataset_id: str,
        tokenizer_id: str = "openai/clip-vit-large-patch14",
        min_aesthetic_tier: int = 2,
    ):
        super().__init__()
        self.dataset = load_dataset(hf_dataset_id, split="train", streaming=True)
        self.tokenizer = CLIPTokenizer.from_pretrained(tokenizer_id)
        self.min_aesthetic_tier = min_aesthetic_tier

        # Standard diffusion image normalization to [-1.0, 1.0]
        self.transform = v2.Compose([
            v2.ToImage(),
            v2.ToDtype(torch.float32, scale=True),
            v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
        ])

    def _process_sample(self, sample: dict):
        # 1. Decode AVIF binary bytes to PIL Image
        image = Image.open(io.BytesIO(sample["image"])).convert("RGB")

        # 2. Reshape image to target bucketing dimensions using bicubic interpolation
        target_w = int(sample["target_width"])
        target_h = int(sample["target_height"])
        image = image.resize((target_w, target_h), Image.Resampling.BICUBIC)
        image_tensor = self.transform(image)

        # 3. Tokenize prompt up to the sample's sequence length tier
        tier_max_len = int(sample.get("tier", 227))
        tokenized = self.tokenizer(
            sample["prompt"],
            padding="max_length",
            truncation=True,
            max_length=tier_max_len,
            return_tensors="pt",
        )

        input_ids = tokenized["input_ids"].squeeze(0)
        attention_mask = tokenized["attention_mask"].squeeze(0)
        tag_weight = torch.tensor(sample["tag_weight"], dtype=torch.float32)
        aes_tier = torch.tensor(sample["aesthetic_tier"], dtype=torch.long)

        return {
            "image": image_tensor,
            "input_ids": input_ids,
            "attention_mask": attention_mask,
            "tag_weight": tag_weight,
            "aesthetic_tier": aes_tier,
            "target_resolution": torch.tensor([target_h, target_w], dtype=torch.int32),
            "booru_id": sample["booru_id"],
        }

    def __iter__(self):
        for sample in self.dataset:
            # Filter low aesthetic quality samples
            if sample["aesthetic_tier"] < self.min_aesthetic_tier:
                continue
            try:
                yield self._process_sample(sample)
            except Exception:
                continue


stream_ds = AnimeDiffusionStreamDataset(
    hf_dataset_id="aipracticecafe/curated-danbooru-2026",
    tokenizer_id="openai/clip-vit-large-patch14",
    min_aesthetic_tier=2,  # Yields good_score (2) and masterpiece (3)
)

loader = DataLoader(stream_ds, batch_size=4)

for batch in loader:
    print("Images tensor shape:", batch["image"].shape)
    print("Tokens tensor shape:", batch["input_ids"].shape)
    print("Tag weights:", batch["tag_weight"])
    print("Target resolutions (H, W):\n", batch["target_resolution"])
    break

Content Advisory & Limitations

  • NSFW & Sensitive Content: This dataset contains uncensored anime-style art, including sensitive, questionable, and explicit material (g, s, q, e ratings). Use appropriate tag filtering during training if a SFW-only model is required.
  • Rating Nuances: Rating flags are derived from Danbooru metadata. In some cases, localized crops or subjective tagging may result in edge-case false positives or false negatives.
  • Legal Disclaimer: Images are sourced from Danbooru for research, educational, and generative modeling purposes under fair use. Copyright of all underlying illustrations belongs to their respective creators.

References


Citation

If you find this material helpful, consider citation!

@misc{danbooru_curated_2026,
  author = {aipracticecafe},
  title = {Curated Danbooru 2026 Dataset},
  year = {2026},
  publisher = {Hugging Face},
  howpublished = {\url{https://huggingface.co/datasets/aipracticecafe/curated-danbooru-2026}}
}
Downloads last month
124