Datasets:

Languages:
English
ArXiv:
License:
zhuqi commited on
Commit
9b483a3
1 Parent(s): f79e049

Upload preprocess.py

Browse files
Files changed (1) hide show
  1. preprocess.py +413 -0
preprocess.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from zipfile import ZipFile, ZIP_DEFLATED
2
+ import json
3
+ import os
4
+ import copy
5
+ import zipfile
6
+ from tqdm import tqdm
7
+ import re
8
+ from collections import Counter
9
+ from shutil import rmtree
10
+ from convlab.util.file_util import read_zipped_json, write_zipped_json
11
+ from pprint import pprint
12
+ import random
13
+
14
+
15
+ descriptions = {
16
+ "flights": {
17
+ "flights": "find a round trip or multi-city flights",
18
+ "type": "type of the flight",
19
+ "destination1": "the first destination city of the trip",
20
+ "destination2": "the second destination city of the trip",
21
+ "origin": "the origin city of the trip",
22
+ "date.depart_origin": "date of departure from origin",
23
+ "date.depart_intermediate": "date of departure from intermediate",
24
+ "date.return": "date of return",
25
+ "time_of_day": "time of the flight",
26
+ "seating_class": "seat type (first class, business class, economy class, etc.",
27
+ "seat_location": "location of the seat",
28
+ "stops": "non-stop, layovers, etc.",
29
+ "price_range": "price range of the flight",
30
+ "num.pax": "number of people",
31
+ "luggage": "luggage information",
32
+ "total_fare": "total cost of the trip",
33
+ "other_description": "other description of the flight",
34
+ "from": "departure of the flight",
35
+ "to": "destination of the flight",
36
+ "airline": "airline of the flight",
37
+ "flight_number": "the number of the flight",
38
+ "date": "date of the flight",
39
+ "from.time": "departure time of the flight",
40
+ "to.time": "arrival time of the flight",
41
+ "stops.location": "location of the stop",
42
+ "fare": "cost of the flight",
43
+ },
44
+ "food-ordering": {
45
+ "food-ordering": "order take-out for a particular cuisine choice",
46
+ "name.item": "name of the item",
47
+ "other_description.item": "other description of the item",
48
+ "type.retrieval": "type of the retrieval method",
49
+ "total_price": "total price",
50
+ "time.pickup": "pick up time",
51
+ "num.people": "number of people",
52
+ "name.restaurant": "name of the restaurant",
53
+ "type.food": "type of food",
54
+ "type.meal": "type of meal",
55
+ "location.restaurant": "location of the restaurant",
56
+ "rating.restaurant": "rating of the restaurant",
57
+ "price_range": "price range of the food",
58
+ },
59
+ "hotels": {
60
+ "hotels": "find a hotel using typical preferences",
61
+ "name.hotel": "name of the hotel",
62
+ "location.hotel": "location of the hotel",
63
+ "sub_location.hotel": "rough location of the hotel",
64
+ "star_rating": "star rating of the hotel",
65
+ "customer_rating": "customer rating of the hotel",
66
+ "customer_review": "customer review of the hotel",
67
+ "price_range": "price range of the hotel",
68
+ "amenity": "amenity of the hotel",
69
+ "num.beds": "number of beds to book",
70
+ "type.bed": "type of the bed",
71
+ "num.rooms": "number of rooms to book",
72
+ "check-in_date": "check-in date",
73
+ "check-out_date": "check-out date",
74
+ "date_range": "date range of the reservation",
75
+ "num.guests": "number of guests",
76
+ "type.room": "type of the room",
77
+ "price_per_night": "price per night",
78
+ "total_fare": "total fare",
79
+ "location": "location of the hotel",
80
+ "other_request": "other request",
81
+ "other_detail": "other detail",
82
+ },
83
+ "movies": {
84
+ "movies": "find a movie to watch in theaters or using a streaming service at home",
85
+ "name.movie": "name of the movie",
86
+ "genre": "genre of the movie",
87
+ "name.theater": "name of the theater",
88
+ "location.theater": "location of the theater",
89
+ "time.start": "start time of the movie",
90
+ "time.end": "end time of the movie",
91
+ "price.ticket": "price of the ticket",
92
+ "price.streaming": "price of the streaming",
93
+ "type.screening": "type of the screening",
94
+ "audience_rating": "audience rating",
95
+ "critic_rating": "critic rating",
96
+ "movie_rating": "film rating",
97
+ "release_date": "release date of the movie",
98
+ "runtime": "running time of the movie",
99
+ "real_person": "name of actors, directors, etc.",
100
+ "character": "name of character in the movie",
101
+ "streaming_service": "streaming service that provide the movie",
102
+ "num.tickets": "number of tickets",
103
+ "seating": "type of seating",
104
+ "other_description": "other description about the movie",
105
+ "synopsis": "synopsis of the movie",
106
+ },
107
+ "music": {
108
+ "music": "find several tracks to play and then comment on each one",
109
+ "name.track": "name of the track",
110
+ "name.artist": "name of the artist",
111
+ "name.album": "name of the album",
112
+ "name.genre": "music genre",
113
+ "type.music": "rough type of the music",
114
+ "describes_track": "description of a track to find",
115
+ "describes_artist": "description of a artist to find",
116
+ "describes_album": "description of an album to find",
117
+ "describes_genre": "description of a genre to find",
118
+ "describes_type.music": "description of the music type",
119
+ "technical_difficulty": "there is a technical difficulty",
120
+ },
121
+ "restaurant-search": {
122
+ "restaurant-search": "ask for recommendations for a particular type of cuisine",
123
+ "name.restaurant": "name of the restaurant",
124
+ "location": "location of the restaurant",
125
+ "sub-location": "rough location of the restaurant",
126
+ "type.food": "the cuisine of the restaurant",
127
+ "menu_item": "item in the menu",
128
+ "type.meal": "type of meal",
129
+ "rating": "rating of the restaurant",
130
+ "price_range": "price range of the restaurant",
131
+ "business_hours": "business hours of the restaurant",
132
+ "name.reservation": "name of the person who make the reservation",
133
+ "num.guests": "number of guests",
134
+ "time.reservation": "time of the reservation",
135
+ "date.reservation": "date of the reservation",
136
+ "type.seating": "type of the seating",
137
+ "other_description": "other description of the restaurant",
138
+ "phone": "phone number of the restaurant",
139
+ },
140
+ "sports": {
141
+ "sports": "discuss facts and stats about players, teams, games, etc. in EPL, MLB, MLS, NBA, NFL",
142
+ "name.team": "name of the team",
143
+ "record.team": "record of the team (number of wins and losses)",
144
+ "record.games_ahead": "number of games ahead",
145
+ "record.games_back": "number of games behind",
146
+ "place.team": "ranking of the team",
147
+ "result.match": "result of the match",
148
+ "score.match": "score of the match",
149
+ "date.match": "date of the match",
150
+ "day.match": "day of the match",
151
+ "time.match": "time of the match",
152
+ "name.player": "name of the player",
153
+ "position.player": "position of the player",
154
+ "record.player": "record of the player",
155
+ "name.non_player": "name of non-palyer such as the manager, coach",
156
+ "venue": "venue of the match take place",
157
+ "other_description.person": "other description of the person",
158
+ "other_description.team": "other description of the team",
159
+ "other_description.match": "other description of the match",
160
+ }
161
+ }
162
+
163
+ anno2slot = {
164
+ "flights": {
165
+ "date.depart": "date.depart_origin", # rename
166
+ "date.intermediate": "date.depart_intermediate", # rename
167
+ "flight_booked": False, # transform to binary dialog act
168
+ },
169
+ "food-ordering": {
170
+ "name.person": None, # no sample, ignore
171
+ "phone.restaurant": None, # no sample, ignore
172
+ "business_hours.restaurant": None, # no sample, ignore
173
+ "official_description.restaurant": None, # 1 sample, ignore
174
+ },
175
+ "hotels": {
176
+ "hotel_booked": False, # transform to binary dialog act
177
+ },
178
+ "movies": {
179
+ "time.end.": "time.end", # rename
180
+ "seating ticket_booking": "seating", # mixed in the original ontology
181
+ "ticket_booking": False, # transform to binary dialog act
182
+ "synopsis": False, # too long, 54 words in avg. transform to binary dialog act
183
+ },
184
+ "music": {},
185
+ "restaurant-search": {
186
+ "offical_description": False, # too long, 15 words in avg. transform to binary dialog act
187
+ },
188
+ "sports": {}
189
+ }
190
+
191
+
192
+ def format_turns(ori_turns):
193
+ # delete invalid turns and merge continuous turns
194
+ new_turns = []
195
+ previous_speaker = None
196
+ utt_idx = 0
197
+ for i, turn in enumerate(ori_turns):
198
+ speaker = 'system' if turn['speaker'] == 'ASSISTANT' else 'user'
199
+ turn['speaker'] = speaker
200
+ if turn['text'] == '(deleted)':
201
+ continue
202
+ if not previous_speaker:
203
+ # first turn
204
+ assert speaker != previous_speaker
205
+ if speaker != previous_speaker:
206
+ # switch speaker
207
+ previous_speaker = speaker
208
+ new_turns.append(copy.deepcopy(turn))
209
+ utt_idx += 1
210
+ else:
211
+ # continuous speaking of the same speaker
212
+ last_turn = new_turns[-1]
213
+ # skip repeated turn
214
+ if turn['text'] in ori_turns[i-1]['text']:
215
+ continue
216
+ # merge continuous turns
217
+ index_shift = len(last_turn['text']) + 1
218
+ last_turn['text'] += ' '+turn['text']
219
+ if 'segments' in turn:
220
+ last_turn.setdefault('segments', [])
221
+ for segment in turn['segments']:
222
+ segment['start_index'] += index_shift
223
+ segment['end_index'] += index_shift
224
+ last_turn['segments'] += turn['segments']
225
+ return new_turns
226
+
227
+
228
+ def preprocess():
229
+ original_data_dir = 'Taskmaster-master'
230
+ new_data_dir = 'data'
231
+
232
+ if not os.path.exists(original_data_dir):
233
+ original_data_zip = 'master.zip'
234
+ if not os.path.exists(original_data_zip):
235
+ raise FileNotFoundError(f'cannot find original data {original_data_zip} in tm2/, should manually download master.zip from https://github.com/google-research-datasets/Taskmaster/archive/refs/heads/master.zip')
236
+ else:
237
+ archive = ZipFile(original_data_zip)
238
+ archive.extractall()
239
+
240
+ os.makedirs(new_data_dir, exist_ok=True)
241
+
242
+ ontology = {'domains': {},
243
+ 'intents': {
244
+ 'inform': {'description': 'inform the value of a slot or general information.'}
245
+ },
246
+ 'state': {},
247
+ 'dialogue_acts': {
248
+ "categorical": {},
249
+ "non-categorical": {},
250
+ "binary": {}
251
+ }}
252
+ global descriptions
253
+ global anno2slot
254
+ domains = ['flights', 'food-ordering', 'hotels', 'movies', 'music', 'restaurant-search', 'sports']
255
+ for domain in domains:
256
+ domain_ontology = json.load(open(os.path.join(original_data_dir, f"TM-2-2020/ontology/{domain}.json")))
257
+ assert len(domain_ontology) == 1
258
+ ontology['domains'][domain] = {'description': descriptions[domain][domain], 'slots': {}}
259
+ ontology['state'][domain] = {}
260
+ for item in list(domain_ontology.values())[0]:
261
+ for anno in item['annotations']:
262
+ slot = anno.strip()
263
+ if slot in anno2slot[domain]:
264
+ if anno2slot[domain][slot] in [None, False]:
265
+ continue
266
+ else:
267
+ slot = anno2slot[domain][slot]
268
+ ontology['domains'][domain]['slots'][slot] = {
269
+ 'description': descriptions[domain][slot],
270
+ 'is_categorical': False,
271
+ 'possible_values': [],
272
+ }
273
+ ontology['state'][domain][slot] = ''
274
+ # add missing slots to the ontology
275
+ for domain, slot in [('movies', 'price.streaming'), ('restaurant-search', 'phone')]:
276
+ ontology['domains'][domain]['slots'][slot] = {
277
+ 'description': descriptions[domain][slot],
278
+ 'is_categorical': False,
279
+ 'possible_values': [],
280
+ }
281
+ ontology['state'][domain][slot] = ''
282
+
283
+ dataset = 'tm2'
284
+ splits = ['train', 'validation', 'test']
285
+ dialogues_by_split = {split:[] for split in splits}
286
+ for domain in domains:
287
+ data = json.load(open(os.path.join(original_data_dir, f"TM-2-2020/data/{domain}.json")))
288
+ # random split, train:validation:test = 8:1:1
289
+ random.seed(42)
290
+ dial_ids = list(range(len(data)))
291
+ random.shuffle(dial_ids)
292
+ dial_id2split = {}
293
+ for dial_id in dial_ids[:int(0.8*len(dial_ids))]:
294
+ dial_id2split[dial_id] = 'train'
295
+ for dial_id in dial_ids[int(0.8*len(dial_ids)):int(0.9*len(dial_ids))]:
296
+ dial_id2split[dial_id] = 'validation'
297
+ for dial_id in dial_ids[int(0.9*len(dial_ids)):]:
298
+ dial_id2split[dial_id] = 'test'
299
+
300
+ for dial_id, d in tqdm(enumerate(data), desc='processing taskmaster-{}'.format(domain)):
301
+ # delete empty dialogs and invalid dialogs
302
+ if len(d['utterances']) == 0:
303
+ continue
304
+ if len(set([t['speaker'] for t in d['utterances']])) == 1:
305
+ continue
306
+ data_split = dial_id2split[dial_id]
307
+ dialogue_id = f'{dataset}-{data_split}-{len(dialogues_by_split[data_split])}'
308
+ cur_domains = [domain]
309
+ dialogue = {
310
+ 'dataset': dataset,
311
+ 'data_split': data_split,
312
+ 'dialogue_id': dialogue_id,
313
+ 'original_id': d["conversation_id"],
314
+ 'domains': cur_domains,
315
+ 'turns': []
316
+ }
317
+ turns = format_turns(d['utterances'])
318
+ prev_state = {}
319
+ prev_state.setdefault(domain, copy.deepcopy(ontology['state'][domain]))
320
+
321
+ for utt_idx, uttr in enumerate(turns):
322
+ speaker = uttr['speaker']
323
+ turn = {
324
+ 'speaker': speaker,
325
+ 'utterance': uttr['text'],
326
+ 'utt_idx': utt_idx,
327
+ 'dialogue_acts': {
328
+ 'binary': [],
329
+ 'categorical': [],
330
+ 'non-categorical': [],
331
+ },
332
+ }
333
+ in_span = [0] * len(turn['utterance'])
334
+
335
+ if 'segments' in uttr:
336
+ # sort the span according to the length
337
+ segments = sorted(uttr['segments'], key=lambda x: len(x['text']))
338
+ for segment in segments:
339
+ # Each conversation was annotated by two workers.
340
+ # only keep the first annotation for the span
341
+ item = segment['annotations'][0]
342
+ intent = 'inform' # default intent
343
+ slot = item['name'].split('.', 1)[-1].strip()
344
+ if slot in anno2slot[domain]:
345
+ if anno2slot[domain][slot] is None:
346
+ # skip
347
+ continue
348
+ elif anno2slot[domain][slot] is False:
349
+ # binary dialog act
350
+ turn['dialogue_acts']['binary'].append({
351
+ 'intent': intent,
352
+ 'domain': domain,
353
+ 'slot': slot,
354
+ })
355
+ continue
356
+ else:
357
+ slot = anno2slot[domain][slot]
358
+ assert slot in ontology['domains'][domain]['slots'], print(domain, [slot])
359
+ assert turn['utterance'][segment['start_index']:segment['end_index']] == segment['text']
360
+ # skip overlapped spans, keep the shortest one
361
+ if sum(in_span[segment['start_index']: segment['end_index']]) > 0:
362
+ continue
363
+ else:
364
+ in_span[segment['start_index']: segment['end_index']] = [1]*(segment['end_index']-segment['start_index'])
365
+ turn['dialogue_acts']['non-categorical'].append({
366
+ 'intent': intent,
367
+ 'domain': domain,
368
+ 'slot': slot,
369
+ 'value': segment['text'],
370
+ 'start': segment['start_index'],
371
+ 'end': segment['end_index']
372
+ })
373
+
374
+ turn['dialogue_acts']['non-categorical'] = sorted(turn['dialogue_acts']['non-categorical'], key=lambda x: x['start'])
375
+
376
+ bdas = set()
377
+ for da in turn['dialogue_acts']['binary']:
378
+ da_tuple = (da['intent'], da['domain'], da['slot'],)
379
+ bdas.add(da_tuple)
380
+ turn['dialogue_acts']['binary'] = [{'intent':bda[0],'domain':bda[1],'slot':bda[2]} for bda in sorted(bdas)]
381
+ # add to dialogue_acts dictionary in the ontology
382
+ for da_type in turn['dialogue_acts']:
383
+ das = turn['dialogue_acts'][da_type]
384
+ for da in das:
385
+ ontology["dialogue_acts"][da_type].setdefault((da['intent'], da['domain'], da['slot']), {})
386
+ ontology["dialogue_acts"][da_type][(da['intent'], da['domain'], da['slot'])][speaker] = True
387
+
388
+ for da in turn['dialogue_acts']['non-categorical']:
389
+ slot, value = da['slot'], da['value']
390
+ assert slot in prev_state[domain]
391
+ prev_state[domain][slot] = value
392
+
393
+ if speaker == 'user':
394
+ turn['state'] = copy.deepcopy(prev_state)
395
+
396
+ dialogue['turns'].append(turn)
397
+ dialogues_by_split[data_split].append(dialogue)
398
+
399
+ for da_type in ontology['dialogue_acts']:
400
+ ontology["dialogue_acts"][da_type] = sorted([str({'user': speakers.get('user', False), 'system': speakers.get('system', False), 'intent':da[0],'domain':da[1], 'slot':da[2]}) for da, speakers in ontology["dialogue_acts"][da_type].items()])
401
+ dialogues = dialogues_by_split['train']+dialogues_by_split['validation']+dialogues_by_split['test']
402
+ json.dump(dialogues[:10], open(f'dummy_data.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
403
+ json.dump(ontology, open(f'{new_data_dir}/ontology.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
404
+ json.dump(dialogues, open(f'{new_data_dir}/dialogues.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
405
+ with ZipFile('data.zip', 'w', ZIP_DEFLATED) as zf:
406
+ for filename in os.listdir(new_data_dir):
407
+ zf.write(f'{new_data_dir}/{filename}')
408
+ rmtree(original_data_dir)
409
+ rmtree(new_data_dir)
410
+ return dialogues, ontology
411
+
412
+ if __name__ == '__main__':
413
+ preprocess()