LightChen2333 commited on
Commit
13b916e
1 Parent(s): c41f77b

Update OpenSLU.py

Browse files
Files changed (1) hide show
  1. OpenSLU.py +239 -183
OpenSLU.py CHANGED
@@ -1,183 +1,239 @@
1
- import json
2
- import os
3
-
4
- import datasets
5
-
6
- _OPEN_SLU_CITATION = """\
7
- xxx"""
8
-
9
- _OPEN_SLU_DESCRIPTION = """\
10
- xxx"""
11
-
12
- _ATIS_DESCRIPTION = """\
13
- @article{wang2019superglue,
14
- title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},
15
- author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},
16
- journal={arXiv preprint arXiv:1905.00537},
17
- year={2019}
18
- }
19
- Note that each SuperGLUE dataset has its own citation. Please see the source to
20
- get the correct citation for each contained dataset.
21
- """
22
-
23
- _BOOLQ_CITATION = """\
24
- @inproceedings{clark2019boolq,
25
- title={BoolQ: Exploring the Surprising Difficulty of Natural Yes/No Questions},
26
- author={Clark, Christopher and Lee, Kenton and Chang, Ming-Wei, and Kwiatkowski, Tom and Collins, Michael, and Toutanova, Kristina},
27
- booktitle={NAACL},
28
- year={2019}
29
- }"""
30
-
31
-
32
- class OpenSLUConfig(datasets.BuilderConfig):
33
- """BuilderConfig for OpenSLU."""
34
-
35
- def __init__(self, features, data_url, citation, url, intent_label_classes=None, slot_label_classes=None, **kwargs):
36
- """BuilderConfig for OpenSLU.
37
- Args:
38
- features: `list[string]`, list of the features that will appear in the
39
- feature dict. Should not include "label".
40
- data_url: `string`, url to download the zip file from.
41
- citation: `string`, citation for the data set.
42
- url: `string`, url for information about the data set.
43
- intent_label_classes: `list[string]`, the list of classes for the intent label
44
- slot_label_classes: `list[string]`, the list of classes for the slot label
45
- **kwargs: keyword arguments forwarded to super.
46
- """
47
- # Version history:
48
- # 0.0.1: Initial version.
49
- super(OpenSLUConfig, self).__init__(version=datasets.Version("0.0.1"), **kwargs)
50
- self.features = features
51
- self.intent_label_classes = intent_label_classes
52
- self.slot_label_classes = slot_label_classes
53
- self.data_url = data_url
54
- self.citation = citation
55
- self.url = url
56
-
57
-
58
- class OpenSLU(datasets.GeneratorBasedBuilder):
59
- """The SuperGLUE benchmark."""
60
-
61
- BUILDER_CONFIGS = [
62
- OpenSLUConfig(
63
- name="atis",
64
- description=_ATIS_DESCRIPTION,
65
- features=["text"],
66
- data_url="https://huggingface.co/datasets/LightChen2333/OpenSLU/resolve/main/atis.tar.gz",
67
- citation="",
68
- url="",
69
- ),
70
- OpenSLUConfig(
71
- name="snips",
72
- description=_ATIS_DESCRIPTION,
73
- features=["text"],
74
- data_url="https://huggingface.co/datasets/LightChen2333/OpenSLU/resolve/main/snips.tar.gz",
75
- citation="",
76
- url="",
77
- ),
78
- OpenSLUConfig(
79
- name="mix-atis",
80
- description=_ATIS_DESCRIPTION,
81
- features=["text"],
82
- data_url="https://huggingface.co/datasets/LightChen2333/OpenSLU/resolve/main/mix-atis.tar.gz",
83
- citation="",
84
- url="",
85
- ),
86
- OpenSLUConfig(
87
- name="mix-snips",
88
- description=_ATIS_DESCRIPTION,
89
- features=["text"],
90
- data_url="https://huggingface.co/datasets/LightChen2333/OpenSLU/resolve/main/mix-snips.tar.gz",
91
- citation="",
92
- url="",
93
- ),
94
- ]
95
-
96
- def _info(self):
97
- features = {feature: datasets.Sequence(datasets.Value("string")) for feature in self.config.features}
98
- features["slot"] = datasets.Sequence(datasets.Value("string"))
99
- features["intent"] = datasets.Value("string")
100
-
101
- return datasets.DatasetInfo(
102
- description=_OPEN_SLU_DESCRIPTION + self.config.description,
103
- features=datasets.Features(features),
104
- homepage=self.config.url,
105
- citation=self.config.citation + "\n" + _OPEN_SLU_CITATION,
106
- )
107
-
108
- def _split_generators(self, dl_manager):
109
- print(self.config.data_url)
110
- dl_dir = dl_manager.download_and_extract(self.config.data_url) or ""
111
-
112
- task_name = _get_task_name_from_data_url(self.config.data_url)
113
- print(dl_dir)
114
- print(task_name)
115
- dl_dir = os.path.join(dl_dir, task_name)
116
- return [
117
- datasets.SplitGenerator(
118
- name=datasets.Split.TRAIN,
119
- gen_kwargs={
120
- "data_file": os.path.join(dl_dir, "train.jsonl"),
121
- "split": datasets.Split.TRAIN,
122
- },
123
- ),
124
- datasets.SplitGenerator(
125
- name=datasets.Split.VALIDATION,
126
- gen_kwargs={
127
- "data_file": os.path.join(dl_dir, "dev.jsonl"),
128
- "split": datasets.Split.VALIDATION,
129
- },
130
- ),
131
- datasets.SplitGenerator(
132
- name=datasets.Split.TEST,
133
- gen_kwargs={
134
- "data_file": os.path.join(dl_dir, "test.jsonl"),
135
- "split": datasets.Split.TEST,
136
- },
137
- ),
138
- ]
139
-
140
- def _generate_examples(self, data_file, split):
141
- with open(data_file, encoding="utf-8") as f:
142
- for index, line in enumerate(f):
143
- row = json.loads(line)
144
- yield index, row
145
-
146
-
147
- def _cast_label(label):
148
- """Converts the label into the appropriate string version."""
149
- if isinstance(label, str):
150
- return label
151
- elif isinstance(label, bool):
152
- return "True" if label else "False"
153
- elif isinstance(label, int):
154
- assert label in (0, 1)
155
- return str(label)
156
- else:
157
- raise ValueError("Invalid label format.")
158
-
159
-
160
- def _get_record_entities(passage):
161
- """Returns the unique set of entities."""
162
- text = passage["text"]
163
- entity_spans = list()
164
- for entity in passage["entities"]:
165
- entity_text = text[entity["start"]: entity["end"] + 1]
166
- entity_spans.append({"text": entity_text, "start": entity["start"], "end": entity["end"] + 1})
167
- entity_spans = sorted(entity_spans, key=lambda e: e["start"]) # sort by start index
168
- entity_texts = set(e["text"] for e in entity_spans) # for backward compatability
169
- return entity_texts, entity_spans
170
-
171
-
172
- def _get_record_answers(qa):
173
- """Returns the unique set of answers."""
174
- if "answers" not in qa:
175
- return []
176
- answers = set()
177
- for answer in qa["answers"]:
178
- answers.add(answer["text"])
179
- return sorted(answers)
180
-
181
-
182
- def _get_task_name_from_data_url(data_url):
183
- return data_url.split("/")[-1].split(".")[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+
4
+ import datasets
5
+
6
+ _OPEN_SLU_CITATION = """\
7
+ xxx"""
8
+
9
+ _OPEN_SLU_DESCRIPTION = """\
10
+ xxx"""
11
+
12
+ _ATIS_CITATION = """\
13
+ @inproceedings{hemphill1990atis,
14
+ title = "The {ATIS} Spoken Language Systems Pilot Corpus",
15
+ author = "Hemphill, Charles T. and
16
+ Godfrey, John J. and
17
+ Doddington, George R.",
18
+ booktitle = "Speech and Natural Language: Proceedings of a Workshop Held at Hidden Valley, {P}ennsylvania, June 24-27,1990",
19
+ year = "1990",
20
+ url = "https://aclanthology.org/H90-1021",
21
+ }
22
+ """
23
+
24
+ _ATIS_DESCRIPTION = """\
25
+ A widely used SLU corpus for single-intent SLU.
26
+ """
27
+
28
+ _SNIPS_CITATION = """\
29
+ @article{coucke2018snips,
30
+ title={Snips voice platform: an embedded spoken language understanding system for private-by-design voice interfaces},
31
+ author={Coucke, Alice and Saade, Alaa and Ball, Adrien and Bluche, Th{\'e}odore and Caulier, Alexandre and Leroy, David and Doumouro, Cl{\'e}ment and Giss\textsf{el}brecht, Thibault and Caltagirone, Francesco and Lavril, Thibaut and others},
32
+ journal={arXiv preprint arXiv:1805.10190},
33
+ year={2018}
34
+ }
35
+ """
36
+
37
+ _SNIPS_DESCRIPTION = """\
38
+ A widely used SLU corpus for single-intent SLU.
39
+ """
40
+
41
+ _MIX_ATIS_CITATION = """\
42
+ @inproceedings{qin2020agif,
43
+ title = "{AGIF}: An Adaptive Graph-Interactive Framework for Joint Multiple Intent Detection and Slot Filling",
44
+ author = "Qin, Libo and
45
+ Xu, Xiao and
46
+ Che, Wanxiang and
47
+ Liu, Ting",
48
+ booktitle = "Findings of the Association for Computational Linguistics: EMNLP 2020",
49
+ month = nov,
50
+ year = "2020",
51
+ address = "Online",
52
+ publisher = "Association for Computational Linguistics",
53
+ url = "https://aclanthology.org/2020.findings-emnlp.163",
54
+ doi = "10.18653/v1/2020.findings-emnlp.163",
55
+ pages = "1807--1816",
56
+ abstract = "In real-world scenarios, users usually have multiple intents in the same utterance. Unfortunately, most spoken language understanding (SLU) models either mainly focused on the single intent scenario, or simply incorporated an overall intent context vector for all tokens, ignoring the fine-grained multiple intents information integration for token-level slot prediction. In this paper, we propose an Adaptive Graph-Interactive Framework (AGIF) for joint multiple intent detection and slot filling, where we introduce an intent-slot graph interaction layer to model the strong correlation between the slot and intents. Such an interaction layer is applied to each token adaptively, which has the advantage to automatically extract the relevant intents information, making a fine-grained intent information integration for the token-level slot prediction. Experimental results on three multi-intent datasets show that our framework obtains substantial improvement and achieves the state-of-the-art performance. In addition, our framework achieves new state-of-the-art performance on two single-intent datasets.",
57
+ }
58
+ """
59
+
60
+ _MIX_ATIS_DESCRIPTION = """\
61
+ A widely used SLU corpus for multi-intent SLU.
62
+ """
63
+
64
+ _MIX_SNIPS_CITATION = """\
65
+ @inproceedings{qin2020agif,
66
+ title = "{AGIF}: An Adaptive Graph-Interactive Framework for Joint Multiple Intent Detection and Slot Filling",
67
+ author = "Qin, Libo and
68
+ Xu, Xiao and
69
+ Che, Wanxiang and
70
+ Liu, Ting",
71
+ booktitle = "Findings of the Association for Computational Linguistics: EMNLP 2020",
72
+ month = nov,
73
+ year = "2020",
74
+ address = "Online",
75
+ publisher = "Association for Computational Linguistics",
76
+ url = "https://aclanthology.org/2020.findings-emnlp.163",
77
+ doi = "10.18653/v1/2020.findings-emnlp.163",
78
+ pages = "1807--1816",
79
+ abstract = "In real-world scenarios, users usually have multiple intents in the same utterance. Unfortunately, most spoken language understanding (SLU) models either mainly focused on the single intent scenario, or simply incorporated an overall intent context vector for all tokens, ignoring the fine-grained multiple intents information integration for token-level slot prediction. In this paper, we propose an Adaptive Graph-Interactive Framework (AGIF) for joint multiple intent detection and slot filling, where we introduce an intent-slot graph interaction layer to model the strong correlation between the slot and intents. Such an interaction layer is applied to each token adaptively, which has the advantage to automatically extract the relevant intents information, making a fine-grained intent information integration for the token-level slot prediction. Experimental results on three multi-intent datasets show that our framework obtains substantial improvement and achieves the state-of-the-art performance. In addition, our framework achieves new state-of-the-art performance on two single-intent datasets.",
80
+ }
81
+ """
82
+
83
+ _MIX_SNIPS_DESCRIPTION = """\
84
+ A widely used SLU corpus for multi-intent SLU.
85
+ """
86
+
87
+
88
+ class OpenSLUConfig(datasets.BuilderConfig):
89
+ """BuilderConfig for OpenSLU."""
90
+
91
+ def __init__(self, features, data_url, citation, url, intent_label_classes=None, slot_label_classes=None, **kwargs):
92
+ """BuilderConfig for OpenSLU.
93
+ Args:
94
+ features: `list[string]`, list of the features that will appear in the
95
+ feature dict. Should not include "label".
96
+ data_url: `string`, url to download the zip file from.
97
+ citation: `string`, citation for the data set.
98
+ url: `string`, url for information about the data set.
99
+ intent_label_classes: `list[string]`, the list of classes for the intent label
100
+ slot_label_classes: `list[string]`, the list of classes for the slot label
101
+ **kwargs: keyword arguments forwarded to super.
102
+ """
103
+ # Version history:
104
+ # 0.0.1: Initial version.
105
+ super(OpenSLUConfig, self).__init__(version=datasets.Version("0.0.1"), **kwargs)
106
+ self.features = features
107
+ self.intent_label_classes = intent_label_classes
108
+ self.slot_label_classes = slot_label_classes
109
+ self.data_url = data_url
110
+ self.citation = citation
111
+ self.url = url
112
+
113
+
114
+ class OpenSLU(datasets.GeneratorBasedBuilder):
115
+ """The SuperGLUE benchmark."""
116
+
117
+ BUILDER_CONFIGS = [
118
+ OpenSLUConfig(
119
+ name="atis",
120
+ description=_ATIS_DESCRIPTION,
121
+ features=["text"],
122
+ data_url="https://huggingface.co/datasets/LightChen2333/OpenSLU/resolve/main/atis.tar.gz",
123
+ citation=_ATIS_CITATION,
124
+ url="https://aclanthology.org/H90-1021",
125
+ ),
126
+ OpenSLUConfig(
127
+ name="snips",
128
+ description=_SNIPS_DESCRIPTION,
129
+ features=["text"],
130
+ data_url="https://huggingface.co/datasets/LightChen2333/OpenSLU/resolve/main/snips.tar.gz",
131
+ citation=_SNIPS_CITATION,
132
+ url="https://arxiv.org/abs/1805.10190",
133
+ ),
134
+ OpenSLUConfig(
135
+ name="mix-atis",
136
+ description=_MIX_ATIS_DESCRIPTION,
137
+ features=["text"],
138
+ data_url="https://huggingface.co/datasets/LightChen2333/OpenSLU/resolve/main/mix-atis.tar.gz",
139
+ citation=_MIX_ATIS_CITATION,
140
+ url="https://aclanthology.org/2020.findings-emnlp.163",
141
+ ),
142
+ OpenSLUConfig(
143
+ name="mix-snips",
144
+ description=_MIX_SNIPS_DESCRIPTION,
145
+ features=["text"],
146
+ data_url="https://huggingface.co/datasets/LightChen2333/OpenSLU/resolve/main/mix-snips.tar.gz",
147
+ citation=_MIX_SNIPS_CITATION,
148
+ url="https://aclanthology.org/2020.findings-emnlp.163",
149
+ ),
150
+ ]
151
+
152
+ def _info(self):
153
+ features = {feature: datasets.Sequence(datasets.Value("string")) for feature in self.config.features}
154
+ features["slot"] = datasets.Sequence(datasets.Value("string"))
155
+ features["intent"] = datasets.Value("string")
156
+
157
+ return datasets.DatasetInfo(
158
+ description=_OPEN_SLU_DESCRIPTION + self.config.description,
159
+ features=datasets.Features(features),
160
+ homepage=self.config.url,
161
+ citation=self.config.citation + "\n" + _OPEN_SLU_CITATION,
162
+ )
163
+
164
+ def _split_generators(self, dl_manager):
165
+ print(self.config.data_url)
166
+ dl_dir = dl_manager.download_and_extract(self.config.data_url) or ""
167
+
168
+ task_name = _get_task_name_from_data_url(self.config.data_url)
169
+ print(dl_dir)
170
+ print(task_name)
171
+ dl_dir = os.path.join(dl_dir, task_name)
172
+ return [
173
+ datasets.SplitGenerator(
174
+ name=datasets.Split.TRAIN,
175
+ gen_kwargs={
176
+ "data_file": os.path.join(dl_dir, "train.jsonl"),
177
+ "split": datasets.Split.TRAIN,
178
+ },
179
+ ),
180
+ datasets.SplitGenerator(
181
+ name=datasets.Split.VALIDATION,
182
+ gen_kwargs={
183
+ "data_file": os.path.join(dl_dir, "dev.jsonl"),
184
+ "split": datasets.Split.VALIDATION,
185
+ },
186
+ ),
187
+ datasets.SplitGenerator(
188
+ name=datasets.Split.TEST,
189
+ gen_kwargs={
190
+ "data_file": os.path.join(dl_dir, "test.jsonl"),
191
+ "split": datasets.Split.TEST,
192
+ },
193
+ ),
194
+ ]
195
+
196
+ def _generate_examples(self, data_file, split):
197
+ with open(data_file, encoding="utf-8") as f:
198
+ for index, line in enumerate(f):
199
+ row = json.loads(line)
200
+ yield index, row
201
+
202
+
203
+ def _cast_label(label):
204
+ """Converts the label into the appropriate string version."""
205
+ if isinstance(label, str):
206
+ return label
207
+ elif isinstance(label, bool):
208
+ return "True" if label else "False"
209
+ elif isinstance(label, int):
210
+ assert label in (0, 1)
211
+ return str(label)
212
+ else:
213
+ raise ValueError("Invalid label format.")
214
+
215
+
216
+ def _get_record_entities(passage):
217
+ """Returns the unique set of entities."""
218
+ text = passage["text"]
219
+ entity_spans = list()
220
+ for entity in passage["entities"]:
221
+ entity_text = text[entity["start"]: entity["end"] + 1]
222
+ entity_spans.append({"text": entity_text, "start": entity["start"], "end": entity["end"] + 1})
223
+ entity_spans = sorted(entity_spans, key=lambda e: e["start"]) # sort by start index
224
+ entity_texts = set(e["text"] for e in entity_spans) # for backward compatability
225
+ return entity_texts, entity_spans
226
+
227
+
228
+ def _get_record_answers(qa):
229
+ """Returns the unique set of answers."""
230
+ if "answers" not in qa:
231
+ return []
232
+ answers = set()
233
+ for answer in qa["answers"]:
234
+ answers.add(answer["text"])
235
+ return sorted(answers)
236
+
237
+
238
+ def _get_task_name_from_data_url(data_url):
239
+ return data_url.split("/")[-1].split(".")[0]