File size: 5,833 Bytes
a6326c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from utils import read_json_file, write_jsonl_file, parse, write_json_file
import os


def get_aligned_index(text, non_space_len, include_tail_space=True):
    cursor = 0
    while non_space_len >= 0 and cursor < len(text):
        if not include_tail_space and non_space_len == 0:
            break
        if include_tail_space and non_space_len == 0 and text[cursor] != " ":
            break

        if text[cursor] != " ":
            non_space_len -= 1

        cursor += 1

    return cursor


def parse_slot2index(slots, text, tokens):
    slot2index = dict()
    prefix_length = [0]
    for token in tokens:
        prefix_length.append(prefix_length[-1] + len(token))

    for trip in slots:
        start = get_aligned_index(text, prefix_length[trip["start"]])
        end = get_aligned_index(text, prefix_length[trip["exclusive_end"]], False)
        if trip["slot"] not in slot2index:
            slot2index[trip["slot"]] = dict()

        value = text[start:end]
        # if text not in [
        #     "there are none available for 8 pm , but there is one at 6.15 pm . would you like 6.15 pm instead ?",
        #     "8 pm is unavailable at 8 pm has been declined by oren hummus . you can choose another time such as 7.15 pm , 7.30 pm , or 8.30 pm .",
        #     "8 pm is not available on wednesday . i was unable to book your table on wednesday night at cetrella for 3 people .",
        # ]:
        #     assert value not in slot2index[trip["slot"]], value
        if value not in slot2index[trip["slot"]]:
            slot2index[trip["slot"]][value] = (start, end)
    return slot2index


def get_slot_index(slot2index, value, slot):
    if slot not in slot2index or value not in slot2index[slot]:
        # print(slot, value)
        return -1, -1
    return slot2index[slot][value]


def parse_dialogue_acts(acts, utter_dict, domain):
    dialog_acts = []
    text = utter_dict["text"]
    # print(utter_dict)
    # print(acts)
    # print()
    slot2index = parse_slot2index(utter_dict["slots"], text, utter_dict["tokens"])

    act_slot_values = dict()
    for act in acts:
        if act["type"] not in act_slot_values:
            act_slot_values[act["type"]] = dict()

        if "slot" in act:
            if act["slot"] not in act_slot_values[act["type"]]:
                act_slot_values[act["type"]][act["slot"]] = []

            if "value" in act:
                act_slot_values[act["type"]][act["slot"]].append(act["value"])

    for act in act_slot_values:
        svt = []
        for slot, values in act_slot_values[act].items():
            svp = {
                "slot": slot,
            }

            if values:
                svp["values"] = []
                svp["relation"] = "="
                for value in values:
                    start, end = get_slot_index(slot2index, value, slot)
                    if start != -1:
                        assert value == text[start:end], f"{value} {text[start: end]}"
                        svp["values"].append(
                            {"value": value, "start": start, "end": end}
                        )
                    else:
                        svp["values"].append({"value": value})
            svt.append(svp)

        dialog_acts.append({"act": act, "slot_value_table": svt, "domain": domain})

    return dialog_acts


def parse_dialogue_state(state, intent, domain, schema):
    svt = []

    for pair in state:
        svt.append(
            {
                "slot": pair["slot"],
                "values": [{"value": pair["value"]}],
                "relation": "=",
            }
        )

        schema[domain].add(pair["slot"])

    dialog_state = [
        {"intent": intent, "informed_slot_value_table": svt, "domain": domain}
    ]

    return dialog_state, schema


def reformat(args, file, domain):
    path = args.input_dir + "/" + file + ".json"
    data = read_json_file(path)
    processed_data = []

    schema = {domain: set()}

    for origin_dial in data:
        dialog = {"turn": "multi", "locale": "en", "dialog": []}
        origin_turns = origin_dial["turns"]
        intent = origin_turns[0]["user_intents"]

        assert len(intent) == 1
        intent = intent[0]

        for origin_turn in origin_turns:
            # system
            if "system_utterance" in origin_turn:
                new_turn = {
                    "roles": ["SYSTEM"],
                    "utterance": origin_turn["system_utterance"]["text"],
                    "dialog_acts": parse_dialogue_acts(
                        origin_turn["system_acts"],
                        origin_turn["system_utterance"],
                        domain,
                    ),
                }
                dialog["dialog"].append(new_turn)

            # user
            bs, schema = parse_dialogue_state(
                origin_turn["dialogue_state"], intent, domain, schema
            )
            new_turn = {
                "roles": ["USER"],
                "utterance": origin_turn["user_utterance"]["text"],
                "dialog_acts": parse_dialogue_acts(
                    origin_turn["user_acts"], origin_turn["user_utterance"], domain
                ),
                "belief_state": bs,
            }
            dialog["dialog"].append(new_turn)
        processed_data.append(dialog)

    write_jsonl_file(processed_data, args.output_dir + "/" + file + ".jsonl")

    schema[domain] = sorted(list(schema[domain]))

    ontology = {domain: {slot: True for slot in schema[domain]}}

    write_json_file(ontology, os.path.join(args.output_dir, f"{file}_ontology.json"))


def preprocess(args, domain):
    reformat(args, "train", domain)
    reformat(args, "dev", domain)
    reformat(args, "test", domain)


if __name__ == "__main__":
    args = parse()
    preprocess(args, args.domain)