-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaggregate.py
executable file
·263 lines (237 loc) · 7.01 KB
/
aggregate.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
import argparse
import json
import os
import networkx as nx
from tqdm import tqdm
LANGS = {
"kirundi",
"indonesian",
"ukrainian",
"spanish",
"arabic",
"kyrgyz",
"thai",
"azerbaijani",
"uzbek",
"igbo",
"french",
"serbian_latin",
"vietnamese",
"marathi",
"pidgin",
"turkish",
"tigrinya",
"punjabi",
"swahili",
"somali",
"nepali",
"hindi",
"telugu",
"persian",
"scottish_gaelic",
"yoruba",
"welsh",
"gujarati",
"serbian_cyrillic",
"korean",
"english",
"sinhala",
"tamil",
"burmese",
"pashto",
"amharic",
"russian",
"japanese",
"urdu",
"portuguese",
"chinese_simplified",
"oromo",
"bengali",
"hausa",
"chinese_traditional",
}
def main():
parser = argparse.ArgumentParser(
description="Aggregate multi-lingual versions of the same document of the CrossSum dataset.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"-d",
"--data_path",
default="./original_data",
type=str,
metavar="",
help="input data directory path",
)
parser.add_argument(
"-o",
"--output",
default="./aggregated_data",
type=str,
metavar="",
help="output data directory path",
)
parser.add_argument(
"-s",
"--split",
default="test",
type=str,
metavar="",
help="split to aggregate (train, val, or test)",
)
parser.add_argument(
"-l",
"--langs",
default="all",
nargs="+",
type=str,
metavar="",
help="languages to download",
)
parser.add_argument(
"--chunk_size",
default=100,
type=int,
metavar="",
help="number of lines per output file",
)
args = parser.parse_args()
if args.langs == "all":
langs = LANGS
else:
langs = args.langs
print("Loading data...")
examples = []
examples_mono = {}
for fname in tqdm(os.listdir(os.path.join(args.data_path))):
if not fname.endswith(f"_{args.split}.jsonl"):
continue
source_lang = fname.split("-")[0]
target_lang = fname.split("-")[1].removesuffix(f"_{args.split}.jsonl")
if source_lang not in langs or target_lang not in langs:
continue
with open(os.path.join(args.data_path, fname), "r") as fd:
lines = fd.readlines()
egs = [
{
"source_url": json.loads(line)["source_url"],
"target_url": json.loads(line)["target_url"],
"source_lang": source_lang,
"target_lang": target_lang,
}
for line in lines
]
examples += egs
if source_lang == target_lang:
egs = [json.loads(line) for line in lines]
examples_mono[source_lang] = {x["source_url"]: x for x in egs}
print("Building the graph")
nodes = {}
graph = nx.Graph()
dir_edges = {}
for example in tqdm(examples):
source_url = example["source_url"]
target_url = example["target_url"]
source_lang = example["source_lang"]
target_lang = example["target_lang"]
if source_url not in nodes:
num_nodes = graph.number_of_nodes()
graph.add_nodes_from(
[(num_nodes, {"url": source_url, "lang": source_lang})]
)
nodes[source_url] = num_nodes
if source_url not in dir_edges:
dir_edges[source_url] = set()
dir_edges[source_url].add(target_url)
if target_url not in nodes:
num_nodes = graph.number_of_nodes()
graph.add_nodes_from(
[(num_nodes, {"url": target_url, "lang": target_lang})]
)
nodes[target_url] = num_nodes
source_node = nodes[source_url]
target_node = nodes[target_url]
graph.add_edge(source_node, target_node)
print("Finding all maximal cliques")
cliques = list(nx.find_cliques(graph))
# discard all cliques with only one document
cliques = [c for c in cliques if len(c) > 1]
# discard all cliques that have two documents with the same language
# as these are very likely to be due to pairing errors in CrossSum
cliques = [
c
for c in cliques
if len(set([graph.nodes[n]["lang"] for n in c]))
== len([graph.nodes[n]["lang"] for n in c])
]
# discard all two-document cliques that are not doubly connected
# as these are very likely to be due to pairing errors in CrossSum
cliques_filtered = []
for c in cliques:
if len(c) > 2:
cliques_filtered.append(c)
continue
source_url = graph.nodes[c[0]]["url"]
target_url = graph.nodes[c[1]]["url"]
if target_url in dir_edges[source_url] and source_url in dir_edges[target_url]:
cliques_filtered.append(c)
cliques = cliques_filtered
print("Writing aggregated data to files...")
num_files, num_lines = 0, 0
stats = [0] * 4
fd = None
for clique in tqdm(cliques):
line = {}
examples_clique, langs_clique = [], []
for node_idx in clique:
url = graph.nodes[node_idx]["url"]
lang = graph.nodes[node_idx]["lang"]
try:
examples_clique.append(examples_mono[lang][url])
langs_clique.append(lang)
except:
continue
line["num_docs"] = len(examples_clique)
for i, (x, lang) in enumerate(zip(examples_clique, langs_clique)):
line[f"url{i}"] = x["source_url"]
line[f"lang{i}"] = lang
line[f"text{i}"] = x["text"]
line[f"summary{i}"] = x["summary"]
if line:
if num_lines == 0:
fd = open(os.path.join(args.output, f"data_{num_files}.jsonl"), "w")
num_lines = 0
num_files += 1
fd.write(json.dumps(line, ensure_ascii=False) + "\n")
num_lines += 1
if num_lines == args.chunk_size:
fd.close()
fd = None
num_lines = 0
if len(clique) < len(stats):
stats[len(clique) - 1] += 1
else:
stats[-1] += 1
if fd is not None:
fd.close()
print("Aggregation stats:")
num_cliques = sum(stats)
print(f" Found {num_cliques} valid clusters of documents:")
print(
" 1 document: {} clusters ({:.1f}%)".format(
stats[0], 100.0 * stats[0] / num_cliques
)
)
for i in range(1, len(stats) - 1):
print(
" {} documents: {} clusters ({:.1f}%)".format(
i + 1, stats[i], 100.0 * stats[i] / num_cliques
)
)
print(
" {}+ documents: {} clusters ({:.1f}%)".format(
len(stats), stats[-1], 100.0 * stats[-1] / num_cliques
)
)
if __name__ == "__main__":
cliques = main()