1
|
#!/usr/bin/env python
|
2
|
# Downloads REMIB data for all nodes
|
3
|
# Usage: self
|
4
|
|
5
|
import csv
|
6
|
import itertools
|
7
|
import os.path
|
8
|
import StringIO
|
9
|
import sys
|
10
|
import urllib2
|
11
|
|
12
|
sys.path.append(os.path.dirname(__file__)+"/../../../lib")
|
13
|
|
14
|
import exc
|
15
|
import profiling
|
16
|
import streams
|
17
|
import strings
|
18
|
import timeout
|
19
|
import util
|
20
|
|
21
|
timeout_ = 20 # sec
|
22
|
|
23
|
alphabet = map(chr, xrange(ord('A'), ord('Z')+1))
|
24
|
|
25
|
class InputException(Exception): pass
|
26
|
|
27
|
def is_ignore(line):
|
28
|
line = strings.remove_line_ending(line)
|
29
|
return line == '' or line.startswith('\t') or line.find(',') < 0
|
30
|
|
31
|
def main():
|
32
|
def clear_line(): sys.stderr.write('\n')
|
33
|
log_indent = 0
|
34
|
def log(msg, line_ending='\n'):
|
35
|
sys.stderr.write((' '*log_indent)+msg+line_ending)
|
36
|
|
37
|
stdout = streams.LineCountOutputStream(sys.stdout)
|
38
|
|
39
|
# Get by family ('familia') because that is the most general level at which
|
40
|
# an identification can be made. This assumes all records have a family.
|
41
|
url_template = ('http://www.conabio.gob.mx/remib/cgi-bin/'
|
42
|
'remib_distribucion.cgi?lengua=EN&niveltax=familia&taxon=[prefix]%25&'
|
43
|
'pais=Todos&pais_otro=&estado=100&formato=csv&mapa=no&mapabase=estados'
|
44
|
'&coleccion=id%3D[node_id]')
|
45
|
done = False
|
46
|
for node_id in itertools.count(1):
|
47
|
if done: break
|
48
|
log('Processing node #'+str(node_id)+'...')
|
49
|
log_indent += 1
|
50
|
start_line_num = stdout.line_num
|
51
|
profiler = profiling.ItersProfiler(start_now=True, iter_text='row')
|
52
|
|
53
|
node_url_template = url_template.replace('[node_id]', str(node_id))
|
54
|
for prefix_chars in itertools.product(alphabet, repeat=2):
|
55
|
if done: break
|
56
|
prefix = ''.join(prefix_chars)
|
57
|
log('Processing prefix '+prefix+'...')
|
58
|
row_ct = 0
|
59
|
def print_status(line_ending='\n'):
|
60
|
log('Processed '+str(row_ct)+' row(s)', line_ending)
|
61
|
log_indent += 1
|
62
|
|
63
|
url = node_url_template.replace('[prefix]', prefix)
|
64
|
stream = streams.StreamIter(streams.TimeoutInputStream(
|
65
|
urllib2.urlopen(url), timeout_))
|
66
|
|
67
|
util.skip(stream, is_ignore) # skip header
|
68
|
try:
|
69
|
metadata_row = csv.reader(stream).next()
|
70
|
assert metadata_row[0] == 'COLLECTION'
|
71
|
except StopIteration: done = True # empty response = no more nodes
|
72
|
|
73
|
# Copy lines
|
74
|
try:
|
75
|
for line in stream:
|
76
|
if is_ignore(line):
|
77
|
error = strings.remove_prefix('\t\t', line)
|
78
|
if len(error) != len(line): raise InputException(error)
|
79
|
break
|
80
|
if row_ct % 100 == 0: print_status('\r')
|
81
|
# CR at end so next print overwrites msg
|
82
|
stdout.write(line)
|
83
|
row_ct += 1
|
84
|
except (InputException, timeout.TimeoutException), e:
|
85
|
clear_line()
|
86
|
log('! Output line '+str(stdout.line_num)+': '+exc.str_(e))
|
87
|
stream.close()
|
88
|
|
89
|
profiler.add_iters(row_ct)
|
90
|
print_status()
|
91
|
log_indent -= 1
|
92
|
|
93
|
profiler.stop()
|
94
|
log(profiler.msg())
|
95
|
|
96
|
if stdout.line_num == start_line_num: line_range = '<none>'
|
97
|
else: line_range = str(start_line_num)+'-'+str(stdout.line_num-1)
|
98
|
log('Used output lines '+line_range)
|
99
|
|
100
|
log_indent -= 1
|
101
|
|
102
|
main()
|