File size: 1,843 Bytes
4cec618
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import print_function, unicode_literals
import os

from tsammalexdata.util import data_file, csv_items, jsondump, jsonload, DataProvider


class GBIF(DataProvider):
    host = 'api.gbif.org'

    def get_id(self, name):
        res = self.get('v1/species/match', name=name)
        if 'rank' not in res:
            return
        rank = res['rank'].lower()
        if rank in ['subspecies', 'variety'] and rank + 'Key' not in res:
            rank = 'species'
        try:
            return res[rank + 'Key']
        except KeyError:
            return

    def get_info(self, id):
        kw = dict(
            taxonKey=id,
            basisOfRecord='HUMAN_OBSERVATION',
            hasCoordinate='true',
            limit=100)
        return self.get('v1/occurrence/search', **kw)

    def update(self, taxon, data):
        if data.get('results'):
            result = data['results'][0]
            for key in 'kingdom phylum class order genus family'.split():
                if result.get(key):
                    taxon[key] = result[key]
            if 'taxonRank' in result:
                taxon['taxonRank'] = result['taxonRank'].lower()


def save_occurrences(sid, sname):
    api = GBIF()
    out = data_file('external', 'gbif', '%s.json' % sid)
    if not os.path.exists(out):
        try:
            res = api.get_info(api.get_id(sname))
            jsondump(res, out)
            print('%s: %s occurrences' % (sname, min([res['count'], res['limit']])))
        except:
            # we'll have to try again next time!
            res = None
    else:
        try:
            res = jsonload(out)
        except:
            os.remove(out)
            res = None
    return res


if __name__ == '__main__':
    for item in csv_items('taxa.csv'):
        save_occurrences(item['id'], item['scientific_name'])