File size: 13,037 Bytes
31da5fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb02642
31da5fd
 
 
 
 
4be5e83
 
31da5fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3035a4e
6c1c7eb
 
 
31da5fd
 
 
 
 
 
 
15fc741
31da5fd
 
 
 
 
 
 
 
15fc741
31da5fd
 
 
 
 
 
 
 
 
 
0939908
31da5fd
 
 
 
15fc741
31da5fd
 
 
 
c8bfa06
 
c95f9b7
 
c8bfa06
 
 
 
 
4f35287
 
c8bfa06
31da5fd
6c1c7eb
31da5fd
 
 
 
 
 
 
 
 
 
2628555
 
3522ada
 
2628555
 
 
 
3522ada
 
6fce7bf
3522ada
2628555
 
 
 
 
 
 
 
 
 
 
 
 
3522ada
 
2628555
 
 
 
3522ada
 
2628555
3522ada
2628555
 
 
 
 
 
 
 
 
 
 
 
 
3522ada
 
2628555
 
 
 
3522ada
 
 
6fce7bf
3522ada
2628555
 
 
 
 
 
 
 
 
 
 
 
 
3522ada
 
2628555
 
 
 
3522ada
 
 
2628555
3522ada
2628555
 
 
 
 
 
 
 
 
 
 
 
31da5fd
 
 
 
 
15fc741
31da5fd
 
 
 
 
 
756f8d2
6c1c7eb
31da5fd
 
 
 
6c1c7eb
31da5fd
 
 
 
 
6c1c7eb
31da5fd
 
 
 
 
6c1c7eb
31da5fd
 
 
 
1a2142d
e4ca04c
 
c160909
e4ca04c
 
 
 
 
 
1a2142d
 
 
 
c160909
1a2142d
 
 
 
 
e4ca04c
 
 
 
 
c160909
e4ca04c
6fce7bf
e4ca04c
 
1a2142d
6cbc3a5
31da5fd
 
2628555
 
 
 
 
 
 
 
 
 
 
 
 
 
d628a86
 
 
 
 
baba2fa
d628a86
 
 
 
 
 
2628555
d628a86
 
 
 
 
baba2fa
2628555
d628a86
 
 
 
 
2628555
d628a86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baba2fa
d628a86
 
 
 
 
 
 
 
 
2628555
787103c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# coding=utf-8
# Copyright 2022 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Lint as: python3
"""Openpi V2: A Dataset for tracking state changes in prcedural text by using an unrestricted library"""

import json
import os
import sys
import textwrap 

import numpy as np
import datasets

logger = datasets.logging.get_logger(__name__)

_OPENPI_V2_CITATION = """\
@inproceedings{
    title={{OPENPI V2}: }
	author={}
	note={}
	year={2022}
}
"""

_OPENPI_V2_DESCRIPTION = """\
TEMPORARY DESCRIPTION
"""

_LICENSE = "CC BY 4.0"
_VERSION = "1.0.0"
_HOMEPAGE = "https://allenai.org/data/openpi"
_URL = "https://huggingface.co/datasets/abhinavk/openpi_v2/resolve/main/data/"
_URLS = {"train": _URL + "train-data.json",
            "dev": _URL + "dev-data.json",
            "test": _URL + "test-data.json"}


class OpenpiConfig(datasets.BuilderConfig):
    """BuilderConfig for Openpi V2."""

    def __init__(
        self, 
        features,
        data_url,
        citation,
        url,
        process_label = lambda x: x,
        **kwargs,
    ):
        
        super(OpenpiConfig, self).__init__(version = datasets.Version(_VERSION), **kwargs)
        self.features = features
        self.data_url = data_url
        self.citation = citation
        self.url = url
        self.process_label = process_label


class OpenpiV2(datasets.GeneratorBasedBuilder):

    BUILDER_CONFIGS = [
        OpenpiConfig(
            name = "openpi_text",
            description = textwrap.dedent(
                """\
            """
            ),
            features = datasets.Features({
                "goal": datasets.Value("string"),
                "steps": [datasets.Value("string")],
                "topics": datasets.Value("string"),
                "image_urls": [datasets.Value("string")],
                "states": [{
                    "answers_openpiv1_metadata": {
                        "entity": datasets.Value("string"),
                        "attribute": datasets.Value("string"),
                        "answers": [datasets.Value("string")],
                        "modality": [datasets.Value("string")]
                    },
                    "entity": datasets.Value("string"),
                    "attribute": datasets.Value("string"),
                    "answers": [datasets.Value("string")],
                    "saliency": datasets.Value("float32")
                }]
            }),
            data_url = _URLS,
            citation = textwrap.dedent(
                """\
                @inproceedings{
                    title={},
                    author={},
                    booktitle={},
                    year={}
                }"""
            ),
            url = _HOMEPAGE
        ),
        OpenpiConfig(
            name = "Task 1",
            description = textwrap.dedent(
                """\
                Given paragraph (e.g., with 5 steps), identify entities that change 
                (challenge: implicit entities, some explicit entities that don’t change)."""
            ),
            features = datasets.Features({
                "steps": [datasets.Value("string")],
                "entity_changes": [[datasets.Value("string")]]
            }),
            data_url = _URLS,
            citation = textwrap.dedent(
                """\
                @inproceedings{
                    title={},
                    author={},
                    booktitle={},
                    year={}
                }"""
            ),
            url = _HOMEPAGE
        ),
        OpenpiConfig(
            name = "Task 3",
            description = textwrap.dedent(
                """\
                Given paragraph (e.g., with 5 steps), identify the attributes of entity that change 
                (challenge: implicit entities, attributes & many combinations)."""
            ),
            features = datasets.Features({
                "steps": [datasets.Value("string")],
                "attr_entity_changes": [datasets.Value("string")]
            }),
            data_url = _URLS,
            citation = textwrap.dedent(
                """\
                @inproceedings{
                    title={},
                    author={},
                    booktitle={},
                    year={}
                }"""
            ),
            url = _HOMEPAGE
        ),
        OpenpiConfig(
            name = "Task 4",
            description = textwrap.dedent(
                """\
                Task 4: Given paragraph & an entity, identify the sequence of attribute value changes 
                (challenge: implicit attributes)."""
            ),
            features = datasets.Features({
                "steps": [datasets.Value("string")],
                "entity": datasets.Value("string"),
                "attribute_changes": [[datasets.Value("string")]]
            }),
            data_url = _URLS,
            citation = textwrap.dedent(
                """\
                @inproceedings{
                    title={},
                    author={},
                    booktitle={},
                    year={}
                }"""
            ),
            url = _HOMEPAGE
        ),
        OpenpiConfig(
            name = "Task 7",
            description = textwrap.dedent(
                """\
                Task 7: Given image url, identify the visual attributes of entity and 
                non-visual attributes of entity that change."""
            ),
            features = datasets.Features({
                "image_url": datasets.Value("string"),
                "visual_attr": [datasets.Value("string")],
                "non_visual_attr": [datasets.Value("string")]
            }),
            data_url = _URLS,
            citation = textwrap.dedent(
                """\
                @inproceedings{
                    title={},
                    author={},
                    booktitle={},
                    year={}
                }"""
            ),
            url = _HOMEPAGE
        ),
    ]

    def _info(self):
        return datasets.DatasetInfo(
            description = _OPENPI_V2_DESCRIPTION,
            features = self.config.features,
            supervised_keys = None,
            homepage = self.config.url,
            citation = self.config.citation + "\n" + _OPENPI_V2_CITATION
        )

    def _split_generators(self, dl_manager):
        downloaded_files = dl_manager.download_and_extract(self.config.data_url)

        return [
            datasets.SplitGenerator(
                name = datasets.Split.TRAIN,
                gen_kwargs = {
                    "filepath": downloaded_files["train"]
                },
            ),
            datasets.SplitGenerator(
                name = datasets.Split.VALIDATION,
                gen_kwargs = {
                    "filepath": downloaded_files["dev"]
                },
            ),
            datasets.SplitGenerator(
                name = datasets.Split.TEST,
                gen_kwargs = {
                    "filepath": downloaded_files["test"]
                }
            ),
        ]


    @staticmethod
    def change_occur(dataset):
        for step in dataset:
            if len(step) > 0:
                return True

        return False

    @staticmethod
    def find_change(key, dataset):
        res = []

        for state in dataset:
            if OpenpiV2.change_occur(state["answers"]):
                list_key = state[key].split(" | ")
                res.append([el for el in list_key])

        return (res)

    @staticmethod
    def find_attr_entity_change(dataset):
        attr_change = []

        for state in dataset:
            if OpenpiV2.change_occur(state["answers"]):
                change_str = "[" + state["attribute"] + "] of [" + state["entity"] + "] changed"
                attr_change.append(change_str)
        
        return attr_change

    def _generate_examples(self, filepath):
        logger.info("generating examples from = %s", filepath)

        if self.config.name == "openpi_text":
            with open(filepath) as f:
                dataset = json.load(f)
    
                for id_ in dataset:
                    yield int(id_), {
                        "goal": dataset[id_]["goal"],
                        "steps": dataset[id_]["steps"],
                        "topics": dataset[id_]["topics"],
                        "image_urls": dataset[id_]["image_urls"],
                        "states": dataset[id_]["states"],
                    }
        
        elif self.config.name == "Task 1":
            with open(filepath) as f:
                dataset = json.load(f)

                for id_ in dataset:
                    steps_ar = dataset[id_]["steps"]
                    entity_changes = OpenpiV2.find_change("entity", dataset[id_]["states"])

                    yield int(id_), {
                        "steps": steps_ar,
                        "entity_changes": entity_changes
                    }

        elif self.config.name == "Task 3":
            with open(filepath) as f:
                dataset = json.load(f)

                for id_ in dataset:
                    steps_ar = dataset[id_]["steps"]
                    attr_entity_changes = OpenpiV2.find_attr_entity_change(dataset[id_]["states"])
        
                    yield int(id_), {
                        "steps": steps_ar,
                        "attr_entity_changes": attr_entity_changes
                    }

        elif self.config.name == "Task 4":
            with open(filepath) as f:
                dataset = json.load(f)

                for id_ in dataset:
                    steps_ar = dataset[id_]["steps"]

                    for state in dataset[id_]["states"]:
                        for el in state["entity"].split(" | "):
                            entity = el
                            attribute_changes = []

                            for state2 in dataset[id_]["states"]:
                                flag = False

                                for el2 in state2["entity"].split(" | "):
                                    if entity == el2:
                                        flag = True
                                        break
                            
                                if flag == False:
                                    continue

                                if OpenpiV2.change_occur(state2["answers"]):
                                    list_attribute = state2["attribute"].split(" | ")
                                    attribute_changes.append([el for el in list_attribute])

                            yield int(id_), {
                                "steps": steps_ar, 
                                "entity": entity,
                                "attribute_changes": attribute_changes
                            }

        elif self.config.name == "Task 7":
            with open(filepath) as f:
                dataset = json.load(f)

                for id_ in dataset:
                    N = len(dataset[id_]["image_urls"])

                    for i in range(N):
                        image_url = dataset[id_]["image_urls"][i]
                        visual_attr = []
                        non_visual_attr = []

                        for state in dataset[id_]["states"]:
                            if len(state["answers"][i]) > 0:
                                visual = False
                                non_visual = False
                                
                                for el in state["answers_openpiv1_metadata"]["modality"][i].split(" | "):
                                    visual = (visual or (el == "with_image"))
                                    non_visual = (non_visual or (el == "without_image"))

                                change_str = "[" + state["attribute"] + "] of [" + state["entity"] + "] changed"
                                
                                if visual:
                                    visual_attr.append(change_str)
                                if non_visual:
                                    non_visual_attr.append(change_str)
                       
                        yield int(id_), {
                            "image_url": image_url,
                            "visual_attr": visual_attr,
                            "non_visual_attr": non_visual_attr
                        }