File size: 3,927 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
import os
from utils import parse, read_json_file, write_jsonl_file, choices
import re
from tqdm import tqdm
import random

options = list(range(4))


def refine_roles_of_dialog(example):
    final = example["options"][0][0]

    assert final.lower() in ["m", "f"]

    lowercase = True
    if final in ["M", "F"]:
        lowercase = False

    if lowercase:
        turns = example["article"].split("m ; f :")
        roles = ["m :", "f :"]
    else:
        turns = example["article"].split("M;F:")
        roles = ["M:", "F:"]

    role_idx = 0 if final.lower() == "m" else 1
    role_idx = (role_idx + (len(turns) % 2) + 1) % 2

    new_turns = []

    for turn in turns:
        if not turn:
            continue
        new_turns.append(roles[role_idx])
        new_turns.append(turn)
        role_idx = 1 - role_idx

    return new_turns


def get_an_order_of_choices(label, sep):
    wrong_choices = options[:label] + options[label + 1 :]
    random.shuffle(wrong_choices)

    choices_order = [label] + wrong_choices

    return sep.join([choices[idx] for idx in choices_order])


def preprocess(args, split, part):
    indir = os.path.join(os.path.join(args.input_dir, part), split)
    outfile = os.path.join(os.path.join(args.output_dir, part), f"{split}.jsonl")

    processed_data = []
    for filename in tqdm(os.listdir(indir)):
        filepath = os.path.join(indir, filename)
        example = read_json_file(filepath)

        dial = {"turn": "multi", "locale": "en", "dialog": []}

        if "plus" not in part:
            turns = re.split("([mf] :)", example["article"])
        else:
            turns = re.split("([MF]:)", example["article"])
        if not turns[0]:
            turns = turns[1:]
            assert len(turns) % 2 == 0, example
        else:
            turns = refine_roles_of_dialog(example)
            # print(turns)
            # print(example)
        for i in range(0, len(turns), 2):
            role = turns[i]
            utterance = turns[i + 1]

            if "plus" not in part:
                assert (
                    len(role) == 3
                    and role[0] in ["m", "f"]
                    and role[1] == " "
                    and role[2] == ":"
                )
            else:
                assert len(role) == 2 and role[0] in ["M", "F"] and role[1] == ":"

            if role[0].lower() == "m":
                role = "male"
            else:
                role = "female"

            dial["dialog"].append({"roles": [role], "utterance": utterance.strip()})
        
        dial["knowledge"] = {"type": "dict", "value": {}}

        for idx, option in enumerate(example["options"]):
            role, utterance = option.split(":", 1)
            role = role.strip().lower()

            assert role in ["m", "f"]

            if role == "m":
                role = "male"
            else:
                role = "female"

            # utterance = f"{role}: {utterance.strip()}"

            # dial["dialog"].append(
            #     {"roles": [f"{choices[idx]} choice"], "utterance": utterance}
            # )
            dial["knowledge"]["value"][chr(ord("A") + idx)] = utterance.strip()

        # label = ord(example["answers"]) - ord("A")
        # assert 0 <= label < 4, example["answers"]

        # This task requires to predicts the order of choices.
        # NOTE: we put the correct answer at the beginning and other options are shuffled.
        # dial["dialog"][-1]["roles_to_select"] = [get_an_order_of_choices(label, ", ")]
        dial["dialog"][-1]["roles_to_select"] = [example["answers"]]

        processed_data.append(dial)

    write_jsonl_file(processed_data, outfile)


if __name__ == "__main__":
    args = parse()
    random.seed(args.seed)
    preprocess(args, "train", "mutual")
    preprocess(args, "dev", "mutual")
    preprocess(args, "train", "mutual_plus")
    preprocess(args, "dev", "mutual_plus")