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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
BIOSCAN-5M Dataset Loader
|
| 3 |
+
|
| 4 |
+
Author: Zahra Gharaee (https://github.com/zahrag)
|
| 5 |
+
License: MIT License
|
| 6 |
+
Description:
|
| 7 |
+
This custom dataset loader provides structured access to the BIOSCAN-5M dataset,
|
| 8 |
+
which includes millions of annotated insect images and associated metadata
|
| 9 |
+
for machine learning and biodiversity research. It supports multiple image resolutions
|
| 10 |
+
(e.g., cropped and original), and predefined splits for training, evaluation,
|
| 11 |
+
and pretraining. The loader integrates with the Hugging Face `datasets` library
|
| 12 |
+
to simplify data access and preparation.
|
| 13 |
+
|
| 14 |
+
Usage
|
| 15 |
+
|
| 16 |
+
To load the dataset locally from bioscan5m.py:
|
| 17 |
+
|
| 18 |
+
from datasets import load_dataset
|
| 19 |
+
ds = load_dataset("bioscan5m.py", name="cropped_256_eval", split="validation", trust_remote_code=True)
|
| 20 |
+
|
| 21 |
+
To load the dataset from the Hugging Face Hub:
|
| 22 |
+
|
| 23 |
+
from datasets import load_dataset
|
| 24 |
+
ds = load_dataset("bioscan-ml/BIOSCAN-5M", name="cropped_256_eval", split="validation", trust_remote_code=True)
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
import os
|
| 29 |
+
import csv
|
| 30 |
+
import datasets
|
| 31 |
+
import json
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
_CITATION = """\n----Citation:\n@inproceedings{gharaee2024bioscan5m,
|
| 35 |
+
title={{BIOSCAN-5M}: A Multimodal Dataset for Insect Biodiversity},
|
| 36 |
+
booktitle={Advances in Neural Information Processing Systems},
|
| 37 |
+
author={Zahra Gharaee and Scott C. Lowe and ZeMing Gong and Pablo Millan Arias
|
| 38 |
+
and Nicholas Pellegrino and Austin T. Wang and Joakim Bruslund Haurum
|
| 39 |
+
and Iuliia Zarubiieva and Lila Kari and Dirk Steinke and Graham W. Taylor
|
| 40 |
+
and Paul Fieguth and Angel X. Chang},
|
| 41 |
+
editor={A. Globerson and L. Mackey and D. Belgrave and A. Fan and U. Paquet and J. Tomczak and C. Zhang},
|
| 42 |
+
pages={36285--36313},
|
| 43 |
+
publisher={Curran Associates, Inc.},
|
| 44 |
+
year={2024},
|
| 45 |
+
volume={37},
|
| 46 |
+
url={https://proceedings.neurips.cc/paper_files/paper/2024/file/3fdbb472813041c9ecef04c20c2b1e5a-Paper-Datasets_and_Benchmarks_Track.pdf}
|
| 47 |
+
}\n"""
|
| 48 |
+
|
| 49 |
+
_DESCRIPTION = (
|
| 50 |
+
"\n----Description:\n'BIOSCAN-5M' is a comprehensive multimodal dataset containing data for over 5 million insect specimens.\n"
|
| 51 |
+
"Released in 2024, this dataset substantially enhances existing image-based biological resources by incorporating:\n"
|
| 52 |
+
"- Taxonomic labels\n- Raw nucleotide barcode sequences \n- Assigned barcode index numbers\n- Geographical information\n"
|
| 53 |
+
"- Specimen size information\n\n"
|
| 54 |
+
"-------------- Dataset Feature Descriptions --------------\n"
|
| 55 |
+
"1- processid: A unique number assigned by BOLD (International Barcode of Life Consortium).\n"
|
| 56 |
+
"2- sampleid: A unique identifier given by the collector.\n"
|
| 57 |
+
"3- taxon: Bio.info: Most specific taxonomy rank.\n"
|
| 58 |
+
"4- phylum: Bio.info: Taxonomic classification label at phylum rank.\n"
|
| 59 |
+
"5- class: Bio.info: Taxonomic classification label at class rank.\n"
|
| 60 |
+
"6- order: Bio.info: Taxonomic classification label at order rank.\n"
|
| 61 |
+
"7- family: Bio.info: Taxonomic classification label at family rank.\n"
|
| 62 |
+
"8- subfamily: Bio.info: Taxonomic classification label at subfamily rank.\n"
|
| 63 |
+
"9- genus: Bio.info: Taxonomic classification label at genus rank.\n"
|
| 64 |
+
"10- species: Bio.info: Taxonomic classification label at species rank.\n"
|
| 65 |
+
"11- dna_bin: Bio.info: Barcode Index Number (BIN).\n"
|
| 66 |
+
"12- dna_barcode: Bio.info: Nucleotide barcode sequence.\n"
|
| 67 |
+
"13- country: Geo.info: Country associated with the site of collection.\n"
|
| 68 |
+
"14- province_state: Geo.info: Province/state associated with the site of collection.\n"
|
| 69 |
+
"15- coord-lat: Geo.info: Latitude (WGS 84; decimal degrees) of the collection site.\n"
|
| 70 |
+
"16- coord-lon: Geo.info: Longitude (WGS 84; decimal degrees) of the collection site.\n"
|
| 71 |
+
"17- image_measurement_value: Size.info: Number of pixels occupied by the organism.\n"
|
| 72 |
+
"18- area_fraction: Size.info: Fraction of the original image the cropped image comprises.\n"
|
| 73 |
+
"19- scale_factor: Size.info: Ratio of the cropped image to the cropped_256 image.\n"
|
| 74 |
+
"20- inferred_ranks: An integer indicating at which taxonomic ranks the label is inferred.\n"
|
| 75 |
+
"21- split: Split set (partition) the sample belongs to.\n"
|
| 76 |
+
"22- index_bioscan_1M_insect: An index to locate organism in BIOSCAN-1M Insect metadata.\n"
|
| 77 |
+
"23- chunk: The packaging subdirectory name (or empty string) for this image.\n"
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
license = "\n----License:\nCC BY 3.0: Creative Commons Attribution 3.0 Unported (https://creativecommons.org/licenses/by/3.0/)\n"
|
| 81 |
+
|
| 82 |
+
SUPPORTED_FORMATS = {"csv": "csv", "jsonld": "jsonld"}
|
| 83 |
+
|
| 84 |
+
SUPPORTED_PACKAGES = {
|
| 85 |
+
"original_256": "BIOSCAN_5M_original_256.zip",
|
| 86 |
+
"original_256_pretrain": "BIOSCAN_5M_original_256_pretrain.zip",
|
| 87 |
+
"original_256_train": "BIOSCAN_5M_original_256_train.zip",
|
| 88 |
+
"original_256_eval": "BIOSCAN_5M_original_256_eval.zip",
|
| 89 |
+
"cropped_256": "BIOSCAN_5M_cropped_256.zip",
|
| 90 |
+
"cropped_256_pretrain": "BIOSCAN_5M_cropped_256_pretrain.zip",
|
| 91 |
+
"cropped_256_train": "BIOSCAN_5M_cropped_256_train.zip",
|
| 92 |
+
"cropped_256_eval": "BIOSCAN_5M_cropped_256_eval.zip",
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def safe_cast(value, cast_type):
|
| 97 |
+
try:
|
| 98 |
+
return cast_type(value) if value else None
|
| 99 |
+
except ValueError:
|
| 100 |
+
return None
|
| 101 |
+
|
| 102 |
+
def extract_info_from_filename(package_name):
|
| 103 |
+
"""
|
| 104 |
+
Extract imgtype and split_name using string ops.
|
| 105 |
+
Assumes package_name format: BIOSCAN_5M_<imgtype>[_<split_name>].zip
|
| 106 |
+
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
if package_name not in SUPPORTED_PACKAGES.values():
|
| 110 |
+
raise ValueError(
|
| 111 |
+
f"Unsupported package: {package_name}\n"
|
| 112 |
+
f"Supported packages are:\n - " + "\n - ".join(sorted(SUPPORTED_PACKAGES.values()))
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# Remove prefix and suffix
|
| 116 |
+
core = package_name.replace("BIOSCAN_5M_", "").replace(".zip", "")
|
| 117 |
+
|
| 118 |
+
parts = core.split("_")
|
| 119 |
+
|
| 120 |
+
if len(parts) == 2:
|
| 121 |
+
imgtype = "_".join(parts)
|
| 122 |
+
data_split = "full"
|
| 123 |
+
elif len(parts) == 3:
|
| 124 |
+
imgtype = "_".join(parts[:2])
|
| 125 |
+
data_split = parts[2]
|
| 126 |
+
else:
|
| 127 |
+
imgtype, data_split = None, None # Unexpected format
|
| 128 |
+
|
| 129 |
+
return imgtype, data_split
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class BIOSCAN5MConfig(datasets.BuilderConfig):
|
| 133 |
+
def __init__(self, metadata_format="csv", package_name="BIOSCAN_5M_cropped_256.zip", **kwargs):
|
| 134 |
+
super().__init__(**kwargs)
|
| 135 |
+
self.metadata_format = metadata_format
|
| 136 |
+
self.package_name = package_name
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class BIOSCAN5M_Dataset(datasets.GeneratorBasedBuilder):
|
| 140 |
+
"""Custom dataset loader for BIOSCAN-5M (images + metadata)."""
|
| 141 |
+
|
| 142 |
+
BUILDER_CONFIGS = [
|
| 143 |
+
BIOSCAN5MConfig(
|
| 144 |
+
name="cropped_256_eval",
|
| 145 |
+
version=datasets.Version("0.0.0"),
|
| 146 |
+
description="Cropped_256 images for evaluation splits.",
|
| 147 |
+
metadata_format=SUPPORTED_FORMATS["csv"],
|
| 148 |
+
package_name=SUPPORTED_PACKAGES["cropped_256_eval"],
|
| 149 |
+
),
|
| 150 |
+
BIOSCAN5MConfig(
|
| 151 |
+
name="cropped_256_train",
|
| 152 |
+
version=datasets.Version("0.0.0"),
|
| 153 |
+
description="Cropped_256 images for training split.",
|
| 154 |
+
metadata_format=SUPPORTED_FORMATS["csv"],
|
| 155 |
+
package_name=SUPPORTED_PACKAGES["cropped_256_train"],
|
| 156 |
+
),
|
| 157 |
+
BIOSCAN5MConfig(
|
| 158 |
+
name="cropped_256_pretrain",
|
| 159 |
+
version=datasets.Version("0.0.0"),
|
| 160 |
+
description="Cropped images for pretraining split.",
|
| 161 |
+
metadata_format=SUPPORTED_FORMATS["csv"],
|
| 162 |
+
package_name=SUPPORTED_PACKAGES["cropped_256_pretrain"],
|
| 163 |
+
),
|
| 164 |
+
BIOSCAN5MConfig(
|
| 165 |
+
name="cropped_256",
|
| 166 |
+
version=datasets.Version("0.0.0"),
|
| 167 |
+
description="Cropped_256 images for full splits.",
|
| 168 |
+
metadata_format=SUPPORTED_FORMATS["csv"],
|
| 169 |
+
package_name=SUPPORTED_PACKAGES["cropped_256"],
|
| 170 |
+
),
|
| 171 |
+
BIOSCAN5MConfig(
|
| 172 |
+
name="original_256_eval",
|
| 173 |
+
version=datasets.Version("0.0.0"),
|
| 174 |
+
description="Original_256 images for evaluation splits.",
|
| 175 |
+
metadata_format=SUPPORTED_FORMATS["csv"],
|
| 176 |
+
package_name=SUPPORTED_PACKAGES["original_256_eval"],
|
| 177 |
+
),
|
| 178 |
+
BIOSCAN5MConfig(
|
| 179 |
+
name="original_256_train",
|
| 180 |
+
version=datasets.Version("0.0.0"),
|
| 181 |
+
description="Original_256 images for training split.",
|
| 182 |
+
metadata_format=SUPPORTED_FORMATS["csv"],
|
| 183 |
+
package_name=SUPPORTED_PACKAGES["original_256_train"],
|
| 184 |
+
),
|
| 185 |
+
BIOSCAN5MConfig(
|
| 186 |
+
name="original_256_pretrain",
|
| 187 |
+
version=datasets.Version("0.0.0"),
|
| 188 |
+
description="Original images for pretraining split.",
|
| 189 |
+
metadata_format=SUPPORTED_FORMATS["csv"],
|
| 190 |
+
package_name=SUPPORTED_PACKAGES["original_256_pretrain"],
|
| 191 |
+
),
|
| 192 |
+
BIOSCAN5MConfig(
|
| 193 |
+
name="original_256",
|
| 194 |
+
version=datasets.Version("0.0.0"),
|
| 195 |
+
description="Original_256 images for full splits.",
|
| 196 |
+
metadata_format=SUPPORTED_FORMATS["csv"],
|
| 197 |
+
package_name=SUPPORTED_PACKAGES["original_256"],
|
| 198 |
+
),
|
| 199 |
+
]
|
| 200 |
+
|
| 201 |
+
def _info(self):
|
| 202 |
+
return datasets.DatasetInfo(
|
| 203 |
+
description=_DESCRIPTION,
|
| 204 |
+
features=datasets.Features({
|
| 205 |
+
"image": datasets.Image(),
|
| 206 |
+
"processid": datasets.Value("string"),
|
| 207 |
+
"sampleid": datasets.Value("string"),
|
| 208 |
+
"taxon": datasets.Value("string"),
|
| 209 |
+
"phylum": datasets.Value("string"),
|
| 210 |
+
"class": datasets.Value("string"),
|
| 211 |
+
"order": datasets.Value("string"),
|
| 212 |
+
"family": datasets.Value("string"),
|
| 213 |
+
"subfamily": datasets.Value("string"),
|
| 214 |
+
"genus": datasets.Value("string"),
|
| 215 |
+
"species": datasets.Value("string"),
|
| 216 |
+
"dna_bin": datasets.Value("string"),
|
| 217 |
+
"dna_barcode": datasets.Value("string"),
|
| 218 |
+
"country": datasets.Value("string"),
|
| 219 |
+
"province_state": datasets.Value("string"),
|
| 220 |
+
"coord-lat": datasets.Value("float"),
|
| 221 |
+
"coord-lon": datasets.Value("float"),
|
| 222 |
+
"image_measurement_value": datasets.Value("int64"),
|
| 223 |
+
"area_fraction": datasets.Value("float"),
|
| 224 |
+
"scale_factor": datasets.Value("float"),
|
| 225 |
+
"inferred_ranks": datasets.Value("int32"),
|
| 226 |
+
"split": datasets.Value("string"),
|
| 227 |
+
"index_bioscan_1M_insect": datasets.Value("int32"),
|
| 228 |
+
"chunk": datasets.Value("string"),
|
| 229 |
+
}),
|
| 230 |
+
supervised_keys=None,
|
| 231 |
+
homepage="https://huggingface.co/datasets/bioscan-ml/BIOSCAN-5M",
|
| 232 |
+
citation=_CITATION,
|
| 233 |
+
license=license,
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
def _split_generators(self, dl_manager, **kwargs ):
|
| 237 |
+
"""Custom dataset split generator"""
|
| 238 |
+
|
| 239 |
+
metadata_format = self.config.metadata_format
|
| 240 |
+
package_name = self.config.package_name
|
| 241 |
+
|
| 242 |
+
imgtype, data_split = extract_info_from_filename(package_name)
|
| 243 |
+
|
| 244 |
+
# Download metadata
|
| 245 |
+
metadata_url = "https://huggingface.co/datasets/bioscan-ml/BIOSCAN-5M/resolve/main/BIOSCAN_5M_Insect_Dataset_metadata_MultiTypes.zip"
|
| 246 |
+
metadata_archive = dl_manager.download_and_extract(metadata_url)
|
| 247 |
+
metadata_file = os.path.join(
|
| 248 |
+
metadata_archive,
|
| 249 |
+
f"bioscan5m/metadata/{metadata_format}/BIOSCAN_5M_Insect_Dataset_metadata.{metadata_format}"
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
# Download image archives
|
| 253 |
+
image_url = f"https://huggingface.co/datasets/bioscan-ml/BIOSCAN-5M/resolve/main/{package_name}"
|
| 254 |
+
image_archives = dl_manager.download_and_extract([image_url])
|
| 255 |
+
image_dirs = [archive for archive in image_archives]
|
| 256 |
+
|
| 257 |
+
# Define all available splits
|
| 258 |
+
eval_splits = [
|
| 259 |
+
"val", "test", "val_unseen", "test_unseen", "key_unseen", "other_heldout"
|
| 260 |
+
]
|
| 261 |
+
splits = ["pretrain", "train"] + eval_splits
|
| 262 |
+
|
| 263 |
+
hf_splits = {
|
| 264 |
+
"train": datasets.Split.TRAIN,
|
| 265 |
+
"val": datasets.Split.VALIDATION,
|
| 266 |
+
"test": datasets.Split.TEST,
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
if data_split == "full": # All partitions
|
| 270 |
+
return [
|
| 271 |
+
datasets.SplitGenerator(
|
| 272 |
+
name=hf_splits.get(split, split),
|
| 273 |
+
gen_kwargs={
|
| 274 |
+
"metadata_path": metadata_file,
|
| 275 |
+
"image_dirs": image_dirs,
|
| 276 |
+
"split": split,
|
| 277 |
+
"imgtype": imgtype,
|
| 278 |
+
},
|
| 279 |
+
)
|
| 280 |
+
for split in splits
|
| 281 |
+
]
|
| 282 |
+
|
| 283 |
+
elif data_split == "eval": # Evaluation partitions
|
| 284 |
+
return [
|
| 285 |
+
datasets.SplitGenerator(
|
| 286 |
+
name=hf_splits.get(split, split),
|
| 287 |
+
gen_kwargs={
|
| 288 |
+
"metadata_path": metadata_file,
|
| 289 |
+
"image_dirs": image_dirs,
|
| 290 |
+
"split": split,
|
| 291 |
+
"imgtype": imgtype,
|
| 292 |
+
},
|
| 293 |
+
)
|
| 294 |
+
for split in eval_splits
|
| 295 |
+
]
|
| 296 |
+
|
| 297 |
+
else: # train and pretrain partitions
|
| 298 |
+
return [
|
| 299 |
+
datasets.SplitGenerator(
|
| 300 |
+
name=hf_splits.get(data_split, data_split),
|
| 301 |
+
gen_kwargs={
|
| 302 |
+
"metadata_path": metadata_file,
|
| 303 |
+
"image_dirs": image_dirs,
|
| 304 |
+
"split": data_split,
|
| 305 |
+
"imgtype": imgtype,
|
| 306 |
+
},
|
| 307 |
+
)
|
| 308 |
+
]
|
| 309 |
+
|
| 310 |
+
def _generate_examples(self, metadata_path, image_dirs, split, imgtype):
|
| 311 |
+
|
| 312 |
+
if metadata_path.endswith(".csv"):
|
| 313 |
+
with open(metadata_path, encoding="utf-8") as f:
|
| 314 |
+
reader = csv.DictReader(f)
|
| 315 |
+
for idx, row in enumerate(reader):
|
| 316 |
+
if row["split"] != split:
|
| 317 |
+
continue # Skip others and keep the chosen split samples
|
| 318 |
+
|
| 319 |
+
processid = row["processid"]
|
| 320 |
+
chunk = row.get("chunk", "").strip() if row.get("chunk") else ""
|
| 321 |
+
|
| 322 |
+
# Construct expected relative path
|
| 323 |
+
if chunk == "":
|
| 324 |
+
rel_path = f"bioscan5m/images/{imgtype}/{split}/{processid}.jpg"
|
| 325 |
+
else:
|
| 326 |
+
rel_path = f"bioscan5m/images/{imgtype}/{split}/{chunk}/{processid}.jpg"
|
| 327 |
+
|
| 328 |
+
# Search for the image file inside extracted image_dirs
|
| 329 |
+
image_path = None
|
| 330 |
+
for image_dir in image_dirs:
|
| 331 |
+
potential_path = os.path.join(image_dir, rel_path)
|
| 332 |
+
if os.path.exists(potential_path):
|
| 333 |
+
image_path = potential_path
|
| 334 |
+
break # Image found; end search
|
| 335 |
+
|
| 336 |
+
if image_path is None:
|
| 337 |
+
print(f" ---- Image NOT Found! ---- \n{potential_path}")
|
| 338 |
+
continue
|
| 339 |
+
|
| 340 |
+
yield idx, {
|
| 341 |
+
"image": image_path,
|
| 342 |
+
"processid": row["processid"],
|
| 343 |
+
"sampleid": row["sampleid"],
|
| 344 |
+
"taxon": row["taxon"],
|
| 345 |
+
"phylum": row["phylum"] or None,
|
| 346 |
+
"class": row["class"] or None,
|
| 347 |
+
"order": row["order"] or None,
|
| 348 |
+
"family": row["family"] or None,
|
| 349 |
+
"subfamily": row["subfamily"] or None,
|
| 350 |
+
"genus": row["genus"] or None,
|
| 351 |
+
"species": row["species"] or None,
|
| 352 |
+
"dna_bin": row["dna_bin"] or None,
|
| 353 |
+
"dna_barcode": row["dna_barcode"],
|
| 354 |
+
"country": row["country"] or None,
|
| 355 |
+
"province_state": row["province_state"] or None,
|
| 356 |
+
"coord-lat": safe_cast(row["coord-lat"], float),
|
| 357 |
+
"coord-lon": safe_cast(row["coord-lon"], float),
|
| 358 |
+
"image_measurement_value": safe_cast(row["image_measurement_value"], float),
|
| 359 |
+
"area_fraction": safe_cast(row["area_fraction"], float),
|
| 360 |
+
"scale_factor": safe_cast(row["scale_factor"], float),
|
| 361 |
+
"inferred_ranks": safe_cast(row["inferred_ranks"], int),
|
| 362 |
+
"split": row["split"],
|
| 363 |
+
"index_bioscan_1M_insect": safe_cast(row["index_bioscan_1M_insect"], float),
|
| 364 |
+
"chunk": row["chunk"] or None,
|
| 365 |
+
}
|
| 366 |
+
elif metadata_path.endswith(".jsonld"):
|
| 367 |
+
with open(metadata_path, encoding="utf-8") as f:
|
| 368 |
+
metadata = json.load(f)
|
| 369 |
+
for idx, row in enumerate(metadata):
|
| 370 |
+
if row["split"] != split:
|
| 371 |
+
continue # Skip others and keep the chosen split samples
|
| 372 |
+
|
| 373 |
+
processid = row["processid"]
|
| 374 |
+
chunk = row.get("chunk", "").strip() if row.get("chunk") else ""
|
| 375 |
+
|
| 376 |
+
# Construct expected relative path
|
| 377 |
+
if chunk == "":
|
| 378 |
+
rel_path = f"bioscan5m/images/{imgtype}/{split}/{processid}.jpg"
|
| 379 |
+
else:
|
| 380 |
+
rel_path = f"bioscan5m/images/{imgtype}/{split}/{chunk}/{processid}.jpg"
|
| 381 |
+
|
| 382 |
+
# Search for the image file inside extracted image_dirs
|
| 383 |
+
image_path = None
|
| 384 |
+
for image_dir in image_dirs:
|
| 385 |
+
potential_path = os.path.join(image_dir, rel_path)
|
| 386 |
+
if os.path.exists(potential_path):
|
| 387 |
+
image_path = potential_path
|
| 388 |
+
break # Image found; end search
|
| 389 |
+
|
| 390 |
+
if image_path is None:
|
| 391 |
+
print(f" ---- Image NOT Found! ---- \n{potential_path}")
|
| 392 |
+
continue
|
| 393 |
+
|
| 394 |
+
yield idx, {
|
| 395 |
+
"image": image_path,
|
| 396 |
+
"processid": row["processid"],
|
| 397 |
+
"sampleid": row["sampleid"],
|
| 398 |
+
"taxon": row["taxon"],
|
| 399 |
+
"phylum": row["phylum"] or None,
|
| 400 |
+
"class": row["class"] or None,
|
| 401 |
+
"order": row["order"] or None,
|
| 402 |
+
"family": row["family"] or None,
|
| 403 |
+
"subfamily": row["subfamily"] or None,
|
| 404 |
+
"genus": row["genus"] or None,
|
| 405 |
+
"species": row["species"] or None,
|
| 406 |
+
"dna_bin": row["dna_bin"] or None,
|
| 407 |
+
"dna_barcode": row["dna_barcode"],
|
| 408 |
+
"country": row["country"] or None,
|
| 409 |
+
"province_state": row["province_state"] or None,
|
| 410 |
+
"coord-lat": safe_cast(row["coord-lat"], float),
|
| 411 |
+
"coord-lon": safe_cast(row["coord-lon"], float),
|
| 412 |
+
"image_measurement_value": safe_cast(row["image_measurement_value"], float),
|
| 413 |
+
"area_fraction": safe_cast(row["area_fraction"], float),
|
| 414 |
+
"scale_factor": safe_cast(row["scale_factor"], float),
|
| 415 |
+
"inferred_ranks": safe_cast(row["inferred_ranks"], int),
|
| 416 |
+
"split": row["split"],
|
| 417 |
+
"index_bioscan_1M_insect": safe_cast(row["index_bioscan_1M_insect"], float),
|
| 418 |
+
"chunk": row["chunk"] or None,
|
| 419 |
+
}
|
| 420 |
+
else:
|
| 421 |
+
raise ValueError(
|
| 422 |
+
f"Unsupported format: {os.path.splitext(metadata_path.lower())[1]}\n"
|
| 423 |
+
f"Supported formats are:\n - " + "\n - ".join(sorted(SUPPORTED_FORMATS.values()))
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
|