File size: 9,972 Bytes
bdc90b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
from turtle import st
from zipfile import ZipFile, ZIP_DEFLATED
from shutil import rmtree
import json
import os
from tqdm import tqdm
from collections import Counter
from pprint import pprint
import re
import requests
from dateutil import parser as date_parser
from string import punctuation
from copy import deepcopy


def value_in_utt(value, utt):
    """return character level (start, end) if value in utt"""
    value = value.strip(punctuation).lower()
    utt = utt
    p = '(^|[\s,\.:\?!-])(?P<v>{})([\s,\.:\?!-\']|$)'.format(re.escape(value))
    p = re.compile(p, re.I)
    m = re.search(p, utt)
    if m:
        # very few value appears more than once, take the first span
        return True, m.span('v')
    else:
        try:
            # solve date representation, e.g. '3 pm' vs '3pm'
            date_parser.parse(value)
            if (value.endswith('pm') or value.endswith('am')) and ''.join(value.split(' ')) in ''.join(utt.split(' ')):
                return True, None
            
        except:
            if value in utt:
                # value appears, but may be in the plural, -ing, -ly, etc.
                return True, None

    return False, None


def preprocess():
    data_file = "kvret_dataset_public.zip"
    if not os.path.exists(data_file):
        response = requests.get("http://nlp.stanford.edu/projects/kvret/kvret_dataset_public.zip")
        open(data_file, "wb").write(response.content)

    archive = ZipFile(data_file)

    new_data_dir = 'data'

    os.makedirs(new_data_dir, exist_ok=True)

    dataset = 'kvret'
    splits = ['train', 'validation', 'test']
    dialogues_by_split = {split:[] for split in splits}

    ontology = {'domains': {},
                'intents': {
                    'inform': {'description': ''},
                    'request': {'description': ''}
                },
                'state': {},
                'dialogue_acts': {
                    "categorical": {},
                    "non-categorical": {},
                    "binary": {}
                }}

    domain2slot = {
        'schedule': ['event', 'time', 'date', 'party', 'room', 'agenda'],
        'weather': ['location', 'weekly_time', 'temperature', 'weather_attribute'],
        'navigate': ['poi', 'traffic_info', 'poi_type', 'address', 'distance']
    }
    slot2domain = {slot: domain for domain in domain2slot for slot in domain2slot[domain]}

    db = []
    with archive.open(f'kvret_entities.json') as f:
        entities = json.load(f)
        for slot, values in entities.items():
            domain = slot2domain[slot]
            ontology['domains'].setdefault(domain, {'description': '', 'slots': {}})
            if slot == 'poi':
                for s in ['poi', 'address', 'poi_type']:
                    ontology['domains'][domain]['slots'][s] = {'description': '', 'is_categorical': False, 'possible_values': []}
                for item in values:
                    poi, address, poi_type = item['poi'], item['address'], item['type']
                    db.append({'poi': poi, 'address': address, 'poi_type': poi_type})
                    for s in ['poi', 'address', 'poi_type']:
                        ontology['domains'][domain]['slots'][s]['possible_values'].append(db[-1][s])
                continue
            elif slot == 'weekly_time':
                slot = 'date'
            elif slot == 'temperature':
                values = [f"{x}F" for x in values]
            elif slot == 'distance':
                values = [f"{x} miles" for x in values]
            
            ontology['domains'][domain]['slots'][slot] = {'description': '', 'is_categorical': False, 'possible_values': values}

    for domain in ontology['domains']:
        for slot in ontology['domains'][domain]['slots']:
            ontology['domains'][domain]['slots'][slot]['possible_values'] = sorted(list(set(ontology['domains'][domain]['slots'][slot]['possible_values'])))

    for data_split in splits:
        filename = data_split if data_split != 'validation' else 'dev'
        with archive.open(f'kvret_{filename}_public.json') as f:
            data = json.load(f)
            for item in tqdm(data):
                if len(item['dialogue']) == 0:
                    continue
                scenario = item['scenario']
                domain = scenario['task']['intent']

                slots = scenario['kb']['column_names']
                db_results = {domain: []}
                if scenario['kb']['items']:
                    for entry in scenario['kb']['items']:
                        db_results[domain].append({s: entry[s] for s in slots})
                
                dialogue_id = f'{dataset}-{data_split}-{len(dialogues_by_split[data_split])}'
                dialogue = {
                    'dataset': dataset,
                    'data_split': data_split,
                    'dialogue_id': dialogue_id,
                    'original_id': f'{data_split}-{len(dialogues_by_split[data_split])}',
                    'domains': [domain],
                    'turns': []
                }
                init_state = {domain: {}}

                for turn in item['dialogue']:
                    speaker = 'user' if turn['turn'] == 'driver' else 'system'
                    utt = turn['data']['utterance'].strip()
                    if len(dialogue['turns']) > 0 and speaker == dialogue['turns'][-1]['speaker']:
                        # repeat, skip
                        if utt == dialogue['turns'][-1]['utterance']:
                            continue
                        else:
                            dialogue['turns'].pop(-1)

                    dialogue['turns'].append({
                        'speaker': speaker,
                        'utterance': utt,
                        'utt_idx': len(dialogue['turns']),
                        'dialogue_acts': {
                            'binary': [],
                            'categorical': [],
                            'non-categorical': [],
                        },
                    })
                    
                    if speaker == 'user':
                        dialogue['turns'][-1]['state'] = deepcopy(init_state)
                    else:
                        user_da = {'binary': [], 'categorical': [], 'non-categorical': []}
                        user_utt = dialogue['turns'][-2]['utterance']

                        for slot, value in turn['data']['slots'].items():
                            value = value.strip()
                            is_appear, span = value_in_utt(value, user_utt)
                            if is_appear:
                                if span:
                                    start, end = span
                                    user_da['non-categorical'].append({
                                        'intent': 'inform', 'domain': domain, 'slot': slot, 'value': user_utt[start:end],
                                        'start': start, 'end': end
                                    })
                                else:
                                    user_da['non-categorical'].append({
                                        'intent': 'inform', 'domain': domain, 'slot': slot, 'value': value,
                                    })
                            init_state[domain][slot] = value
                            ontology['state'].setdefault(domain, {})
                            ontology['state'][domain].setdefault(slot, '')
                        dialogue['turns'][-2]['state'] = deepcopy(init_state)
                        
                        for slot, present in turn['data']['requested'].items():
                            if slot not in turn['data']['slots'] and present:
                                user_da['binary'].append({'intent': 'request', 'domain': domain, 'slot': slot})
                        
                        dialogue['turns'][-2]['dialogue_acts'] = user_da
                        dialogue['turns'][-1]['db_results'] = db_results

                        for da_type in user_da:
                            das = user_da[da_type]
                            for da in das:
                                ontology["dialogue_acts"][da_type].setdefault((da['intent'], da['domain'], da['slot']), {})
                                ontology["dialogue_acts"][da_type][(da['intent'], da['domain'], da['slot'])]['user'] = True

                        assert all([s in ontology['domains'][domain]['slots'] for s in turn['data']['requested']]), print(turn['data']['requested'], ontology['domains'][domain]['slots'].keys())
                        assert all([s in ontology['domains'][domain]['slots'] for s in turn['data']['slots']]), print(turn['data']['slots'], ontology['domains'][domain]['slots'].keys())

                dialogues_by_split[data_split].append(dialogue)

    for da_type in ontology['dialogue_acts']:
        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()])
    dialogues = dialogues_by_split['train']+dialogues_by_split['validation']+dialogues_by_split['test']
    json.dump(dialogues[:10], open(f'dummy_data.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
    json.dump(ontology, open(f'{new_data_dir}/ontology.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
    json.dump(dialogues, open(f'{new_data_dir}/dialogues.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
    json.dump(db, open(f'{new_data_dir}/db.json', 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
    with ZipFile('data.zip', 'w', ZIP_DEFLATED) as zf:
        for filename in os.listdir(new_data_dir):
            zf.write(f'{new_data_dir}/{filename}')
    rmtree(new_data_dir)
    return dialogues, ontology


if __name__ == '__main__':
    preprocess()