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File, ZIP_DEFLATED
4
+ from shutil import copy2, rmtree
5
+ import json
6
+ import os
7
+ from tqdm import tqdm
8
+ from collections import Counter
9
+ from pprint import pprint
10
+ from nltk.tokenize import TreebankWordTokenizer, PunktSentenceTokenizer
11
+ from data.unified_datasets.multiwoz21.booking_remapper import BookingActRemapper
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
+ 'train': {
568
+ 'day': 'day', 'time': "duration"
569
+ },
570
+ 'police': {}
571
+ }
572
+
573
+ reverse_da_slot_name_map = {
574
+ 'address': 'Addr',
575
+ 'postcode': 'Post',
576
+ 'price range': 'Price',
577
+ 'arrive by': 'Arrive',
578
+ 'leave at': 'Leave',
579
+ 'departure': 'Depart',
580
+ 'destination': 'Dest',
581
+ 'entrance fee': 'Fee',
582
+ 'open hours': 'Open',
583
+ 'price': 'Ticket',
584
+ 'train id': 'Id',
585
+ 'book people': 'People',
586
+ 'book stay': 'Stay',
587
+ 'book day': 'Day',
588
+ 'book time': 'Time',
589
+ 'duration': 'Time',
590
+ 'taxi': {
591
+ 'type': 'Car',
592
+ 'phone': 'Phone'
593
+ }
594
+ }
595
+
596
+ digit2word = {
597
+ '0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five',
598
+ '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '10': 'ten'
599
+ }
600
+
601
+ cnt_domain_slot = Counter()
602
+
603
+
604
+ def reverse_da(dialogue_acts):
605
+ global reverse_da_slot_name_map
606
+ das = {}
607
+ for da_type in dialogue_acts:
608
+ for da in dialogue_acts[da_type]:
609
+ intent, domain, slot, value = da['intent'], da['domain'], da['slot'], da.get('value', '')
610
+ if domain == 'general':
611
+ Domain_Intent = '-'.join([domain, intent])
612
+ elif intent == 'nooffer':
613
+ Domain_Intent = '-'.join([domain.capitalize(), 'NoOffer'])
614
+ elif intent == 'nobook':
615
+ Domain_Intent = '-'.join([domain.capitalize(), 'NoBook'])
616
+ elif intent == 'offerbook':
617
+ Domain_Intent = '-'.join([domain.capitalize(), 'OfferBook'])
618
+ else:
619
+ Domain_Intent = '-'.join([domain.capitalize(), intent.capitalize()])
620
+ das.setdefault(Domain_Intent, [])
621
+ if slot in reverse_da_slot_name_map:
622
+ Slot = reverse_da_slot_name_map[slot]
623
+ elif domain in reverse_da_slot_name_map and slot in reverse_da_slot_name_map[domain]:
624
+ Slot = reverse_da_slot_name_map[domain][slot]
625
+ else:
626
+ Slot = slot.capitalize()
627
+ if value == '':
628
+ if intent == 'request':
629
+ value = '?'
630
+ else:
631
+ value = 'none'
632
+ if Slot == '':
633
+ Slot = 'none'
634
+ das[Domain_Intent].append([Slot, value])
635
+ return das
636
+
637
+
638
+ def normalize_domain_slot_value(domain, slot, value):
639
+ global ontology, slot_name_map
640
+ domain = domain.lower()
641
+ slot = slot.lower()
642
+ value = value.strip()
643
+ if value in ['do nt care', "do n't care"]:
644
+ value = 'dontcare'
645
+ if value in ['?', 'none', 'not mentioned']:
646
+ value = ""
647
+ if domain not in ontology['domains']:
648
+ raise Exception(f'{domain} not in ontology')
649
+ if slot not in ontology['domains'][domain]['slots']:
650
+ if slot in slot_name_map:
651
+ slot = slot_name_map[slot]
652
+ elif slot in slot_name_map[domain]:
653
+ slot = slot_name_map[domain][slot]
654
+ else:
655
+ raise Exception(f'{domain}-{slot} not in ontology')
656
+ assert slot == '' or slot in ontology['domains'][domain]['slots'], f'{(domain, slot, value)} not in ontology'
657
+ return domain, slot, value
658
+
659
+
660
+ def convert_da(da_dict, utt, sent_tokenizer, word_tokenizer):
661
+ '''
662
+ convert multiwoz dialogue acts to required format
663
+ :param da_dict: dict[(intent, domain, slot, value)] = [word_start, word_end]
664
+ :param utt: user or system utt
665
+ '''
666
+ global ontology, digit2word, cnt_domain_slot
667
+
668
+ converted_da = {
669
+ 'categorical': [],
670
+ 'non-categorical': [],
671
+ 'binary': []
672
+ }
673
+ sentences = sent_tokenizer.tokenize(utt)
674
+ sent_spans = sent_tokenizer.span_tokenize(utt)
675
+ tokens = [token for sent in sentences for token in word_tokenizer.tokenize(sent)]
676
+ token_spans = [(sent_span[0] + token_span[0], sent_span[0] + token_span[1]) for sent, sent_span in
677
+ zip(sentences, sent_spans) for token_span in word_tokenizer.span_tokenize(sent)]
678
+ # assert len(tokens) == len(token_spans)
679
+ # for token, span in zip(tokens, token_spans):
680
+ # if utt[span[0]:span[1]] != '"':
681
+ # assert utt[span[0]:span[1]] == token
682
+
683
+ for (intent, domain, slot, value), span in da_dict.items():
684
+ if intent == 'request' or slot == '' or value == '':
685
+ # binary dialog acts
686
+ assert value == ''
687
+ converted_da['binary'].append({
688
+ 'intent': intent,
689
+ 'domain': domain,
690
+ 'slot': slot
691
+ })
692
+ elif ontology['domains'][domain]['slots'][slot]['is_categorical']:
693
+ # categorical dialog acts
694
+ converted_da['categorical'].append({
695
+ 'intent': intent,
696
+ 'domain': domain,
697
+ 'slot': slot,
698
+ 'value': value
699
+ })
700
+ else:
701
+ # non-categorical dialog acts
702
+ converted_da['non-categorical'].append({
703
+ 'intent': intent,
704
+ 'domain': domain,
705
+ 'slot': slot,
706
+ 'value': value
707
+ })
708
+ # correct some value and try to give char level span
709
+ match = False
710
+ value = value.lower()
711
+ if span and span[0] <= span[1]:
712
+ # use original span annotation, but tokenizations are different
713
+ start_word, end_word = span
714
+ if end_word >= len(tokens):
715
+ # due to different tokenization, sometimes will out of index
716
+ delta = end_word - len(tokens) + 1
717
+ start_word -= delta
718
+ end_word -= delta
719
+ start_char, end_char = token_spans[start_word][0], token_spans[end_word][1]
720
+ value_span = utt[start_char:end_char].lower()
721
+ match = True
722
+ if value_span == value:
723
+ cnt_domain_slot['span match'] += 1
724
+ elif value.isdigit() and value in digit2word and digit2word[value] == value_span:
725
+ # !!!CHANGE VALUE: value is digit but value span is word
726
+ cnt_domain_slot['digit value match'] += 1
727
+ elif ''.join(value.split()) == ''.join(value_span.split()):
728
+ # !!!CHANGE VALUE: equal when remove blank
729
+ cnt_domain_slot['remove blank'] += 1
730
+ elif value in value_span:
731
+ # value in value_span
732
+ start_char += value_span.index(value)
733
+ end_char = start_char + len(value)
734
+ assert utt[start_char:end_char].lower() == value, f'{[value, utt[start_char:end_char], utt]}'
735
+ cnt_domain_slot['value in span'] += 1
736
+ elif ':' in value and value == '0' + value_span:
737
+ # !!!CHANGE VALUE: time x:xx == 0x:xx
738
+ cnt_domain_slot['x:xx == 0x:xx'] += 1
739
+ else:
740
+ # span mismatch, search near 1-2 words
741
+ for window in range(1, 3):
742
+ start = max(0, start_word - window)
743
+ end = min(len(token_spans) - 1, end_word + window)
744
+ large_span = utt[token_spans[start][0]:token_spans[end][1]].lower()
745
+ if value in large_span:
746
+ start_char = token_spans[start][0] + large_span.index(value)
747
+ end_char = start_char + len(value)
748
+ assert utt[
749
+ start_char:end_char].lower() == value, f'{[value, utt[start_char:end_char], utt]}'
750
+ cnt_domain_slot[f'window={window}'] += 1
751
+ break
752
+ else:
753
+ # still not found
754
+ match = False
755
+
756
+ if match:
757
+ converted_da['non-categorical'][-1]['value'] = utt[start_char:end_char]
758
+ converted_da['non-categorical'][-1]['start'] = start_char
759
+ converted_da['non-categorical'][-1]['end'] = end_char
760
+ cnt_domain_slot['have span'] += 1
761
+ else:
762
+ cnt_domain_slot['no span'] += 1
763
+ return converted_da
764
+
765
+
766
+ def preprocess():
767
+ original_data_dir = 'MultiWOZ_2.1'
768
+ new_data_dir = 'data'
769
+
770
+ if not os.path.exists(original_data_dir):
771
+ original_data_zip = 'MultiWOZ_2.1.zip'
772
+ if not os.path.exists(original_data_zip):
773
+ raise FileNotFoundError(
774
+ 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')
775
+ else:
776
+ archive = ZipFile(original_data_zip)
777
+ archive.extractall()
778
+
779
+ os.makedirs(new_data_dir, exist_ok=True)
780
+ for filename in os.listdir(original_data_dir):
781
+ if 'db' in filename:
782
+ copy2(f'{original_data_dir}/{filename}', new_data_dir)
783
+
784
+ original_data = json.load(open(f'{original_data_dir}/data.json'))
785
+ global ontology, cnt_domain_slot
786
+
787
+ val_list = set(open(f'{original_data_dir}/valListFile.txt').read().split())
788
+ test_list = set(open(f'{original_data_dir}/testListFile.txt').read().split())
789
+ dataset = 'multiwoz21'
790
+ splits = ['train', 'validation', 'test']
791
+ dialogues_by_split = {split: [] for split in splits}
792
+ sent_tokenizer = PunktSentenceTokenizer()
793
+ word_tokenizer = TreebankWordTokenizer()
794
+ booking_remapper = BookingActRemapper(ontology)
795
+ for ori_dialog_id, ori_dialog in tqdm(original_data.items()):
796
+ if ori_dialog_id in val_list:
797
+ split = 'validation'
798
+ elif ori_dialog_id in test_list:
799
+ split = 'test'
800
+ else:
801
+ split = 'train'
802
+ dialogue_id = f'{dataset}-{split}-{len(dialogues_by_split[split])}'
803
+
804
+ # get user goal and involved domains
805
+ cur_domains = []
806
+ goal = {
807
+ 'description': '. '.join(ori_dialog['goal']['message']),
808
+ 'inform': {},
809
+ 'request': {}
810
+ }
811
+ for k, v in ori_dialog['goal'].items():
812
+ if len(v) != 0 and k in ontology['domains']:
813
+ cur_domains.append(k)
814
+ goal['inform'][k] = {}
815
+ goal['request'][k] = {}
816
+ for attr in ['fail_info', 'info', 'fail_book', 'book']:
817
+ if attr in v:
818
+ for slot, value in v[attr].items():
819
+ if 'invalid' in slot:
820
+ continue
821
+ domain, slot, value = normalize_domain_slot_value(k, slot, value)
822
+ if slot in goal['inform'][domain]:
823
+ goal['inform'][domain][slot] += '|' + value
824
+ else:
825
+ goal['inform'][domain][slot] = value
826
+ if 'reqt' in v:
827
+ for slot in v['reqt']:
828
+ domain, slot, _ = normalize_domain_slot_value(k, slot, '')
829
+ goal['request'][domain][slot] = ''
830
+
831
+ dialogue = {
832
+ 'dataset': dataset,
833
+ 'data_split': split,
834
+ 'dialogue_id': dialogue_id,
835
+ 'original_id': ori_dialog_id,
836
+ 'domains': cur_domains, # will be updated by dialog_acts and state
837
+ 'goal': goal,
838
+ 'turns': []
839
+ }
840
+
841
+ booking_remapper.reset()
842
+ belief_domains = ['attraction', 'restaurant', 'train', 'hotel', 'taxi', 'hospital']
843
+ entity_booked_dict = dict((domain, False) for domain in belief_domains)
844
+ for turn_id, turn in enumerate(ori_dialog['log']):
845
+ # correct some grammar errors in the text, mainly following `tokenization.md` in MultiWOZ_2.1
846
+ text = turn['text']
847
+ text = re.sub(" Im ", " I'm ", text)
848
+ text = re.sub(" im ", " i'm ", text)
849
+ text = re.sub(r"^Im ", "I'm ", text)
850
+ text = re.sub(r"^im ", "i'm ", text)
851
+ text = re.sub("theres", "there's", text)
852
+ text = re.sub("dont", "don't", text)
853
+ text = re.sub("whats", "what's", text)
854
+ text = re.sub('thats', "that's", text)
855
+ utt = text
856
+ speaker = 'user' if turn_id % 2 == 0 else 'system'
857
+
858
+ das = turn.get('dialog_act', [])
859
+ spans = turn.get('span_info', [])
860
+
861
+ if speaker == 'system':
862
+ das, spans = booking_remapper.remap(turn_id, ori_dialog['log'])
863
+
864
+ da_dict = {}
865
+ # transform DA
866
+ for Domain_Intent in das:
867
+ domain, intent = Domain_Intent.lower().split('-')
868
+ assert intent in ontology['intents'], f'{ori_dialog_id}:{turn_id}:da\t{intent} not in ontology'
869
+ for Slot, value in das[Domain_Intent]:
870
+ domain, slot, value = normalize_domain_slot_value(domain, Slot, value)
871
+ if domain not in cur_domains:
872
+ # update original cur_domains
873
+ cur_domains.append(domain)
874
+ da_dict[(intent, domain, slot, value,)] = []
875
+
876
+ for span in spans:
877
+ Domain_Intent, Slot, value, start_word, end_word = span
878
+ domain, intent = Domain_Intent.lower().split('-')
879
+ domain, slot, value = normalize_domain_slot_value(domain, Slot, value)
880
+ assert (intent, domain, slot, value,) in da_dict
881
+ da_dict[(intent, domain, slot, value,)] = [start_word, end_word]
882
+
883
+ dialogue_acts = convert_da(da_dict, utt, sent_tokenizer, word_tokenizer)
884
+
885
+ # reverse_das = reverse_da(dialogue_acts)
886
+ # das_list = sorted([(Domain_Intent, Slot, ''.join(value.split()).lower()) for Domain_Intent in das for Slot, value in das[Domain_Intent]])
887
+ # 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]])
888
+ # if das_list != reverse_das_list:
889
+ # print(das_list)
890
+ # print(reverse_das_list)
891
+ # print()
892
+ # print()
893
+
894
+ dialogue['turns'].append({
895
+ 'speaker': speaker,
896
+ 'utterance': utt,
897
+ 'utt_idx': turn_id,
898
+ 'dialogue_acts': dialogue_acts,
899
+ })
900
+
901
+ # add to dialogue_acts dictionary in the ontology
902
+ for da_type in dialogue_acts:
903
+ das = dialogue_acts[da_type]
904
+ for da in das:
905
+ ontology["dialogue_acts"][da_type].setdefault((da['intent'], da['domain'], da['slot']), {})
906
+ ontology["dialogue_acts"][da_type][(da['intent'], da['domain'], da['slot'])][speaker] = True
907
+
908
+ if speaker == 'system':
909
+ # add state to last user turn
910
+ # add empty db_results
911
+ turn_state = turn['metadata']
912
+ cur_state = copy.deepcopy(ontology['state'])
913
+ booked = {}
914
+ for domain in turn_state:
915
+ if domain not in cur_state:
916
+ continue
917
+ for subdomain in ['semi', 'book']:
918
+ for slot, value in turn_state[domain][subdomain].items():
919
+ if slot == 'ticket':
920
+ continue
921
+ elif slot == 'booked':
922
+ assert domain in ontology['domains']
923
+ booked[domain] = value
924
+ continue
925
+ _, slot, value = normalize_domain_slot_value(domain, slot, value)
926
+ cur_state[domain][slot] = value
927
+ dialogue['turns'][-2]['state'] = cur_state
928
+ entity_booked_dict, booked = fix_entity_booked_info(entity_booked_dict, booked)
929
+ dialogue['turns'][-1]['booked'] = booked
930
+ dialogues_by_split[split].append(dialogue)
931
+ # pprint(cnt_domain_slot.most_common())
932
+ dialogues = []
933
+ for split in splits:
934
+ dialogues += dialogues_by_split[split]
935
+ for da_type in ontology['dialogue_acts']:
936
+ ontology["dialogue_acts"][da_type] = sorted([str(
937
+ {'user': speakers.get('user', False), 'system': speakers.get('system', False), 'intent': da[0],
938
+ 'domain': da[1], 'slot': da[2]}) for da, speakers in ontology["dialogue_acts"][da_type].items()])
939
+ json.dump(dialogues[:10], open(f'dummy_data.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
940
+ json.dump(ontology, open(f'{new_data_dir}/ontology.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
941
+ json.dump(dialogues, open(f'{new_data_dir}/dialogues.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
942
+ with ZipFile('data.zip', 'w', ZIP_DEFLATED) as zf:
943
+ for filename in os.listdir(new_data_dir):
944
+ zf.write(f'{new_data_dir}/{filename}')
945
+ rmtree(original_data_dir)
946
+ rmtree(new_data_dir)
947
+ return dialogues, ontology
948
+
949
+
950
+ def fix_entity_booked_info(entity_booked_dict, booked):
951
+ for domain in entity_booked_dict:
952
+ if not entity_booked_dict[domain] and booked[domain]:
953
+ entity_booked_dict[domain] = True
954
+ booked[domain] = []
955
+ return entity_booked_dict, booked
956
+
957
+
958
+ if __name__ == '__main__':
959
+ preprocess()