anime-keyframes / README.md
codeShare's picture
Update README.md
d5eb803 verified
|
Raw History Blame Contribute Delete
13 kB
---
license: other
task_categories:
- image-classification
- image-feature-extraction
- image-to-text
tags:
- anime
- keyframes
- images
- clip
- aesthetic-scoring
- k-means
- parquet
- jsonl
pretty_name: Anime Keyframes
---
# Anime Keyframes
## Overview
This dataset contains anime keyframe images and associated metadata for
visual exploration, image retrieval, clustering, aesthetic analysis, and
multimodal 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 necessarily
valid 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 the
relative path on the local filesystem.
Use the explicit Hugging Face Hub download and path-resolution procedure
in this card to load images reliably.
## Repository layout
```text
anime-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 as
missing or ungenerated annotations, not as negative labels.
### JSONL records
The JSONL shards contain serialized metadata records. An image reference
inside a JSONL record may be a relative path, for example:
`../images/00000000_f8597d6a05.jpg`
Resolve this path against the repository layout, not against the JSONL
file's local directory. In the loading example below, the leading `../`
is removed and the remaining `images/...` path is downloaded from the
dataset repository.
### CLIP clustering
`group_number` is an unsupervised K-means cluster identifier derived from
OpenCLIP 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 a
learned 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 measure
of image quality or a human rating. It should be treated as a model-derived
ranking feature.
### Tagging fields
The WD tagger may have been skipped during dataset preparation. In that
case, `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 not
generated in this dataset build.
## Loading the dataset
Install the required packages:
```bash
pip 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.
```python
from huggingface_hub import HfApi, hf_hub_download
from PIL import Image
from pathlib import Path
import json
import 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 it
to a repository path before downloading it.
The following helper searches common image-reference fields. If your
record schema uses a different field, inspect a record and add that
field name to `IMAGE_KEYS`.
```python
IMAGE_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 local
image paths. This avoids the broken relative-path behavior of directly
casting the original JSONL image references.
```python
from 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 and
disk space for a large dataset. For exploratory work, download only the
images needed for the current task.
### Load the Parquet metadata table
```python
import pandas as pd
from 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:
```python
from 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 record
to 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.
```python
import json
from 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 are
rewritten, concatenated, or re-encoded, their byte offsets may become
invalid. Regenerate the Parquet index whenever the JSONL byte layout changes.
## Example analysis tasks
### Filter by aesthetic score
```python
high_scoring = df[
df["clip_aesthetic_score"] >= 7.0
]
print(len(high_scoring))
```
### Rank images by aesthetic score
```python
ranked = df.sort_values(
"clip_aesthetic_score",
ascending=False,
)
print(
ranked[
["idx", "group_number", "clip_aesthetic_score"]
].head(20)
)
```
### Inspect cluster sizes
```python
cluster_counts = (
df["group_number"]
.value_counts()
.sort_index()
)
print(cluster_counts)
```
### Compare aesthetic scores across clusters
```python
cluster_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
```python
cluster_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 was
not run.
Public availability does not automatically grant unrestricted rights to
redistribute or commercially use the images. Users are responsible for
checking 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.