zhuqi commited on
Commit
1884ed2
1 Parent(s): b1735c8

Upload 6 files

Browse files
Files changed (6) hide show
  1. README.md +61 -3
  2. data.zip +3 -0
  3. database.py +239 -0
  4. dummy_data.json +0 -0
  5. preprocess.py +535 -0
  6. shuffled_dial_ids.json +0 -0
README.md CHANGED
@@ -1,3 +1,61 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dataset Card for CrossWOZ
2
+
3
+ - **Repository:** https://github.com/thu-coai/CrossWOZ
4
+ - **Paper:** https://aclanthology.org/2020.tacl-1.19/
5
+ - **Leaderboard:** None
6
+ - **Who transforms the dataset:** Qi Zhu(zhuq96 at gmail dot com)
7
+
8
+ ### Dataset Summary
9
+
10
+ CrossWOZ is the first large-scale Chinese Cross-Domain Wizard-of-Oz task-oriented dataset. It contains 6K dialogue sessions and 102K utterances for 5 domains, including hotel, restaurant, attraction, metro, and taxi. Moreover, the corpus contains rich annotation of dialogue states and dialogue acts at both user and system sides. We also provide a user simulator and several benchmark models for pipelined taskoriented dialogue systems, which will facilitate researchers to compare and evaluate their models on this corpus.
11
+
12
+ - **How to get the transformed data from original data:**
13
+ - Run `python preprocess.py` in the current directory. Need `../../crosswoz/` as the original data.
14
+ - **Main changes of the transformation:**
15
+ - Add simple description for domains, slots, and intents.
16
+ - switch intent&domain of `General` dialog acts => domain == 'General' and intent in ['thank','bye','greet','welcome']
17
+ - Binary dialog acts include: 1) domain == 'General'; 2) intent in ['NoOffer', 'Request', 'Select']; 3) slot in ['酒店设施']
18
+ - Categorical dialog acts include: slot in ['酒店类型', '车型', '车牌']
19
+ - Non-categorical dialogue acts: others. assert intent in ['Inform', 'Recommend'] and slot != 'none' and value != 'none'
20
+ - Transform original user goal to list of `{domain: {'inform': {slot: [value, mentioned/not mentioned]}, 'request': {slot: [value, mentioned/not mentioned]}}}`, stored as `user_state` of user turns.
21
+ - Transform `sys_state_init` (first API call of system turns) without `selectedResults` as belief state in user turns.
22
+ - Transform `sys_state` (last API call of system turns) to `db_query` with domain states that contain non-empty `selectedResults`. The `selectedResults` are saved as `db_results`. Both stored in system turns.
23
+ - **Annotations:**
24
+ - user goal, user state, dialogue acts, state, db query, db results.
25
+ - Multiple values in state are separated by spaces, meaning all constraints should be satisfied.
26
+
27
+ ### Supported Tasks and Leaderboards
28
+
29
+ NLU, DST, Policy, NLG, E2E, User simulator
30
+
31
+ ### Languages
32
+
33
+ Chinese
34
+
35
+ ### Data Splits
36
+
37
+ | split | dialogues | utterances | avg_utt | avg_tokens | avg_domains | cat slot match(state) | cat slot match(goal) | cat slot match(dialogue act) | non-cat slot span(dialogue act) |
38
+ |------------|-------------|--------------|-----------|--------------|---------------|-------------------------|------------------------|--------------------------------|-----------------------------------|
39
+ | train | 5010 | 84660 | 16.9 | 20.55 | 3.02 | 99.67 | - | 100 | 94.39 |
40
+ | validation | 500 | 8458 | 16.92 | 20.53 | 3.04 | 99.62 | - | 100 | 94.36 |
41
+ | test | 500 | 8476 | 16.95 | 20.51 | 3.08 | 99.61 | - | 100 | 94.85 |
42
+ | all | 6010 | 101594 | 16.9 | 20.54 | 3.03 | 99.66 | - | 100 | 94.43 |
43
+
44
+ 6 domains: ['景点', '餐馆', '酒店', '地铁', '出租', 'General']
45
+ - **cat slot match**: how many values of categorical slots are in the possible values of ontology in percentage.
46
+ - **non-cat slot span**: how many values of non-categorical slots have span annotation in percentage.
47
+
48
+ ### Citation
49
+
50
+ ```
51
+ @article{zhu2020crosswoz,
52
+ author = {Qi Zhu and Kaili Huang and Zheng Zhang and Xiaoyan Zhu and Minlie Huang},
53
+ title = {Cross{WOZ}: A Large-Scale Chinese Cross-Domain Task-Oriented Dialogue Dataset},
54
+ journal = {Transactions of the Association for Computational Linguistics},
55
+ year = {2020}
56
+ }
57
+ ```
58
+
59
+ ### Licensing Information
60
+
61
+ Apache License, Version 2.0
data.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ddc310bba9fada91f266bd455d50b064ec897f069b960c6ca63447cefb8355bb
3
+ size 15918515
database.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Modifed from https://github.com/thu-coai/CrossWOZ/blob/master/convlab2/util/crosswoz/dbquery.py"""
2
+ import json
3
+ import os
4
+ import re
5
+ from zipfile import ZipFile
6
+
7
+ from convlab.util.unified_datasets_util import (BaseDatabase,
8
+ download_unified_datasets)
9
+
10
+
11
+ def contains(arr, s):
12
+ return not len(tuple(filter(lambda item: (not (item.find(s) < 0)), arr)))
13
+
14
+ class Database(BaseDatabase):
15
+ def __init__(self):
16
+ """extract data.zip and load the database."""
17
+ data_path = download_unified_datasets('crosswoz', 'data.zip', os.path.dirname(os.path.abspath(__file__)))
18
+ archive = ZipFile(data_path)
19
+ self.domains = ['景点', '餐馆', '酒店', '地铁', '出租']
20
+ domain2eng = {'景点': 'attraction', '餐馆': 'restaurant', '酒店': 'hotel', '地铁': 'metro'}
21
+ self.data = {}
22
+ for domain in self.domains[:-1]:
23
+ with archive.open('data/{}_db.json'.format(domain2eng[domain])) as f:
24
+ self.data[domain] = json.loads(f.read())
25
+
26
+ self.schema = {
27
+ '景点': {
28
+ '名称': {'params': None},
29
+ '门票': {'type': 'between', 'params': [None, None]},
30
+ '游玩时间': {'params': None},
31
+ '评分': {'type': 'between', 'params': [None, None]},
32
+ '周边景点': {'type': 'in', 'params': None},
33
+ '周边餐馆': {'type': 'in', 'params': None},
34
+ '周边酒店': {'type': 'in', 'params': None},
35
+ },
36
+ '餐馆': {
37
+ '名称': {'params': None},
38
+ '推荐菜': {'type': 'multiple_in', 'params': None},
39
+ '人均消费': {'type': 'between', 'params': [None, None]},
40
+ '评分': {'type': 'between', 'params': [None, None]},
41
+ '周边景点': {'type': 'in', 'params': None},
42
+ '周边餐馆': {'type': 'in', 'params': None},
43
+ '周边酒店': {'type': 'in', 'params': None}
44
+ },
45
+ '酒店': {
46
+ '名称': {'params': None},
47
+ '酒店类型': {'params': None},
48
+ '酒店设施': {'type': 'multiple_in', 'params': None},
49
+ '价格': {'type': 'between', 'params': [None, None]},
50
+ '评分': {'type': 'between', 'params': [None, None]},
51
+ '周边景点': {'type': 'in', 'params': None},
52
+ '周边餐馆': {'type': 'in', 'params': None},
53
+ '周边酒店': {'type': 'in', 'params': None}
54
+ },
55
+ '地铁': {
56
+ '起点': {'params': None},
57
+ '终点': {'params': None},
58
+ },
59
+ '出租': {
60
+ '起点': {'params': None},
61
+ '终点': {'params': None},
62
+ }
63
+ }
64
+
65
+ def query(self, domain: str, state: dict, topk: int) -> list:
66
+ """
67
+ return a list of topk entities (dict containing slot-value pairs) for a given domain based on the dialogue state.
68
+ query database using belief state, return list of entities, same format as database
69
+ :param state: belief state of the format {domain: {slot: value}}
70
+ :param domain: maintain by DST, current query domain
71
+ :param topk: max number of entities
72
+ :return: list of entities
73
+ """
74
+ if not domain:
75
+ return []
76
+ cur_query_form = {}
77
+ for slot, value in state[domain].items():
78
+ if not value:
79
+ continue
80
+ if slot == '出发地':
81
+ slot = '起点'
82
+ elif slot == '目的地':
83
+ slot = '终点'
84
+ if slot == '名称':
85
+ # DONE: if name is specified, ignore other constraints
86
+ cur_query_form = {'名称': value}
87
+ break
88
+ elif slot == '评分':
89
+ if re.match('(\d\.\d|\d)', value):
90
+ if re.match('\d\.\d', value):
91
+ score = float(re.match('\d\.\d', value)[0])
92
+ else:
93
+ score = int(re.match('\d', value)[0])
94
+ cur_query_form[slot] = [score, None]
95
+ # else:
96
+ # assert 0, value
97
+ elif slot in ['门票', '人均消费', '价格']:
98
+ low, high = None, None
99
+ if re.match('(\d+)-(\d+)', value):
100
+ low = int(re.match('(\d+)-(\d+)', value)[1])
101
+ high = int(re.match('(\d+)-(\d+)', value)[2])
102
+ elif re.match('\d+', value):
103
+ if '以上' in value:
104
+ low = int(re.match('\d+', value)[0])
105
+ elif '以下' in value:
106
+ high = int(re.match('\d+', value)[0])
107
+ else:
108
+ low = high = int(re.match('\d+', value)[0])
109
+ elif slot == '门票':
110
+ if value == '免费':
111
+ low = high = 0
112
+ elif value == '不免费':
113
+ low = 1
114
+ else:
115
+ print(value)
116
+ # assert 0
117
+ cur_query_form[slot] = [low, high]
118
+ else:
119
+ cur_query_form[slot] = value
120
+ cur_res = self.query_schema(field=domain, args=cur_query_form)
121
+ if domain == '出租':
122
+ res = [cur_res]
123
+ elif domain == '地铁':
124
+ res = []
125
+ for r in cur_res:
126
+ if not res and '起点' in r[0]:
127
+ res.append(r)
128
+ break
129
+ for r in cur_res:
130
+ if '终点' in r[0]:
131
+ res.append(r)
132
+ break
133
+ else:
134
+ res = cur_res
135
+
136
+ return res[:topk]
137
+
138
+ def query_schema(self, field, args):
139
+ if not field in self.schema:
140
+ raise Exception('Unknown field %s' % field)
141
+ if not isinstance(args, dict):
142
+ raise Exception('`args` must be dict')
143
+ db = self.data.get(field)
144
+ plan = self.schema[field]
145
+ for key, value in args.items():
146
+ if not key in plan:
147
+ raise Exception('Unknown key %s' % key)
148
+ value_type = plan[key].get('type')
149
+ if value_type == 'between':
150
+ if not value[0] is None:
151
+ plan[key]['params'][0] = float(value[0])
152
+ if not value[1] is None:
153
+ plan[key]['params'][1] = float(value[1])
154
+ else:
155
+ if not isinstance(value, str):
156
+ raise Exception('Value for `%s` must be string' % key)
157
+ plan[key]['params'] = value
158
+ if field in ['地铁', '出租']:
159
+ s = plan['起点']['params']
160
+ e = plan['终点']['params']
161
+ if not s or not e:
162
+ return []
163
+ if field == '出租':
164
+ return [
165
+ '出租 (%s - %s)' % (s, e), {
166
+ '领域': '出租',
167
+ '车型': '#CX',
168
+ '车牌': '#CP'
169
+ }
170
+ ]
171
+ else:
172
+ def func1(item):
173
+ if item[0].find(s) >= 0:
174
+ return ['(起点) %s' % item[0], item[1]]
175
+
176
+ def func2(item):
177
+ if item[0].find(e) >= 0:
178
+ return ['(终点) %s' % item[0], item[1]]
179
+ return None
180
+
181
+ return list(filter(lambda item: not item is None, list(map(func1, db)))) + list(
182
+ filter(lambda item: not item is None, list(map(func2, db))))
183
+
184
+ def func3(item):
185
+ details = item[1]
186
+ for key, val in args.items():
187
+ val = details.get(key)
188
+ absence = val is None
189
+ options = plan[key]
190
+ if options.get('type') == 'between':
191
+ L = options['params'][0]
192
+ R = options['params'][1]
193
+ if not L is None:
194
+ if absence:
195
+ return False
196
+ else:
197
+ L = float('-inf')
198
+ if not R is None:
199
+ if absence:
200
+ return False
201
+ else:
202
+ R = float('inf')
203
+ if L > val or val > R:
204
+ return False
205
+ elif options.get('type') == 'in':
206
+ s = options['params']
207
+ if not s is None:
208
+ if absence:
209
+ return False
210
+ if contains(val, s):
211
+ return False
212
+ elif options.get('type') == 'multiple_in':
213
+ s = options['params']
214
+ if not s is None:
215
+ if absence:
216
+ return False
217
+ sarr = list(filter(lambda t: bool(t), s.split(' ')))
218
+ if len(list(filter(lambda t: contains(val, t), sarr))):
219
+ return False
220
+ else:
221
+ s = options['params']
222
+ if not s is None:
223
+ if absence:
224
+ return False
225
+ if val.find(s) < 0:
226
+ return False
227
+ return True
228
+
229
+ return [x[1] for x in filter(func3, db)]
230
+
231
+
232
+ if __name__ == '__main__':
233
+ db = Database()
234
+ assert issubclass(Database, BaseDatabase)
235
+ assert isinstance(db, BaseDatabase)
236
+ res = db.query("餐馆", {"餐馆":{'评分':'4.5以上'}}, topk=3)
237
+ from pprint import pprint
238
+ pprint(res)
239
+ print(len(res))
dummy_data.json ADDED
The diff for this file is too large to render. See raw diff
 
preprocess.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import json
3
+ import os
4
+ import re
5
+ from collections import Counter
6
+ from pprint import pprint
7
+ from shutil import copy2, rmtree
8
+ from zipfile import ZIP_DEFLATED, ZipFile
9
+
10
+ from tqdm import tqdm
11
+
12
+ ontology = {
13
+ "domains": {
14
+ "景点": {
15
+ "description": "查找景点",
16
+ "slots": {
17
+ "名称": {
18
+ "description": "景点名称",
19
+ "is_categorical": False,
20
+ "possible_values": []
21
+ },
22
+ "门票": {
23
+ "description": "景点门票价格",
24
+ "is_categorical": False,
25
+ "possible_values": []
26
+ },
27
+ "游玩时间": {
28
+ "description": "景点游玩时间",
29
+ "is_categorical": False,
30
+ "possible_values": []
31
+ },
32
+ "评分": {
33
+ "description": "景点评分",
34
+ "is_categorical": False,
35
+ "possible_values": []
36
+ },
37
+ "地址": {
38
+ "description": "景点地址",
39
+ "is_categorical": False,
40
+ "possible_values": []
41
+ },
42
+ "电话": {
43
+ "description": "景点电话",
44
+ "is_categorical": False,
45
+ "possible_values": []
46
+ },
47
+ "周边景点": {
48
+ "description": "景点周边景点",
49
+ "is_categorical": False,
50
+ "possible_values": []
51
+ },
52
+ "周边餐馆": {
53
+ "description": "景点周边餐馆",
54
+ "is_categorical": False,
55
+ "possible_values": []
56
+ },
57
+ "周边酒店": {
58
+ "description": "景点周边酒店",
59
+ "is_categorical": False,
60
+ "possible_values": []
61
+ }
62
+ }
63
+ },
64
+ "餐馆": {
65
+ "description": "查找餐馆",
66
+ "slots": {
67
+ "名称": {
68
+ "description": "餐馆名称",
69
+ "is_categorical": False,
70
+ "possible_values": []
71
+ },
72
+ "推荐菜": {
73
+ "description": "餐馆推荐菜",
74
+ "is_categorical": False,
75
+ "possible_values": []
76
+ },
77
+ "人均消费": {
78
+ "description": "餐馆人均消费",
79
+ "is_categorical": False,
80
+ "possible_values": []
81
+ },
82
+ "评分": {
83
+ "description": "餐馆评分",
84
+ "is_categorical": False,
85
+ "possible_values": []
86
+ },
87
+ "地址": {
88
+ "description": "餐馆地址",
89
+ "is_categorical": False,
90
+ "possible_values": []
91
+ },
92
+ "电话": {
93
+ "description": "餐馆电话",
94
+ "is_categorical": False,
95
+ "possible_values": []
96
+ },
97
+ "营业时间": {
98
+ "description": "餐馆营业时间",
99
+ "is_categorical": False,
100
+ "possible_values": []
101
+ },
102
+ "周边景点": {
103
+ "description": "餐馆周边景点",
104
+ "is_categorical": False,
105
+ "possible_values": []
106
+ },
107
+ "周边餐馆": {
108
+ "description": "餐馆周边餐馆",
109
+ "is_categorical": False,
110
+ "possible_values": []
111
+ },
112
+ "周边酒店": {
113
+ "description": "餐馆周边酒店",
114
+ "is_categorical": False,
115
+ "possible_values": []
116
+ }
117
+ }
118
+ },
119
+ "酒店": {
120
+ "description": "查找酒店",
121
+ "slots": {
122
+ "名称": {
123
+ "description": "酒店名称",
124
+ "is_categorical": False,
125
+ "possible_values": []
126
+ },
127
+ "酒店类型": {
128
+ "description": "酒店类型",
129
+ "is_categorical": True,
130
+ "possible_values": [
131
+ '高档型', '豪华型', '经济型', '舒适型'
132
+ ]
133
+ },
134
+ "酒店设施": {
135
+ "description": "酒店设施",
136
+ "is_categorical": False,
137
+ "possible_values": []
138
+ },
139
+ "价格": {
140
+ "description": "酒店价格",
141
+ "is_categorical": False,
142
+ "possible_values": []
143
+ },
144
+ "评分": {
145
+ "description": "酒店评分",
146
+ "is_categorical": False,
147
+ "possible_values": []
148
+ },
149
+ "地址": {
150
+ "description": "酒店地址",
151
+ "is_categorical": False,
152
+ "possible_values": []
153
+ },
154
+ "电话": {
155
+ "description": "酒店电话",
156
+ "is_categorical": False,
157
+ "possible_values": []
158
+ },
159
+ "周边景点": {
160
+ "description": "酒店周边景点",
161
+ "is_categorical": False,
162
+ "possible_values": []
163
+ },
164
+ "周边餐馆": {
165
+ "description": "酒店周边餐馆",
166
+ "is_categorical": False,
167
+ "possible_values": []
168
+ },
169
+ "周边酒店": {
170
+ "description": "酒店周边酒店",
171
+ "is_categorical": False,
172
+ "possible_values": []
173
+ }
174
+ }
175
+ },
176
+ "地铁": {
177
+ "description": "乘坐地铁从某地到某地",
178
+ "slots": {
179
+ "出发地": {
180
+ "description": "地铁出发地",
181
+ "is_categorical": False,
182
+ "possible_values": []
183
+ },
184
+ "目的地": {
185
+ "description": "地铁目的地",
186
+ "is_categorical": False,
187
+ "possible_values": []
188
+ },
189
+ "出发地附近地铁站": {
190
+ "description": "出发地附近地铁站",
191
+ "is_categorical": False,
192
+ "possible_values": []
193
+ },
194
+ "目的地附近地铁站": {
195
+ "description": "目的地附近地铁站",
196
+ "is_categorical": False,
197
+ "possible_values": []
198
+ }
199
+ }
200
+ },
201
+ "出租": {
202
+ "description": "乘坐出租车从某地到某地",
203
+ "slots": {
204
+ "出发地": {
205
+ "description": "出租出发地",
206
+ "is_categorical": False,
207
+ "possible_values": []
208
+ },
209
+ "目的地": {
210
+ "description": "出租目的地",
211
+ "is_categorical": False,
212
+ "possible_values": []
213
+ },
214
+ "车型": {
215
+ "description": "出租车车型",
216
+ "is_categorical": True,
217
+ "possible_values": [
218
+ "#CX"
219
+ ]
220
+ },
221
+ "车牌": {
222
+ "description": "出租车车牌",
223
+ "is_categorical": True,
224
+ "possible_values": [
225
+ "#CP"
226
+ ]
227
+ }
228
+ }
229
+ },
230
+ "General": {
231
+ "description": "通用领域",
232
+ "slots": {}
233
+ }
234
+ },
235
+ "intents": {
236
+ "Inform": {
237
+ "description": "告知相关属性"
238
+ },
239
+ "Request": {
240
+ "description": "询问相关属性"
241
+ },
242
+ "Recommend": {
243
+ "description": "推荐搜索结果"
244
+ },
245
+ "Select": {
246
+ "description": "在附近搜索"
247
+ },
248
+ "NoOffer": {
249
+ "description": "未找到符合用户要求的结果"
250
+ },
251
+ "bye": {
252
+ "description": "再见"
253
+ },
254
+ "thank": {
255
+ "description": "感谢"
256
+ },
257
+ "welcome": {
258
+ "description": "不客气"
259
+ },
260
+ "greet": {
261
+ "description": "打招呼"
262
+ },
263
+ },
264
+ "state": {
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
+ "dialogue_acts": {
303
+ "categorical": {},
304
+ "non-categorical": {},
305
+ "binary": {}
306
+ }
307
+ }
308
+
309
+ cnt_domain_slot = Counter()
310
+
311
+ def convert_da(da_list, utt):
312
+ '''
313
+ convert dialogue acts to required format
314
+ :param da_dict: list of (intent, domain, slot, value)
315
+ :param utt: user or system utt
316
+ '''
317
+ global ontology, cnt_domain_slot
318
+
319
+ converted_da = {
320
+ 'categorical': [],
321
+ 'non-categorical': [],
322
+ 'binary': []
323
+ }
324
+
325
+ for intent, domain, slot, value in da_list:
326
+ # if intent in ['Inform', 'Recommend']:
327
+ if intent == 'NoOffer':
328
+ assert slot == 'none' and value == 'none'
329
+ converted_da['binary'].append({
330
+ 'intent': intent,
331
+ 'domain': domain,
332
+ 'slot': ''
333
+ })
334
+ elif intent == 'General':
335
+ # intent=General, domain=thank/bye/greet/welcome
336
+ assert slot == 'none' and value == 'none'
337
+ converted_da['binary'].append({
338
+ 'intent': domain,
339
+ 'domain': intent,
340
+ 'slot': ''
341
+ })
342
+ elif intent == 'Request':
343
+ assert value == '' and slot != 'none'
344
+ converted_da['binary'].append({
345
+ 'intent': intent,
346
+ 'domain': domain,
347
+ 'slot': slot
348
+ })
349
+ elif '酒店设施' in slot:
350
+ converted_da['binary'].append({
351
+ 'intent': intent,
352
+ 'domain': domain,
353
+ 'slot': f"{slot}-{value}"
354
+ })
355
+ elif intent == 'Select':
356
+ assert slot == '源领域'
357
+ converted_da['binary'].append({
358
+ 'intent': intent,
359
+ 'domain': domain,
360
+ 'slot': f"{slot}-{value}"
361
+ })
362
+ elif slot in ['酒店类型', '车型', '车牌']:
363
+ assert intent in ['Inform', 'Recommend']
364
+ assert slot != 'none' and value != 'none'
365
+ converted_da['categorical'].append({
366
+ 'intent': intent,
367
+ 'domain': domain,
368
+ 'slot': slot,
369
+ 'value': value
370
+ })
371
+ else:
372
+ assert intent in ['Inform', 'Recommend']
373
+ assert slot != 'none' and value != 'none'
374
+ matches = utt.count(value)
375
+ if matches == 1:
376
+ start = utt.index(value)
377
+ end = start + len(value)
378
+
379
+ converted_da['non-categorical'].append({
380
+ 'intent': intent,
381
+ 'domain': domain,
382
+ 'slot': slot,
383
+ 'value': value,
384
+ 'start': start,
385
+ 'end': end
386
+ })
387
+ cnt_domain_slot['have span'] += 1
388
+ else:
389
+ # can not find span
390
+ converted_da['non-categorical'].append({
391
+ 'intent': intent,
392
+ 'domain': domain,
393
+ 'slot': slot,
394
+ 'value': value
395
+ })
396
+ cnt_domain_slot['no span'] += 1
397
+ # cnt_domain_slot.setdefault(f'{domain}-{slot}', set())
398
+ # cnt_domain_slot[f'{domain}-{slot}'].add(value)
399
+
400
+ return converted_da
401
+
402
+ def transform_user_state(user_state):
403
+ goal = []
404
+ for subgoal in user_state:
405
+ gid, domain, slot, value, mentioned = subgoal
406
+ if len(value) != 0:
407
+ t = 'inform'
408
+ else:
409
+ t = 'request'
410
+ if len(goal) < gid:
411
+ goal.append({domain: {'inform': {}, 'request': {}}})
412
+ goal[gid-1][domain][t][slot] = [value, 'mentioned' if mentioned else 'not mentioned']
413
+ return goal
414
+
415
+
416
+ def preprocess():
417
+ original_data_dir = '../../crosswoz'
418
+ new_data_dir = 'data'
419
+
420
+ os.makedirs(new_data_dir, exist_ok=True)
421
+ for filename in os.listdir(os.path.join(original_data_dir,'database')):
422
+ copy2(f'{original_data_dir}/database/{filename}', new_data_dir)
423
+
424
+ global ontology
425
+
426
+ dataset = 'crosswoz'
427
+ splits = ['train', 'validation', 'test']
428
+ dialogues_by_split = {split: [] for split in splits}
429
+ for split in ['train', 'val', 'test']:
430
+ data = json.load(ZipFile(os.path.join(original_data_dir, f'{split}.json.zip'), 'r').open(f'{split}.json'))
431
+ if split == 'val':
432
+ split = 'validation'
433
+
434
+ for ori_dialog_id, ori_dialog in data.items():
435
+ if ori_dialog_id in ['10550', '11724']:
436
+ # skip error dialog
437
+ continue
438
+ dialogue_id = f'{dataset}-{split}-{len(dialogues_by_split[split])}'
439
+
440
+ # get user goal and involved domains
441
+ goal = {'inform': {}, 'request': {}}
442
+ goal["description"] = '\n'.join(ori_dialog["task description"])
443
+ cur_domains = [x[1] for i, x in enumerate(ori_dialog['goal']) if i == 0 or ori_dialog['goal'][i-1][1] != x[1]]
444
+
445
+ dialogue = {
446
+ 'dataset': dataset,
447
+ 'data_split': split,
448
+ 'dialogue_id': dialogue_id,
449
+ 'original_id': ori_dialog_id,
450
+ 'domains': cur_domains,
451
+ 'goal': goal,
452
+ 'user_state_init': transform_user_state(ori_dialog['goal']),
453
+ 'type': ori_dialog['type'],
454
+ 'turns': [],
455
+ 'user_state_final': transform_user_state(ori_dialog['final_goal'])
456
+ }
457
+
458
+ for turn_id, turn in enumerate(ori_dialog['messages']):
459
+ if ori_dialog_id == '2660' and turn_id in [8,9]:
460
+ # skip error turns
461
+ continue
462
+ elif ori_dialog_id == '7467' and turn_id in [14,15]:
463
+ # skip error turns
464
+ continue
465
+ elif ori_dialog_id == '11726' and turn_id in [4,5]:
466
+ # skip error turns
467
+ continue
468
+ speaker = 'user' if turn['role'] == 'usr' else 'system'
469
+ utt = turn['content']
470
+
471
+ das = turn['dialog_act']
472
+
473
+ dialogue_acts = convert_da(das, utt)
474
+
475
+ dialogue['turns'].append({
476
+ 'speaker': speaker,
477
+ 'utterance': utt,
478
+ 'utt_idx': len(dialogue['turns']),
479
+ 'dialogue_acts': dialogue_acts,
480
+ })
481
+
482
+ # add to dialogue_acts dictionary in the ontology
483
+ for da_type in dialogue_acts:
484
+ das = dialogue_acts[da_type]
485
+ for da in das:
486
+ ontology["dialogue_acts"][da_type].setdefault((da['intent'], da['domain'], da['slot']), {})
487
+ ontology["dialogue_acts"][da_type][(da['intent'], da['domain'], da['slot'])][speaker] = True
488
+
489
+ if speaker == 'user':
490
+ dialogue['turns'][-1]['user_state'] = transform_user_state(turn['user_state'])
491
+ else:
492
+ # add state to last user turn
493
+ belief_state = turn['sys_state_init']
494
+ for domain in belief_state:
495
+ belief_state[domain].pop('selectedResults')
496
+ dialogue['turns'][-2]['state'] = belief_state
497
+ db_query = turn['sys_state']
498
+ db_results = {}
499
+ for domain in list(db_query.keys()):
500
+ db_res = db_query[domain].pop('selectedResults')
501
+ if len(db_res) > 0:
502
+ db_results[domain] = [{'名称': x} for x in db_res]
503
+ else:
504
+ db_query.pop(domain)
505
+ dialogue['turns'][-1]['db_query'] = db_query
506
+ dialogue['turns'][-1]['db_results'] = db_results
507
+ dialogues_by_split[split].append(dialogue)
508
+ pprint(cnt_domain_slot.most_common())
509
+ dialogues = []
510
+ for split in splits:
511
+ dialogues += dialogues_by_split[split]
512
+ for da_type in ontology['dialogue_acts']:
513
+ ontology["dialogue_acts"][da_type] = sorted([str(
514
+ {'user': speakers.get('user', False), 'system': speakers.get('system', False), 'intent': da[0],
515
+ 'domain': da[1], 'slot': da[2]}) for da, speakers in ontology["dialogue_acts"][da_type].items()])
516
+ json.dump(dialogues[:10], open(f'dummy_data.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
517
+ json.dump(ontology, open(f'{new_data_dir}/ontology.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
518
+ json.dump(dialogues, open(f'{new_data_dir}/dialogues.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
519
+ with ZipFile('data.zip', 'w', ZIP_DEFLATED) as zf:
520
+ for filename in os.listdir(new_data_dir):
521
+ zf.write(f'{new_data_dir}/{filename}')
522
+ rmtree(new_data_dir)
523
+ return dialogues, ontology
524
+
525
+
526
+ def fix_entity_booked_info(entity_booked_dict, booked):
527
+ for domain in entity_booked_dict:
528
+ if not entity_booked_dict[domain] and booked[domain]:
529
+ entity_booked_dict[domain] = True
530
+ booked[domain] = []
531
+ return entity_booked_dict, booked
532
+
533
+
534
+ if __name__ == '__main__':
535
+ preprocess()
shuffled_dial_ids.json ADDED
The diff for this file is too large to render. See raw diff