-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocess_perturber.py
64 lines (56 loc) · 2.18 KB
/
preprocess_perturber.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
"""
* Copyright (c) 2022, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import json
import csv
import os
import glob
import random
from tqdm import tqdm
import spacy
nlp = spacy.load("en_core_web_lg")
random.seed(0)
threshold = 0.75
#location of uncompressed files from https://github.com/google-research-datasets/sentence-compression/data
#TODO
DIR=""
with open(os.path.join(DIR, "train.csv"), "w") as outt, open(os.path.join(DIR, "val.csv"), "w") as outv:
writert = csv.DictWriter(outt, fieldnames=["text", "summary"])
writert.writeheader()
writerv = csv.DictWriter(outv, fieldnames=["text", "summary"])
writerv.writeheader()
datas = []
# after gunzip'ing the files
for fname in glob.iglob(f"{DIR}/*.json"):
file_data = open(fname).read().split("\n\n")
file_data = [x for x in file_data if len(x.strip()) > 0]
for ex in tqdm(file_data, total=len(file_data)):
data = json.loads(ex)
comp_sent = data['compression']['text']
sent = data['graph']['sentence']
ratio = data['compression_ratio']
if ratio > threshold:
doc = nlp(sent)
ents = [x.text for x in doc.ents]
missing_ents = []
for ent in ents:
# here did string match different from entity precision calculation
if ent.lower() not in comp_sent.lower():
missing_ents.append(ent)
if missing_ents:
missing_ents = list(dict.fromkeys(missing_ents))
missing_ents_str = " | ".join(missing_ents)
text = f"{comp_sent} <s> {missing_ents_str}".strip()
summary = sent.strip()
datas.append({"text": text, "summary": summary})
idxs = list(range(len(datas)))
random.shuffle(idxs)
train = [datas[x] for x in idxs[:-500]]
val = [datas[x] for x in idxs[-500:]]
for ex in train:
writert.writerow(ex)
for ex in val:
writerv.writerow(ex)