File size: 11,937 Bytes
1ae9e7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e093a86
1ae9e7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14d67e4
 
4a68a6a
 
 
 
 
 
 
14d67e4
1ae9e7b
 
 
 
ca87119
1ae9e7b
 
 
 
 
 
 
 
 
 
 
 
52c9efa
 
 
 
 
1ae9e7b
 
 
 
 
 
 
 
 
 
 
a1c5bf4
3659374
 
a1c5bf4
 
1ae9e7b
 
 
 
 
 
 
 
5391641
 
 
d65105b
5391641
 
 
 
 
 
d65105b
 
5391641
1ae9e7b
 
 
 
 
74dbbd7
1ae9e7b
 
 
 
 
 
 
 
 
4a68a6a
 
 
 
 
 
 
 
 
 
1ae9e7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a68a6a
52c9efa
4a68a6a
be9549c
b5cba51
 
 
 
 
 
 
 
 
 
7d85704
 
 
 
 
 
f1bb559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e093a86
f1bb559
 
 
 
 
 
 
 
 
e093a86
f1bb559
 
 
 
 
 
 
 
 
e093a86
f1bb559
1ae9e7b
27b0931
1ae9e7b
 
 
 
 
 
5391641
7d85704
5391641
7d85704
5391641
7d85704
5391641
7d85704
1ae9e7b
 
 
 
 
 
 
5391641
1ae9e7b
 
 
 
5391641
 
1ae9e7b
 
 
 
 
 
 
5391641
1ae9e7b
01b104d
1ae9e7b
 
 
 
 
 
 
7d85704
1ae9e7b
 
 
db54a32
7d85704
 
1ae9e7b
 
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
# coding=utf-8
# Copyright 2020 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
"""SQUALL: Lexical-level Supervised Table Question Answering Dataset."""


import json
import re
import datasets
from datasets.tasks import QuestionAnsweringExtractive


logger = datasets.logging.get_logger(__name__)


_CITATION = """\
@inproceedings{Shi:Zhao:Boyd-Graber:Daume-III:Lee-2020,
	Title = {On the Potential of Lexico-logical Alignments for Semantic Parsing to {SQL} Queries},
	Author = {Tianze Shi and Chen Zhao and Jordan Boyd-Graber and Hal {Daum\'{e} III} and Lillian Lee},
	Booktitle = {Findings of EMNLP},
	Year = {2020},
}
"""

_DESCRIPTION = """\
To explore the utility of fine-grained, lexical-level supervision, authors \
introduce SQUALL, a dataset that enriches 11,276 WikiTableQuestions \ 
English-language questions with manually created SQL equivalents plus \ 
alignments between SQL and question fragments.
"""

_URL = "https://raw.githubusercontent.com/tzshi/squall/main/data/"
_URLS = {
    "squall": _URL + "squall.json",
    "wtq-test": _URL + "wtq-test.json",
    "dev-0": _URL +  "dev-0.ids",
    "dev-1": _URL +  "dev-1.ids",
    "dev-2": _URL +  "dev-2.ids",
    "dev-3": _URL +  "dev-3.ids",
    "dev-4": _URL +  "dev-4.ids",
}

class SquallConfig(datasets.BuilderConfig):
    """BuilderConfig for Squall."""

    def __init__(self, **kwargs):
        """BuilderConfig for Squall.

        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        super(SquallConfig, self).__init__(**kwargs)


class Squall(datasets.GeneratorBasedBuilder):
    """SQUALL: Lexical-level Supervised Table Question Answering Dataset."""

    BUILDER_CONFIGS = [
        SquallConfig(name = '0'),
        SquallConfig(name = '1'),
        SquallConfig(name = '2'),
        SquallConfig(name = '3'),
        SquallConfig(name = '4')
    ]
    
    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "nt": datasets.Value("string"),
                    "tbl": datasets.Value("string"),
                    "columns":
                        {
                            "raw_header": datasets.features.Sequence(datasets.Value("string")),
                            "tokenized_header": datasets.features.Sequence(datasets.features.Sequence(datasets.Value("string"))),
                            "column_suffixes": datasets.features.Sequence(datasets.features.Sequence(datasets.Value("string"))),
                            "column_dtype": datasets.features.Sequence(datasets.Value("string")),
                            "example": datasets.features.Sequence(datasets.Value("string"))
                        },
                    "nl": datasets.features.Sequence(datasets.Value("string")),
                    "nl_pos": datasets.features.Sequence(datasets.Value("string")),
                    "nl_ner": datasets.features.Sequence(datasets.Value("string")),
                    "nl_incolumns": datasets.features.Sequence(datasets.Value("bool_")),
                    "nl_incells": datasets.features.Sequence(datasets.Value("bool_")),
                    "columns_innl": datasets.features.Sequence(datasets.Value("bool_")),
                    "tgt": datasets.Value("string"),
                    "sql": {
                        "sql_type": datasets.features.Sequence(datasets.Value("string")), 
                        "value": datasets.features.Sequence(datasets.Value("string")), 
                        "span_indices": datasets.features.Sequence(datasets.features.Sequence(datasets.Value("int32")))
                    },
                    "nl_ralign": {
                        "aligned_sql_token_type":datasets.features.Sequence(datasets.Value("string")),
                        "aligned_sql_token_info":datasets.features.Sequence(datasets.Value("string")),
                    },
                    "align":{
                        "nl_indices": datasets.features.Sequence(datasets.features.Sequence(datasets.Value("int32"))),
                        "sql_indices": datasets.features.Sequence(datasets.features.Sequence(datasets.Value("int32")))
                    }
                }
            ),
            # No default supervised_keys (as we have to pass both question
            # and context as input).
            supervised_keys=None,
            homepage="https://github.com/tzshi/squall/",
            citation=_CITATION,
            task_templates=[
                QuestionAnsweringExtractive(
                    question_column="nl", context_column="columns", answers_column="tgt"
                )
            ],
        )

    def _split_generators(self, dl_manager):
        urls_to_download = {
            "squall": _URLS["squall"],
            "wtq-test": _URLS["wtq-test"],
            "dev-0": _URLS["dev-0"],
            "dev-1": _URLS["dev-1"],
            "dev-2": _URLS["dev-2"],
            "dev-3": _URLS["dev-3"],
            "dev-4": _URLS["dev-4"],
        }
        downloaded_files = dl_manager.download_and_extract(urls_to_download)
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN, 
                gen_kwargs={"split_key": "train", "filepath": downloaded_files}),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION, 
                gen_kwargs={"split_key": "dev", "filepath": downloaded_files}),
            datasets.SplitGenerator(
                name=datasets.Split.TEST, 
                gen_kwargs={"split_key": "test", "filepath": downloaded_files}),
        ]

    def _generate_examples(self, split_key, filepath):
        """This function returns the examples in the raw (text) form."""
        logger.info("generating examples from = %s", filepath)

        squall_full = filepath["squall"]
        dev_ids = filepath["dev-" + self.config.name]
        test = filepath["wtq-test"]

        # transform the original squall data structure (list of things) to dict 
        def transform(sample, sample_key, keys):
            cols = {}
            n_col = len(sample[sample_key])
            for k in range(len(keys)):
                tmp = []
                for j in range(n_col):
                    tmp.append(sample[sample_key][j][k])
                cols[keys[k]] = tmp
            return cols

        columns_keys = ["raw_header", "tokenized_header", "column_suffixes", "column_dtype", "example"]
        sql_keys = ["sql_type", "value", "span_indices"]
        align_keys = ["nl_indices", "sql_indices"]
        ralign_keys = ["aligned_sql_token_type", "aligned_sql_token_info"]

        with open(squall_full, encoding="utf-8") as f:
            squall_full_data = json.load(f)
    
        NUM_MAPPING = {
            'half': 0.5,
            'one': 1,
            'two': 2,
            'three': 3,
            'four': 4,
            'five': 5,
            'six': 6,
            'seven': 7,
            'eight': 8,
            'nine': 9,
            'ten': 10,
            'eleven': 11,
            'twelve': 12,
            'twenty': 20,
            'thirty': 30,
            'once': 1,
            'twice': 2,
            'first': 1,
            'second': 2,
            'third': 3,
            'fourth': 4,
            'fifth': 5,
            'sixth': 6,
            'seventh': 7,
            'eighth': 8,
            'ninth': 9,
            'tenth': 10,
            'hundred': 100,
            'thousand': 1000,
            'million': 1000000,
            'jan': 1,
            'feb': 2,
            'mar': 3,
            'apr': 4,
            'may': 5,
            'jun': 6,
            'jul': 7,
            'aug': 8,
            'sep': 9,
            'oct': 10,
            'nov': 11,
            'dec': 12,
            'january': 1,
            'february': 2,
            'march': 3,
            'april': 4,
            'june': 6,
            'july': 7,
            'august': 8,
            'september': 9,
            'october': 10,
            'november': 11,
            'december': 12,
        }

        def parse_number(s):
            if s in NUM_MAPPING:
                return NUM_MAPPING[s]
            s = s.replace(',', '')
            # https://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string
            ret = re.findall(r"[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", s)
            if len(ret) > 0:
                return ret[0]
            return None

        for instance in squall_full_data:
            has_number = False
            numbers = []
            for x in instance["nl"]:
                numbers.append(parse_number(x))
                if numbers[-1] is not None:
                    has_number = True
            instance["numbers"] = numbers
            instance["has_number"] = has_number

        if split_key != 'test':
            with open(dev_ids) as f:
                dev_ids = json.load(f)
            if split_key == "train":
                set = [x for x in squall_full_data if x["tbl"] not in dev_ids]
            else:
                set = [x for x in squall_full_data if x["tbl"] in dev_ids]
            idx = 0
            for sample in set:
                # transform columns
                cols = transform(sample, "columns", columns_keys)
                # transform sql
                sqls = transform(sample, "sql", sql_keys)
                # transform align
                aligns = transform(sample, "align", align_keys)
                # transform ralign
                raligns = transform(sample, "nl_ralign", ralign_keys)
                yield idx, {
                    "nt": sample["nt"],
                    "tbl": sample["tbl"],
                    "columns": cols,
                    "nl": sample["nl"],
                    "nl_pos": sample["nl_pos"],
                    "nl_ner": sample["nl_ner"],
                    "nl_ralign": raligns,
                    "nl_incolumns": sample["nl_incolumns"],
                    "nl_incells": sample["nl_incells"],
                    "columns_innl": sample["columns_innl"],
                    "tgt": sample["tgt"],
                    "sql": sqls,
                    "align": aligns
                }
                idx += 1
        else:
            with open(test, encoding="utf-8") as f:
                test_data = json.load(f)
            idx = 0
            for sample in test_data:
                # transform columns
                keys = ["raw_header", "tokenized_header", "column_suffixes", "column_dtype", "example"]
                cols = transform(sample, "columns", keys)
                yield idx, {
                    "nt": sample["nt"],
                    "tbl": sample["tbl"],
                    "columns": cols,
                    "nl": sample["nl"],
                    "nl_pos": sample["nl_pos"],
                    "nl_ner": sample["nl_ner"],
                    "nl_ralign": {k:[] for k in ralign_keys},
                    "nl_incolumns": sample["nl_incolumns"],
                    "nl_incells": sample["nl_incells"],
                    "columns_innl": sample["columns_innl"],
                    "tgt": '',
                    "sql": {k:[] for k in sql_keys},
                    "align": {k:[] for k in align_keys}
                }
                idx += 1