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
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483

---
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.