codeShare commited on
Commit
a16ab76
·
verified ·
1 Parent(s): c407533

Document repaired dataset image access

Browse files
Files changed (1) hide show
  1. README.md +288 -1
README.md CHANGED
@@ -315,4 +315,291 @@ for _, row in sampled.iterrows():
315
 
316
  - 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.
317
  - Image data is stored as base64 in JSONL records; it is decoded into image bytes when retrieved.
318
- - 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.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
 
316
  - 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.
317
  - Image data is stored as base64 in JSONL records; it is decoded into image bytes when retrieved.
318
+ - 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.
319
+
320
+ <!-- BEGIN REPAIRED DATA ACCESS DOCUMENTATION -->
321
+
322
+ ## Browsing images and captions in the repaired dataset
323
+
324
+ This repository stores its caption index and image records separately:
325
+
326
+ ```text
327
+ captions.parquet
328
+ images/
329
+ part_00000.jsonl
330
+ part_00001.jsonl
331
+ ...
332
+ ```
333
+
334
+ ### How the files relate
335
+
336
+ `captions.parquet` is the index. Each row describes a caption/image
337
+ record and contains the information needed to locate the corresponding
338
+ record in a JSONL shard.
339
+
340
+ The important fields are:
341
+
342
+ | Field | Meaning |
343
+ |---|---|
344
+ | `idx` | Global, sequential record ID across the dataset |
345
+ | `author` | Author/source associated with the record |
346
+ | `json_file` | Repository-relative path to the JSONL shard |
347
+ | `byte_offset` | Starting byte position of the JSONL record |
348
+ | `byte_length` | Number of bytes belonging to that record |
349
+
350
+ The `json_file`, `byte_offset`, and `byte_length` fields work together:
351
+ open the named JSONL shard in binary mode, seek to `byte_offset`, and
352
+ read exactly `byte_length` bytes. Decode those bytes as UTF-8 and parse
353
+ the resulting JSON.
354
+
355
+ **Important:** `idx` is a global dataset ID. It is not an author-local
356
+ ID and should not be interpreted as a line number or byte position.
357
+ Use the byte reference fields to retrieve the JSONL record.
358
+
359
+ The JSONL record contains the corresponding record data, including its
360
+ global `idx` and author information. The Parquet row and JSONL record
361
+ refer to the same logical item.
362
+
363
+ ### 1. Install dependencies
364
+
365
+ ```python
366
+ !pip -q install -U huggingface_hub pyarrow pandas
367
+ ```
368
+
369
+ ### 2. Load the Parquet index
370
+
371
+ ```python
372
+ import pyarrow.parquet as pq
373
+ from huggingface_hub import hf_hub_download
374
+
375
+ REPO_ID = "codeShare/adcom_captioned_ai_images"
376
+
377
+ parquet_path = hf_hub_download(
378
+ repo_id=REPO_ID,
379
+ repo_type="dataset",
380
+ filename="captions.parquet",
381
+ )
382
+
383
+ captions = pq.read_table(parquet_path)
384
+
385
+ print("Rows:", captions.num_rows)
386
+ print("Columns:", captions.column_names)
387
+ ```
388
+
389
+ ### 3. Find a record using its global `idx`
390
+
391
+ For example, retrieve global record ID `123`:
392
+
393
+ ```python
394
+ import pyarrow.compute as pc
395
+
396
+ def find_caption_row(global_idx):
397
+ matches = pc.equal(captions["idx"], global_idx)
398
+ result = captions.filter(matches)
399
+
400
+ if result.num_rows == 0:
401
+ raise KeyError(f"Global idx {global_idx} was not found.")
402
+
403
+ if result.num_rows > 1:
404
+ raise ValueError(
405
+ f"Global idx {global_idx} occurs more than once."
406
+ )
407
+
408
+ return result.to_pylist()[0]
409
+
410
+
411
+ row = find_caption_row(123)
412
+
413
+ print("Global idx:", row["idx"])
414
+ print("Author:", row["author"])
415
+ print("JSONL shard:", row["json_file"])
416
+ print("Byte offset:", row["byte_offset"])
417
+ print("Byte length:", row["byte_length"])
418
+ ```
419
+
420
+ You can also browse by author or other caption metadata using the
421
+ Parquet columns:
422
+
423
+ ```python
424
+ import pandas as pd
425
+
426
+ df = captions.to_pandas()
427
+
428
+ print(df.head())
429
+ print(df["author"].value_counts())
430
+ ```
431
+
432
+ ### 4. Retrieve the exact JSONL record using its byte reference
433
+
434
+ This is the recommended random-access method. It does not require
435
+ reading the entire JSONL shard or counting lines.
436
+
437
+ ```python
438
+ import json
439
+
440
+ def load_jsonl_record(row):
441
+ shard_path = hf_hub_download(
442
+ repo_id=REPO_ID,
443
+ repo_type="dataset",
444
+ filename=row["json_file"],
445
+ )
446
+
447
+ offset = int(row["byte_offset"])
448
+ length = int(row["byte_length"])
449
+
450
+ with open(shard_path, "rb") as f:
451
+ f.seek(offset)
452
+ record_bytes = f.read(length)
453
+
454
+ if len(record_bytes) != length:
455
+ raise IOError(
456
+ f"Expected {length} bytes, got {len(record_bytes)}."
457
+ )
458
+
459
+ record = json.loads(record_bytes.decode("utf-8"))
460
+
461
+ # Verify the Parquet-to-JSONL relationship.
462
+ assert int(record["idx"]) == int(row["idx"]), (
463
+ f"ID mismatch: Parquet={row['idx']}, "
464
+ f"JSONL={record.get('idx')}"
465
+ )
466
+
467
+ if "author" in record and "author" in row:
468
+ assert record["author"] == row["author"], (
469
+ "Author mismatch between Parquet and JSONL."
470
+ )
471
+
472
+ return record
473
+
474
+
475
+ record = load_jsonl_record(row)
476
+
477
+ print(json.dumps(record, indent=2, ensure_ascii=False))
478
+ ```
479
+
480
+ ### 5. Browse a record by global ID
481
+
482
+ Combine the two operations into one helper:
483
+
484
+ ```python
485
+ def get_record(global_idx):
486
+ row = find_caption_row(global_idx)
487
+ record = load_jsonl_record(row)
488
+ return row, record
489
+
490
+
491
+ row, record = get_record(123)
492
+
493
+ print("Global ID:", row["idx"])
494
+ print("Author:", row["author"])
495
+ print("Shard:", row["json_file"])
496
+ print("Record:")
497
+ print(json.dumps(record, indent=2, ensure_ascii=False))
498
+ ```
499
+
500
+ ### 6. Browse several records
501
+
502
+ ```python
503
+ global_ids = [0, 1, 2, 100, 123]
504
+
505
+ for global_idx in global_ids:
506
+ try:
507
+ row, record = get_record(global_idx)
508
+
509
+ print(
510
+ f"\nID={global_idx} | "
511
+ f"author={row['author']} | "
512
+ f"shard={row['json_file']}"
513
+ )
514
+ print(json.dumps(record, indent=2, ensure_ascii=False))
515
+
516
+ except KeyError:
517
+ print(f"Global ID {global_idx} not found.")
518
+ ```
519
+
520
+ ### 7. Inspect image-related fields
521
+
522
+ The JSONL record is the source of the image data and associated
523
+ metadata. Field names and image encoding should be inspected from
524
+ the record rather than assumed.
525
+
526
+ ```python
527
+ row, record = get_record(123)
528
+
529
+ print("Available fields:")
530
+ for key, value in record.items():
531
+ print(f"{key}: {type(value).__name__}")
532
+
533
+ print("\nPotential image-related fields:")
534
+ for key, value in record.items():
535
+ if any(term in key.lower() for term in ("image", "img", "url", "path")):
536
+ print(f"{key}: {str(value)[:300]}")
537
+ ```
538
+
539
+ If a record contains an image URL or a base64 data URI, the following
540
+ example can preview it:
541
+
542
+ ```python
543
+ import base64
544
+ import requests
545
+ from io import BytesIO
546
+ from PIL import Image
547
+ from IPython.display import display
548
+
549
+ def preview_image_field(record):
550
+ # Common URL field names.
551
+ for key in ("image_url", "url"):
552
+ value = record.get(key)
553
+ if isinstance(value, str) and value.startswith(("http://", "https://")):
554
+ response = requests.get(value, timeout=30)
555
+ response.raise_for_status()
556
+ display(Image.open(BytesIO(response.content)))
557
+ return
558
+
559
+ # Common base64 data URI field.
560
+ for key in ("image", "image_data", "image_base64"):
561
+ value = record.get(key)
562
+
563
+ if not isinstance(value, str):
564
+ continue
565
+
566
+ if value.startswith("data:image/") and "," in value:
567
+ encoded = value.split(",", 1)[1]
568
+ image_bytes = base64.b64decode(encoded)
569
+ display(Image.open(BytesIO(image_bytes)))
570
+ return
571
+
572
+ if key == "image_base64":
573
+ image_bytes = base64.b64decode(value)
574
+ display(Image.open(BytesIO(image_bytes)))
575
+ return
576
+
577
+ print(
578
+ "No recognized URL or base64 image field was found. "
579
+ "Inspect the record fields above to determine its image encoding."
580
+ )
581
+
582
+
583
+ row, record = get_record(123)
584
+ preview_image_field(record)
585
+ ```
586
+
587
+ ### Data integrity and access rules
588
+
589
+ - Use `idx` as the global record identifier.
590
+ - Use `json_file` to identify the JSONL shard.
591
+ - Use `byte_offset` and `byte_length` together for exact random access.
592
+ - Read JSONL files in binary mode when using byte offsets.
593
+ - Decode the selected byte range as UTF-8 before parsing JSON.
594
+ - Do not treat byte offsets as character offsets or line numbers.
595
+ - Do not derive JSONL paths from author names or local IDs.
596
+ - The Parquet index and JSONL record should agree on global `idx`
597
+ and author.
598
+ - When adding records, assign new global IDs after the current maximum
599
+ and calculate byte offsets and lengths from the exact serialized
600
+ UTF-8 JSONL bytes.
601
+
602
+ This structure allows efficient lookup of an individual record without
603
+ loading every JSONL shard into memory.
604
+
605
+ <!-- END REPAIRED DATA ACCESS DOCUMENTATION -->