nflubis commited on
Commit
3941e20
·
verified ·
1 Parent(s): a6fb521

upload files

Browse files
Files changed (5) hide show
  1. data.zip +3 -0
  2. database.py +125 -0
  3. dummy_data.json +0 -0
  4. preprocess.py +1303 -0
  5. shuffled_dial_ids.json +0 -0
data.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:540ba08b83169dad99488200c8e6cb28571d671316120971cb4eb8d7f2b34e2b
3
+ size 13114217
database.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import random
4
+ from fuzzywuzzy import fuzz
5
+ from itertools import chain
6
+ from zipfile import ZipFile
7
+ from copy import deepcopy
8
+ from convlab.util.unified_datasets_util import BaseDatabase, download_unified_datasets
9
+
10
+
11
+ class Database(BaseDatabase):
12
+ def __init__(self):
13
+ """extract data.zip and load the database."""
14
+ data_path = download_unified_datasets('multiwoz21', 'data.zip', os.path.dirname(os.path.abspath(__file__)))
15
+ archive = ZipFile(data_path)
16
+ self.domains = ['restaurant', 'hotel', 'attraction', 'train', 'hospital', 'police']
17
+ self.dbs = {}
18
+ for domain in self.domains:
19
+ with archive.open('data/{}_db.json'.format(domain)) as f:
20
+ self.dbs[domain] = json.loads(f.read())
21
+ # add some missing information
22
+ self.dbs['taxi'] = {
23
+ "taxi_colors": ["black","white","red","yellow","blue","grey"],
24
+ "taxi_types": ["toyota","skoda","bmw","honda","ford","audi","lexus","volvo","volkswagen","tesla"],
25
+ "taxi_phone": ["^[0-9]{10}$"]
26
+ }
27
+ self.dbs['police'][0]['postcode'] = "cb11jg"
28
+ for entity in self.dbs['hospital']:
29
+ entity['postcode'] = "cb20qq"
30
+ entity['address'] = "Hills Rd, Cambridge"
31
+
32
+ self.slot2dbattr = {
33
+ 'open hours': 'openhours',
34
+ 'price range': 'pricerange',
35
+ 'arrive by': 'arriveBy',
36
+ 'leave at': 'leaveAt',
37
+ 'train id': 'trainID'
38
+ }
39
+
40
+ def query(self, domain: str, state: dict, topk: int, ignore_open=False, soft_contraints=(), fuzzy_match_ratio=60) -> list:
41
+ """
42
+ return a list of topk entities (dict containing slot-value pairs) for a given domain based on the dialogue state.
43
+ :param state: support two formats: 1) [[slot,value], [slot,value]...]; 2) {domain: {slot: value, slot: value...}} (the same as belief state)
44
+ """
45
+ if isinstance(state, dict):
46
+ assert domain in state, print(f"domain {domain} not in state {state}")
47
+ state = state[domain].items()
48
+ # query the db
49
+ if domain == 'taxi':
50
+ return [{'taxi_colors': random.choice(self.dbs[domain]['taxi_colors']),
51
+ 'taxi_types': random.choice(self.dbs[domain]['taxi_types']),
52
+ 'taxi_phone': ''.join([str(random.randint(1, 9)) for _ in range(11)])}]
53
+ if domain == 'police':
54
+ return deepcopy(self.dbs['police'])
55
+ if domain == 'hospital':
56
+ department = None
57
+ for key, val in state:
58
+ if key == 'department':
59
+ department = val
60
+ if not department:
61
+ for key, val in soft_contraints:
62
+ if key == 'department':
63
+ department = val
64
+ if not department:
65
+ return deepcopy(self.dbs['hospital'])
66
+ else:
67
+ return [deepcopy(x) for x in self.dbs['hospital'] if x['department'].lower() == department.strip().lower()]
68
+ state = list(map(lambda ele: (self.slot2dbattr.get(ele[0], ele[0]), ele[1]) if not(ele[0] == 'area' and ele[1] == 'center') else ('area', 'centre'), state))
69
+ soft_contraints = list(map(lambda ele: (self.slot2dbattr.get(ele[0], ele[0]), ele[1]) if not(ele[0] == 'area' and ele[1] == 'center') else ('area', 'centre'), soft_contraints))
70
+
71
+ found = []
72
+ for i, record in enumerate(self.dbs[domain]):
73
+ constraints_iterator = zip(state, [False] * len(state))
74
+ soft_contraints_iterator = zip(soft_contraints, [True] * len(soft_contraints))
75
+ for (key, val), fuzzy_match in chain(constraints_iterator, soft_contraints_iterator):
76
+ if val in ["", "dont care", 'not mentioned', "don't care", "dontcare", "do n't care", "do not care"]:
77
+ pass
78
+ else:
79
+ try:
80
+ if key not in record:
81
+ continue
82
+ if key == 'leaveAt':
83
+ val1 = int(val.split(':')[0]) * 100 + int(val.split(':')[1])
84
+ val2 = int(record['leaveAt'].split(':')[0]) * 100 + int(record['leaveAt'].split(':')[1])
85
+ if val1 > val2:
86
+ break
87
+ elif key == 'arriveBy':
88
+ val1 = int(val.split(':')[0]) * 100 + int(val.split(':')[1])
89
+ val2 = int(record['arriveBy'].split(':')[0]) * 100 + int(record['arriveBy'].split(':')[1])
90
+ if val1 < val2:
91
+ break
92
+ # elif ignore_open and key in ['destination', 'departure', 'name']:
93
+ elif ignore_open and key in ['destination', 'departure']:
94
+ continue
95
+ elif record[key].strip() == '?':
96
+ # '?' matches any constraint
97
+ continue
98
+ else:
99
+ if not fuzzy_match:
100
+ if val.strip().lower() != record[key].strip().lower():
101
+ break
102
+ else:
103
+ if fuzz.partial_ratio(val.strip().lower(), record[key].strip().lower()) < fuzzy_match_ratio:
104
+ break
105
+ except:
106
+ continue
107
+ else:
108
+ res = deepcopy(record)
109
+ res['Ref'] = '{0:08d}'.format(i)
110
+ found.append(res)
111
+ if len(found) == topk:
112
+ return found
113
+ return found
114
+
115
+
116
+ if __name__ == '__main__':
117
+ db = Database()
118
+ assert issubclass(Database, BaseDatabase)
119
+ assert isinstance(db, BaseDatabase)
120
+ # both calls will be ok
121
+ res1 = db.query("restaurant", [['price range', 'expensive']], topk=3)
122
+ res2 = db.query("restaurant", {'restaurant':{'price range': 'expensive'}}, topk=3)
123
+ assert res1 == res2
124
+ print(res1, len(res1))
125
+ # print(db.query("hotel", [['price range', 'moderate'], ['stars','4'], ['type', 'guesthouse'], ['internet', 'yes'], ['parking', 'no'], ['area', 'east']]))
dummy_data.json ADDED
The diff for this file is too large to render. See raw diff
 
preprocess.py ADDED
@@ -0,0 +1,1303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import re
3
+ from zipfile import ZipFile, ZIP_DEFLATED
4
+ from shutil import copy2, rmtree
5
+ import json
6
+ import os
7
+ import random
8
+ from tqdm import tqdm
9
+ from collections import Counter
10
+ from pprint import pprint
11
+ from nltk.tokenize import TreebankWordTokenizer, PunktSentenceTokenizer
12
+
13
+ ontology = {
14
+ "domains": { # descriptions are adapted from multiwoz22, but is_categorical may be different
15
+ "attraction": {
16
+ "description": "find an attraction",
17
+ "slots": {
18
+ "area": {
19
+ "description": "area to search for attractions",
20
+ "is_categorical": True,
21
+ "possible_values": [
22
+ "centre",
23
+ "east",
24
+ "north",
25
+ "south",
26
+ "west"
27
+ ]
28
+ },
29
+ "name": {
30
+ "description": "name of the attraction",
31
+ "is_categorical": False,
32
+ "possible_values": []
33
+ },
34
+ "type": {
35
+ "description": "type of the attraction",
36
+ "is_categorical": True,
37
+ "possible_values": [
38
+ "architecture",
39
+ "boat",
40
+ "cinema",
41
+ "college",
42
+ "concerthall",
43
+ "entertainment",
44
+ "museum",
45
+ "multiple sports",
46
+ "nightclub",
47
+ "park",
48
+ "swimmingpool",
49
+ "theatre"
50
+ ]
51
+ },
52
+ "entrance fee": {
53
+ "description": "how much is the entrance fee",
54
+ "is_categorical": False,
55
+ "possible_values": []
56
+ },
57
+ "open hours": {
58
+ "description": "open hours of the attraction",
59
+ "is_categorical": False,
60
+ "possible_values": []
61
+ },
62
+ "address": {
63
+ "description": "address of the attraction",
64
+ "is_categorical": False,
65
+ "possible_values": []
66
+ },
67
+ "phone": {
68
+ "description": "phone number of the attraction",
69
+ "is_categorical": False,
70
+ "possible_values": []
71
+ },
72
+ "postcode": {
73
+ "description": "postcode of the attraction",
74
+ "is_categorical": False,
75
+ "possible_values": []
76
+ },
77
+ "choice": {
78
+ "description": "number of attractions that meet the requirement",
79
+ "is_categorical": False,
80
+ "possible_values": []
81
+ }
82
+ }
83
+ },
84
+ "hotel": {
85
+ "description": "find and book a hotel",
86
+ "slots": {
87
+ "internet": {
88
+ "description": "whether the hotel has internet",
89
+ "is_categorical": True,
90
+ "possible_values": [
91
+ "free",
92
+ "no",
93
+ "yes"
94
+ ]
95
+ },
96
+ "parking": {
97
+ "description": "whether the hotel has parking",
98
+ "is_categorical": True,
99
+ "possible_values": [
100
+ "free",
101
+ "no",
102
+ "yes"
103
+ ]
104
+ },
105
+ "area": {
106
+ "description": "area or place of the hotel",
107
+ "is_categorical": True,
108
+ "possible_values": [
109
+ "centre",
110
+ "east",
111
+ "north",
112
+ "south",
113
+ "west"
114
+ ]
115
+ },
116
+ "stars": {
117
+ "description": "star rating of the hotel",
118
+ "is_categorical": True,
119
+ "possible_values": [
120
+ "0",
121
+ "1",
122
+ "2",
123
+ "3",
124
+ "4",
125
+ "5"
126
+ ]
127
+ },
128
+ "price range": {
129
+ "description": "price budget of the hotel",
130
+ "is_categorical": True,
131
+ "possible_values": [
132
+ "expensive",
133
+ "cheap",
134
+ "moderate"
135
+ ]
136
+ },
137
+ "type": {
138
+ "description": "what is the type of the hotel",
139
+ "is_categorical": False,
140
+ "possible_values": [
141
+ "guesthouse",
142
+ "hotel"
143
+ ]
144
+ },
145
+ "name": {
146
+ "description": "name of the hotel",
147
+ "is_categorical": False,
148
+ "possible_values": []
149
+ },
150
+ "book people": {
151
+ "description": "number of people for the hotel booking",
152
+ "is_categorical": False,
153
+ "possible_values": []
154
+ },
155
+ "book stay": {
156
+ "description": "length of stay at the hotel",
157
+ "is_categorical": False,
158
+ "possible_values": []
159
+ },
160
+ "book day": {
161
+ "description": "day of the hotel booking",
162
+ "is_categorical": True,
163
+ "possible_values": [
164
+ "monday",
165
+ "tuesday",
166
+ "wednesday",
167
+ "thursday",
168
+ "friday",
169
+ "saturday",
170
+ "sunday"
171
+ ]
172
+ },
173
+ "phone": {
174
+ "description": "phone number of the hotel",
175
+ "is_categorical": False,
176
+ "possible_values": []
177
+ },
178
+ "postcode": {
179
+ "description": "postcode of the hotel",
180
+ "is_categorical": False,
181
+ "possible_values": []
182
+ },
183
+ "address": {
184
+ "description": "address of the hotel",
185
+ "is_categorical": False,
186
+ "possible_values": []
187
+ },
188
+ "ref": {
189
+ "description": "reference number of the hotel booking",
190
+ "is_categorical": False,
191
+ "possible_values": []
192
+ },
193
+ "choice": {
194
+ "description": "number of hotels that meet the requirement",
195
+ "is_categorical": False,
196
+ "possible_values": []
197
+ }
198
+ }
199
+ },
200
+ "taxi": {
201
+ "description": "rent taxi to travel",
202
+ "slots": {
203
+ "destination": {
204
+ "description": "destination of taxi",
205
+ "is_categorical": False,
206
+ "possible_values": []
207
+ },
208
+ "departure": {
209
+ "description": "departure location of taxi",
210
+ "is_categorical": False,
211
+ "possible_values": []
212
+ },
213
+ "leave at": {
214
+ "description": "leaving time of taxi",
215
+ "is_categorical": False,
216
+ "possible_values": []
217
+ },
218
+ "arrive by": {
219
+ "description": "arrival time of taxi",
220
+ "is_categorical": False,
221
+ "possible_values": []
222
+ },
223
+ "phone": {
224
+ "description": "phone number of the taxi",
225
+ "is_categorical": False,
226
+ "possible_values": []
227
+ },
228
+ "type": {
229
+ "description": "car type of the taxi",
230
+ "is_categorical": False,
231
+ "possible_values": []
232
+ }
233
+ }
234
+ },
235
+ "restaurant": {
236
+ "description": "find and book a restaurant",
237
+ "slots": {
238
+ "price range": {
239
+ "description": "price budget for the restaurant",
240
+ "is_categorical": True,
241
+ "possible_values": [
242
+ "cheap",
243
+ "expensive",
244
+ "moderate"
245
+ ]
246
+ },
247
+ "area": {
248
+ "description": "area or place of the restaurant",
249
+ "is_categorical": True,
250
+ "possible_values": [
251
+ "centre",
252
+ "east",
253
+ "north",
254
+ "south",
255
+ "west"
256
+ ]
257
+ },
258
+ "food": {
259
+ "description": "the cuisine of the restaurant",
260
+ "is_categorical": False,
261
+ "possible_values": []
262
+ },
263
+ "name": {
264
+ "description": "name of the restaurant",
265
+ "is_categorical": False,
266
+ "possible_values": []
267
+ },
268
+ "address": {
269
+ "description": "address of the restaurant",
270
+ "is_categorical": False,
271
+ "possible_values": []
272
+ },
273
+ "postcode": {
274
+ "description": "postcode of the restaurant",
275
+ "is_categorical": False,
276
+ "possible_values": []
277
+ },
278
+ "phone": {
279
+ "description": "phone number of the restaurant",
280
+ "is_categorical": False,
281
+ "possible_values": []
282
+ },
283
+ "book people": {
284
+ "description": "number of people for the restaurant booking",
285
+ "is_categorical": False,
286
+ "possible_values": []
287
+ },
288
+ "book time": {
289
+ "description": "time of the restaurant booking",
290
+ "is_categorical": False,
291
+ "possible_values": []
292
+ },
293
+ "book day": {
294
+ "description": "day of the restaurant booking",
295
+ "is_categorical": True,
296
+ "possible_values": [
297
+ "monday",
298
+ "tuesday",
299
+ "wednesday",
300
+ "thursday",
301
+ "friday",
302
+ "saturday",
303
+ "sunday"
304
+ ]
305
+ },
306
+ "ref": {
307
+ "description": "reference number of the restaurant booking",
308
+ "is_categorical": False,
309
+ "possible_values": []
310
+ },
311
+ "choice": {
312
+ "description": "number of restaurants that meet the requirement",
313
+ "is_categorical": False,
314
+ "possible_values": []
315
+ }
316
+ }
317
+ },
318
+ "train": {
319
+ "description": "find a train to travel",
320
+ "slots": {
321
+ "destination": {
322
+ "description": "destination of the train",
323
+ "is_categorical": False,
324
+ "possible_values": []
325
+ },
326
+ "arrive by": {
327
+ "description": "arrival time of the train",
328
+ "is_categorical": False,
329
+ "possible_values": []
330
+ },
331
+ "departure": {
332
+ "description": "departure location of the train",
333
+ "is_categorical": False,
334
+ "possible_values": []
335
+ },
336
+ "leave at": {
337
+ "description": "leaving time for the train",
338
+ "is_categorical": False,
339
+ "possible_values": []
340
+ },
341
+ "duration": {
342
+ "description": "duration of the travel",
343
+ "is_categorical": False,
344
+ "possible_values": []
345
+ },
346
+ "book people": {
347
+ "description": "number of people booking for train",
348
+ "is_categorical": False,
349
+ "possible_values": []
350
+ },
351
+ "day": {
352
+ "description": "day of the train",
353
+ "is_categorical": True,
354
+ "possible_values": [
355
+ "monday",
356
+ "tuesday",
357
+ "wednesday",
358
+ "thursday",
359
+ "friday",
360
+ "saturday",
361
+ "sunday"
362
+ ]
363
+ },
364
+ "ref": {
365
+ "description": "reference number of the train booking",
366
+ "is_categorical": False,
367
+ "possible_values": []
368
+ },
369
+ "price": {
370
+ "description": "price of the train ticket",
371
+ "is_categorical": False,
372
+ "possible_values": []
373
+ },
374
+ "train id": {
375
+ "description": "id of the train",
376
+ "is_categorical": False
377
+ },
378
+ "choice": {
379
+ "description": "number of trains that meet the requirement",
380
+ "is_categorical": False,
381
+ "possible_values": []
382
+ }
383
+ }
384
+ },
385
+ "police": {
386
+ "description": "find a police station for help",
387
+ "slots": {
388
+ "name": {
389
+ "description": "name of the police station",
390
+ "is_categorical": False,
391
+ "possible_values": []
392
+ },
393
+ "address": {
394
+ "description": "address of the police station",
395
+ "is_categorical": False,
396
+ "possible_values": []
397
+ },
398
+ "postcode": {
399
+ "description": "postcode of the police station",
400
+ "is_categorical": False,
401
+ "possible_values": []
402
+ },
403
+ "phone": {
404
+ "description": "phone number of the police station",
405
+ "is_categorical": False,
406
+ "possible_values": []
407
+ }
408
+ }
409
+ },
410
+ "hospital": {
411
+ "description": "find a hospital for help",
412
+ "slots": {
413
+ "department": {
414
+ "description": "specific department of the hospital",
415
+ "is_categorical": False,
416
+ "possible_values": []
417
+ },
418
+ "address": {
419
+ "description": "address of the hospital",
420
+ "is_categorical": False,
421
+ "possible_values": []
422
+ },
423
+ "phone": {
424
+ "description": "phone number of the hospital",
425
+ "is_categorical": False,
426
+ "possible_values": []
427
+ },
428
+ "postcode": {
429
+ "description": "postcode of the hospital",
430
+ "is_categorical": False,
431
+ "possible_values": []
432
+ }
433
+ }
434
+ },
435
+ "general": {
436
+ "description": "general domain without slots",
437
+ "slots": {}
438
+ }
439
+ },
440
+ "intents": {
441
+ "inform": {
442
+ "description": "inform the value of a slot"
443
+ },
444
+ "request": {
445
+ "description": "ask for the value of a slot"
446
+ },
447
+ "nobook": {
448
+ "description": "inform the user that the booking is failed"
449
+ },
450
+ "reqmore": {
451
+ "description": "ask the user for more instructions"
452
+ },
453
+ "book": {
454
+ "description": "book something for the user"
455
+ },
456
+ "bye": {
457
+ "description": "say goodbye to the user and end the conversation"
458
+ },
459
+ "thank": {
460
+ "description": "thanks for the help"
461
+ },
462
+ "welcome": {
463
+ "description": "you're welcome"
464
+ },
465
+ "greet": {
466
+ "description": "express greeting"
467
+ },
468
+ "recommend": {
469
+ "description": "recommend a choice to the user"
470
+ },
471
+ "select": {
472
+ "description": "provide several choices for the user"
473
+ },
474
+ "offerbook": {
475
+ "description": "ask the user if he or she needs booking"
476
+ },
477
+ "offerbooked": {
478
+ "description": "provide information about the booking"
479
+ },
480
+ "nooffer": {
481
+ "description": "inform the user that there is no result satisfies user requirements"
482
+ }
483
+ },
484
+ "state": {
485
+ "attraction": {
486
+ "type": "",
487
+ "name": "",
488
+ "area": ""
489
+ },
490
+ "hotel": {
491
+ "name": "",
492
+ "area": "",
493
+ "parking": "",
494
+ "price range": "",
495
+ "stars": "",
496
+ "internet": "",
497
+ "type": "",
498
+ "book stay": "",
499
+ "book day": "",
500
+ "book people": ""
501
+ },
502
+ "restaurant": {
503
+ "food": "",
504
+ "price range": "",
505
+ "name": "",
506
+ "area": "",
507
+ "book time": "",
508
+ "book day": "",
509
+ "book people": ""
510
+ },
511
+ "taxi": {
512
+ "leave at": "",
513
+ "destination": "",
514
+ "departure": "",
515
+ "arrive by": ""
516
+ },
517
+ "train": {
518
+ "leave at": "",
519
+ "destination": "",
520
+ "day": "",
521
+ "arrive by": "",
522
+ "departure": "",
523
+ "book people": ""
524
+ },
525
+ "hospital": {
526
+ "department": ""
527
+ }
528
+ },
529
+ "dialogue_acts": {
530
+ "categorical": {},
531
+ "non-categorical": {},
532
+ "binary": {}
533
+ }
534
+ }
535
+
536
+ slot_name_map = {
537
+ 'addr': "address",
538
+ 'post': "postcode",
539
+ 'pricerange': "price range",
540
+ 'arrive': "arrive by",
541
+ 'arriveby': "arrive by",
542
+ 'leave': "leave at",
543
+ 'leaveat': "leave at",
544
+ 'depart': "departure",
545
+ 'dest': "destination",
546
+ 'fee': "entrance fee",
547
+ 'open': 'open hours',
548
+ 'car': "type",
549
+ 'car type': "type",
550
+ 'ticket': 'price',
551
+ 'trainid': 'train id',
552
+ 'id': 'train id',
553
+ 'people': 'book people',
554
+ 'stay': 'book stay',
555
+ 'none': '',
556
+ 'attraction': {
557
+ 'price': 'entrance fee'
558
+ },
559
+ 'hospital': {},
560
+ 'hotel': {
561
+ 'day': 'book day', 'price': "price range"
562
+ },
563
+ 'restaurant': {
564
+ 'day': 'book day', 'time': 'book time', 'price': "price range"
565
+ },
566
+ 'taxi': {
567
+ 'time': 'leave at',
568
+ 'pickup time': 'leave at',
569
+ 'leaving time': 'leave at',
570
+ 'leaving': 'leave at',
571
+ 'arrival time': 'arrive by',
572
+ 'arriving': 'arrive by',
573
+ 'car': "type",
574
+ 'car type': "type"
575
+ },
576
+ 'train': {
577
+ 'day': 'day', 'time': "duration"
578
+ },
579
+ 'police': {},
580
+ 'booking': {}
581
+ }
582
+
583
+ reverse_da_slot_name_map = {
584
+ 'address': 'Addr',
585
+ 'postcode': 'Post',
586
+ 'price range': 'Price',
587
+ 'arrive by': 'Arrive',
588
+ 'leave at': 'Leave',
589
+ 'departure': 'Depart',
590
+ 'destination': 'Dest',
591
+ 'entrance fee': 'Fee',
592
+ 'open hours': 'Open',
593
+ 'price': 'Ticket',
594
+ 'train id': 'Id',
595
+ 'book people': 'People',
596
+ 'book stay': 'Stay',
597
+ 'book day': 'Day',
598
+ 'book time': 'Time',
599
+ 'duration': 'Time',
600
+ 'taxi': {
601
+ 'type': 'Car',
602
+ 'phone': 'Phone'
603
+ }
604
+ }
605
+
606
+ digit2word = {
607
+ '0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five',
608
+ '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '10': 'ten'
609
+ }
610
+
611
+ cnt_domain_slot = Counter()
612
+
613
+
614
+ class BookingActRemapper:
615
+
616
+ def __init__(self, ontology):
617
+ self.ontology = ontology
618
+ self.reset()
619
+
620
+ def reset(self):
621
+ self.current_domains_user = []
622
+ self.current_domains_system = []
623
+ self.booked_domains = []
624
+
625
+ def retrieve_current_domain_from_user(self, turn_id, ori_dialog):
626
+ prev_user_turn = ori_dialog[turn_id - 1]
627
+
628
+ dialog_acts = prev_user_turn.get('dialog_act', [])
629
+ keyword_domains_user = get_keyword_domains(prev_user_turn)
630
+ current_domains_temp = get_current_domains_from_act(dialog_acts)
631
+ self.current_domains_user = current_domains_temp if current_domains_temp else self.current_domains_user
632
+ next_user_domains = get_next_user_act_domains(ori_dialog, turn_id)
633
+
634
+ return keyword_domains_user, next_user_domains
635
+
636
+ def retrieve_current_domain_from_system(self, turn_id, ori_dialog):
637
+
638
+ system_turn = ori_dialog[turn_id]
639
+ dialog_acts = system_turn.get('dialog_act', [])
640
+ keyword_domains_system = get_keyword_domains(system_turn)
641
+ current_domains_temp = get_current_domains_from_act(dialog_acts)
642
+ self.current_domains_system = current_domains_temp if current_domains_temp else self.current_domains_system
643
+ booked_domain_current = self.check_domain_booked(system_turn)
644
+
645
+ return keyword_domains_system, booked_domain_current
646
+
647
+ def remap(self, turn_id, ori_dialog):
648
+
649
+ keyword_domains_user, next_user_domains = self.retrieve_current_domain_from_user(turn_id, ori_dialog)
650
+ keyword_domains_system, booked_domain_current = self.retrieve_current_domain_from_system(turn_id, ori_dialog)
651
+
652
+ # only need to remap if there is a dialog action labelled
653
+ dialog_acts = ori_dialog[turn_id].get('dialog_act', [])
654
+ spans = ori_dialog[turn_id].get('span_info', [])
655
+ if dialog_acts:
656
+
657
+ flattened_acts = flatten_acts(dialog_acts)
658
+ flattened_spans = flatten_span_acts(spans)
659
+ remapped_acts, error_local = remap_acts(flattened_acts, self.current_domains_user,
660
+ booked_domain_current, keyword_domains_user,
661
+ keyword_domains_system, self.current_domains_system,
662
+ next_user_domains, self.ontology)
663
+
664
+ remapped_spans, _ = remap_acts(flattened_spans, self.current_domains_user,
665
+ booked_domain_current, keyword_domains_user,
666
+ keyword_domains_system, self.current_domains_system,
667
+ next_user_domains, self.ontology)
668
+
669
+ deflattened_remapped_acts = deflat_acts(remapped_acts)
670
+ deflattened_remapped_spans = deflat_span_acts(remapped_spans)
671
+
672
+ return deflattened_remapped_acts, deflattened_remapped_spans
673
+ else:
674
+ return dialog_acts, spans
675
+
676
+ def check_domain_booked(self, turn):
677
+
678
+ booked_domain_current = None
679
+ for domain in turn['metadata']:
680
+ if turn['metadata'][domain]["book"]["booked"] and domain not in self.booked_domains:
681
+ booked_domain_current = domain.capitalize()
682
+ self.booked_domains.append(domain)
683
+ return booked_domain_current
684
+
685
+ def infer_booking_target_domain(slot_raw: str, value: str, cur_domains: list):
686
+ """
687
+ Decide which concrete domain a stray 'Booking-*' act should map to, based on slot semantics
688
+ and currently active dialogue domains. Then validate via normalize_domain_slot_value.
689
+ """
690
+ s = (slot_raw or "").lower().strip()
691
+
692
+ # Heuristic candidate orders by slot semantics
693
+ if s in {"time", "book time"}:
694
+ base_order = ["restaurant", "train", "taxi", "hotel"]
695
+ elif s in {"stay", "book stay"}:
696
+ base_order = ["hotel"]
697
+ elif s in {"day", "book day"}:
698
+ base_order = ["hotel", "restaurant", "train"]
699
+ elif s in {"people", "book people"}:
700
+ base_order = ["hotel", "restaurant", "train"]
701
+ elif s in {"ref", "reference", "reference number"}:
702
+ base_order = ["train", "restaurant", "hotel", "taxi"]
703
+ else:
704
+ base_order = ["hotel", "restaurant", "train", "taxi"]
705
+
706
+ # Prefer already active domains, then the rest
707
+ ordered = [d for d in base_order if d in cur_domains] + [d for d in base_order if d not in cur_domains]
708
+
709
+ # Try to validate against ontology via normalize_domain_slot_value
710
+ for d in ordered:
711
+ try:
712
+ dom, slot, val = normalize_domain_slot_value(d, slot_raw, value)
713
+ return dom, slot, val
714
+ except Exception:
715
+ continue
716
+
717
+ # Nothing validated — surface a clear error
718
+ raise Exception(f"booking-slot '{slot_raw}' could not be mapped to a concrete domain")
719
+
720
+
721
+ def load_id_list(base_dir: str, base_name: str) -> set:
722
+ """
723
+ Try several filename variants in `base_dir`:
724
+ base_name.txt, base_name.json, base_name (no extension).
725
+ TXT is parsed as whitespace-separated IDs.
726
+ JSON may be a list of IDs or a dict containing a common split key.
727
+ """
728
+ candidates = [
729
+ os.path.join(base_dir, base_name + ".txt"),
730
+ os.path.join(base_dir, base_name + ".json"),
731
+ os.path.join(base_dir, base_name),
732
+ ]
733
+ for path in candidates:
734
+ if os.path.isfile(path):
735
+ if path.endswith(".txt") or "." not in os.path.basename(path):
736
+ with open(path, "r", encoding="utf-8") as f:
737
+ return set(f.read().split())
738
+ else: # JSON
739
+ with open(path, "r", encoding="utf-8") as f:
740
+ obj = json.load(f)
741
+ if isinstance(obj, list):
742
+ return set(obj)
743
+ if isinstance(obj, dict):
744
+ # try common keys seen in different releases
745
+ for k in ("val", "valid", "validation", "dev", "test", "valList", "valListFile"):
746
+ if k in obj and isinstance(obj[k], list):
747
+ return set(obj[k])
748
+ raise ValueError(f"Unrecognized JSON structure in {path}")
749
+ raise FileNotFoundError(f"No split file variants found for {base_name} in {base_dir}")
750
+
751
+ def _resolve_booking_target(cur_domains):
752
+ """Pick a deterministic target domain for stray 'booking' acts."""
753
+ for d in ('hotel', 'restaurant', 'train', 'taxi'):
754
+ if d in cur_domains:
755
+ return d
756
+ return 'hotel' # final fallback
757
+
758
+ def get_keyword_domains(turn):
759
+ keyword_domains = []
760
+ text = turn['text']
761
+ for d in ["Hotel", "Restaurant", "Train"]:
762
+ if d.lower() in text.lower():
763
+ keyword_domains.append(d)
764
+ return keyword_domains
765
+
766
+
767
+ def get_current_domains_from_act(dialog_acts):
768
+
769
+ current_domains_temp = []
770
+ for dom_int in dialog_acts:
771
+ domain, intent = dom_int.split('-')
772
+ if domain in ["general", "Booking"]:
773
+ continue
774
+ if domain not in current_domains_temp:
775
+ current_domains_temp.append(domain)
776
+
777
+ return current_domains_temp
778
+
779
+
780
+ def get_next_user_act_domains(ori_dialog, turn_id):
781
+ domains = []
782
+ try:
783
+ next_user_act = ori_dialog[turn_id + 1]['dialog_act']
784
+ domains = get_current_domains_from_act(next_user_act)
785
+ except:
786
+ # will fail if system act is the last act of the dialogue
787
+ pass
788
+ return domains
789
+
790
+
791
+ def flatten_acts(dialog_acts):
792
+ flattened_acts = []
793
+ for dom_int in dialog_acts:
794
+ domain, intent = dom_int.split('-')
795
+ for slot_value in dialog_acts[dom_int]:
796
+ slot = slot_value[0]
797
+ value = slot_value[1]
798
+ flattened_acts.append((domain, intent, slot, value))
799
+
800
+ return flattened_acts
801
+
802
+
803
+ def flatten_span_acts(span_acts):
804
+
805
+ flattened_acts = []
806
+ for span_act in span_acts:
807
+ domain, intent = span_act[0].split("-")
808
+ flattened_acts.append((domain, intent, span_act[1], span_act[2:]))
809
+ return flattened_acts
810
+
811
+
812
+ def deflat_acts(flattened_acts):
813
+
814
+ dialog_acts = dict()
815
+
816
+ for act in flattened_acts:
817
+ domain, intent, slot, value = act
818
+ if f"{domain}-{intent}" not in dialog_acts.keys():
819
+ dialog_acts[f"{domain}-{intent}"] = [[slot, value]]
820
+ else:
821
+ dialog_acts[f"{domain}-{intent}"].append([slot, value])
822
+
823
+ return dialog_acts
824
+
825
+
826
+ def deflat_span_acts(flattened_acts):
827
+
828
+ dialog_span_acts = []
829
+ for act in flattened_acts:
830
+ domain, intent, slot, value = act
831
+ if value == 'none':
832
+ continue
833
+ new_act = [f"{domain}-{intent}", slot]
834
+ new_act.extend(value)
835
+ dialog_span_acts.append(new_act)
836
+
837
+ return dialog_span_acts
838
+
839
+
840
+ def remap_acts(flattened_acts, current_domains, booked_domain=None, keyword_domains_user=None,
841
+ keyword_domains_system=None, current_domain_system=None, next_user_domain=None, ontology=None):
842
+
843
+ # We now look for all cases that can happen: Booking domain, Booking within a domain or taxi-inform-car for booking
844
+ error = 0
845
+ remapped_acts = []
846
+
847
+ # if there is more than one current domain or none at all, we try to get booked domain differently
848
+ if len(current_domains) != 1 and booked_domain:
849
+ current_domains = [booked_domain]
850
+ elif len(current_domains) != 1 and len(keyword_domains_user) == 1:
851
+ current_domains = keyword_domains_user
852
+ elif len(current_domains) != 1 and len(keyword_domains_system) == 1:
853
+ current_domains = keyword_domains_system
854
+ elif len(current_domains) != 1 and len(current_domain_system) == 1:
855
+ current_domains = current_domain_system
856
+ elif len(current_domains) != 1 and len(next_user_domain) == 1:
857
+ current_domains = next_user_domain
858
+
859
+ for act in flattened_acts:
860
+ try:
861
+ domain, intent, slot, value = act
862
+ if f"{domain}-{intent}-{slot}" == "Booking-Book-Ref":
863
+ # We need to remap that booking act now
864
+ potential_domain = current_domains[0]
865
+ remapped_acts.append((potential_domain, "Book", "none", "none"))
866
+ if ontology_check(potential_domain, slot, ontology):
867
+ remapped_acts.append((potential_domain, "Inform", "Ref", value))
868
+ elif domain == "Booking" and intent == "Book" and slot != "Ref":
869
+ # the book intent is here actually an inform intent according to the data
870
+ potential_domain = current_domains[0]
871
+ if ontology_check(potential_domain, slot, ontology):
872
+ remapped_acts.append((potential_domain, "Inform", slot, value))
873
+ elif domain == "Booking" and intent == "Inform":
874
+ # the inform intent is here actually a request intent according to the data
875
+ potential_domain = current_domains[0]
876
+ if ontology_check(potential_domain, slot, ontology):
877
+ remapped_acts.append((potential_domain, "OfferBook", slot, value))
878
+ elif domain == "Booking" and intent in ["NoBook", "Request"]:
879
+ potential_domain = current_domains[0]
880
+ if ontology_check(potential_domain, slot, ontology):
881
+ remapped_acts.append((potential_domain, intent, slot, value))
882
+ elif f"{domain}-{intent}-{slot}" == "Taxi-Inform-Car":
883
+ # taxi-inform-car actually triggers the booking and informs on a car
884
+ remapped_acts.append((domain, "Book", "none", "none"))
885
+ remapped_acts.append((domain, intent, slot, value))
886
+ elif f"{domain}-{intent}-{slot}" in ["Train-Inform-Ref", "Train-OfferBooked-Ref"]:
887
+ # train-inform/offerbooked-ref actually triggers the booking and informs on the reference number
888
+ remapped_acts.append((domain, "Book", "none", "none"))
889
+ remapped_acts.append((domain, "Inform", slot, value))
890
+ elif domain == "Train" and intent == "OfferBooked" and slot != "Ref":
891
+ # this is actually an inform act
892
+ remapped_acts.append((domain, "Inform", slot, value))
893
+ else:
894
+ remapped_acts.append(act)
895
+ except Exception as e:
896
+ print("Error detected:", e)
897
+ error += 1
898
+
899
+ return remapped_acts, error
900
+
901
+
902
+ def ontology_check(domain_, slot_, init_ontology):
903
+
904
+ domain = domain_.lower()
905
+ slot = slot_.lower()
906
+ if slot not in init_ontology['domains'][domain]['slots']:
907
+ if slot in slot_name_map:
908
+ slot = slot_name_map[slot]
909
+ elif slot in slot_name_map[domain]:
910
+ slot = slot_name_map[domain][slot]
911
+ return slot in init_ontology['domains'][domain]['slots']
912
+
913
+
914
+ def reverse_da(dialogue_acts):
915
+ global reverse_da_slot_name_map
916
+ das = {}
917
+ for da_type in dialogue_acts:
918
+ for da in dialogue_acts[da_type]:
919
+ intent, domain, slot, value = da['intent'], da['domain'], da['slot'], da.get('value', '')
920
+ if domain == 'general':
921
+ Domain_Intent = '-'.join([domain, intent])
922
+ elif intent == 'nooffer':
923
+ Domain_Intent = '-'.join([domain.capitalize(), 'NoOffer'])
924
+ elif intent == 'nobook':
925
+ Domain_Intent = '-'.join([domain.capitalize(), 'NoBook'])
926
+ elif intent == 'offerbook':
927
+ Domain_Intent = '-'.join([domain.capitalize(), 'OfferBook'])
928
+ else:
929
+ Domain_Intent = '-'.join([domain.capitalize(), intent.capitalize()])
930
+ das.setdefault(Domain_Intent, [])
931
+ if slot in reverse_da_slot_name_map:
932
+ Slot = reverse_da_slot_name_map[slot]
933
+ elif domain in reverse_da_slot_name_map and slot in reverse_da_slot_name_map[domain]:
934
+ Slot = reverse_da_slot_name_map[domain][slot]
935
+ else:
936
+ Slot = slot.capitalize()
937
+ if value == '':
938
+ if intent == 'request':
939
+ value = '?'
940
+ else:
941
+ value = 'none'
942
+ if Slot == '':
943
+ Slot = 'none'
944
+ das[Domain_Intent].append([Slot, value])
945
+ return das
946
+
947
+
948
+ def normalize_domain_slot_value(domain, slot, value):
949
+ global ontology, slot_name_map
950
+ domain = domain.lower()
951
+ slot = slot.lower()
952
+ value = value.strip()
953
+ if value in ['do nt care', "do n't care"]:
954
+ value = 'dontcare'
955
+ if value in ['?', 'none', 'not mentioned']:
956
+ value = ""
957
+ if domain not in ontology['domains']:
958
+ raise Exception(f'{domain} not in ontology')
959
+ if slot not in ontology['domains'][domain]['slots']:
960
+ if slot in slot_name_map:
961
+ slot = slot_name_map[slot]
962
+ elif slot in slot_name_map[domain]:
963
+ slot = slot_name_map[domain][slot]
964
+ else:
965
+ raise Exception(f'{domain}-{slot} not in ontology')
966
+ assert slot == '' or slot in ontology['domains'][domain]['slots'], f'{(domain, slot, value)} not in ontology'
967
+ return domain, slot, value
968
+
969
+
970
+ def convert_da(da_dict, utt, sent_tokenizer, word_tokenizer):
971
+ '''
972
+ convert multiwoz dialogue acts to required format
973
+ :param da_dict: dict[(intent, domain, slot, value)] = [word_start, word_end]
974
+ :param utt: user or system utt
975
+ '''
976
+ global ontology, digit2word, cnt_domain_slot
977
+
978
+ converted_da = {
979
+ 'categorical': [],
980
+ 'non-categorical': [],
981
+ 'binary': []
982
+ }
983
+ sentences = sent_tokenizer.tokenize(utt)
984
+ sent_spans = sent_tokenizer.span_tokenize(utt)
985
+ tokens = [token for sent in sentences for token in word_tokenizer.tokenize(sent)]
986
+ token_spans = [(sent_span[0] + token_span[0], sent_span[0] + token_span[1]) for sent, sent_span in
987
+ zip(sentences, sent_spans) for token_span in word_tokenizer.span_tokenize(sent)]
988
+ # assert len(tokens) == len(token_spans)
989
+ # for token, span in zip(tokens, token_spans):
990
+ # if utt[span[0]:span[1]] != '"':
991
+ # assert utt[span[0]:span[1]] == token
992
+
993
+ for (intent, domain, slot, value), span in da_dict.items():
994
+ if intent == 'request' or slot == '' or value == '':
995
+ # binary dialog acts
996
+ assert value == ''
997
+ converted_da['binary'].append({
998
+ 'intent': intent,
999
+ 'domain': domain,
1000
+ 'slot': slot
1001
+ })
1002
+ elif ontology['domains'][domain]['slots'][slot]['is_categorical']:
1003
+ # categorical dialog acts
1004
+ converted_da['categorical'].append({
1005
+ 'intent': intent,
1006
+ 'domain': domain,
1007
+ 'slot': slot,
1008
+ 'value': value
1009
+ })
1010
+ else:
1011
+ # non-categorical dialog acts
1012
+ converted_da['non-categorical'].append({
1013
+ 'intent': intent,
1014
+ 'domain': domain,
1015
+ 'slot': slot,
1016
+ 'value': value
1017
+ })
1018
+ # correct some value and try to give char level span
1019
+ match = False
1020
+ value = value.lower()
1021
+ if span and span[0] <= span[1]:
1022
+ # use original span annotation, but tokenizations are different
1023
+ start_word, end_word = span
1024
+ if end_word >= len(tokens):
1025
+ # due to different tokenization, sometimes will out of index
1026
+ delta = end_word - len(tokens) + 1
1027
+ start_word -= delta
1028
+ end_word -= delta
1029
+ start_char, end_char = token_spans[start_word][0], token_spans[end_word][1]
1030
+ value_span = utt[start_char:end_char].lower()
1031
+ match = True
1032
+ if value_span == value:
1033
+ cnt_domain_slot['span match'] += 1
1034
+ elif value.isdigit() and value in digit2word and digit2word[value] == value_span:
1035
+ # !!!CHANGE VALUE: value is digit but value span is word
1036
+ cnt_domain_slot['digit value match'] += 1
1037
+ elif ''.join(value.split()) == ''.join(value_span.split()):
1038
+ # !!!CHANGE VALUE: equal when remove blank
1039
+ cnt_domain_slot['remove blank'] += 1
1040
+ elif value in value_span:
1041
+ # value in value_span
1042
+ start_char += value_span.index(value)
1043
+ end_char = start_char + len(value)
1044
+ assert utt[start_char:end_char].lower() == value, f'{[value, utt[start_char:end_char], utt]}'
1045
+ cnt_domain_slot['value in span'] += 1
1046
+ elif ':' in value and value == '0' + value_span:
1047
+ # !!!CHANGE VALUE: time x:xx == 0x:xx
1048
+ cnt_domain_slot['x:xx == 0x:xx'] += 1
1049
+ else:
1050
+ # span mismatch, search near 1-2 words
1051
+ for window in range(1, 3):
1052
+ start = max(0, start_word - window)
1053
+ end = min(len(token_spans) - 1, end_word + window)
1054
+ large_span = utt[token_spans[start][0]:token_spans[end][1]].lower()
1055
+ if value in large_span:
1056
+ start_char = token_spans[start][0] + large_span.index(value)
1057
+ end_char = start_char + len(value)
1058
+ assert utt[
1059
+ start_char:end_char].lower() == value, f'{[value, utt[start_char:end_char], utt]}'
1060
+ cnt_domain_slot[f'window={window}'] += 1
1061
+ break
1062
+ else:
1063
+ # still not found
1064
+ match = False
1065
+
1066
+ if match:
1067
+ converted_da['non-categorical'][-1]['value'] = utt[start_char:end_char]
1068
+ converted_da['non-categorical'][-1]['start'] = start_char
1069
+ converted_da['non-categorical'][-1]['end'] = end_char
1070
+ cnt_domain_slot['have span'] += 1
1071
+ else:
1072
+ cnt_domain_slot['no span'] += 1
1073
+ return converted_da
1074
+
1075
+
1076
+ def preprocess():
1077
+ original_data_dir = 'MultiWOZ2_3'
1078
+ new_data_dir = 'data'
1079
+
1080
+ if not os.path.exists(original_data_dir):
1081
+ original_data_zip = 'MultiWOZ2_3.zip'
1082
+ if not os.path.exists(original_data_zip):
1083
+ raise FileNotFoundError(
1084
+ f'cannot find original data {original_data_zip} in multiwoz21/, should manually download MultiWOZ_2.1.zip from https://github.com/budzianowski/multiwoz/blob/master/data/MultiWOZ_2.1.zip')
1085
+ else:
1086
+ archive = ZipFile(original_data_zip)
1087
+ archive.extractall()
1088
+
1089
+ os.makedirs(new_data_dir, exist_ok=True)
1090
+ for filename in os.listdir(original_data_dir):
1091
+ if 'db' in filename:
1092
+ copy2(f'{original_data_dir}/{filename}', new_data_dir)
1093
+
1094
+ # Load core data
1095
+ with open(f'{original_data_dir}/data.json', 'r', encoding='utf-8') as f:
1096
+ original_data = json.load(f)
1097
+ global ontology, cnt_domain_slot
1098
+
1099
+ try:
1100
+ val_list = load_id_list(original_data_dir, "valListFile")
1101
+ test_list = load_id_list(original_data_dir, "testListFile")
1102
+ except FileNotFoundError:
1103
+ all_ids = list(original_data.keys())
1104
+ rng = random.Random(42)
1105
+ rng.shuffle(all_ids)
1106
+ n = len(all_ids)
1107
+ n_val = max(1, n // 10)
1108
+ n_test = max(1, n // 10)
1109
+ val_list = set(all_ids[:n_val])
1110
+ test_list = set(all_ids[n_val:n_val + n_test])
1111
+
1112
+ dataset = 'multiwoz23'
1113
+ splits = ['train', 'validation', 'test']
1114
+ dialogues_by_split = {split: [] for split in splits}
1115
+ sent_tokenizer = PunktSentenceTokenizer()
1116
+ word_tokenizer = TreebankWordTokenizer()
1117
+ booking_remapper = BookingActRemapper(ontology)
1118
+ for ori_dialog_id, ori_dialog in tqdm(original_data.items()):
1119
+ if ori_dialog_id in val_list:
1120
+ split = 'validation'
1121
+ elif ori_dialog_id in test_list:
1122
+ split = 'test'
1123
+ else:
1124
+ split = 'train'
1125
+ dialogue_id = f'{dataset}-{split}-{len(dialogues_by_split[split])}'
1126
+
1127
+ # get user goal and involved domains
1128
+ cur_domains = []
1129
+ goal = {
1130
+ 'description': '. '.join(ori_dialog['goal']['message']),
1131
+ 'inform': {},
1132
+ 'request': {}
1133
+ }
1134
+ for k, v in ori_dialog['goal'].items():
1135
+ if len(v) != 0 and k in ontology['domains']:
1136
+ cur_domains.append(k)
1137
+ goal['inform'][k] = {}
1138
+ goal['request'][k] = {}
1139
+ for attr in ['fail_info', 'info', 'fail_book', 'book']:
1140
+ if attr in v:
1141
+ for slot, value in v[attr].items():
1142
+ if 'invalid' in slot:
1143
+ continue
1144
+ domain, slot, value = normalize_domain_slot_value(k, slot, value)
1145
+ if slot in goal['inform'][domain]:
1146
+ goal['inform'][domain][slot] += '|' + value
1147
+ else:
1148
+ goal['inform'][domain][slot] = value
1149
+ if 'reqt' in v:
1150
+ for slot in v['reqt']:
1151
+ domain, slot, _ = normalize_domain_slot_value(k, slot, '')
1152
+ goal['request'][domain][slot] = ''
1153
+
1154
+ dialogue = {
1155
+ 'dataset': dataset,
1156
+ 'data_split': split,
1157
+ 'dialogue_id': dialogue_id,
1158
+ 'original_id': ori_dialog_id,
1159
+ 'domains': cur_domains, # will be updated by dialog_acts and state
1160
+ 'goal': goal,
1161
+ 'turns': []
1162
+ }
1163
+
1164
+ booking_remapper.reset()
1165
+ belief_domains = ['attraction', 'restaurant', 'train', 'hotel', 'taxi', 'hospital']
1166
+ entity_booked_dict = dict((domain, False) for domain in belief_domains)
1167
+ for turn_id, turn in enumerate(ori_dialog['log']):
1168
+ # correct some grammar errors in the text, mainly following `tokenization.md` in MultiWOZ_2.1
1169
+ text = turn['text']
1170
+ text = re.sub(" Im ", " I'm ", text)
1171
+ text = re.sub(" im ", " i'm ", text)
1172
+ text = re.sub(r"^Im ", "I'm ", text)
1173
+ text = re.sub(r"^im ", "i'm ", text)
1174
+ text = re.sub("theres", "there's", text)
1175
+ text = re.sub("dont", "don't", text)
1176
+ text = re.sub("whats", "what's", text)
1177
+ text = re.sub('thats', "that's", text)
1178
+ utt = text
1179
+ speaker = 'user' if turn_id % 2 == 0 else 'system'
1180
+
1181
+ das = turn.get('dialog_act', [])
1182
+ spans = turn.get('span_info', [])
1183
+
1184
+ if speaker == 'system':
1185
+ das, spans = booking_remapper.remap(turn_id, ori_dialog['log'])
1186
+
1187
+ da_dict = {}
1188
+ # transform DA (robust to raw 'Booking-*' that slipped through)
1189
+ for Domain_Intent in das:
1190
+ domain, intent = Domain_Intent.lower().split('-')
1191
+ assert intent in ontology['intents'], f'{ori_dialog_id}:{turn_id}:da\t{intent} not in ontology'
1192
+ for Slot, value in das[Domain_Intent]:
1193
+ if domain == 'booking':
1194
+ # infer the correct concrete domain from the slot/value, then validate
1195
+ dom_, slot_, val_ = infer_booking_target_domain(Slot, value, cur_domains)
1196
+ target_domain = dom_
1197
+ else:
1198
+ dom_, slot_, val_ = normalize_domain_slot_value(domain, Slot, value)
1199
+ target_domain = dom_
1200
+
1201
+ if target_domain not in cur_domains:
1202
+ cur_domains.append(target_domain)
1203
+
1204
+ da_dict[(intent, target_domain, slot_, val_,)] = []
1205
+
1206
+ # transform SPANs (also robust to 'Booking-*' and backfills missing DAs)
1207
+ for span in spans:
1208
+ Domain_Intent, Slot, value, start_word, end_word = span
1209
+ domain, intent = Domain_Intent.lower().split('-')
1210
+
1211
+ if domain == 'booking':
1212
+ dom_, slot_, val_ = infer_booking_target_domain(Slot, value, cur_domains)
1213
+ else:
1214
+ dom_, slot_, val_ = normalize_domain_slot_value(domain, Slot, value)
1215
+
1216
+ # ensure target domain is tracked
1217
+ if dom_ not in cur_domains:
1218
+ cur_domains.append(dom_)
1219
+
1220
+ key = (intent, dom_, slot_, val_)
1221
+ # If the DA loop didn’t produce this entry (annotation mismatch/legacy alias), backfill it.
1222
+ if key not in da_dict:
1223
+ da_dict[key] = [] # no word-span yet; we’re about to set it
1224
+
1225
+ da_dict[key] = [start_word, end_word]
1226
+
1227
+ dialogue_acts = convert_da(da_dict, utt, sent_tokenizer, word_tokenizer)
1228
+
1229
+ # reverse_das = reverse_da(dialogue_acts)
1230
+ # das_list = sorted([(Domain_Intent, Slot, ''.join(value.split()).lower()) for Domain_Intent in das for Slot, value in das[Domain_Intent]])
1231
+ # reverse_das_list = sorted([(Domain_Intent, Slot, ''.join(value.split()).lower()) for Domain_Intent in reverse_das for Slot, value in reverse_das[Domain_Intent]])
1232
+ # if das_list != reverse_das_list:
1233
+ # print(das_list)
1234
+ # print(reverse_das_list)
1235
+ # print()
1236
+ # print()
1237
+
1238
+ dialogue['turns'].append({
1239
+ 'speaker': speaker,
1240
+ 'utterance': utt,
1241
+ 'utt_idx': turn_id,
1242
+ 'dialogue_acts': dialogue_acts,
1243
+ })
1244
+
1245
+ # add to dialogue_acts dictionary in the ontology
1246
+ for da_type in dialogue_acts:
1247
+ das = dialogue_acts[da_type]
1248
+ for da in das:
1249
+ ontology["dialogue_acts"][da_type].setdefault((da['intent'], da['domain'], da['slot']), {})
1250
+ ontology["dialogue_acts"][da_type][(da['intent'], da['domain'], da['slot'])][speaker] = True
1251
+
1252
+ if speaker == 'system':
1253
+ # add state to last user turn
1254
+ # add empty db_results
1255
+ turn_state = turn['metadata']
1256
+ cur_state = copy.deepcopy(ontology['state'])
1257
+ booked = {}
1258
+ for domain in turn_state:
1259
+ if domain not in cur_state:
1260
+ continue
1261
+ for subdomain in ['semi', 'book']:
1262
+ for slot, value in turn_state[domain][subdomain].items():
1263
+ if slot == 'ticket':
1264
+ continue
1265
+ elif slot == 'booked':
1266
+ assert domain in ontology['domains']
1267
+ booked[domain] = value
1268
+ continue
1269
+ _, slot, value = normalize_domain_slot_value(domain, slot, value)
1270
+ cur_state[domain][slot] = value
1271
+ dialogue['turns'][-2]['state'] = cur_state
1272
+ entity_booked_dict, booked = fix_entity_booked_info(entity_booked_dict, booked)
1273
+ dialogue['turns'][-1]['booked'] = booked
1274
+ dialogues_by_split[split].append(dialogue)
1275
+ # pprint(cnt_domain_slot.most_common())
1276
+ dialogues = []
1277
+ for split in splits:
1278
+ dialogues += dialogues_by_split[split]
1279
+ for da_type in ontology['dialogue_acts']:
1280
+ ontology["dialogue_acts"][da_type] = sorted([str(
1281
+ {'user': speakers.get('user', False), 'system': speakers.get('system', False), 'intent': da[0],
1282
+ 'domain': da[1], 'slot': da[2]}) for da, speakers in ontology["dialogue_acts"][da_type].items()])
1283
+ json.dump(dialogues[:10], open(f'dummy_data.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
1284
+ json.dump(ontology, open(f'{new_data_dir}/ontology.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
1285
+ json.dump(dialogues, open(f'{new_data_dir}/dialogues.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
1286
+ with ZipFile('data.zip', 'w', ZIP_DEFLATED) as zf:
1287
+ for filename in os.listdir(new_data_dir):
1288
+ zf.write(f'{new_data_dir}/{filename}')
1289
+ rmtree(original_data_dir)
1290
+ rmtree(new_data_dir)
1291
+ return dialogues, ontology
1292
+
1293
+
1294
+ def fix_entity_booked_info(entity_booked_dict, booked):
1295
+ for domain in entity_booked_dict:
1296
+ if not entity_booked_dict[domain] and booked[domain]:
1297
+ entity_booked_dict[domain] = True
1298
+ booked[domain] = []
1299
+ return entity_booked_dict, booked
1300
+
1301
+
1302
+ if __name__ == '__main__':
1303
+ preprocess()
shuffled_dial_ids.json ADDED
The diff for this file is too large to render. See raw diff