-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcuela.py
80 lines (64 loc) · 2.41 KB
/
cuela.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
# coding: utf-8
import os
import glob
import gzip
import logging
import codecs
import colador
import argparse
try:
import ujson as json
except ImportError:
import json
if __name__ == '__main__':
options = None
with open('config.json', 'r') as f:
options = json.load(f)
logging.basicConfig(level=options['log_level'])
logging.debug(options)
if options is None:
logging.error('No valid options.')
sys.exit(1)
prefix = options['project_name']
source_storage = options['storage_path']
target_storage = options['filtered_path']
project_path = options['project_data_path']
sources = glob.glob('{0}/{1}_*.gz'.format(source_storage, prefix))
logging.info(sources)
col = colador.Colador(data_path=project_path)
for source in sources:
filename = source.split('/')[-1]
if os.path.exists('{0}/{1}.stats.json'.format(target_storage, filename)):
logging.info('{0} already processed'.format(filename))
continue
target_file = '{0}/{1}'.format(target_storage, filename)
with gzip.open(target_file, 'wb') as dst:
try:
with gzip.open(source, 'r') as src:
for line in src:
try:
tweet = json.loads(line.decode('utf-8'))
except ValueError as e:
logging.error(str(e))
logging.error(line)
continue
try:
if col.accept_tweet(tweet):
col.prepare_and_write(dst, tweet)
except TypeError as e:
logging.error(str(e))
logging.error(tweet)
continue
except IOError:
logging.error('invalid source file')
logging.error(source)
continue
stats = {
'source_file': source,
'total_tweets': col.total_tweet_count,
'discarded_sources': list(col.discarded_sources.most_common(10)),
'reject_reasons': list(col.reject_reasons.items())
}
with open('{0}/{1}.stats.json'.format(target_storage, filename), 'w') as f:
json.dump(stats, f)
logging.debug(stats)