Datasets:
File size: 16,301 Bytes
8c3aca3 1749280 c334f1c 8c3aca3 c334f1c 1749280 c334f1c 1749280 c334f1c 8c3aca3 1749280 8c3aca3 d4684ad 8c3aca3 a16ab76 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 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 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 | ---
pretty_name: Adcom Captioned AI Images
configs:
- config_name: default
data_files:
- split: train
path: captions.parquet
tags:
- images
- captions
- ai-generated-images
- natural-language
license: apache-2.0
language:
- en
---
# ADCOM Captioned AI Images
## Dataset description
Adcom's captioned AI Images is a collection of images paired with associated
captioning and descriptive metadata.
A notebook is provided for sampling this dataset at https://huggingface.co/datasets/codeShare/adcom_captioned_ai_images/blob/main/sample_multi_author_dataset_fixed.ipynb
This dataset does **not** have NSFW content aside from suggestive female oriented themes.
The repository uses an indexed storage layout designed to make image retrieval
more efficient. Instead of storing all image data directly inside a single
metadata file, it separates the metadata index from the image data.
The dataset consists of:
- A Parquet metadata index: `captions.parquet`
- JSONL image shards containing the image data
- Byte offsets and record lengths in the Parquet index for direct image access
This layout allows users to retrieve individual images without downloading
and scanning every image shard.
## Repository structure
```text
adcom_captioned_ai_images/
│
├── README.md
├── captions.parquet
│
└── [JSONL image shards]
├── ...
└── ...
```
The exact shard paths are stored in the `json_file` column of
`captions.parquet`. Use those paths rather than assuming fixed shard names.
### 1. Metadata index: `captions.parquet`
The Parquet file contains one metadata/index row per image.
| Column | Description |
|---|---|
| `idx` | Image identifier |
| `prompt` | Text prompt or caption associated with the image |
| `tags` | Descriptive tags associated with the image |
| `author` | Author or contributor |
| `json_file` | Repository-relative path to the JSONL shard containing the image |
| `byte_offset` | Zero-based byte offset of the JSONL record within that shard |
| `byte_length` | Number of bytes to read for that record |
The index columns `json_file`, `byte_offset`, and `byte_length` are used
together to locate an image record directly.
Offsets and lengths refer to bytes, not character positions.
### 2. Image data: JSONL shards
Images are stored in JSONL files. Each line represents an individual image
record encoded as JSON.
A record has the following structure:
```json
{
"idx": "IMAGE_ID",
"image": "data:image/png;base64,..."
}
```
The `image` field contains a base64-encoded image, commonly represented as
a data URI. Consumers should also allow for a raw base64 string.
The `idx` field identifies the image and corresponds to the `idx` value in
the Parquet index.
### 3. How indexed retrieval works
For an image with a given `idx`:
1. Find its row in `captions.parquet`.
2. Read the row's `json_file`, `byte_offset`, and `byte_length`.
3. Download the referenced JSONL shard.
4. Seek to `byte_offset` in binary mode.
5. Read `byte_length` bytes.
6. Parse the JSON record and decode its base64 image.
This avoids scanning the entire shard for the selected image.
---
## Quick start
### Install dependencies
```bash
pip install pandas pyarrow pillow huggingface_hub
```
### Load the metadata index
```python
import pandas as pd
from huggingface_hub import hf_hub_download
REPO_ID = "codeShare/adcom_captioned_ai_images"
parquet_path = hf_hub_download(
repo_id=REPO_ID,
filename="captions.parquet",
repo_type="dataset"
)
metadata = pd.read_parquet(parquet_path)
print(metadata.head())
print(f"Total indexed images: {len(metadata):,}")
```
For a private or gated repository, authenticate with a Hugging Face
access token and pass it as the `token` argument to `hf_hub_download`.
### Retrieve one image by ID
This example downloads only the shard containing the requested image and
reads only the indexed record.
```python
import json
import base64
import re
import io
import pandas as pd
from PIL import Image
from huggingface_hub import hf_hub_download
REPO_ID = "codeShare/adcom_captioned_ai_images"
# Load the metadata index.
parquet_path = hf_hub_download(
repo_id=REPO_ID,
filename="captions.parquet",
repo_type="dataset"
)
metadata = pd.read_parquet(parquet_path)
# Choose an image ID from the index.
target_idx = str(metadata.iloc[0]["idx"])
# Find its index entry.
row = metadata.loc[
metadata["idx"].astype(str) == target_idx
].iloc[0]
# Download only the required shard.
shard_path = hf_hub_download(
repo_id=REPO_ID,
filename=str(row["json_file"]),
repo_type="dataset"
)
# Read the exact JSONL record using its byte location.
with open(shard_path, "rb") as f:
f.seek(int(row["byte_offset"]))
raw_record = f.read(int(row["byte_length"]))
record = json.loads(raw_record.decode("utf-8"))
# Verify the retrieved record.
assert str(record["idx"]) == target_idx
# Decode the image.
image_value = record["image"].strip()
if image_value.startswith("data:") and "," in image_value:
image_value = image_value.split(",", 1)[1]
image_value = re.sub(r"\s+", "", image_value)
image_bytes = base64.b64decode(image_value)
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
display(image)
print("Image ID:", target_idx)
print("Prompt:", row["prompt"])
print("Author:", row["author"])
print("Tags:", row["tags"])
```
### Retrieve a random sample of images
The following example samples metadata first and downloads only the shards
needed for the selected images.
```python
import json
import base64
import re
import io
import pandas as pd
from PIL import Image
from huggingface_hub import hf_hub_download
REPO_ID = "codeShare/adcom_captioned_ai_images"
NUM_SAMPLES = 10
RANDOM_SEED = 42
# Load the index.
parquet_path = hf_hub_download(
repo_id=REPO_ID,
filename="captions.parquet",
repo_type="dataset"
)
metadata = pd.read_parquet(parquet_path)
# Optional author filter.
# Set to None to include all authors.
AUTHOR_FILTER = "Adcom"
if AUTHOR_FILTER is not None:
metadata = metadata[
metadata["author"].fillna("").astype(str).str.casefold()
== AUTHOR_FILTER.casefold()
]
if metadata.empty:
raise ValueError("No matching records found.")
# Reproducible random sample.
sampled = metadata.sample(
n=min(NUM_SAMPLES, len(metadata)),
random_state=RANDOM_SEED
)
# Download only the shards required by the sample.
shard_cache = {}
for _, row in sampled.iterrows():
shard_name = str(row["json_file"])
if shard_name not in shard_cache:
shard_cache[shard_name] = hf_hub_download(
repo_id=REPO_ID,
filename=shard_name,
repo_type="dataset"
)
# Retrieve the indexed JSONL record.
with open(shard_cache[shard_name], "rb") as f:
f.seek(int(row["byte_offset"]))
raw_record = f.read(int(row["byte_length"]))
record = json.loads(raw_record.decode("utf-8"))
if str(record["idx"]) != str(row["idx"]):
raise ValueError("Image ID does not match the metadata index.")
# Decode image data.
image_value = record["image"].strip()
if image_value.startswith("data:") and "," in image_value:
image_value = image_value.split(",", 1)[1]
image_value = re.sub(r"\s+", "", image_value)
image_bytes = base64.b64decode(image_value)
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
print("Image ID:", row["idx"])
print("Prompt:", row["prompt"])
print("Author:", row["author"])
display(image)
image.close()
```
---
## Performance notes
- **Metadata-first sampling:** Select records from the Parquet index before downloading image data.
- **Selective shard downloads:** Only download shards referenced by the selected records.
- **Direct record access:** Use byte offsets and lengths instead of scanning JSONL files.
- **Reproducible sampling:** Set `random_state` to a fixed integer to reproduce a sample.
- **Private repository support:** Pass a Hugging Face token to the download functions when authentication is required.
## Important notes
- The Parquet index and JSONL shards must remain consistent. If shard contents are rewritten or reordered, the corresponding byte offsets and lengths must be regenerated.
- Image data is stored as base64 in JSONL records; it is decoded into image bytes when retrieved.
- The dataset card does not declare a license. Please consult the dataset owner for licensing and usage permissions before redistributing or using the data commercially.
<!-- BEGIN REPAIRED DATA ACCESS DOCUMENTATION -->
## Browsing images and captions in the repaired dataset
This repository stores its caption index and image records separately:
```text
captions.parquet
images/
part_00000.jsonl
part_00001.jsonl
...
```
### How the files relate
`captions.parquet` is the index. Each row describes a caption/image
record and contains the information needed to locate the corresponding
record in a JSONL shard.
The important fields are:
| Field | Meaning |
|---|---|
| `idx` | Global, sequential record ID across the dataset |
| `author` | Author/source associated with the record |
| `json_file` | Repository-relative path to the JSONL shard |
| `byte_offset` | Starting byte position of the JSONL record |
| `byte_length` | Number of bytes belonging to that record |
The `json_file`, `byte_offset`, and `byte_length` fields work together:
open the named JSONL shard in binary mode, seek to `byte_offset`, and
read exactly `byte_length` bytes. Decode those bytes as UTF-8 and parse
the resulting JSON.
**Important:** `idx` is a global dataset ID. It is not an author-local
ID and should not be interpreted as a line number or byte position.
Use the byte reference fields to retrieve the JSONL record.
The JSONL record contains the corresponding record data, including its
global `idx` and author information. The Parquet row and JSONL record
refer to the same logical item.
### 1. Install dependencies
```python
!pip -q install -U huggingface_hub pyarrow pandas
```
### 2. Load the Parquet index
```python
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
REPO_ID = "codeShare/adcom_captioned_ai_images"
parquet_path = hf_hub_download(
repo_id=REPO_ID,
repo_type="dataset",
filename="captions.parquet",
)
captions = pq.read_table(parquet_path)
print("Rows:", captions.num_rows)
print("Columns:", captions.column_names)
```
### 3. Find a record using its global `idx`
For example, retrieve global record ID `123`:
```python
import pyarrow.compute as pc
def find_caption_row(global_idx):
matches = pc.equal(captions["idx"], global_idx)
result = captions.filter(matches)
if result.num_rows == 0:
raise KeyError(f"Global idx {global_idx} was not found.")
if result.num_rows > 1:
raise ValueError(
f"Global idx {global_idx} occurs more than once."
)
return result.to_pylist()[0]
row = find_caption_row(123)
print("Global idx:", row["idx"])
print("Author:", row["author"])
print("JSONL shard:", row["json_file"])
print("Byte offset:", row["byte_offset"])
print("Byte length:", row["byte_length"])
```
You can also browse by author or other caption metadata using the
Parquet columns:
```python
import pandas as pd
df = captions.to_pandas()
print(df.head())
print(df["author"].value_counts())
```
### 4. Retrieve the exact JSONL record using its byte reference
This is the recommended random-access method. It does not require
reading the entire JSONL shard or counting lines.
```python
import json
def load_jsonl_record(row):
shard_path = hf_hub_download(
repo_id=REPO_ID,
repo_type="dataset",
filename=row["json_file"],
)
offset = int(row["byte_offset"])
length = int(row["byte_length"])
with open(shard_path, "rb") as f:
f.seek(offset)
record_bytes = f.read(length)
if len(record_bytes) != length:
raise IOError(
f"Expected {length} bytes, got {len(record_bytes)}."
)
record = json.loads(record_bytes.decode("utf-8"))
# Verify the Parquet-to-JSONL relationship.
assert int(record["idx"]) == int(row["idx"]), (
f"ID mismatch: Parquet={row['idx']}, "
f"JSONL={record.get('idx')}"
)
if "author" in record and "author" in row:
assert record["author"] == row["author"], (
"Author mismatch between Parquet and JSONL."
)
return record
record = load_jsonl_record(row)
print(json.dumps(record, indent=2, ensure_ascii=False))
```
### 5. Browse a record by global ID
Combine the two operations into one helper:
```python
def get_record(global_idx):
row = find_caption_row(global_idx)
record = load_jsonl_record(row)
return row, record
row, record = get_record(123)
print("Global ID:", row["idx"])
print("Author:", row["author"])
print("Shard:", row["json_file"])
print("Record:")
print(json.dumps(record, indent=2, ensure_ascii=False))
```
### 6. Browse several records
```python
global_ids = [0, 1, 2, 100, 123]
for global_idx in global_ids:
try:
row, record = get_record(global_idx)
print(
f"\nID={global_idx} | "
f"author={row['author']} | "
f"shard={row['json_file']}"
)
print(json.dumps(record, indent=2, ensure_ascii=False))
except KeyError:
print(f"Global ID {global_idx} not found.")
```
### 7. Inspect image-related fields
The JSONL record is the source of the image data and associated
metadata. Field names and image encoding should be inspected from
the record rather than assumed.
```python
row, record = get_record(123)
print("Available fields:")
for key, value in record.items():
print(f"{key}: {type(value).__name__}")
print("\nPotential image-related fields:")
for key, value in record.items():
if any(term in key.lower() for term in ("image", "img", "url", "path")):
print(f"{key}: {str(value)[:300]}")
```
If a record contains an image URL or a base64 data URI, the following
example can preview it:
```python
import base64
import requests
from io import BytesIO
from PIL import Image
from IPython.display import display
def preview_image_field(record):
# Common URL field names.
for key in ("image_url", "url"):
value = record.get(key)
if isinstance(value, str) and value.startswith(("http://", "https://")):
response = requests.get(value, timeout=30)
response.raise_for_status()
display(Image.open(BytesIO(response.content)))
return
# Common base64 data URI field.
for key in ("image", "image_data", "image_base64"):
value = record.get(key)
if not isinstance(value, str):
continue
if value.startswith("data:image/") and "," in value:
encoded = value.split(",", 1)[1]
image_bytes = base64.b64decode(encoded)
display(Image.open(BytesIO(image_bytes)))
return
if key == "image_base64":
image_bytes = base64.b64decode(value)
display(Image.open(BytesIO(image_bytes)))
return
print(
"No recognized URL or base64 image field was found. "
"Inspect the record fields above to determine its image encoding."
)
row, record = get_record(123)
preview_image_field(record)
```
### Data integrity and access rules
- Use `idx` as the global record identifier.
- Use `json_file` to identify the JSONL shard.
- Use `byte_offset` and `byte_length` together for exact random access.
- Read JSONL files in binary mode when using byte offsets.
- Decode the selected byte range as UTF-8 before parsing JSON.
- Do not treat byte offsets as character offsets or line numbers.
- Do not derive JSONL paths from author names or local IDs.
- The Parquet index and JSONL record should agree on global `idx`
and author.
- When adding records, assign new global IDs after the current maximum
and calculate byte offsets and lengths from the exact serialized
UTF-8 JSONL bytes.
This structure allows efficient lookup of an individual record without
loading every JSONL shard into memory.
<!-- END REPAIRED DATA ACCESS DOCUMENTATION -->
|