Project

General

Profile

1
# TNRS
2

    
3
import re
4
import sys
5
import time
6
import urllib2
7

    
8
import csvs
9
import exc
10
import profiling
11
import streams
12
import strings
13

    
14
# Config
15
initial_pause = 0.35 # sec
16
pause_growth_factor = 1.3
17
max_pause = 30*60 # sec; = 30 min; TNRS sometimes freezes for ~10 min
18
assert initial_pause <= max_pause
19
max_names = 5000 # according to http://tnrs.iplantcollaborative.org/TNRSapp.html
20
max_names = 500 # the maximum above crashes the TNRS server
21

    
22
# Protocol params
23
url_base = 'http://tnrs.iplantcollaborative.org/tnrsdemo/'
24
url = url_base+'search'
25
initial_headers = {
26
    'Content-Type': 'text/x-gwt-rpc; charset=utf-8',
27
    'X-GWT-Module-Base': url_base,
28
    'X-GWT-Permutation': '574AA16D15D917C7704646FD92AFF6B3',
29
}
30
submission_request_template = ('7|0|7|'+url_base+
31
'||org.iplantc.tnrs.demo.client.SearchService|doSearch|\
32
java.lang.String/2004016611|{"sources":"gcc,tropicos,usda", "names":"[names]"\
33
, "type":"matching", "taxonomic":"true", "classification":"tropicos", \
34
"match_to_rank":"true"}|0.05|1|2|3|4|2|5|5|6|7|')
35
submission_response_pattern = r'^//OK\[1,\["(\w+)"\],0,7\]$'
36
retrieval_request_template = ('7|0|15|'+url_base+
37
'|1E87C78041CEFBF0992F46BDF84D7D60|org.iplantc.tnrs.demo.client.SearchService\
38
|getRemoteData|com.extjs.gxt.ui.client.data.PagingLoadConfig|\
39
java.lang.String/2004016611|com.extjs.gxt.ui.client.data.BasePagingLoadConfig/\
40
2011366567|com.extjs.gxt.ui.client.data.RpcMap/3441186752|sortField|sortDir|\
41
com.extjs.gxt.ui.client.Style$SortDir/640452531|offset|java.lang.Integer/\
42
3438268394|limit|{"email":"tnrs@lka5jjs.orv", "key":"[key]", \
43
"taxonomic_constraint":"false", "source_sorting":"false", "first":"false"}\
44
|1|2|3|4|2|5|6|7|0|1|8|4|9|0|10|11|0|12|13|0|14|13|100|15|')
45
retrieval_response_pattern = '^//OK\[.*?\["com.extjs.gxt.ui.client.data.\
46
BasePagingLoadResult/496878394","java.util.ArrayList/4159755760","org.iplantc.\
47
tnrs.demo.shared.BeanTNRSEntry/1039545748",".*"\],0,7\]$'
48
retrieval_response_info_pattern = r'(?ms).*^Set-Cookie: JSESSIONID=(\w+);'
49
download_request_template = ('7|0|6|'+url_base+
50
'|1E87C78041CEFBF0992F46BDF84D7D60|org.iplantc.tnrs.demo.client.SearchService|\
51
downloadRemoteResults|java.lang.String/2004016611|{"name":"tnrs_results.txt", \
52
"mode":"Best", "type":"Detailed", "encoding":"utf8", "dirty":"false", \
53
"sources":"false", "taxonomic":"false", "email":"tnrs@lka5jjs.orv", \
54
"key":"[key]"}|1|2|3|4|1|5|6|')
55
download_response_pattern = '^//OK\[1,\["(.*)"\],0,7\]$'
56
download_url_suffix = '&name=tnrs_results.txt&encoding=utf8'
57

    
58
class InvalidResponse(Exception): pass
59

    
60
def gwt_encode(str_):
61
    return strings.esc_quotes(strings.json_encode(str_), '|', quote_esc='\!')
62

    
63
def make_spliced_decode_map(decode_map):
64
    return [(r'(?: |(?<=\t)|^)'+re.escape(from_.strip())+r'(?: |(?=\t)|$)',
65
        strings.regexp_repl_esc(to)) for from_, to in decode_map]
66

    
67
encode_map = [
68
    ('!', ' !exc '), # escape char
69
    ('\t', ' !tab '),
70
    ('\n', ' !nl '),
71
    ('\r', ' !cr '),
72
    ('%', ' !pct '),
73
    ('&', ' !amp '),
74
    (';', ' !sem '),
75
    ('\\', ' !bsl '),
76
]
77
decode_map = strings.flip_map(encode_map)
78
spliced_decode_map = make_spliced_decode_map(decode_map)
79

    
80
def encode(str_): return strings.replace_all(encode_map, str_)
81

    
82
def decode(str_): return strings.replace_all_re(spliced_decode_map, str_)
83

    
84
decode_for_tsv_map = make_spliced_decode_map([(from_, strings.replace_all(
85
    csvs.tsv_encode_map, to)) for from_, to in decode_map])
86

    
87
def decode_for_tsv(str_):
88
    return strings.replace_all_re(decode_for_tsv_map, str_)
89

    
90
class TnrsOutputStream(streams.FilterStream):
91
    '''Decodes a TNRS response whose names were encoded with encode()'''
92
    def __init__(self, stream):
93
        streams.FilterStream.__init__(self, decode_for_tsv, stream)
94

    
95
def parse_response(name, pattern, str_, response, response_info):
96
    match = re.match(pattern, str_)
97
    if not match:
98
        raise InvalidResponse('Invalid '+name+' response:\n'+response_info+'\n'
99
            +response)
100
    return match.groups()
101

    
102
def tnrs_request(names, debug=False):
103
    '''
104
    Note that names containing only whitespace characters (after gwt_encode())
105
    are ignored by TNRS and do not receive a response row. Thus, you should
106
    always match up the Name_submitted returned by TNRS with the actual
107
    submitted name to determine the corresponding TNRS response row.
108
    '''
109
    name_ct = len(names)
110
    assert name_ct <= max_names
111
    
112
    # Logging
113
    def debug_log(label, str_=''):
114
        if debug: sys.stderr.write('\n'+label+':\n'+str_+'\n')
115
    
116
    ## HTTP
117
    headers = initial_headers.copy() # don't modify global constant!
118
    
119
    def do_request(request):
120
        debug_log('request', str(request))
121
        response = urllib2.urlopen(urllib2.Request(url, request, headers))
122
        response_str = streams.read_all(response)
123
        response_info = str(response.info())
124
        debug_log('response info', response_info)
125
        debug_log('response str', response_str)
126
        return response_str, response_info
127
    
128
    def do_repeated_request(request):
129
        pause = initial_pause
130
        total_pause = 0
131
        while True:
132
            total_pause += pause
133
            if total_pause > max_pause: raise # error is not temporary
134
            debug_log('total_pause', str(total_pause)+'s')
135
            time.sleep(pause) # wait for job to complete
136
            
137
            try: return do_request(request)
138
            except urllib2.HTTPError: pass # try again
139
            pause *= pause_growth_factor
140
    
141
    profiler = profiling.ItersProfiler(start_now=True, iter_text='name')
142
    try:
143
        debug_log('Submit')
144
        request = submission_request_template.replace('[names]',
145
            gwt_encode('\n'.join(map(encode, names))))
146
        response, response_info = do_request(request)
147
        key, = parse_response('submission', submission_response_pattern,
148
            response, response, response_info)
149
        debug_log('key', key)
150
        key_enc = gwt_encode(key)
151
        
152
        debug_log('Retrieve')
153
        request = retrieval_request_template.replace('[key]', key_enc)
154
        response, response_info = do_repeated_request(request)
155
        parse_response('retrieval', retrieval_response_pattern, response,
156
            response, response_info)
157
        session_id, = parse_response('retrieval info',
158
            retrieval_response_info_pattern, response_info, response,
159
            response_info)
160
        debug_log('session_id', session_id)
161
        headers['Cookie'] = 'JSESSIONID='+session_id
162
        
163
        # The output of the retrieve step is unusable because the array has
164
        # different lengths depending on the taxonomic ranks present in the
165
        # provided taxon name. The extra download step is therefore necessary.
166
        
167
        debug_log('Prepare download')
168
        request = download_request_template.replace('[key]', key_enc)
169
        response, response_info = do_request(request)
170
        csv_url, = parse_response('download', download_response_pattern,
171
            response, response, response_info)
172
        csv_url += download_url_suffix
173
        debug_log('csv_url', csv_url)
174
        
175
        debug_log('Download')
176
        response = urllib2.urlopen(urllib2.Request(csv_url))
177
        debug_log('response info', str(response.info()))
178
        return TnrsOutputStream(response)
179
    finally:
180
        profiler.stop(name_ct)
181
        sys.stderr.write(profiler.msg()+'\n')
182

    
183
def repeated_tnrs_request(names, debug=False, **kw_args):
184
    for try_num in xrange(2):
185
        try: return tnrs_request(names, debug, **kw_args)
186
        except InvalidResponse, e:
187
            exc.print_ex(e, detail=False)
188
            debug = True
189
            # try again with debug turned on
190
    raise # error is not temporary
(34-34/41)