L2T-NeurIPS-2023 / L2T-NeurIPS-2023.py
Dakhoo's picture
update the read me with example to load the dataset
4e49c6d
raw
history blame
15.6 kB
import datasets
import json
logger = datasets.logging.get_logger(__name__)
USERNAME = "Dakhoo"
REPO_NAME = "L2T-NeurIPS-2023"
LOCAL = False
_CITATION = """\
@article{bender2023learning,
title={Learning to Taste: A Multimodal Wine Dataset},
author={Bender, Thoranna and S{\o}rensen, Simon M{\o}e and Kashani, Alireza and Hjorleifsson, K Eldjarn and Hyldig, Grethe and Hauberg, S{\o}ren and Belongie, Serge and Warburg, Frederik},
journal={arXiv preprint arXiv:2308.16900},
year={2023}
}
"""
_DESCRIPTION = (
"The dataset encompasses 897k images of wine labels and 824k reviews of wines "
"curated from the Vivino platform. It has over 350k unique vintages, annotated "
"with year, region, rating, alcohol percentage, price, and grape composition. "
"We obtained fine-grained flavor annotations on a subset by conducting a wine-tasting experiment "
"with 256 participants who were asked to rank wines based on their similarity in flavor, "
"resulting in more than 5k pairwise flavor distances."
)
_HOMEPAGE = "https://https://thoranna.github.io/learning_to_taste/"
_LICENSE = """\
LICENSE AGREEMENT
=================
- WineSensed by Thoranna Bender, Simon Søresen, Alireza Kashani, Kristjan Eldjarn, Grethe Hyldig,
Søren Hauberg, Serge Belongie, Frederik Warburg is licensed under a CC BY-NC-ND 4.0 Licence
"""
reviews = ['Deliciously fragrant xxx',
'Barolo & Brunello Tasting with Janne',
'Oak',
'Muito bom. Foi uma agradável surpresa. Óptimo sabor e guloso a acompanhar o almoço. Recomendo. ',
'Flauw zwoele smaak zonder al teveel afdronk. Voor de prijs oké zonder meer. Ik ben geen fan. ',
'Very different, very pink. Quite fruity can feel at the back sides of tongue ',
'Honey, apricot, tinned peaches in syrup. Oily, silky texture. Sweetness is well balanced with acidity. ',
'Amazing fruit and great finish. ',
'Dry, floral nose with fruit on the back',
'This Riesling Kabinett was good. Had a few minor problems, but cant complain to much at $13 ',
'Such an unusual drop, honey, spice notes. Drank it chilled. Nose like the skin on a sauccison...!',
'Very sweet and light bubbly red wine ',
'Great value. Really enjoyable wine and went down a treat with a steak 👌🏻',
'',
'Quite refreshing with a light citrus taste.',
'Pours in dark amber colour with excellant lacing. Aroma of raisins, caramel. Highly sweet, medium sour, light bitterness, taste of nutts, raisins. Full bodied, thick feel, long lasting aftertaste',
'Light, dry, grapefruit flavor, delicious ']
_REPO = f"https://huggingface.co/datasets/{USERNAME}/{REPO_NAME}/resolve/main/"
_REPO = "https://huggingface.co/datasets/Dakhoo/L2T-NeurIPS-2023/resolve/main/"
if LOCAL:
_REPO = f"/Users/alka/Devel/L2T-NeurIPS-2023"
class WineSensedConfig(datasets.BuilderConfig):
"""BuilderConfig for WineSensed."""
def __init__(self, data_url, metadata_urls, **kwargs):
"""BuilderConfig for WineSensed.
Args:
data_url: `string`, url to download the zip file from.
matadata_urls: dictionary with 'train' containing the metadata URLs
**kwargs: keyword arguments forwarded to super.
"""
super(WineSensedConfig, self).__init__(version=datasets.Version("1.0.0"), **kwargs)
self.data_url = data_url
self.metadata_urls = metadata_urls
class WineSensed(datasets.GeneratorBasedBuilder):
"""WineSensed Images dataset"""
BUILDER_CONFIGS = [
WineSensedConfig(
name="vintages",
description="All tasted vintages along with their attributions.",
data_url=f"{_REPO}/data/vintages/vintages_dataset.tar.gz",
metadata_urls={
"train": f"{_REPO}/data/vintages/train.txt",
},
),
WineSensedConfig(
name="napping_participants",
description="Napping and Participants datasets",
data_url=f"{_REPO}/data/napping_participants/napping_participants.tar.gz",
metadata_urls={
"train": f"{_REPO}/data/napping_participants/train.txt",
},
),
WineSensedConfig(
name="small",
description="Small dataset.",
data_url=f"{_REPO}/data/small/small.tar.gz",
metadata_urls={
"train": f"{_REPO}/data/small/small_dataset.jsonl",
},
),
WineSensedConfig(
name="wt_session",
description="Image-Review dataset.",
data_url=f"{_REPO}/data/wt_session/wt_session.tar.gz",
metadata_urls={
"train": f"{_REPO}/data/wt_session/wt_session.jsonl",
},
),
WineSensedConfig(
name="all",
description="All images.",
data_url=f"{_REPO}/data/all/all.tar.gz",
metadata_urls={
"train": f"{_REPO}/data/all/all_dataset.jsonl",
},
),
]
def _info(self):
if self.config.name == 'vintages':
features = datasets.Features(
{
"vintage_id": datasets.Value("string"),
"year": datasets.Value("string"),
"winery_id": datasets.Value("string"),
"wine_alcohol": datasets.Value("string"),
"country": datasets.Value("string"),
"region": datasets.Value("string"),
"price": datasets.Value("string"),
"rating": datasets.Value("string"),
"grape": datasets.Value("string"),
}
)
elif self.config.name == 'napping_participants':
features = datasets.Features(
{
"event_name": datasets.Value("string"),
"session_round_name": datasets.Value("string"),
"experiment_no": datasets.Value("string"),
"round_id": datasets.Value("string"),
"participant_id": datasets.Value("string"),
"experiment_id": datasets.Value("string"),
"coor1": datasets.Value("string"),
"coor2": datasets.Value("string"),
"color": datasets.Value("string"),
}
)
else:
features = datasets.Features(
{
"image": datasets.Image(),
"vintage_id": datasets.Value("string"),
"year": datasets.Value("string"),
"winery_id": datasets.Value("string"),
"wine_alcohol": datasets.Value("string"),
"country": datasets.Value("string"),
"region": datasets.Value("string"),
"price": datasets.Value("string"),
"rating": datasets.Value("string"),
"grape": datasets.Value("string"),
"review": datasets.Value("string"),
"event_name": datasets.Value("string"),
"session_round_name": datasets.Value("string"),
"experiment_no": datasets.Value("string"),
"round_id": datasets.Value("string"),
"participant_id": datasets.Value("string"),
"experiment_id": datasets.Value("string"),
"coor1": datasets.Value("string"),
"coor2": datasets.Value("string"),
"color": datasets.Value("string"),
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION + self.config.description,
features=features,
supervised_keys=None,
homepage=_HOMEPAGE,
citation=_CITATION,
license=_LICENSE,
)
def _split_generators(self, dl_manager):
archive_path = dl_manager.download(self.config.data_url)
metadata_paths = dl_manager.download(self.config.metadata_urls)
record_iters = dl_manager.iter_archive(archive_path)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"records": record_iters,
"metadata_path": metadata_paths["train"],
},
),
]
def _generate_examples(self, records, metadata_path):
"""Generate images and metadata for splits."""
# Process the JSONL file to extract all metadata
if self.config.name == 'vintages':
for idx, (filepath, image) in enumerate(records):
file_jsonl = image.read()
jsonl_string = file_jsonl.decode('utf-8')
json_objects = jsonl_string.strip().split('\n')
id = 0
for json_object in json_objects:
data_dict = json.loads(json_object)
yield id, {
"vintage_id": data_dict['vintage_id'],
"year": data_dict['year'],
"winery_id": data_dict['winery_id'],
"wine_alcohol": data_dict['wine_alcohol'],
"country": data_dict['country'],
"region": data_dict['region'],
"price": data_dict['price'],
"rating": data_dict['rating'],
"grape": data_dict['grape'],
}
id += 1
elif self.config.name == 'napping_participants':
for idx, (filepath, image) in enumerate(records):
file_jsonl = image.read()
jsonl_string = file_jsonl.decode('utf-8')
json_objects = jsonl_string.strip().split('\n')
id = 0
for json_object in json_objects:
data_dict = json.loads(json_object)
yield id, {
"event_name": data_dict['event_name'],
"session_round_name": data_dict['session_round_name'],
"experiment_no": data_dict['experiment_no'],
"round_id": data_dict['round_id'],
"participant_id": data_dict['participant_id'],
"experiment_id": data_dict['experiment_id'],
"coor1": data_dict['coor1'],
"coor2": data_dict['coor2'],
"color": data_dict['color'],
}
id += 1
else:
metadata_dict = self._process_images_jsonl_file(metadata_path)
for idx, (filepath, image) in enumerate(records):
yield idx, {
"image": {"path": filepath, "bytes": image.read()},
"vintage_id": metadata_dict.get(filepath.split('/')[1], {}).get('vintage_id', None),
"year": metadata_dict.get(filepath.split('/')[1], {}).get('year', None),
"winery_id": metadata_dict.get(filepath.split('/')[1], {}).get('winery_id', None),
"wine_alcohol": metadata_dict.get(filepath.split('/')[1], {}).get('wine_alcohol', None),
"country": metadata_dict.get(filepath.split('/')[1], {}).get('country', None),
"region": metadata_dict.get(filepath.split('/')[1], {}).get('region', None),
"price": metadata_dict.get(filepath.split('/')[1], {}).get('price', None),
"rating": metadata_dict.get(filepath.split('/')[1], {}).get('rating', None),
"grape": metadata_dict.get(filepath.split('/')[1], {}).get('grape', None),
"review": metadata_dict.get(filepath.split('/')[1], {}).get('review', None),
"event_name": metadata_dict.get(filepath.split('/')[1], {}).get('event_name', None),
"session_round_name": metadata_dict.get(filepath.split('/')[1], {}).get('session_round_name', None),
"experiment_no": metadata_dict.get(filepath.split('/')[1], {}).get('experiment_no', None),
"round_id": metadata_dict.get(filepath.split('/')[1], {}).get('round_id', None),
"participant_id": metadata_dict.get(filepath.split('/')[1], {}).get('participant_id', None),
"experiment_id": metadata_dict.get(filepath.split('/')[1], {}).get('experiment_id', None),
"coor1": metadata_dict.get(filepath.split('/')[1], {}).get('coor1', None),
"coor2": metadata_dict.get(filepath.split('/')[1], {}).get('coor2', None),
"color": metadata_dict.get(filepath.split('/')[1], {}).get('color', None),
}
def _process_images_jsonl_file(self, jsonl_file_path):
"""A utility function defined within the WineSensed class.
This function reads and processes a JSONL (JSON Lines) file containing metadata about images and reviews.
It iterates through the lines in the JSONL file, parsing each line as JSON data.
For each JSON object in the file, it extracts relevant information such as image paths, reviews, vintage IDs, and more.
The extracted information is stored in a dictionary called metadata_dict, which is returned by the function. """
metadata_dict = {}
with open(jsonl_file_path, 'r', encoding="utf-8") as jsonl_file:
for line in jsonl_file:
try:
data = json.loads(line)
image = data.get('image', None)
# Check if 'image' is present in the JSON object
if image is not None:
metadata_dict[image] = {
"review": data.get('review', None),
"vintage_id": data.get('vintage_id', None),
"experiment_id": data.get('experiment_id', None),
"year": data.get('year', None),
"winery_id": data.get('winery_id', None),
"wine_alcohol": data.get('wine_alcohol', None),
"country": data.get('country', None),
"region": data.get('region', None),
"price": data.get('price', None),
"rating": data.get('rating', None),
"grape": data.get('grape', None),
"event_name": data.get('event_name', None),
"session_round_name": data.get('session_round_name', None),
"experiment_no": data.get('experiment_no', None),
"round_id": data.get('round_id', None),
"participant_id": data.get('participant_id', None),
"experiment_id": data.get('experiment_id', None),
"coor1": data.get('coor1', None),
"coor2": data.get('coor2', None),
"color": data.get('color', None),
}
except json.JSONDecodeError as e:
print(f"Error parsing JSON: {e}")
return metadata_dict