File size: 8,435 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
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
212
import argparse
import os
import shutil
from transformers import T5Tokenizer
from tqdm import tqdm


def parse():
    parser = argparse.ArgumentParser()

    parser.add_argument("--input-dir", type=str)
    parser.add_argument("--output-dir", type=str)
    parser.add_argument("--max-src-length", type=int, default=512)
    parser.add_argument("--max-dialogue-history-len", type=int, default=256)
    parser.add_argument("--tokenizer-path", type=str)
    parser.add_argument("--special-tokens-file", type=str, default=None)
    parser.add_argument(
        "--truncate-side", type=str, default="left", choices=["left", "right"]
    )

    return parser.parse_args()


def truncate(args):
    left_tokenizer = T5Tokenizer.from_pretrained(
        args.tokenizer_path, truncate_side="left"
    )
    right_tokenizer = T5Tokenizer.from_pretrained(
        args.tokenizer_path, truncate_side="right"
    )
    tokenizer = T5Tokenizer.from_pretrained(args.tokenizer_path)

    if args.special_tokens_file is not None:
        with open(args.special_tokens_file, "r") as reader:
            special_tokens_dict = {
                "additional_special_tokens": [
                    token.strip() for token in reader.readlines()
                ]
            }

        left_tokenizer.add_special_tokens(special_tokens_dict)
        right_tokenizer.add_special_tokens(special_tokens_dict)
        tokenizer.add_special_tokens(special_tokens_dict)

    def normalize(x):
        return tokenizer.decode(tokenizer(x).input_ids[:-1])

    def divide_chunks(src):
        prefix, postfix = src.split("]", 1)
        prefix = prefix + "]"

        knowledge_start_index = postfix.index("[EK]")
        dialogue = postfix[: knowledge_start_index - 1]
        knowledge_and_instruction = postfix[knowledge_start_index - 1 :]

        instruction_start_index = knowledge_and_instruction.rfind("[C]")
        knowledge = knowledge_and_instruction[: instruction_start_index - 1]
        instruction = knowledge_and_instruction[instruction_start_index - 1 :]

        return prefix, dialogue, knowledge, instruction

    def token_num(x):
        return len(tokenizer.tokenize(x))

    min_knowledge_len = token_num(" [EK] None")

    if not os.path.exists(args.output_dir):
        os.makedirs(args.output_dir)

    print(f" {os.path.basename(args.input_dir)} ".center(70, "="))

    for filename in os.listdir(args.input_dir):
        if not filename.endswith(".src"):
            filepath = os.path.join(args.input_dir, filename)
            if not os.path.exists(os.path.join(args.output_dir, filename)):
                if os.path.isfile(filepath):
                    shutil.copyfile(
                        os.path.join(args.input_dir, filename),
                        os.path.join(args.output_dir, filename),
                    )
                else:
                    shutil.copytree(
                        os.path.join(args.input_dir, filename),
                        os.path.join(args.output_dir, filename),
                    )
        else:
            dialogue_cut_num = 0
            knowledge_cut_num = 0
            cut_token_num = 0
            # Truncate the source file
            with open(os.path.join(args.input_dir, filename), "r") as reader, open(
                os.path.join(args.output_dir, filename), "w"
            ) as writer:
                for line in tqdm(reader.readlines()):
                    src = line.strip()
                    src = normalize(src)

                    prefix, dialogue, knowledge, instruction = divide_chunks(src)

                    prefix_token_num = token_num(prefix)
                    dialogue_token_num = token_num(dialogue)
                    knowledge_token_num = token_num(knowledge)
                    instruction_token_num = token_num(instruction)

                    assert (
                        args.max_src_length >= prefix_token_num + instruction_token_num
                    )

                    origin_src_token_num = (
                        prefix_token_num
                        + dialogue_token_num
                        + knowledge_token_num
                        + instruction_token_num
                    )
                    # origin_src_token_num = token_num(src)

                    # assert (
                    #     prefix_token_num
                    #     + dialogue_token_num
                    #     + knowledge_token_num
                    #     + instruction_token_num
                    #     == origin_src_token_num
                    # )

                    if origin_src_token_num > args.max_src_length:
                        left_token_num = (
                            args.max_src_length
                            - prefix_token_num
                            - instruction_token_num
                        )
                        max_dialogue_token_num = min(
                            max(
                                args.max_dialogue_history_len,
                                left_token_num - knowledge_token_num,
                            ),
                            left_token_num - min_knowledge_len,
                        )

                        # The dialogue is out of the maximum token number
                        if dialogue_token_num > max_dialogue_token_num:
                            # Truncate the dialogue from left or right (For DDRel)
                            truncate_tokenizer = (
                                left_tokenizer
                                if args.truncate_side == "left"
                                else right_tokenizer
                            )
                            dialogue_ids = truncate_tokenizer(
                                dialogue,
                                max_length=max_dialogue_token_num
                                + 1,  # +1 is for the eos
                                truncation=True,
                            ).input_ids

                            dialogue = tokenizer.decode(dialogue_ids[:-1])
                            dialogue_token_num = max_dialogue_token_num
                            dialogue_cut_num += 1

                            # assert token_num(dialogue) <= dialogue_token_num

                        if knowledge_token_num > left_token_num - dialogue_token_num:
                            # Truncate the knowledge from right
                            knowledge_ids = right_tokenizer(
                                knowledge,
                                max_length=left_token_num - dialogue_token_num + 1,
                                truncation=True,
                            ).input_ids

                            knowledge = tokenizer.decode(knowledge_ids[:-1])

                            knowledge = " " + knowledge

                            knowledge_token_num = left_token_num - dialogue_token_num
                            knowledge_cut_num += 1

                            # assert (
                            #     token_num(knowledge) <= knowledge_token_num
                            # ), f"{knowledge_token_num}, {token_num(knowledge)}, {tokenizer.convert_ids_to_tokens(knowledge_ids)}, {knowledge_ids}"

                        src = (
                            prefix.strip()
                            + " "
                            + dialogue.strip()
                            + " "
                            + knowledge.strip()
                            + " "
                            + instruction.strip()
                        )

                        src_token_num = token_num(src)

                        # assert src_token_num <= args.max_src_length

                        cut_token_num += origin_src_token_num - src_token_num

                    prefix, dialogue, knowledge, instruction = divide_chunks(src)

                    prefix_token_num = token_num(prefix)
                    dialogue_token_num = token_num(dialogue)
                    knowledge_token_num = token_num(knowledge)
                    instruction_token_num = token_num(instruction)

                    writer.write(src + "\n")

            print(f" {filename} ".center(40, "-"))
            print(f"dialogue cut num: {dialogue_cut_num}")
            print(f"knowledge cut num: {knowledge_cut_num}")
            print(f"token cut num: {cut_token_num}")


if __name__ == "__main__":
    truncate(parse())