File size: 15,596 Bytes
ba48b51
 
 
 
 
 
9fd81e4
10951b9
ba48b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0765cf
4e49c6d
10951b9
 
ba48b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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