File size: 2,655 Bytes
79052be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ac8011
79052be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
BIOSCAN-5M Dataset Loader

Author: Zahra Gharaee (https://github.com/zahrag)
License: MIT License
Description:
    This script serves as a usage demo for loading and accessing the BIOSCAN-5M dataset,
    which includes millions of annotated insect images along with associated metadata for machine learning and biodiversity research.
    It demonstrates how to use the dataset loader to access multiple image resolutions (e.g., cropped and original)
    and predefined splits (e.g., training, validation, pretraining).
    The demo integrates with the Hugging Face `datasets` library, showcasing how to load
    the dataset locally or from the Hugging Face Hub for seamless data preparation and machine learning workflows.
"""

import matplotlib.pyplot as plt
from datasets import load_dataset


def plot_image_with_metadata(ex):

    image = ex["image"]

    # Define the metadata fields to show
    fields_to_show = [
        "processid", "sampleid", "phylum", "class", "order", "family", "subfamily", "genus", "species",
        "dna_bin", "dna_barcode", "country", "province_state", "coord-lat", "coord-lon",
        "image_measurement_value", "area_fraction", "scale_factor", "split"
    ]

    # Prepare metadata as formatted strings
    metadata_lines = []
    for cnt, field in enumerate(fields_to_show):
        value = ex.get(field, "N/A")
        if field == "dna_barcode" and value not in ("N/A", None, ""):
            value = value[:10] + " ... " + f"({len(value)} bp)"  # bp: base pairs
        if field == "image_measurement_value" and value not in (None, "", "N/A"):
            value = int(value)
        metadata_lines.append(f"{cnt + 1}- {field}: {value}")

    fig, axs = plt.subplots(1, 2, figsize=(12, 6), gridspec_kw={'width_ratios': [1.2, 2]})
    plt.subplots_adjust(wspace=0.1)
    fig.suptitle(f"Image and Metadata: {ex.get('processid', '')}", fontsize=14)

    # Left: metadata
    axs[0].axis("off")
    metadata_text = "\n".join(metadata_lines)
    axs[0].text(0, 0.9, metadata_text, fontsize=14, va='top', ha='left', transform=axs[0].transAxes, wrap=True)

    # Right: image
    axs[1].imshow(image)
    axs[1].axis("off")

    plt.tight_layout()
    plt.show()


def main():

    ds_val = load_dataset("dataset.py", name="cropped_256_eval", split="validation", trust_remote_code=True)
    print(f"{ds_val.description}{ds_val.license}{ds_val.citation}")

    # Print and visualize a few examples
    samples_to_show = 10
    cnt = 1
    for i, sp in enumerate(ds_val):
        plot_image_with_metadata(sp)
        if cnt == samples_to_show:
            break
        cnt += 1

if __name__ == '__main__':
    main()