File size: 9,222 Bytes
a93e458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import argparse
import gzip
import json
from pathlib import Path
from typing import (
    Callable,
    Dict,
    Iterable,
    Iterator,
    List,
    Optional,
    Sequence,
    TextIO,
    Tuple,
    Union,
)

import datasets
import numpy as np
import pandas as pd

TO_REMOVE = [
    "meta",
    "perplexity_score",
    "text_length",
    "url",
    "domain",
    "dup_ratio",
    "pairs",
    "repetitions",
    "included_in_dedup",
    "cluster",
    "id",
]

L_TO_NAME = {
    "en": "English",
    "de": "German",
    "fr": "French",
    "es": "Spanish",
    "it": "Italian",
    "ru": "Russian",
    "zh": "Chinese",
    "ko": "Korean",
    "pt": "Portuguese",
    "nl": "Dutch",
    "pl": "Polish",
    "sv": "Swedish",
}


def gen(l):
    for x in l:
        yield x


def _close_when_exhausted(file: TextIO) -> Iterable[str]:
    with file:
        for line in file:
            yield json.loads(line)


def _close_when_exhausted_txt(file: TextIO) -> Iterable[str]:
    with file:
        for line in file:
            yield line[:-1]  # ignore new line


def open_read_cleaned(filename) -> Iterable[str]:
    file: TextIO = gzip.open(filename, "rt")  # type: ignore
    return _close_when_exhausted(file)


def open_gzip_txt(filename) -> Iterable[str]:
    file: TextIO = gzip.open(filename, "rt")  # type: ignore
    return _close_when_exhausted_txt(file)


def read_parallel_corpus(dir: str, lp: str) -> Tuple[Iterable[str], Iterable[str]]:
    src_l, tgt_l = lp.split("-")
    if src_l != "en":
        lp_path = f"{tgt_l}-{src_l}"
    else:
        lp_path = lp
    src_path = Path(dir) / f"cometkiwi_data.{lp_path}.{src_l}"
    tgt_path = Path(dir) / f"cometkiwi_data.{lp_path}.{tgt_l}"
    src_corpus = open_gzip_txt(src_path)
    tgt_corpus = open_gzip_txt(tgt_path)
    return src_corpus, tgt_corpus


def unroll_chat(chat):
    chat_str = ""
    for i, turn in enumerate(chat):
        if type(turn["value"]) != str:
            pass
        else:
            chat_str += turn["value"]
    return chat_str


parser = argparse.ArgumentParser()
parser.add_argument("--dataset_path", type=str, required=True)
parser.add_argument("--output", type=str, required=True)
parser.add_argument("--is_hf_dataset", type=str, required=True, default=False)
parser.add_argument("--n_tokens", type=int, required=False, default=None)
parser.add_argument("--threshold", type=int, required=False, default=None)
parser.add_argument("--min_perplexity", type=int, required=False, default=None)
parser.add_argument("--wikipedia", type=str, required=False, default=False)
parser.add_argument("--posterior_tokens", type=str, required=False, default=False)
parser.add_argument("--n_posterior_tokens", type=int, required=False, default=None)
parser.add_argument("--is_parallel", type=str, required=False, default=False)
parser.add_argument("--lp", type=str, required=False)

args = parser.parse_args()
if args.posterior_tokens == "False":
    if args.wikipedia == "True":
        print("on wikipedia")
        data = []
        dataset_paths = [p for p in Path(args.dataset_path).iterdir()]
        dfs = []
        for dataset_path in dataset_paths:
            print("on path", dataset_path)
            corpus = open_read_cleaned(dataset_path)

            for doc in corpus:
                data.append({"text": doc["text"]})

            print(dataset_path)

            sub_df = pd.DataFrame(data=data)
            dfs.append(sub_df)

        df = pd.concat(dfs, ignore_index=True)
        dataset = datasets.Dataset.from_pandas(df)
        dataset.to_json(args.output, lines=True)

    else:
        if args.is_hf_dataset == "True":
            if args.dataset_path == "Unbabel/TowerBlocks-v0.1":
                df = datasets.load_dataset(
                    "Unbabel/TowerBlocks-v0.1", split="train"
                ).to_pandas()
                dataset = pd.DataFrame()
                dataset["text"] = df["conversations"].apply(unroll_chat)
                dataset = datasets.Dataset.from_pandas(dataset)
            else:
                dataset = datasets.load_from_disk(args.dataset_path)
                instances_to_select = []
                n_words = 0
                for idx in range(len(dataset)):
                    perplexity = dataset[int(idx)]["perplexity_score"]
                    if perplexity < args.threshold and perplexity > args.min_perplexity:
                        instances_to_select.append(idx)
                        n_words += len(dataset[int(idx)]["text"].split(" "))
                        print(f"Selected {n_words} of {args.n_tokens} tokens.")
                        if n_words >= args.n_tokens:
                            break

                dataset = dataset.select(instances_to_select)

                # Remove columns if they exist
                for column in TO_REMOVE:
                    if column in dataset.column_names:
                        dataset = dataset.remove_columns(column)

                print("English")
                print("n words", n_words)

        elif args.is_parallel == "False":
            data = []
            corpus = open_read_cleaned(args.dataset_path)

            n_words = 0
            for doc in corpus:
                perplexity = doc["perplexity"]
                if perplexity < args.threshold and perplexity > args.min_perplexity:
                    if args.lp == "zh":
                        n_words += len(doc["text"])
                    else:
                        n_words += len(doc["text"].split(" "))
                    data.append({"text": doc["text"]})
                    if n_words >= args.n_tokens:
                        break

            print(args.dataset_path)
            print("n words", n_words)

            dataset = datasets.Dataset.from_pandas(pd.DataFrame(data=data))

        elif args.is_parallel == "True":
            data = []
            src_data, tgt_data = read_parallel_corpus(
                dir=f"{args.dataset_path}", lp=args.lp
            )
            n_sents = 0
            for src, tgt in zip(src_data, tgt_data):
                if n_sents >= args.n_tokens:
                    break
                data.append(
                    {
                        "text": f"{L_TO_NAME[args.lp.split('-')[0]]}: {src}\n{L_TO_NAME[args.lp.split('-')[-1]]}: {tgt}"
                    }
                )
                n_sents += 1
                if n_sents % 1000 == 0:
                    print(f"Selected {n_sents} of {args.n_tokens} sentences.")
            data_len = len(data)
            # if xx-en, take 1st half of data; otherwise, take 2nd half
            if "-en" in args.lp:
                data = data[: int(data_len / 2)]
            else:
                data = data[int(data_len / 2) :]
            dataset = datasets.Dataset.from_pandas(pd.DataFrame(data=data))

        dataset.to_json(args.output, lines=True)

else:
    if args.is_hf_dataset:
        dataset = datasets.load_from_disk(args.dataset_path)
        instances_to_select = []
        n_words = 0
        surpassed = False
        for idx in range(len(dataset)):
            perplexity = dataset[int(idx)]["perplexity_score"]
            if perplexity < args.threshold and perplexity > args.min_perplexity:
                n_words += len(dataset[int(idx)]["text"].split(" "))
                if n_words >= args.n_tokens:
                    if surpassed:
                        instances_to_select.append(idx)
                        n_posterior_words += len(dataset[int(idx)]["text"].split(" "))
                        if n_posterior_words >= args.n_posterior_tokens:
                            break
                    else:
                        n_posterior_words = 0
                        surpassed = True

        dataset = dataset.select(instances_to_select)

        # Remove columns if they exist
        for column in TO_REMOVE:
            if column in dataset.column_names:
                dataset = dataset.remove_columns(column)

        print("English")
        print("n words", n_words)

    # here, we only start appending after the n_words threshold is satisfied once (this should be connected to another run)
    else:
        data = []
        corpus = open_read_cleaned(args.dataset_path)

        n_words = 0
        surpassed = False
        for doc in corpus:
            perplexity = doc["perplexity"]
            if perplexity < args.threshold and perplexity > args.min_perplexity:
                n_words += len(doc["text"].split(" "))
                # once we surpass the number of tokens, start appending on the next iteration
                if n_words >= args.n_tokens:
                    if surpassed:
                        data.append({"text": doc["text"]})
                        n_posterior_words += len(doc["text"].split(" "))
                        if n_posterior_words >= args.n_posterior_tokens:
                            break
                    if not surpassed:
                        n_posterior_words = 0
                        surpassed = True

        print(args.dataset_path)
        print("n words", n_words)

        dataset = datasets.Dataset.from_pandas(pd.DataFrame(data=data))

    dataset.to_json(args.output, lines=True)