zhuqi commited on
Commit
fe4afad
1 Parent(s): 3873f0e

Upload preprocess.py

Browse files
Files changed (1) hide show
  1. preprocess.py +262 -0
preprocess.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import glob
14
+
15
+
16
+ descriptions = {
17
+ 'movie': 'Book movie tickets for the user',
18
+ 'name.movie': 'Name of the movie, e.g. Joker, Parasite, The Avengers',
19
+ 'name.theater': 'Name of the theater, e.g. Century City, AMC Mercado 20',
20
+ 'num.tickets': 'Number of tickets, e.g. two, me and my friend, John and I',
21
+ 'time.preference': 'Preferred time or range, e.g. around 2pm, later in the evening, 4:30pm',
22
+ 'time.showing': 'The showtimes published by the theater, e.g. 5:10pm, 8:30pm',
23
+ 'date.showing': 'the date or day of the showing, e.g. today, tonight, tomrrow, April 12th.',
24
+ 'location': 'The city, or city and state, zip code and sometimes more specific regions, e.g. downtown',
25
+ 'type.screening': 'IMAX, Dolby, 3D, standard, or similar phrases for technology offerings',
26
+ 'seating': 'Various phrases from specific "row 1" to "near the back", "on an aisle", etc.',
27
+ 'date.release': 'Movie attribute published for the official movie release date.',
28
+ 'price.ticket': 'Price per ticket',
29
+ 'price.total': 'The total for the purchase of all tickets',
30
+ 'name.genre': 'Includes a wide range from classic genres like action, drama, etc. to categories like "slasher" or series like Marvel or Harry Potter',
31
+ 'description.plot': 'The movie synopsis or shorter description',
32
+ 'description.other': 'Any other movie description that is not captured by genre, name, plot.',
33
+ 'duration.movie': 'The movie runtime, e.g. 120 minutes',
34
+ 'name.person': 'Names of actors, directors, producers but NOT movie characters',
35
+ 'name.character': 'Character names like James Bond, Harry Potter, Wonder Woman',
36
+ 'review.audience': 'The audience review',
37
+ 'review.critic': 'Critic reviews like those from Rotten Tomatoes, IMDB, etc.',
38
+ 'rating.movie': 'G, PG, PG-13, R, etc.',
39
+ }
40
+
41
+ anno2slot = {
42
+ "movie": {
43
+ "description.other": False, # transform to binary dialog act
44
+ "description.plot": False, # too long, 19 words in avg. transform to binary dialog act
45
+ }
46
+ }
47
+
48
+
49
+ def format_turns(ori_turns):
50
+ # delete invalid turns and merge continuous turns
51
+ new_turns = []
52
+ previous_speaker = None
53
+ utt_idx = 0
54
+ for i, turn in enumerate(ori_turns):
55
+ speaker = 'system' if turn['speaker'].upper() == 'ASSISTANT' else 'user'
56
+ turn['speaker'] = speaker
57
+ if turn['text'] == '(deleted)':
58
+ continue
59
+ if not previous_speaker:
60
+ # first turn
61
+ assert speaker != previous_speaker
62
+ if speaker != previous_speaker:
63
+ # switch speaker
64
+ previous_speaker = speaker
65
+ new_turns.append(copy.deepcopy(turn))
66
+ utt_idx += 1
67
+ else:
68
+ # continuous speaking of the same speaker
69
+ last_turn = new_turns[-1]
70
+ # skip repeated turn
71
+ if turn['text'] in ori_turns[i-1]['text']:
72
+ continue
73
+ # merge continuous turns
74
+ index_shift = len(last_turn['text']) + 1
75
+ last_turn['text'] += ' '+turn['text']
76
+ if 'segments' in turn:
77
+ last_turn.setdefault('segments', [])
78
+ for segment in turn['segments']:
79
+ segment['start_index'] += index_shift
80
+ segment['end_index'] += index_shift
81
+ last_turn['segments'] += turn['segments']
82
+ return new_turns
83
+
84
+
85
+ def preprocess():
86
+ original_data_dir = 'Taskmaster-master'
87
+ new_data_dir = 'data'
88
+
89
+ if not os.path.exists(original_data_dir):
90
+ original_data_zip = 'master.zip'
91
+ if not os.path.exists(original_data_zip):
92
+ raise FileNotFoundError(f'cannot find original data {original_data_zip} in tm3/, should manually download master.zip from https://github.com/google-research-datasets/Taskmaster/archive/refs/heads/master.zip')
93
+ else:
94
+ archive = ZipFile(original_data_zip)
95
+ archive.extractall()
96
+
97
+ os.makedirs(new_data_dir, exist_ok=True)
98
+
99
+ ontology = {'domains': {},
100
+ 'intents': {
101
+ 'inform': {'description': 'inform the value of a slot or general information.'}
102
+ },
103
+ 'state': {},
104
+ 'dialogue_acts': {
105
+ "categorical": {},
106
+ "non-categorical": {},
107
+ "binary": {}
108
+ }}
109
+ global descriptions
110
+ global anno2slot
111
+ ori_ontology = json.load(open(os.path.join(original_data_dir, "TM-3-2020/ontology/entities.json")))
112
+ assert len(ori_ontology) == 1
113
+ domain = list(ori_ontology.keys())[0]
114
+ domain_ontology = ori_ontology[domain]
115
+ ontology['domains'][domain] = {'description': descriptions[domain], 'slots': {}}
116
+ ontology['state'][domain] = {}
117
+ for slot in domain_ontology['required']+domain_ontology['optional']:
118
+ ontology['domains'][domain]['slots'][slot] = {
119
+ 'description': descriptions[slot],
120
+ 'is_categorical': False,
121
+ 'possible_values': [],
122
+ }
123
+ if slot not in anno2slot[domain]:
124
+ ontology['state'][domain][slot] = ''
125
+
126
+ dataset = 'tm3'
127
+ splits = ['train', 'validation', 'test']
128
+ dialogues_by_split = {split:[] for split in splits}
129
+ data_files = sorted(glob.glob(os.path.join(original_data_dir, f"TM-3-2020/data/*.json")))
130
+ for data_file in tqdm(data_files, desc='processing taskmaster-{}'.format(domain)):
131
+ data = json.load(open(data_file))
132
+ # random split, train:validation:test = 8:1:1
133
+ random.seed(42)
134
+ dial_ids = list(range(len(data)))
135
+ random.shuffle(dial_ids)
136
+ dial_id2split = {}
137
+ for dial_id in dial_ids[:int(0.8*len(dial_ids))]:
138
+ dial_id2split[dial_id] = 'train'
139
+ for dial_id in dial_ids[int(0.8*len(dial_ids)):int(0.9*len(dial_ids))]:
140
+ dial_id2split[dial_id] = 'validation'
141
+ for dial_id in dial_ids[int(0.9*len(dial_ids)):]:
142
+ dial_id2split[dial_id] = 'test'
143
+
144
+ for dial_id, d in enumerate(data):
145
+ # delete empty dialogs and invalid dialogs
146
+ if len(d['utterances']) == 0:
147
+ continue
148
+ if len(set([t['speaker'] for t in d['utterances']])) == 1:
149
+ continue
150
+ data_split = dial_id2split[dial_id]
151
+ dialogue_id = f'{dataset}-{data_split}-{len(dialogues_by_split[data_split])}'
152
+ cur_domains = [domain]
153
+ goal = {
154
+ 'description': d['instructions'],
155
+ 'inform': {},
156
+ 'request': {}
157
+ }
158
+ dialogue = {
159
+ 'dataset': dataset,
160
+ 'data_split': data_split,
161
+ 'dialogue_id': dialogue_id,
162
+ 'original_id': d["conversation_id"],
163
+ 'domains': cur_domains,
164
+ 'goal': goal,
165
+ 'turns': []
166
+ }
167
+ turns = format_turns(d['utterances'])
168
+ prev_state = {}
169
+ prev_state.setdefault(domain, copy.deepcopy(ontology['state'][domain]))
170
+
171
+ for utt_idx, uttr in enumerate(turns):
172
+ speaker = uttr['speaker']
173
+ turn = {
174
+ 'speaker': speaker,
175
+ 'utterance': uttr['text'],
176
+ 'utt_idx': utt_idx,
177
+ 'dialogue_acts': {
178
+ 'binary': [],
179
+ 'categorical': [],
180
+ 'non-categorical': [],
181
+ },
182
+ }
183
+ in_span = [0] * len(turn['utterance'])
184
+
185
+ if 'segments' in uttr:
186
+ # sort the span according to the length
187
+ segments = sorted(uttr['segments'], key=lambda x: len(x['text']))
188
+ for segment in segments:
189
+ assert len(['annotations']) == 1
190
+ item = segment['annotations'][0]
191
+ intent = 'inform' # default intent
192
+ slot = item['name'].strip()
193
+ assert slot in ontology['domains'][domain]['slots']
194
+ if slot in anno2slot[domain]:
195
+ # binary dialog act
196
+ turn['dialogue_acts']['binary'].append({
197
+ 'intent': intent,
198
+ 'domain': domain,
199
+ 'slot': slot,
200
+ })
201
+ continue
202
+ assert turn['utterance'][segment['start_index']:segment['end_index']] == segment['text']
203
+ # skip overlapped spans, keep the shortest one
204
+ if sum(in_span[segment['start_index']: segment['end_index']]) > 0:
205
+ continue
206
+ else:
207
+ in_span[segment['start_index']: segment['end_index']] = [1]*(segment['end_index']-segment['start_index'])
208
+ turn['dialogue_acts']['non-categorical'].append({
209
+ 'intent': intent,
210
+ 'domain': domain,
211
+ 'slot': slot,
212
+ 'value': segment['text'],
213
+ 'start': segment['start_index'],
214
+ 'end': segment['end_index']
215
+ })
216
+
217
+ turn['dialogue_acts']['non-categorical'] = sorted(turn['dialogue_acts']['non-categorical'], key=lambda x: x['start'])
218
+
219
+ bdas = set()
220
+ for da in turn['dialogue_acts']['binary']:
221
+ da_tuple = (da['intent'], da['domain'], da['slot'],)
222
+ bdas.add(da_tuple)
223
+ turn['dialogue_acts']['binary'] = [{'intent':bda[0],'domain':bda[1],'slot':bda[2]} for bda in sorted(bdas)]
224
+ # add to dialogue_acts dictionary in the ontology
225
+ for da_type in turn['dialogue_acts']:
226
+ das = turn['dialogue_acts'][da_type]
227
+ for da in das:
228
+ ontology["dialogue_acts"][da_type].setdefault((da['intent'], da['domain'], da['slot']), {})
229
+ ontology["dialogue_acts"][da_type][(da['intent'], da['domain'], da['slot'])][speaker] = True
230
+
231
+ for da in turn['dialogue_acts']['non-categorical']:
232
+ slot, value = da['slot'], da['value']
233
+ assert slot in prev_state[domain], print(da)
234
+ prev_state[domain][slot] = value
235
+
236
+ if speaker == 'user':
237
+ turn['state'] = copy.deepcopy(prev_state)
238
+ else:
239
+ turn['db_results'] = {}
240
+ if 'apis' in turns[utt_idx-1]:
241
+ turn['db_results'].setdefault(domain, [])
242
+ apis = turns[utt_idx-1]['apis']
243
+ turn['db_results'][domain] += apis
244
+
245
+ dialogue['turns'].append(turn)
246
+ dialogues_by_split[data_split].append(dialogue)
247
+
248
+ for da_type in ontology['dialogue_acts']:
249
+ 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()])
250
+ dialogues = dialogues_by_split['train']+dialogues_by_split['validation']+dialogues_by_split['test']
251
+ json.dump(dialogues[:10], open(f'dummy_data.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
252
+ json.dump(ontology, open(f'{new_data_dir}/ontology.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
253
+ json.dump(dialogues, open(f'{new_data_dir}/dialogues.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
254
+ with ZipFile('data.zip', 'w', ZIP_DEFLATED) as zf:
255
+ for filename in os.listdir(new_data_dir):
256
+ zf.write(f'{new_data_dir}/{filename}')
257
+ rmtree(original_data_dir)
258
+ rmtree(new_data_dir)
259
+ return dialogues, ontology
260
+
261
+ if __name__ == '__main__':
262
+ preprocess()