-
Notifications
You must be signed in to change notification settings - Fork 9
/
preprocess_heideltime.py
81 lines (64 loc) · 2.48 KB
/
preprocess_heideltime.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
import os
import argparse
import arrow
import pathlib
import subprocess
import collections
import shutil
from news_tls import utils
def write_input_articles(articles, out_dir):
utils.force_mkdir(out_dir)
date_to_articles = collections.defaultdict(list)
for a in articles:
date = arrow.get(a['time']).datetime.date()
date_to_articles[date].append(a)
for date in sorted(date_to_articles):
utils.force_mkdir(out_dir / str(date))
date_articles = date_to_articles[date]
for a in date_articles:
fpath = out_dir / str(date) / '{}.txt'.format(a['id'])
with open(fpath, 'w') as f:
f.write(a['text'])
def delete_input_articles(articles, out_dir):
date_to_articles = collections.defaultdict(list)
for a in articles:
date = arrow.get(a['time']).datetime.date()
date_to_articles[date].append(a)
for date in sorted(date_to_articles):
date_articles = date_to_articles[date]
for a in date_articles:
fpath = out_dir / str(date) / '{}.txt'.format(a['id'])
if os.path.exists(fpath):
os.remove(fpath)
def heideltime_preprocess(dataset_dir, heideltime_path):
apply_heideltime = heideltime_path / 'apply-heideltime.jar'
heideltime_config = heideltime_path / 'config.props'
for topic in os.listdir(dataset_dir):
print('TOPIC:', topic)
articles = utils.read_jsonl_gz(dataset_dir / topic / 'articles.tokenized.jsonl.gz')
out_dir = dataset_dir / topic / 'time_annotated'
utils.force_mkdir(out_dir)
write_input_articles(articles, out_dir)
subprocess.run([
'java',
'-jar',
str(apply_heideltime),
str(heideltime_config),
str(out_dir),
'txt'
])
delete_input_articles(articles, out_dir)
def main(args):
dataset_dir = pathlib.Path(args.dataset)
heideltime_path = pathlib.Path(args.heideltime)
if not dataset_dir.exists():
raise FileNotFoundError('dataset not found')
if not heideltime_path.exists():
raise FileNotFoundError('heideltime not found')
heideltime_preprocess(dataset_dir, heideltime_path)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--heideltime', required=True,
help='location of heideltime software')
parser.add_argument('--dataset', required=True, help='dataset directory')
main(parser.parse_args())