File size: 15,397 Bytes
d796a3a f3983dd 1009812 f3983dd 20183e7 f3983dd a2a878b 79e43cd f3983dd f739aba f3983dd f739aba f3983dd f739aba f3983dd ccfb93b f3983dd 2881e1f f3983dd 2881e1f f739aba 1009812 f739aba f3983dd f739aba f3983dd f739aba f3983dd f739aba 9c99040 d796a3a f3b5e28 d796a3a f3983dd ccfb93b 4f3541d f3983dd f739aba 4f3541d ccfb93b 4f3541d ccfb93b 3fae74d ccfb93b d27aea0 4f3541d 3fae74d 9c99040 3fae74d 9c99040 3fae74d 4f3541d ccfb93b f739aba 2881e1f ccfb93b f739aba f3983dd 5be181a c411cde 5be181a 9c99040 f3983dd 5be181a f3983dd 5be181a db07df4 f3983dd 5be181a f3983dd ec66a54 5f65f4b c411cde 5f65f4b a2a878b c411cde a6568f8 73a3818 |
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 |
import sys
import csv
import json
import os
import os.path as op
import base64
import zipfile
from getpass import getpass
from tqdm import tqdm
import platform
import subprocess
import requests
from urllib.parse import urlparse
import datasets
from tqdm import tqdm
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@article{mehrer2021ecologically,
title={An ecologically motivated image dataset for deep learning yields better models of human vision},
author={Mehrer, Johannes and Spoerer, Courtney J and Jones, Emer C and Kriegeskorte, Nikolaus and Kietzmann, Tim C},
journal={Proceedings of the National Academy of Sciences},
volume={118},
number={8},
year={2021},
publisher={National Acad Sciences}
}
"""
# You can copy an official description
_DESCRIPTION = """\
Tired of all the dogs in ImageNet (ILSVRC)? Then ecoset is here for you. 1.5m images
from 565 basic level categories, chosen to be both (i) frequent in linguistic usage,
and (ii) rated by human observers as concrete (e.g. ‘table’ is concrete, ‘romance’
is not). Here we collect resources associated with ecoset. This includes the dataset,
trained deep neural network models, code to interact with them, and published papers
using it.
"""
# official homepage for the dataset here
_HOMEPAGE = "https://www.kietzmannlab.org/ecoset/"
# licence for the dataset here
_LICENSE = "CC BY NC SA 2.0"
# dataset URLs here
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_URLS = {
"ikw": "https://files.ikw.uni-osnabrueck.de/ml/ecoset/ecoset.zip",
}
# Define the labels available for ecoset
labels = ['cymbals', 'bison', 'lemonade', 'crib', 'chestnut', 'mosquito', 'aloe', 'extinguisher', 'onion', 'starfish', 'basket', 'jar', 'snail', 'mushroom', 'coffin', 'joystick', 'raspberry', 'gearshift', 'tyrannosaurus', 'stadium', 'telescope', 'blueberry', 'hippo', 'cannabis', 'hairbrush', 'river', 'artichoke', 'wallet', 'city', 'bee', 'rifle', 'boar', 'bib', 'envelope', 'silverfish', 'shower', 'curtain', 'pinwheel', 'guillotine', 'snowplow', 'hut', 'jukebox', 'gecko', 'marshmallow', 'lobster', 'flashlight', 'breadfruit', 'cow', 'spoon', 'blender', 'croissant', 'greenhouse', 'church', 'antenna', 'monkey', 'zucchini', 'snake', 'manatee', 'child', 'table', 'winterberry', 'sloth', 'cannon', 'baguette', 'persimmon', 'candelabra', 'necklace', 'flag', 'geyser', 'thermos', 'tweezers', 'chandelier', 'kebab', 'mailbox', 'steamroller', 'crayon', 'lawnmower', 'pomegranate', 'fire', 'violin', 'matchstick', 'train', 'hamster', 'bobsleigh', 'boat', 'bullet', 'forklift', 'clock', 'saltshaker', 'anteater', 'crowbar', 'lightbulb', 'pier', 'muffin', 'paintbrush', 'crawfish', 'bench', 'nectarine', 'eyedropper', 'backpack', 'goat', 'hotplate', 'fishnet', 'robot', 'rice', 'shovel', 'candle', 'blimp', 'bridge', 'mountain', 'coleslaw', 'stagecoach', 'waterfall', 'ladle', 'radiator', 'drain', 'tray', 'house', 'key', 'skunk', 'lake', 'earpiece', 'gazebo', 'blackberry', 'groundhog', 'paperclip', 'cookie', 'milk', 'rug', 'thermostat', 'milkshake', 'scoreboard', 'bean', 'giraffe', 'antelope', 'newsstand', 'camcorder', 'sawmill', 'balloon', 'ladder', 'videotape', 'microphone', 'coin', 'hay', 'moth', 'octopus', 'honeycomb', 'wrench', 'cane', 'bobcat', 'banner', 'newspaper', 'reef', 'worm', 'cucumber', 'beach', 'couch', 'streetlamp', 'rhino', 'ceiling', 'cupcake', 'hourglass', 'caterpillar', 'tamale', 'asparagus', 'flower', 'frog', 'dog', 'knife', 'lamp', 'walnut', 'grape', 'scone', 'peanut', 'ferret', 'kettle', 'elephant', 'oscilloscope', 'weasel', 'guava', 'gramophone', 'stove', 'bamboo', 'chicken', 'guacamole', 'toolbox', 'tractor', 'tiger', 'butterfly', 'coffeepot', 'bus', 'meteorite', 'fish', 'graveyard', 'blowtorch', 'grapefruit', 'cat', 'jellyfish', 'carousel', 'wheat', 'tadpole', 'kazoo', 'raccoon', 'typewriter', 'scissors', 'pothole', 'earring', 'drawers', 'cup', 'warthog', 'wall', 'lighthouse', 'burrito', 'cassette', 'nacho', 'sink', 'seashell', 'bed', 'noodles', 'woman', 'rabbit', 'fence', 'pistachio', 'pencil', 'hotdog', 'ball', 'ship', 'strawberry', 'pan', 'custard', 'dolphin', 'tent', 'bun', 'tortilla', 'tumbleweed', 'playground', 'scallion', 'anchor', 'hare', 'waterspout', 'dough', 'burner', 'kale', 'razor', 'chocolate', 'doughnut', 'squeegee', 'bandage', 'beaver', 'refrigerator', 'cork', 'anvil', 'microchip', 'banana', 'thumbtack', 'chair', 'sharpener', 'bird', 'castle', 'wand', 'doormat', 'celery', 'steak', 'ant', 'apple', 'cave', 'scaffolding', 'bell', 'towel', 'mantis', 'thimble', 'bowl', 'chess', 'pickle', 'lollypop', 'leek', 'barrel', 'dollhouse', 'tapioca', 'spareribs', 'fig', 'apricot', 'strongbox', 'brownie', 'beaker', 'manhole', 'piano', 'whale', 'hammer', 'dishrag', 'pecan', 'highlighter', 'pretzel', 'earwig', 'cogwheel', 'trashcan', 'syringe', 'turnip', 'pear', 'lettuce', 'hedgehog', 'guardrail', 'bubble', 'pineapple', 'burlap', 'moon', 'spider', 'fern', 'binoculars', 'gravel', 'plum', 'scorpion', 'cube', 'squirrel', 'book', 'crouton', 'bag', 'lantern', 'parsley', 'jaguar', 'thyme', 'oyster', 'kumquat', 'chinchilla', 'cherry', 'umbrella', 'bicycle', 'eggbeater', 'pig', 'kitchen', 'fondue', 'treadmill', 'casket', 'papaya', 'beetle', 'shredder', 'grasshopper', 'anthill', 'chili', 'bottle', 'calculator', 'gondola', 'pizza', 'compass', 'mop', 'hamburger', 'chipmunk', 'bagel', 'outhouse', 'pliers', 'wolf', 'matchbook', 'corn', 'salamander', 'lasagna', 'stethoscope', 'eggroll', 'avocado', 'eggplant', 'mouse', 'walrus', 'sprinkler', 'glass', 'cauldron', 'parsnip', 'canoe', 'pancake', 'koala', 'deer', 'chalk', 'urinal', 'toilet', 'cabbage', 'platypus', 'lizard', 'leopard', 'cake', 'hammock', 'defibrillator', 'sundial', 'beet', 'popcorn', 'spinach', 'cauliflower', 'canyon', 'spacecraft', 'teapot', 'tunnel', 'porcupine', 'jail', 'spearmint', 'dustpan', 'calipers', 'toast', 'drum', 'phone', 'wire', 'alligator', 'vase', 'motorcycle', 'toothpick', 'coconut', 'lion', 'turtle', 'cheetah', 'bugle', 'casino', 'fountain', 'pie', 'bread', 'meatball', 'windmill', 'gun', 'projector', 'chameleon', 'tomato', 'nutmeg', 'plate', 'bulldozer', 'camel', 'sphinx', 'mall', 'hanger', 'ukulele', 'wheelbarrow', 'ring', 'dildo', 'loudspeaker', 'odometer', 'ruler', 'mousetrap', 'breadbox', 'parachute', 'bolt', 'bracelet', 'library', 'otter', 'airplane', 'pea', 'tongs', 'cactus', 'knot', 'shrimp', 'computer', 'sheep', 'television', 'melon', 'kangaroo', 'helicopter', 'birdcage', 'pumpkin', 'dishwasher', 'crocodile', 'stairs', 'garlic', 'barnacle', 'crate', 'lime', 'axe', 'hairpin', 'egg', 'emerald', 'candy', 'stegosaurus', 'broom', 'mistletoe', 'submarine', 'fireworks', 'peach', 'ape', 'chalkboard', 'bumblebee', 'potato', 'battery', 'guitar', 'opossum', 'volcano', 'llama', 'ashtray', 'sieve', 'coliseum', 'cinnamon', 'moose', 'tree', 'donkey', 'wasp', 'corkscrew', 'gargoyle', 'taco', 'macadamia', 'camera', 'mandolin', 'kite', 'cranberry', 'thermometer', 'tofu', 'closet', 'hovercraft', 'escalator', 'horseshoe', 'wristwatch', 'lemon', 'sushi', 'rat', 'rainbow', 'pillow', 'radish', 'granola', 'okra', 'pastry', 'mango', 'dragonfly', 'flashbulb', 'chalice', 'acorn', 'birdhouse', 'gooseberry', 'locker', 'padlock', 'missile', 'clarinet', 'panda', 'iceberg', 'road', 'flea', 'hazelnut', 'cockroach', 'needle', 'omelet', 'desert', 'condom', 'graffiti', 'iguana', 'bucket', 'photocopier', 'blanket', 'microscope', 'horse', 'nest', 'screwdriver', 'toaster', 'car', 'doll', 'salsa', 'man', 'zebra', 'stapler', 'grate', 'truck', 'bear', 'carrot', 'auditorium', 'cashew', 'shield', 'crown', 'altar', 'pudding', 'cheese', 'rhubarb', 'broccoli', 'tower', 'cumin', 'elevator', 'wheelchair', 'flyswatter']
# handle password entry
_PWD_MSG = "\nIn order to use ecoset, please read the README and License agreement found under:\nhttps://codeocean.com/capsule/9570390\nand enter the mentioned password.\n\nPlease Enter Password:\n"
def check_pass(pw):
if base64.b64encode(pw.encode("ascii")) != (b"ZWNvc2V0X21zamtr"):
raise AttributeError("Wrong password! Please try again.")
else:
print("Password correct.\n")
# Name of the dataset usually match the script name with CamelCase instead of snake_case
class Ecoset(datasets.GeneratorBasedBuilder):
"""Ecoset is a large clean and ecologically valid image dataset."""
VERSION = datasets.Version("1.1.0")
# This is an example of a dataset with multiple configurations.
# If you don't want/need to define several sub-sets in your dataset,
# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
# If you need to make complex sub-parts in the datasets with configurable options
# You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
# BUILDER_CONFIG_CLASS = MyBuilderConfig
# You will be able to load one or the other configurations in the following list with
# data = datasets.load_dataset('my_dataset', 'first_domain')
# data = datasets.load_dataset('my_dataset', 'second_domain')
BUILDER_CONFIGS = [
datasets.BuilderConfig(name="Full", version=VERSION, description="We could do different splits of the dataset here. But we don't"),
]
DEFAULT_CONFIG_NAME = "Full" # It's not mandatory to have a default configuration. Just use one if it make sense.
def _info(self):
# define dataset features
features=datasets.Features(
{
"image": datasets.Image(),
"label": datasets.ClassLabel(names=labels),
}
)
return datasets.DatasetInfo(
# This is the description that will appear on the datasets page.
description=_DESCRIPTION,
# This defines the different columns of the dataset and their types
features=features, # Here we define them above because they are different between the two configurations
# Homepage of the dataset for documentation
homepage=_HOMEPAGE,
# License for the dataset if available
license=_LICENSE,
# Citation for the dataset
citation=_CITATION,
)
def _split_generators(self, dl_manager):
# Ask password of user. This could be also handled through dataset config
def abslist(path):
"""Helper function to give abspaths of os.listdir"""
return [os.path.join(path, p) for p in os.listdir(path)if os.path.isdir(os.path.join(path, p))]
def filelist(path):
"""Helper function to give abspaths of os.listdir"""
return [os.path.join(path, p) for p in os.listdir(path)if os.path.isfile(os.path.join(path, p))]
def subprocess_call_print(command_list):
"""Execute a subprocess while printing the command line output"""
p = subprocess.Popen(command_list, stdout=subprocess.PIPE)
while True:
line = p.stdout.readline()
if not line:
break
print(line.strip())
sys.stdout.flush()
def subprocess_download(source_url, target_dir):
"""Moderately slow download"""
# ask password
password = getpass(_PWD_MSG)
check_pass(password)
# download
print('Using native OS unzipping. This will take about 15h on a typical Linux/Mac and 8h on a typical Windows Computer.')
# Ensure the target directory exists, or create it if it doesn't.
if not os.path.exists(target_dir):
os.makedirs(target_dir)
# Extract the filename from the URL.
filename = source_url.split("/")[-1]
# Combine the target directory and the filename to get the full path.
zip_file_path = os.path.join(target_dir, filename)
# Use subprocess to execute the modified wget command.
wget_command = f"wget --no-check-certificate {source_url} -O {zip_file_path}"
subprocess.run(wget_command, shell=True)
print(f"Downloaded {filename}")
# unzip using platform-based subprocess
if platform.system() in ("Linux", "Darwin"):
subprocess_call_print(["unzip", "-n", "-P", password.encode("ascii"), "-o", zip_file_path, "-d", target_dir])
else:
subprocess_call_print(["tar.exe", "-xf", zip_file_path, "-C", target_dir, "--passphrase", password])
# download and unzip using subprocess. S3 download was discontinued due to being extremely slow
archives = dl_manager.download_custom(_URLS["ikw"], subprocess_download)
print("Ecoset files are stored under: \n", archives)
split_dict = {split:[] for split in ("train", "val", "test")}
for split in split_dict.keys():
# Get a list of subdirectories within the current split's directory
subdirectories = [d for d in os.listdir(os.path.join(archives, split)) if os.path.isdir(os.path.join(archives, split, d))]
# Iterate through the subdirectories and collect file paths
for subdirectory in subdirectories:
subdirectory_path = os.path.join(archives, split, subdirectory)
file_paths = filelist(subdirectory_path)
split_dict[split].extend(file_paths)
# return data splits
return [datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"archives": split_dict,
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"archives": split_dict,
"split": "val",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"archives": split_dict,
"split": "test",
},
),
]
# method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
def _generate_examples(self, archives, split):
idx = 0
split_archives = archives[split]
acceptable_formats = [".JPEG", ".JPG", ".jpeg", ".jpg"]
for item in tqdm(split_archives):
parts = item.split('/')
second_last_part = parts[-2]
name_parts = second_last_part.split('_')
label = name_parts[-1]
if any(item.endswith(f) for f in acceptable_formats):
abs_path = os.path.abspath(item)
with open(abs_path, 'rb') as file_handle:
ex = {"image": {"path": abs_path, "bytes": file_handle.read()}, "label": label}
yield idx, ex
idx += 1 |