Datasets:
Update dataset card with correct image loading instructions
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
---license: othertask_categories: - image-classification - image-feature-extraction - image-to-text - clusteringtags: - anime - keyframes - images - clip - aesthetic-scoring - k-means - parquet - jsonlpretty_name: Anime Keyframes---
# Anime Keyframes
## Overview
This dataset contains anime keyframe images and associated metadata forvisual exploration, image retrieval, clustering, aesthetic analysis, andmultimodal machine-learning tasks.
The repository contains three main data components:
- `images/`: image files.- `jsonl/`: JSONL metadata shards. Each JSONL record contains metadata and an image reference.- `captions.parquet`: a tabular index containing metadata and processing results.
The JSONL records may refer to images using relative paths such as:
`../images/00000000_f8597d6a05.jpg`
**Important:** These are repository-relative references, not necessarilyvalid local filesystem paths. Loading JSONL directly with`datasets.load_dataset("json", ...)` and casting the image column to`datasets.Image` can fail because the image decoder may try to open therelative path on the local filesystem.
Use the explicit Hugging Face Hub download and path-resolution procedurein this card to load images reliably.
## Repository layout
```textanime-keyframes/├── README.md├── captions.parquet├── images/│ ├── 00000000_f8597d6a05.jpg│ └── ...└── jsonl/ ├── shard_00000.jsonl └── ...```
The exact number and names of JSONL shards and images may vary.
## Data schema
### `captions.parquet`
Each row represents one image/keyframe.
| Column | Description ||---|---|| `idx` | Dataset-local image or record index. || `prompt` | Prompt text, if available. May be empty. || `tags` | Tag text, if available. May be empty. || `author` | Dataset author/source attribution field. || `json_file` | JSONL filename containing the corresponding serialized record. || `byte_offset` | Zero-based byte offset of the record in the JSONL file. || `byte_length` | Number of bytes occupied by the record. || `instruction` | Instruction metadata, if present. || `thinking_response` | Thinking/reasoning metadata, if present. || `written_response` | Written response or description, if present. || `addendum` | Additional metadata or notes, if present. || `tag_prediction` | Serialized tagger prediction data. May be `[]` if tagging was skipped. || `group_number` | K-means cluster assignment based on CLIP image embeddings. || `clip_aesthetic_score` | Predicted aesthetic score based on a CLIP ViT-B/32 embedding and a learned linear predictor. |
Some text fields may contain empty strings. Empty values should be treated asmissing or ungenerated annotations, not as negative labels.
### JSONL records
The JSONL shards contain serialized metadata records. An image referenceinside a JSONL record may be a relative path, for example:
`../images/00000000_f8597d6a05.jpg`
Resolve this path against the repository layout, not against the JSONLfile's local directory. In the loading example below, the leading `../`is removed and the remaining `images/...` path is downloaded from thedataset repository.
### CLIP clustering
`group_number` is an unsupervised K-means cluster identifier derived fromOpenCLIP ViT-B/32 embeddings using the `laion400m_e32` pretrained weights.
Cluster IDs are categorical identifiers, not semantic class labels.A cluster number does not inherently represent a character, series, style,or scene type.
### Aesthetic score
`clip_aesthetic_score` is a model prediction calculated by applying alearned linear aesthetic predictor to a CLIP ViT-B/32 image embedding,applying sigmoid, and multiplying the result by 10.
The score is approximately on a 0–10 scale. It is not an objective measureof image quality or a human rating. It should be treated as a model-derivedranking feature.
### Tagging fields
The WD tagger may have been skipped during dataset preparation. In thatcase, `tags` and `prompt` may be empty, and `tag_prediction` may contain`[]`.
This does not mean that an image contains no recognizable objects,characters, or visual concepts. It means that those annotations were notgenerated in this dataset build.
## Loading the dataset
Install the required packages:
```bashpip install -U huggingface_hub datasets pandas pyarrow pillow```
### Recommended method: download metadata and resolve image paths
This method works with JSONL records containing relative image references.
```pythonfrom huggingface_hub import HfApi, hf_hub_downloadfrom PIL import Imagefrom pathlib import Pathimport jsonimport io
REPO_ID = "codeShare/anime-keyframes"
api = HfApi()
# List files in the dataset repository.repo_files = api.list_repo_files( repo_id=REPO_ID, repo_type="dataset",)
# Download all JSONL shards.jsonl_files = sorted([ path for path in repo_files if path.endswith(".jsonl")])
records = []
for jsonl_file in jsonl_files: local_jsonl = hf_hub_download( repo_id=REPO_ID, repo_type="dataset", filename=jsonl_file, )
with open(local_jsonl, "r", encoding="utf-8") as f: for line in f: if line.strip(): records.append(json.loads(line))
print("Records:", len(records))print("Example record:", records[0])```
### Resolve and load an image
The image path in a record may be stored as `../images/...`. Convert itto a repository path before downloading it.
The following helper searches common image-reference fields. If yourrecord schema uses a different field, inspect a record and add thatfield name to `IMAGE_KEYS`.
```pythonIMAGE_KEYS = [ "image", "image_path", "file_name", "filename", "path",]
def get_image_reference(record): for key in IMAGE_KEYS: value = record.get(key)
if isinstance(value, str) and value.strip(): return value
# Support datasets where image is stored as a dictionary. if isinstance(value, dict): for nested_key in ("path", "image", "file_name"): nested_value = value.get(nested_key) if isinstance(nested_value, str) and nested_value.strip(): return nested_value
raise KeyError( "Could not find an image reference. " f"Available fields: {list(record.keys())}" )
def resolve_repo_image_path(image_reference): path = str(image_reference).replace("\\", "/").lstrip("/")
while path.startswith("../"): path = path[3:]
if path.startswith("images/"): return path
# Reject unexpected paths rather than silently downloading # a file from an unrelated repository directory. raise ValueError( f"Unexpected image reference: {image_reference}" )
def load_record_image(record): image_reference = get_image_reference(record) repo_image_path = resolve_repo_image_path(image_reference)
local_image = hf_hub_download( repo_id=REPO_ID, repo_type="dataset", filename=repo_image_path, )
return Image.open(local_image).convert("RGB")
# Example: load and display the first image.image = load_record_image(records[0])display(image)```
### Create a Hugging Face Dataset with decoded images
Once the image paths have been resolved, create a dataset using localimage paths. This avoids the broken relative-path behavior of directlycasting the original JSONL image references.
```pythonfrom datasets import Dataset, Image as HFImage
rows = []
for record in records: image_reference = get_image_reference(record) repo_image_path = resolve_repo_image_path(image_reference)
local_image_path = hf_hub_download( repo_id=REPO_ID, repo_type="dataset", filename=repo_image_path, )
row = dict(record) row["image"] = local_image_path rows.append(row)
dataset = Dataset.from_list(rows)dataset = dataset.cast_column("image", HFImage())
print(dataset)print(dataset[0])display(dataset[0]["image"])```
This approach downloads every referenced image, so it can take time anddisk space for a large dataset. For exploratory work, download only theimages needed for the current task.
### Load the Parquet metadata table
```pythonimport pandas as pdfrom huggingface_hub import hf_hub_download
parquet_path = hf_hub_download( repo_id=REPO_ID, repo_type="dataset", filename="captions.parquet",)
df = pd.read_parquet(parquet_path)
print(df.shape)print(df.dtypes)print(df.head())```
Alternatively, use the Hugging Face Datasets library:
```pythonfrom datasets import load_dataset
metadata = load_dataset( "parquet", data_files={ "train": f"hf://datasets/{REPO_ID}/captions.parquet" }, split="train",)
print(metadata)print(metadata[0])```
### Retrieve a JSONL record using the Parquet byte offsets
The `json_file`, `byte_offset`, and `byte_length` columns allow a recordto be retrieved without scanning the entire JSONL shard.
Byte offsets must be used with binary file access. They are byte positions,not character positions or line numbers.
```pythonimport jsonfrom huggingface_hub import hf_hub_download
def read_jsonl_record(row): local_path = hf_hub_download( repo_id=REPO_ID, repo_type="dataset", filename=row["json_file"], )
with open(local_path, "rb") as f: f.seek(int(row["byte_offset"])) raw = f.read(int(row["byte_length"]))
return json.loads(raw.decode("utf-8").strip())
record = read_jsonl_record(df.iloc[0])print(json.dumps(record, indent=2, ensure_ascii=False))```
The JSONL files and Parquet index must remain paired. If JSONL files arerewritten, concatenated, or re-encoded, their byte offsets may becomeinvalid. Regenerate the Parquet index whenever the JSONL byte layout changes.
## Example analysis tasks
### Filter by aesthetic score
```pythonhigh_scoring = df[ df["clip_aesthetic_score"] >= 7.0]
print(len(high_scoring))```
### Rank images by aesthetic score
```pythonranked = df.sort_values( "clip_aesthetic_score", ascending=False,)
print( ranked[ ["idx", "group_number", "clip_aesthetic_score"] ].head(20))```
### Inspect cluster sizes
```pythoncluster_counts = ( df["group_number"] .value_counts() .sort_index())
print(cluster_counts)```
### Compare aesthetic scores across clusters
```pythoncluster_summary = ( df.groupby("group_number")["clip_aesthetic_score"] .agg(["count", "mean", "median", "min", "max"]) .sort_values("mean", ascending=False))
print(cluster_summary)```
### Sample images from a cluster
```pythoncluster_id = 0
cluster_rows = df[df["group_number"] == cluster_id]sample = cluster_rows.sample( n=min(10, len(cluster_rows)), random_state=42,)
for _, row in sample.iterrows(): record = read_jsonl_record(row) image = load_record_image(record)
print( "Index:", row["idx"], "Cluster:", row["group_number"], "Aesthetic score:", row["clip_aesthetic_score"], ) display(image)```
## Guidance for downstream machine-learning tasks
- Use `captions.parquet` as the primary table for filtering and statistical analysis.- Use JSONL records to inspect the full serialized metadata and discover image references.- Resolve repository-relative image paths before opening images.- Use `group_number` as an unsupervised grouping feature, not as a class label.- Use `clip_aesthetic_score` as a model-derived score, not as ground truth.- Treat empty tag and prompt fields as unavailable annotations.- Consider cluster-aware train/validation/test splits when visual similarity leakage is a concern.- Verify image dimensions, file formats, duplicate images, and metadata completeness before training.- Record the dataset revision and preprocessing settings for reproducibility.- Verify image rights and licensing before redistribution, publication, commercial use, or model training.
## Limitations
This dataset should not be assumed to be balanced across characters,series, styles, artists, or scene types.
Cluster assignments depend on the embedding model and K-means settings.Aesthetic scores may reflect biases in the predictor's training data.Optional annotation fields may be empty because an annotation stage wasnot run.
Public availability does not automatically grant unrestricted rights toredistribute or commercially use the images. Users are responsible forchecking the applicable rights and restrictions.
## Intended uses
Potential applications include:
- Anime image similarity search.- Visual clustering and cluster exploration.- Image retrieval and ranking.- Aesthetic-score analysis.- Image captioning and image understanding.- Dataset curation and filtering.- Representation learning and multimodal model experiments.- Studying visual composition and style.
README.mdAdded+483