forked from GRAAL-Research/deepparse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.py
343 lines (295 loc) · 9.61 KB
/
tools.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
# pylint: disable=too-many-locals
import json
import os
import pandas as pd
import pycountry
from deepparse.dataset_container import PickleDatasetContainer
from deepparse.parser import AddressParser
def clean_up_name(country: str) -> str:
"""
Function to clean up pycountry name
"""
if "Korea" in country:
country = "South Korea"
elif "Russian Federation" in country:
country = "Russia"
elif "Venezuela" in country:
country = "Venezuela"
elif "Moldova" in country:
country = "Moldova"
elif "Bosnia" in country:
country = "Bosnia"
return country
# country that we trained on
train_test_files = [
"br.p",
"us.p",
"kp.p",
"ru.p",
"de.p",
"fr.p",
"nl.p",
"ch.p",
"fi.p",
"es.p",
"cz.p",
"gb.p",
"mx.p",
"no.p",
"ca.p",
"it.p",
"au.p",
"dk.p",
"pl.p",
"at.p",
]
def train_country_file(file: str) -> bool:
"""
Validate if a file is a training country (as reference of our article).
"""
return file in train_test_files
# country that we did not train on
other_test_files = [
"ie.p",
"rs.p",
"uz.p",
"ua.p",
"za.p",
"py.p",
"gr.p",
"dz.p",
"by.p",
"se.p",
"pt.p",
"hu.p",
"is.p",
"co.p",
"lv.p",
"my.p",
"ba.p",
"in.p",
"re.p",
"hr.p",
"ee.p",
"nc.p",
"jp.p",
"nz.p",
"sg.p",
"ro.p",
"bd.p",
"sk.p",
"ar.p",
"kz.p",
"ve.p",
"id.p",
"bg.p",
"cy.p",
"bm.p",
"md.p",
"si.p",
"lt.p",
"ph.p",
"be.p",
"fo.p",
]
def zero_shot_eval_country_file(file: str) -> bool:
"""
Validate if a file is a zero shot country (as reference of our article).
"""
return file in other_test_files
def convert_2_letters_name_into_country_name(country_file_name: str) -> str:
country_name = pycountry.countries.get(alpha_2=country_file_name.replace(".p", "").upper()).name
country_name = clean_up_name(country_name)
return country_name
def convert_two_letter_name_to_country_name_in_json(file_path: str) -> None:
"""
Function to convert the name of the countries in a results file into their complete name.
"""
with open(file_path, "r") as file:
data = json.load(file)
new_data = {}
for country_name, value in data.items():
new_data.update({convert_2_letters_name_into_country_name(country_name): value})
with open(file_path, "w") as file:
json.dump(new_data, file)
def test_on_country_data(address_parser: AddressParser, file: str, directory_path: str, args) -> tuple:
"""
Compute the results over a country data.
"""
country = convert_2_letters_name_into_country_name(file)
print(f"Testing on test files {country}")
test_file_path = os.path.join(directory_path, file)
test_container = PickleDatasetContainer(test_file_path, is_training_container=False)
results = address_parser.test(
test_container,
batch_size=args.batch_size,
num_workers=4,
logging_path=f"./checkpoints/{args.model_type}",
checkpoint=args.model_path,
)
return results, country
def make_table(data_type: str, root_path: str = ".", with_attention: bool = False):
"""
Function to generate an Markdown table
"""
table_dir = os.path.join("tables", "actual")
os.makedirs(table_dir, exist_ok=True)
fasttext_all_res = json.load(open(os.path.join(root_path, f"{data_type}_test_results_fasttext.json"), "r"))
bpemb_all_res = json.load(open(os.path.join(root_path, f"{data_type}_test_results_bpemb.json"), "r"))
zipped_data = zip(fasttext_all_res.items(), bpemb_all_res.items())
columns_name = ["Country", r"FastText (%)", r"BPEmb (%)"]
if with_attention:
fasttext_att_all_res = json.load(
open(
os.path.join(root_path, f"{data_type}_test_results_fasttext_attention.json"),
"r",
)
)
bpemb_att_all_res = json.load(
open(
os.path.join(root_path, f"{data_type}_test_results_bpemb_attention.json"),
"r",
)
)
zipped_data = zip(
fasttext_all_res.items(),
fasttext_att_all_res.items(),
bpemb_all_res.items(),
bpemb_att_all_res.items(),
)
columns_name = [
"Country",
r"FastText (%)",
r"FastTextAtt (%)",
r"BPEmb (%)",
r"BPEmbAtt (%)",
]
columns = columns_name * 2
formatted_data = []
# We format the data to have two pairs of columns for a less long table
for idx, all_model_data in enumerate(zipped_data):
country = all_model_data[0][0]
res_data = [model_res[1] for model_res in all_model_data]
if idx % 2 and idx != 0:
row_data = [country]
row_data.extend(res_data)
data.extend(row_data)
formatted_data.append(data)
else:
data = [country]
data.extend(res_data)
if idx == 40:
data.extend([0] * (len(res_data) + 1))
formatted_data.append(data)
table = pd.DataFrame(formatted_data, columns=columns).round(2).to_markdown(index=False)
with open(os.path.join(table_dir, f"{data_type}_table.md"), "w", encoding="utf-8") as file:
file.writelines(table)
def make_table_rst(data_type: str, root_path: str = ".", with_attention: bool = False):
# pylint: disable=too-many-locals
"""
Function to generate an Sphinx RST table
"""
table_dir = os.path.join("tables", "actual")
os.makedirs(table_dir, exist_ok=True)
fasttext_all_res = json.load(open(os.path.join(root_path, f"{data_type}_test_results_fasttext.json"), "r"))
bpemb_all_res = json.load(open(os.path.join(root_path, f"{data_type}_test_results_bpemb.json"), "r"))
zipped_data = zip(fasttext_all_res.items(), bpemb_all_res.items())
columns_name = ["Country", r"FastText (%)", r"BPEmb (%)"]
if with_attention:
fasttext_att_all_res = json.load(
open(
os.path.join(root_path, f"{data_type}_test_results_fasttext_attention.json"),
"r",
)
)
bpemb_att_all_res = json.load(
open(
os.path.join(root_path, f"{data_type}_test_results_bpemb_attention.json"),
"r",
)
)
zipped_data = zip(
fasttext_all_res.items(),
fasttext_att_all_res.items(),
bpemb_all_res.items(),
bpemb_att_all_res.items(),
)
columns_name = [
"Country",
r"FastText (%)",
r"FastTextAtt (%)",
r"BPEmb (%)",
r"BPEmbAtt (%)",
]
columns = columns_name * 2
formatted_data = []
# we format the data to have two pairs of columns for a less long table
for idx, all_model_data in enumerate(zipped_data):
country = all_model_data[0][0]
res_data = [model_res[1] for model_res in all_model_data]
if idx % 2 and idx != 0:
row_data = [country]
row_data.extend(res_data)
data.extend(row_data)
formatted_data.append(data)
else:
data = [country]
data.extend(res_data)
if idx == 40:
data.extend([0] * (len(res_data) + 1))
formatted_data.append(data)
table = pd.DataFrame(formatted_data, columns=columns).round(2)
new_line_prefix = "\t\t"
string = ".. list-table::\n" + new_line_prefix + ":header-rows: 1\n" + "\n"
for idx, column in enumerate(table.columns):
if idx == 0:
string = string + new_line_prefix + "*" + f"\t- {column}\n"
else:
string = string + new_line_prefix + f"\t- {column}\n"
for _, row in table.iterrows():
for idx, data in enumerate(list(row)):
if idx == 0:
string = string + new_line_prefix + "*" + f"\t- {data}\n"
else:
string = string + new_line_prefix + f"\t- {data}\n"
with open(os.path.join(table_dir, f"{data_type}_table.rst"), "w", encoding="utf-8") as file:
file.writelines(string)
def make_comparison_table(results_a_file_name: str, results_b_file_name: str, root_path: str = "."):
"""
Function to generate an Markdown table
"""
table_dir = os.path.join("tables", "comparison")
os.makedirs(table_dir, exist_ok=True)
model_a_res = json.load(open(os.path.join(root_path, results_a_file_name), "r"))
model_b_res = json.load(open(os.path.join(root_path, results_b_file_name), "r"))
formatted_data = []
# we format the data to have two pairs of columns for a less long table
for idx, ((country, fasttext_res), (_, bpemb_res)) in enumerate(zip(model_a_res.items(), model_b_res.items())):
if idx % 2 and idx != 0:
data.extend([country, fasttext_res, bpemb_res])
formatted_data.append(data)
else:
data = [country, fasttext_res, bpemb_res]
if idx == 40:
formatted_data.append(data)
table = (
pd.DataFrame(
formatted_data,
columns=[
"Country",
r"Model A (%)",
r"Model B (%)",
"Country",
r"Model A (%)",
r"Model B (%)",
],
)
.round(2)
.to_markdown(index=False)
)
with open(
os.path.join(table_dir, f"{results_a_file_name}_vs_{results_b_file_name}_table.md"),
"w",
encoding="utf-8",
) as file:
file.writelines(table)