holylovenia commited on
Commit
8a6c69b
1 Parent(s): c8a6c0b

Upload globalwoz.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. globalwoz.py +226 -0
globalwoz.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from pathlib import Path
4
+ from typing import Dict, List, Tuple
5
+
6
+ import datasets
7
+ import itertools
8
+
9
+ from seacrowd.utils import schemas
10
+ from seacrowd.utils.configs import SEACrowdConfig
11
+ from seacrowd.utils.constants import Tasks, Licenses
12
+
13
+ _CITATION = """\
14
+ @inproceedings{ding-etal-2022-globalwoz,
15
+ title = "{G}lobal{W}o{Z}: Globalizing {M}ulti{W}o{Z} to Develop Multilingual Task-Oriented Dialogue Systems",
16
+ author = "Ding, Bosheng and
17
+ Hu, Junjie and
18
+ Bing, Lidong and
19
+ Aljunied, Mahani and
20
+ Joty, Shafiq and
21
+ Si, Luo and
22
+ Miao, Chunyan",
23
+ editor = "Muresan, Smaranda and
24
+ Nakov, Preslav and
25
+ Villavicencio, Aline",
26
+ booktitle = "Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",
27
+ month = may,
28
+ year = "2022",
29
+ }
30
+ """
31
+
32
+ _DATASETNAME = "globalwoz"
33
+
34
+ _DESCRIPTION = """\
35
+ This is the data of the paper “GlobalWoZ: Globalizing MultiWoZ to Develop Multilingual Task-Oriented Dialogue Systems” accepted by ACL 2022. The dataset contains several sub-datasets in 20 languages and 3 schemes (F&E, E&F, F&F), including Indonesian (id), Thai (th), and Vietnamese (vi) language. The method is based on translating dialogue templates and filling them with local entities in the target language countries.
36
+ """
37
+
38
+
39
+ _HOMEPAGE = "https://github.com/bosheng2020/globalwoz"
40
+
41
+
42
+ _LANGUAGES = ["ind", "tha", "vie"]
43
+
44
+ _LICENSE = Licenses.UNKNOWN.value
45
+
46
+ _LOCAL = True
47
+
48
+ _URLS = {}
49
+
50
+ _SUPPORTED_TASKS = [Tasks.E2E_TASK_ORIENTED_DIALOGUE]
51
+
52
+ _SOURCE_VERSION = "2.0.0"
53
+
54
+ _SEACROWD_VERSION = "2024.06.20"
55
+
56
+
57
+ def seacrowd_config_constructor(dial_type, lang, schema, version):
58
+ if dial_type not in ["EandF", "FandE", "FandF"]:
59
+ raise ValueError(f"Invalid dialogue type {dial_type}")
60
+
61
+ if lang == "":
62
+ raise ValueError(f"Invalid lang {lang}")
63
+
64
+ if schema not in ["source", "seacrowd_tod"]:
65
+ raise ValueError(f"Invalid schema: {schema}")
66
+
67
+ return SEACrowdConfig(
68
+ name="globalwoz_{dial_type}_{lang}_{schema}".format(dial_type=dial_type, lang=lang, schema=schema),
69
+ version=datasets.Version(version),
70
+ description="GlobalWoZ schema for {schema}: {dial_type}_{lang}".format(schema=schema, dial_type=dial_type, lang=lang),
71
+ schema=schema,
72
+ subset_id="globalwoz_{dial_type}_{lang}".format(dial_type=dial_type, lang=lang),
73
+ )
74
+
75
+
76
+ class GlobalWoZ(datasets.GeneratorBasedBuilder):
77
+ """This is the data of the paper “GlobalWoZ: Globalizing MultiWoZ to Develop Multilingual Task-Oriented Dialogue Systems” accepted by ACL 2022.
78
+ The dataset contains several sub-datasets in 20 languages and 3 schemes (F&E, E&F, F&F), including Indonesian (id), Thai (th),
79
+ and Vietnamese (vi) language. The method is based on translating dialogue templates and filling them with local entities in the target language countries.
80
+ """
81
+
82
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
83
+ SEACROWD_VERSION = datasets.Version(_SEACROWD_VERSION)
84
+
85
+ BUILDER_CONFIGS = [
86
+ seacrowd_config_constructor(tod_format, lang, schema, _SOURCE_VERSION if schema == "source" else _SEACROWD_VERSION) for tod_format, lang, schema in itertools.product(("EandF", "FandE", "FandF"), ("id", "th", "vi"), ("source", "seacrowd_tod"))
87
+ ]
88
+
89
+ def _info(self) -> datasets.DatasetInfo:
90
+ if self.config.schema == "source":
91
+ features = datasets.Features(
92
+ {
93
+ "id": datasets.Value("string"),
94
+ "goal": {
95
+ "attraction": datasets.Value("string"),
96
+ "hospital": datasets.Value("string"),
97
+ "hotel": datasets.Value("string"),
98
+ "police": datasets.Value("string"),
99
+ "restaurant": datasets.Value("string"),
100
+ "taxi": datasets.Value("string"),
101
+ "train": datasets.Value("string"),
102
+ },
103
+ "log": [
104
+ {
105
+ "dialog_act": datasets.Value("string"),
106
+ "metadata": datasets.Value("string"),
107
+ "span_info": [[datasets.Value("string")]],
108
+ "text": datasets.Value("string"),
109
+ }
110
+ ],
111
+ }
112
+ )
113
+
114
+ elif self.config.schema == "seacrowd_tod":
115
+ features = schemas.tod_features
116
+ else:
117
+ raise NotImplementedError()
118
+
119
+ return datasets.DatasetInfo(
120
+ description=_DESCRIPTION,
121
+ features=features,
122
+ homepage=_HOMEPAGE,
123
+ license=_LICENSE,
124
+ citation=_CITATION,
125
+ )
126
+
127
+ def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
128
+ """Returns SplitGenerators."""
129
+ _split_generators = []
130
+
131
+ type_and_lang = {"dial_type": self.config.subset_id.split("_")[1].replace("and", "&"), "lang": self.config.subset_id.split("_")[2]} # globalwoz_{dial_type}_{lang}
132
+
133
+ if self.config.data_dir is None:
134
+ raise ValueError("This is a local dataset. Please pass the data_dir kwarg to load_dataset.")
135
+ else:
136
+ data_dir = self.config.data_dir
137
+
138
+ if not os.path.exists(os.path.join(data_dir, f"{type_and_lang['dial_type']}_{type_and_lang['lang']}.json")):
139
+ raise FileNotFoundError()
140
+
141
+ return [
142
+ datasets.SplitGenerator(
143
+ name=datasets.Split.TRAIN,
144
+ gen_kwargs={
145
+ # "filepath": data_dir + f"_{type_and_lang['dial_type']}_{type_and_lang['lang']}.json",
146
+ "filepath": os.path.join(data_dir, f"{type_and_lang['dial_type']}_{type_and_lang['lang']}.json"),
147
+ "split": "train",
148
+ },
149
+ ),
150
+ ]
151
+
152
+ def _generate_examples(self, filepath: Path, split: str) -> Tuple[int, Dict]:
153
+ """Yields examples as (key, example) tuples."""
154
+ # For local datasets you will have access to self.config.data_dir and self.config.data_files
155
+ with open(filepath, "r+", encoding="utf8") as fw:
156
+ data = json.load(fw)
157
+
158
+ if self.config.schema == "source":
159
+ for idx, tod_dialogue in enumerate(data.values()):
160
+ example = {}
161
+ example["id"] = str(idx)
162
+ example["goal"] = {}
163
+
164
+ for goal_key in ["attraction", "hospital", "hotel", "police", "restaurant", "taxi", "train"]:
165
+ example["goal"][goal_key] = json.dumps(tod_dialogue["goal"][goal_key])
166
+ example["log"] = []
167
+
168
+ for dial_log in tod_dialogue["log"]:
169
+ dial = {}
170
+ dial["dialog_act"] = json.dumps(dial_log["dialog_act"])
171
+ dial["metadata"] = json.dumps(dial_log["metadata"])
172
+ for i in range(len(dial_log["span_info"])):
173
+ for j in range(len(dial_log["span_info"][i])):
174
+ dial_log["span_info"][i][j] = str(dial_log["span_info"][i][j]) # casting to str
175
+ dial["span_info"] = [[str(span)] if isinstance(span, str) else span for span in dial_log["span_info"]]
176
+ dial["text"] = dial_log["text"]
177
+
178
+ example["log"].append(dial)
179
+
180
+ yield example["id"], example
181
+
182
+ elif self.config.schema == "seacrowd_tod":
183
+ for idx, tod_dialogue in enumerate(data.values()):
184
+ example = {}
185
+ example["dialogue_idx"] = idx
186
+
187
+ dialogue = []
188
+ # NOTE: the dialogue always started with `user` as first utterance
189
+ for turn, i in enumerate(range(0, len(tod_dialogue["log"]) + 2, 2)):
190
+ dial = {}
191
+ dial["turn_idx"] = turn
192
+
193
+ # system_utterance properties
194
+ dial["system_utterance"] = ""
195
+ dial["system_acts"] = []
196
+ if turn != 0:
197
+ dial["system_utterance"] = tod_dialogue["log"][i - 1]["text"]
198
+ if i < len(tod_dialogue["log"]):
199
+ # NOTE: "system_acts will be populated with the `dialog_act` from the user utterance in the original dataset, as our schema dictates
200
+ # that `system_acts` should represent the system's intended actions based on the user's utterance."
201
+ for acts in tod_dialogue["log"][i]["dialog_act"].values():
202
+ for act in acts:
203
+ dial["system_acts"].append([act[0]])
204
+
205
+ # user_utterance properties
206
+ dial["turn_label"] = [] # left as an empty array
207
+ dial["belief_state"] = []
208
+ if i == len(tod_dialogue["log"]):
209
+ # case if turn_idx > len(dialogue) --> add dummy user_utterance
210
+ dial["user_utterance"] = ""
211
+ else:
212
+ dial["user_utterance"] = tod_dialogue["log"][i]["text"]
213
+ # NOTE: "the belief_state will be populated with the `span_info` from the user utterance in the original dataset, as our schema dictates
214
+ # that `belief_state` should represent the system's belief state based on the user's utterance."
215
+ for span in tod_dialogue["log"][i]["span_info"]:
216
+ if span[0].split("-")[1] == "request": # Request action
217
+ dial["belief_state"].append({"slots": [["slot", span[1]]], "act": "request"})
218
+ else:
219
+ dial["belief_state"].append({"slots": [[span[1], span[2]]], "act": span[0].split("-")[1]})
220
+
221
+ # append to dialogue
222
+ dialogue.append(dial)
223
+
224
+ example["dialogue"] = dialogue
225
+
226
+ yield example["dialogue_idx"], example