Project

General

Profile

1
#!/usr/bin/env python
2
# Scrubs the taxonpaths 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 sql
15
import sql_gen
16
import sql_io
17
import streams
18
import strings
19
import tnrs
20

    
21
# Config
22
pause = 60 # sec
23
max_pause = 2*60*60 # sec; = 2 hr; must be >= max import time of one partition
24
assert pause <= max_pause
25
max_taxons = 500 # less than the limit to avoid slowing down the TNRS server
26

    
27
tnrs_data = sql_gen.Table('tnrs')
28

    
29
def main():
30
    # Input
31
    env_names = []
32
    db_config = opts.get_env_vars(sql.db_config_names, None, env_names)
33
    verbosity = float(opts.get_env_var('verbosity', 3, env_names))
34
    if not 'engine' in db_config: raise SystemExit('Usage: '
35
        +opts.env_usage(env_names)+' '+sys.argv[0]+' 2>>log')
36
    
37
    def log(msg, level=1):
38
        '''Higher level -> more verbose'''
39
        if level <= verbosity:
40
            sys.stderr.write(strings.to_raw_str(msg.rstrip('\n')+'\n'))
41
    
42
    # Connect to DB
43
    db = sql.connect(db_config, log_debug=log)
44
    
45
    # Iterate over unscrubbed verbatim taxonpaths
46
    start = 0
47
    total_pause = 0
48
    while True:
49
        # Fetch next set
50
        cur = sql.select(db, 'taxonpath', ['taxonomicnamewithauthor'],
51
            [('canon_taxonpath_id', None)], limit=max_taxons, start=start,
52
            cacheable=False)
53
        this_ct = cur.rowcount
54
        start += this_ct # advance start to fetch next set
55
        if this_ct == 0:
56
            total_pause += pause
57
            if total_pause > max_pause: break
58
            log('Waited '+str(total_pause)+' sec. Waiting...')
59
            time.sleep(pause) # wait for more rows
60
            continue # try again
61
        # otherwise, rows found
62
        total_pause = 0
63
        
64
        # Run TNRS
65
        log('Making TNRS request')
66
        try: stream = tnrs.repeated_tnrs_request(list(sql.values(cur)))
67
        except InvalidResponse: pass # skip this set in case it caused the error
68
        else:
69
            log('Storing TNRS response data')
70
            stream_info = csvs.stream_info(stream, parse_header=True)
71
            stream = streams.ProgressInputStream(stream, sys.stderr, n=1000)
72
            sql_io.append_csv(db, tnrs_data, stream_info, stream)
73

    
74
main()
(56-56/61)