1
|
#!/usr/bin/env python
|
2
|
# Scrubs the taxonlabels in VegBIEN using TNRS.
|
3
|
# Runs continuously until no new rows are added after max_pause.
|
4
|
|
5
|
import os.path
|
6
|
import StringIO
|
7
|
import sys
|
8
|
import time
|
9
|
|
10
|
sys.path.append(os.path.dirname(__file__)+"/../lib")
|
11
|
|
12
|
import csvs
|
13
|
import opts
|
14
|
import profiling
|
15
|
import sql
|
16
|
import sql_gen
|
17
|
import sql_io
|
18
|
import streams
|
19
|
import strings
|
20
|
import tnrs
|
21
|
|
22
|
# Config
|
23
|
pause = 2*60*60 # sec; = 2 hr
|
24
|
max_pause = 9*60*60 # sec; = 9 hr; must be >= max partition import time (1.5 hr)
|
25
|
assert pause <= max_pause
|
26
|
|
27
|
tnrs_input = sql_gen.Table('tnrs_input_name')
|
28
|
tnrs_data = sql_gen.Table('tnrs')
|
29
|
|
30
|
def main():
|
31
|
# Input
|
32
|
env_names = []
|
33
|
db_config = opts.get_env_vars(sql.db_config_names, None, env_names)
|
34
|
verbosity = float(opts.get_env_var('verbosity', 3, env_names))
|
35
|
wait = opts.env_flag('wait', False, env_names)
|
36
|
if not 'engine' in db_config: raise SystemExit('Usage: '
|
37
|
+opts.env_usage(env_names)+' '+sys.argv[0]+' 2>>log')
|
38
|
|
39
|
def log(msg, level=1):
|
40
|
'''Higher level -> more verbose'''
|
41
|
if level <= verbosity:
|
42
|
sys.stderr.write(strings.to_raw_str(msg.rstrip('\n')+'\n'))
|
43
|
|
44
|
# Connect to DB
|
45
|
db = sql.connect(db_config, log_debug=log)
|
46
|
|
47
|
tnrs_profiler = profiling.ItersProfiler(iter_text='name')
|
48
|
|
49
|
# Iterate over unscrubbed verbatim taxonlabels
|
50
|
total_pause = 0
|
51
|
while True:
|
52
|
# Fetch next set
|
53
|
cur = sql.select(db, tnrs_input, None, limit=tnrs.max_names,
|
54
|
cacheable=False)
|
55
|
this_ct = cur.rowcount
|
56
|
log('Processing '+str(this_ct)+' taxonlabels')
|
57
|
if this_ct == 0:
|
58
|
if not wait: break
|
59
|
log('Waited '+str(total_pause)+' sec total')
|
60
|
total_pause += pause
|
61
|
if total_pause > max_pause: break
|
62
|
log('Waiting '+str(pause)+' sec...')
|
63
|
time.sleep(pause) # wait for more rows
|
64
|
continue # try again
|
65
|
# otherwise, rows found
|
66
|
total_pause = 0
|
67
|
names = list(sql.values(cur))
|
68
|
|
69
|
# Run TNRS
|
70
|
log('Making TNRS request')
|
71
|
tnrs_profiler.start()
|
72
|
try:
|
73
|
try: stream = tnrs.repeated_tnrs_request(names)
|
74
|
finally:
|
75
|
tnrs_profiler.stop(iter_ct=this_ct)
|
76
|
log('Cumulatively: '+tnrs_profiler.msg())
|
77
|
except tnrs.InvalidResponse: pass # skip set in case it caused error
|
78
|
else:
|
79
|
log('Storing TNRS response data')
|
80
|
sql_io.append_csv(db, tnrs_data, *csvs.reader_and_header(stream))
|
81
|
|
82
|
main()
|