|
20 | 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
21 | 21 | # THE SOFTWARE. |
22 | 22 |
|
23 | | -import requests |
| 23 | +import os |
24 | 24 | import json |
| 25 | +import requests |
25 | 26 |
|
26 | 27 | DEFAULT_BASE_URL = "http://api.cept.at" |
27 | 28 | DEFAULT_VERSION = "v1" |
| 29 | +DEFAULT_CACHE_DIR = "/tmp/pycept" |
28 | 30 |
|
29 | 31 | class Cept(object): |
30 | 32 | """ |
31 | 33 | Main class for the Cept API. |
32 | 34 | """ |
33 | 35 |
|
34 | | - def __init__(self, app_id, app_key, base_url=DEFAULT_BASE_URL, version=DEFAULT_VERSION): |
| 36 | + def __init__(self, app_id, app_key, base_url=DEFAULT_BASE_URL, |
| 37 | + version=DEFAULT_VERSION, cache_dir=DEFAULT_CACHE_DIR): |
35 | 38 | self.app_id = app_id |
36 | 39 | self.app_key = app_key |
37 | 40 | self.api_url = "%s/%s" % (base_url, version) |
| 41 | + # Create the cache directory if necessary. |
| 42 | + if not os.path.exists(cache_dir): |
| 43 | + os.mkdir(cache_dir) |
| 44 | + self.cache_dir = cache_dir |
| 45 | + |
38 | 46 |
|
39 | 47 |
|
40 | 48 | def getBitmap(self, term): |
41 | 49 | urlParams = self._buildUrlParams() |
42 | 50 | urlParams['term'] = term |
43 | 51 | url = "%s/term2bitmap" % (self.api_url,) |
44 | | - response = requests.get(url, params=urlParams) |
45 | | - return response.json['bitmap'] |
| 52 | + # Create a cache location for each term, where it will either be read in from |
| 53 | + # or cached within if we have to go to the CEPT API to get the SDR. |
| 54 | + cache_file = os.path.join(self.cache_dir, term + '.json') |
| 55 | + # Get it from the cache if it's there. |
| 56 | + if os.path.exists(cache_file): |
| 57 | + cached_sdr = json.loads(open(cache_file).read()) |
| 58 | + # Get it from CEPT API if it's not cached. |
| 59 | + else: |
| 60 | + print '\tfetching %s from CEPT API' % term |
| 61 | + response = requests.get(url, params=urlParams) |
| 62 | + cached_sdr = response.json['bitmap'] |
| 63 | + # attach the sparcity for reference |
| 64 | + total = float(cached_sdr['width']) * float(cached_sdr['height']) |
| 65 | + on = len(cached_sdr['positions']) |
| 66 | + sparcity = round((on / total) * 100) |
| 67 | + cached_sdr['sparcity'] = sparcity |
| 68 | + # write to cache |
| 69 | + with open(cache_file, 'w') as f: |
| 70 | + f.write(json.dumps(cached_sdr)) |
| 71 | + |
| 72 | + return cached_sdr |
46 | 73 |
|
47 | 74 |
|
48 | 75 | def getSdr(self, term): |
|
0 commit comments