Skip to content

Commit

Permalink
Merge client and abraia files
Browse files Browse the repository at this point in the history
  • Loading branch information
jrrodri committed Oct 17, 2020
1 parent 064628e commit ad5aec2
Show file tree
Hide file tree
Showing 5 changed files with 219 additions and 218 deletions.
5 changes: 2 additions & 3 deletions abraia/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from . import config
from .client import Client, APIError
from .abraia import Abraia
from .abraia import Abraia, APIError

__all__ = ['config', 'Client', 'APIError', 'Abraia']
__all__ = ['config', 'Abraia', 'APIError']
139 changes: 138 additions & 1 deletion abraia/abraia.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,143 @@
import os
import base64
import requests
import mimetypes

from .client import Client
from fnmatch import fnmatch
from datetime import datetime
from io import BytesIO
from . import config


class APIError(Exception):
def __init__(self, message, code=0):
super(APIError, self).__init__(message, code)
self.message = message
self.code = code


class Client(object):
def __init__(self):
self.auth = config.load_auth()

def load_user(self):
if self.auth[0] and self.auth[1]:
url = '{}/users'.format(config.API_URL)
resp = requests.get(url, auth=self.auth)
if resp.status_code != 200:
raise APIError(resp.text, resp.status_code)
return resp.json()['user']
raise APIError('Unauthorized', 401)

def list_files(self, path=''):
url = '{}/files/{}'.format(config.API_URL, path)
resp = requests.get(url, auth=self.auth)
if resp.status_code != 200:
raise APIError(resp.text, resp.status_code)
resp = resp.json()
for f in resp['files']:
f['date'] = datetime.fromtimestamp(f['date'])
return resp['files'], resp['folders']

def upload_remote(self, url, path):
json = {'url': url}
url = '{}/files/{}'.format(config.API_URL, path)
resp = requests.post(url, json=json, auth=self.auth)
if resp.status_code != 201:
raise APIError(resp.text, resp.status_code)
resp = resp.json()
return resp['file']

def upload_file(self, file, path):
source = path + os.path.basename(file) if path.endswith('/') else path
name = os.path.basename(source)
type = mimetypes.guess_type(name)[0] or 'binary/octet-stream'
# json = {'name': name, 'type': type, 'md5': md5} if md5 else {'name': name, 'type': type}
json = {'name': name, 'type': type}
url = '{}/files/{}'.format(config.API_URL, source)
resp = requests.post(url, json=json, auth=self.auth)
if resp.status_code != 201:
raise APIError(resp.text, resp.status_code)
url = resp.json()['uploadURL']
data = file if isinstance(file, BytesIO) else open(file, 'rb')
resp = requests.put(url, data=data, headers={'Content-Type': type})
if resp.status_code != 200:
raise APIError(resp.text, resp.status_code)
return {'name': name, 'source': source}

def move_file(self, old_path, new_path):
url = '{}/files/{}'.format(config.API_URL, new_path)
resp = requests.post(url, json={'store': old_path}, auth=self.auth)
if resp.status_code != 201:
raise APIError(resp.text, resp.status_code)
resp = resp.json()
return resp['file']

def download_file(self, path, dest=''):
# T0D0 Add dest ptina paramater to save file
url = '{}/files/{}'.format(config.API_URL, path)
resp = requests.get(url, stream=True, auth=self.auth)
if resp.status_code != 200:
raise APIError(resp.text, resp.status_code)
return BytesIO(resp.content)

def remove_file(self, path):
url = '{}/files/{}'.format(config.API_URL, path)
resp = requests.delete(url, auth=self.auth)
if resp.status_code != 200:
raise APIError(resp.text, resp.status_code)
resp = resp.json()
return resp['file']

def load_metadata(self, path):
url = '{}/metadata/{}'.format(config.API_URL, path)
resp = requests.get(url, auth=self.auth)
if resp.status_code != 200:
raise APIError(resp.text, resp.status_code)
return resp.json()

def remove_metadata(self, path):
url = '{}/metadata/{}'.format(config.API_URL, path)
resp = requests.delete(url, auth=self.auth)
if resp.status_code != 200:
raise APIError(resp.text, resp.status_code)
return resp.json()

def analyze_image(self, path, params={}):
url = '{}/analysis/{}'.format(config.API_URL, path)
resp = requests.get(url, auth=self.auth)
if resp.status_code != 200:
raise APIError(resp.text, resp.status_code)
resp = resp.json()
if resp.get('salmap'):
resp['salmap'] = BytesIO(base64.b64decode(resp['salmap'][23:]))
return resp

def detect_labels(self, path, params={}):
url = '{}/rekognition/{}'.format(config.API_URL, path)
resp = requests.get(url, auth=self.auth)
if resp.status_code != 200:
raise APIError(resp.text, resp.status_code)
return resp.json()

def transform_image(self, path, params={}):
if params.get('action'):
params['background'] = '{}/images/{}'.format(config.API_URL, path)
if params.get('fmt') is None:
params['fmt'] = params['background'].split('.').pop()
path = '{}/{}'.format(path.split('/')[0], params['action'])
url = '{}/images/{}'.format(config.API_URL, path)
resp = requests.get(url, params=params, stream=True, auth=self.auth)
if resp.status_code != 200:
raise APIError(resp.text, resp.status_code)
return BytesIO(resp.content)

def transform_video(self, path, params={}):
url = '{}/videos/{}'.format(config.API_URL, path)
resp = requests.get(url, params=params, auth=self.auth)
if resp.status_code != 200:
raise APIError(resp.text, resp.status_code)
return resp.json()


class Abraia(Client):
Expand Down
132 changes: 0 additions & 132 deletions abraia/client.py

This file was deleted.

83 changes: 79 additions & 4 deletions tests/test_abraia.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,85 @@
import pytest

from io import BytesIO

from abraia import Abraia, Client, APIError
from abraia import Abraia, APIError

abraia = Abraia()
userid = abraia.load_user()['id']
filename = 'tiger.jpg'


def test_load_user():
"""Test an API call to load user info"""
user = abraia.load_user()
assert isinstance(user, dict)


def test_list_files():
"""Test an API call to list stored files and folders"""
files, folders = abraia.list_files(userid+'/')
assert isinstance(files, list)
assert isinstance(folders, list)


def test_upload_remote():
"""Tests an API call to upload a remote file"""
url = 'https://api.abraia.me/files/demo/birds.jpg'
resp = abraia.upload_remote(url, userid+'/')
assert resp['name'] == 'birds.jpg'


def test_upload_file():
"""Tests an API call to upload a local file"""
resp = abraia.upload_file(os.path.join('images', filename), userid+'/')
assert resp['name'] == 'tiger.jpg'


def test_move_file():
"""Test an API call to move a stored file"""
abraia.move_file(os.path.join(userid, filename),
userid + '/test/tiger.jpg')
resp = abraia.move_file(userid + '/test/tiger.jpg',
os.path.join(userid, filename))
assert resp['name'] == 'tiger.jpg'


def test_download_file():
"""Tests an API call to download an stored file"""
resp = abraia.download_file(os.path.join(userid, 'tiger.jpg'))
assert isinstance(resp, BytesIO)


def test_load_metadata():
"""Tests an API call to load metadata from an stored file"""
resp = abraia.load_metadata(os.path.join(userid, 'tiger.jpg'))
assert resp['MIMEType'] == 'image/jpeg'
# assert resp['ImageSize'] == '1920x1271'


def test_analyze_image():
"""Tests an API call to analyze an image"""
resp = abraia.analyze_image(os.path.join(userid, 'tiger.jpg'), {'ar': 1})
assert isinstance(resp, dict)


def test_transform_image():
"""Test an API call to transform an image"""
resp = abraia.transform_image(os.path.join(
userid, 'tiger.jpg'), {'width': 333})
assert isinstance(resp, BytesIO)


def test_transform_video():
"""Test an API call to transform a video"""
resp = abraia.transform_video(os.path.join(
userid, 'videos/bigbuckbunny.mp4'), {'format': 'jpg'})
assert isinstance(resp, dict)


def test_remove_file():
"""Test an API call to remove an stored file"""
resp = abraia.remove_file(os.path.join(userid, 'tiger.jpg'))
assert resp['name'] == 'tiger.jpg'


def test_list():
Expand All @@ -19,15 +94,15 @@ def test_list():
def test_from_file():
"""Tests an API call to upload a local file"""
resp = abraia.from_file('images/tiger.jpg')
assert isinstance(resp, Client)
assert isinstance(resp, Abraia)
assert resp.path.endswith('tiger.jpg')


def test_from_url():
"""Test an API call to upload a remote file"""
url = 'https://upload.wikimedia.org/wikipedia/commons/f/f1/100_m_final_Berlin_2009.JPG'
source = abraia.from_url(url)
assert isinstance(source, Client)
assert isinstance(source, Abraia)
assert source.path.endswith('100_m_final_Berlin_2009.JPG')


Expand Down
Loading

0 comments on commit ad5aec2

Please sign in to comment.