-
Notifications
You must be signed in to change notification settings - Fork 0
/
postprocessing.py
489 lines (384 loc) · 14.4 KB
/
postprocessing.py
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import hashlib
import re
from functools import wraps
from typing import Callable, Dict, List
import fasttext
import ftfy
import numpy as np
import pandas as pd
import requests
from datasets import Dataset, disable_caching
from .common.logging import get_logger
from .common.utils import get_cache_path
from .models.types import GENERATION_ERROR
from .types import TaskType
_logger = get_logger(__name__)
disable_caching()
# Monkeypatch to disable fasttext warning:
# https://stackoverflow.com/questions/66353366/cant-suppress-fasttext-warning-load-model-does-not-return
fasttext.FastText.eprint = lambda x: None
def batched_map(
f: Callable[[List[str]], Dict[str, List[str]]]
) -> Callable[[Dataset], Dataset]:
"""
Runs a function `f` on a dataset with batched mapping.
Args:
f (Callable[[List[str]], Dict[str, List[str]]]): the function.
Returns:
Callable[[Dataset], Dataset]: the modified function.
"""
@wraps(f)
def with_batched_mapping(dataset: Dataset) -> Dataset:
"""Applies batched map to a function, shows name in progress bar"""
desc = " ".join(f.__name__.split("_")).capitalize()
dataset = dataset.map(
f,
input_columns=["text"],
batched=True,
load_from_cache_file=False,
desc=desc,
)
return dataset
return with_batched_mapping
def remove_generation_errors(dataset: Dataset) -> Dataset:
"""
Removes generation errors, i.e. texts marked with `GENERATION_ERROR`.
Args:
dataset (Dataset): the dataset to filter.
Returns:
Dataset: a filtered dataset with no error annotations.
"""
return dataset.filter(lambda x: x["text"] != GENERATION_ERROR)
def truncate(
dataset: Dataset,
min_length: int = 5,
min_tokens_to_truncate: int = 2,
sampling_radius_size: float = 2.0,
) -> Dataset:
"""
Truncates texts to remove token length bias per class in each domain.
This is done by:
1. Sampling the same number of texts per label in each domain
2. Sorting them by token length
3. Grouping them such that each group has one text per label
4. Truncating the texts in the group to have the same length
5. Truncating the remainder of 1. between mean +- 2*std
6. Dropping texts with lengths < min_length
Note that all the texts are truncated, this can be modified with
min_tokens_to_truncate = 0.
Args:
dataset (Dataset): the dataset to truncate.
min_length (int): the minimum (spacy) token length.
min_tokens_to_truncate (int): the minimum (spacy) tokens to truncate.
sampling_radius_size (float): the radius size for the sampling of
token lengths for non-grouped texts.
Returns:
Dataset: the truncated dataset
"""
from .extractors.utils import spacy_pipeline
np.random.seed(0)
df = dataset.to_pandas()
# tokenize with spacy multilingual model
df["tokenized"] = spacy_pipeline(
df["text"],
"multilingual",
)
# get tokenized length: we'll keep track of this and a
# "difference" column to know how much to truncate
# so then we only have to run the truncation itself once
df["token_length"] = df["tokenized"].apply(len)
to_truncate = []
# set new token lengths (actual truncation happens later)
for domain in df["domain"].unique():
# sample enough data per label
min_size = df[df["domain"] == domain].groupby("label").size().min()
grouped = df[df["domain"] == domain].groupby("label").sample(min_size)
# the remainder will be truncated based on mean +-std estimations
remainder = df[~df.index.isin(grouped.index)].copy()
remainder = remainder[remainder["domain"] == "domain"]
# texts with similar token lengths are grouped together
# to better approximate domain token length distribution
# and truncate less from longer texts.
grouped["group"] = grouped.groupby("label")["token_length"].rank(
"first"
)
# truncate a text by setting its new length to:
# min_token_length_per_group - min_tokens_to_truncate
grouped["new_token_length"] = (
grouped.groupby("group")["token_length"].transform(min)
- min_tokens_to_truncate
)
grouped = grouped.drop(["group"], axis=1)
# compute mean and std to tuncate the ungrouped texts
# for this we must only consider new lengths within desired min and max
new_lengths_above_min = grouped["new_token_length"][
(grouped["new_token_length"] >= min_length)
]
mean, std = new_lengths_above_min.mean(), new_lengths_above_min.std()
# Sample lengths around mean +- 2 std
low = int(max(min_length, mean - sampling_radius_size * std))
high = int(mean + sampling_radius_size * std)
sampled_new_token_lengths = np.random.randint(
low=low, high=high, size=len(remainder)
)
# account for cases where the sampled token length > current token length
remainder["new_token_length"] = np.minimum(
sampled_new_token_lengths,
remainder["token_length"] - min_tokens_to_truncate,
)
both = pd.concat([grouped, remainder])
# drop rows not within length bounds
both = both[(both["new_token_length"] >= min_length)]
to_truncate.append(both)
new_df = pd.concat(to_truncate).reset_index(drop=True)
assert (new_df["token_length"] < new_df["new_token_length"]).sum() == 0
def truncate_and_decode_one(row: Dict) -> str:
tokenized_truncated = row["tokenized"][: row["new_token_length"]]
text = "".join([token.text_with_ws for token in tokenized_truncated])
return text
new_df["text"] = new_df.apply(truncate_and_decode_one, axis=1)
diff = new_df["token_length"] - new_df["new_token_length"]
dropped_quantity = len(df) - len(new_df)
_logger.info(
f"Truncated texts. Length difference statistics: {diff.describe().to_dict()}"
)
if dropped_quantity:
_logger.info(
f"{dropped_quantity} texts were too short and were dropped in the truncation process."
)
new_df = new_df.drop(
["token_length", "new_token_length", "tokenized"], axis=1
)
dataset = Dataset.from_pandas(new_df)
return dataset
def filter_by_language(dataset: Dataset, language: str = "en") -> Dataset:
"""
Applies a language id filter, removing texts in undesired languages.
Args:
dataset (Dataset): the dataset to apply the language id filter on.
Returns:
Dataset: the filtered dataset.
"""
model = get_langid_model()
@batched_map
def annotate_texts_with_language(texts: List[str]):
keep = []
for text in texts:
# need to replace newlines since fasttexts doesn't accept them
predicted_language = model.predict(text.replace("\n", " "), k=1)
# fasttext model output looks like: (('__label__en',), array([0.98803425]))
# so we grab the suffix with the language ISO code
predicted_language = predicted_language[0][0][-2:]
if predicted_language != language:
keep.append(False)
else:
keep.append(True)
return {"keep": keep}
dataset = annotate_texts_with_language(dataset)
dataset = dataset.filter(lambda x: x["keep"], desc="Filter by language")
dataset = dataset.remove_columns(["keep"])
return dataset
def get_langid_model() -> fasttext.FastText:
url = (
"https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.bin"
)
model_path = get_cache_path() / "fasttext" / "lid.176.bin"
# Need to download if it doesn't exist
try:
model = fasttext.load_model(str(model_path))
except (ValueError, FileNotFoundError):
model_path.parent.mkdir(parents=True, exist_ok=True)
content = requests.get(url, stream=True).content
with model_path.open("wb") as f:
f.write(content)
model = fasttext.load_model(str(model_path))
return model
def remove_label_duplicates(dataset: Dataset) -> Dataset:
"""
Removes text with more than one associated label.
Args
dataset (Dataset): the dataset to remove label duplicates from.
Returns:
Dataset: the dataset with removed label duplicates.
"""
old_len = len(dataset)
df = dataset.to_pandas()
groups = df.groupby("text")["label"].nunique()
single_label_texts = groups[groups == 1].index
filtered = df[df["text"].isin(single_label_texts)]
dataset = Dataset.from_pandas(filtered, preserve_index=False)
new_len = len(dataset)
_logger.info(f"Removed {old_len - new_len} texts with more than one label.")
return dataset
def remove_text_duplicates(dataset: Dataset) -> Dataset:
"""
Removes all text duplicates.
Args
dataset (Dataset): the dataset to remove duplicates from.
Returns:
Dataset: the dataset with removed duplicates.
"""
old_len = len(dataset)
def hash_str(s: str) -> str:
x = s.encode("utf8")
return hashlib.sha256(x).hexdigest()
dataset = dataset.map(
lambda example: {"hash": hash_str(example["text"])},
load_from_cache_file=False,
)
_, unique_indices = np.unique(dataset["hash"], return_index=True)
dataset = dataset.select(unique_indices)
dataset = dataset.remove_columns(["hash"])
new_len = len(dataset)
_logger.info(f"Removed {old_len - new_len} duplicated texts.")
return dataset
def remove_empty_texts(dataset: Dataset) -> Dataset:
"""
Removes empty texts from a dataset.
Args:
dataset (Dataset): the dataset to remove empty texts from.
Returns:
Datset: the dataset with removed empty texts.
"""
old_len = len(dataset)
dataset = dataset.filter(
lambda example: example["text"], load_from_cache_file=False
)
new_len = len(dataset)
_logger.info(f"Removed {old_len - new_len} empty texts.")
return dataset
@batched_map
def remove_special_tokens(texts: List[str]) -> Dict[str, List[str]]:
"""
Removes special text generation tokens from a list of texts.
Args:
texts (List[str]): the texts to apply special-token removal to.
Returns:
Dict[str, List[str]]: the cleaned texts in dict form.
The result is returned as so in order to run this using
batched mapping from huggingface datasets.
"""
special_tokens = [
"[CLS]",
"[SEP]",
"[PAD]",
"[MASK]",
"[UNK]",
"[BOS]",
"[EOS]",
"[EOD]",
"[EOP]",
"<endoftext>",
]
# Also remove brackets from ends
special_tokens += [x[1:-1] for x in special_tokens]
regex = re.compile("|".join(map(re.escape, special_tokens)))
clean = []
for text in texts:
text = regex.sub("", text)
clean.append(text)
return {"text": clean}
@batched_map
def remove_disclosure_phrases(texts: List[str]) -> Dict[str, List[str]]:
"""
Removes a set of disclosure phrases.
Args:
texts (List[str]): the texts from which to remove disclosure phrases.
Returns:
Dict[str, List[str]]: the cleaned texts in dict form.
The result is returned as so in order to run this using
batched mapping from huggingface datasets.
"""
# These patterns match the prefixes until next word
patterns = [
r"As an AI language model.+?(?=\w)",
r"I am sorry, I am an AI language model and.+?(?=\w)",
r"I am sorry, I'm an AI language model and.+?(?=\w)",
r"I'm sorry, I'm an AI language model and.+?(?=\w)",
r"I'm sorry, I am an AI language model and.+?(?=\w)",
r"I'm sorry, but I am an AI language model and.+?(?=\w)",
]
regexes = [re.compile(pattern, flags=re.IGNORECASE) for pattern in patterns]
clean = []
for text in texts:
original_text = text
for regex in regexes:
text = regex.sub("", text)
# At least one regex was applied so we correct the capitalization
if original_text != text:
text = text.capitalize()
clean.append(text)
return {"text": clean}
@batched_map
def fix_encoding(texts: List[str]) -> Dict[str, List[str]]:
"""
Fixes the encoding in a list of texts.
Args:
texts (List[str]): the texts to apply encoding-fixing to.
Returns:
Dict[str, List[str]]: the cleaned texts in dict form.
The result is returned as so in order to run this using
batched mapping from huggingface datasets.
"""
clean = []
for text in texts:
text = ftfy.fix_text(text)
clean.append(text)
return {"text": clean}
@batched_map
def strip(texts: List[str]) -> Dict[str, List[str]]:
"""
Strips whitespace from a list of texts.
Args:
texts (List[str]): the texts to apply stripping to.
Returns:
Dict[str, List[str]]: the cleaned texts in dict form.
The result is returned as so in order to run this using
batched mapping from huggingface datasets.
"""
clean = []
for text in texts:
text = text.strip()
clean.append(text)
return {"text": clean}
def postprocess(dataset: Dataset, task_type: TaskType) -> Dataset:
"""
Postprocesses a dataset.
Args:
dataset (Dataset): the dataset to postprocess.
Returns:
Dataset: the postprocessed dataset.
"""
single_text_actions = [
fix_encoding,
strip,
remove_special_tokens,
remove_disclosure_phrases,
]
full_dataset_actions = [
remove_generation_errors,
remove_empty_texts,
remove_text_duplicates,
]
if task_type in {TaskType.DETECTION, TaskType.ATTRIBUTION}:
if len(set(dataset["label"])) < 2:
_logger.info(
"Dataset only has single label, truncation will not be applied."
)
actions = (
single_text_actions
+ full_dataset_actions
+ [remove_label_duplicates]
)
else:
actions = (
single_text_actions
+ [truncate]
+ full_dataset_actions
+ [remove_label_duplicates]
)
else:
actions = single_text_actions + full_dataset_actions # type: ignore
for action in actions:
dataset = action(dataset) # type: ignore
return dataset