Skip to content

Commit

Permalink
Update to the new serverless API
Browse files Browse the repository at this point in the history
  • Loading branch information
jrrodri committed Jul 20, 2018
1 parent 6d7a73c commit f10f72d
Show file tree
Hide file tree
Showing 7 changed files with 80 additions and 46 deletions.
15 changes: 8 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
[![PyPI version](https://badge.fury.io/py/abraia.svg)](https://badge.fury.io/py/abraia)
[![Build Status](https://travis-ci.org/abraia/abraia-python.svg)](https://travis-ci.org/abraia/abraia-python)
[![Coverage Status](https://coveralls.io/repos/github/abraia/abraia-python/badge.svg?branch=develop)](https://coveralls.io/github/abraia/abraia-python?branch=develop)

Expand All @@ -21,10 +22,10 @@ abraia optimize --width 800 --height 400 https://images.pexels.com/photos/700948

![Optimized and smart cropped skater](./images/skater.jpg)

The example takes an [image by Willian Was from Pexels](https://www.pexels.com/photo/f-s-flip-700948/)
with a size of 4865x3321 pixels and a weight of 10.1MB and automatically
generates a header of 800x400 pixels cropping, resizing, and optimizing the
image to directly be used on Web.
The example takes a 10.1MB [image by Willian Was from Pexels](https://www.pexels.com/photo/f-s-flip-700948/)
with a size of 4865x3321 pixels and automatically generates a 94.4kB header of
800x400 pixels, cropping, resizing, and optimizing the image to directly be
used on Web.

## Installation

Expand Down Expand Up @@ -56,9 +57,9 @@ abraia configure

### API usage:

The fluent design of the Abraia API makes easy to compress and transform
images. You just need to define the source of the image, the transformation
operation, and the sink for the resultant image.
Abraia API makes easy to compress and transform images. You just need to define
the source of the image, the transformation operation, and the sink for the
resultant image.

```python
import abraia
Expand Down
35 changes: 21 additions & 14 deletions abraia/abraia.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ def from_store(path):
return Client().from_store(path)


def list():
return Client().list()
def list(path=''):
return Client().list(path=path)


def remove(path):
Expand All @@ -48,7 +48,7 @@ def __init__(self):
self.params = {}

def from_file(self, file):
url = '{}/images'.format(config.API_URL)
url = '{}/images/'.format(config.API_URL)
file = file if isinstance(file, BytesIO) else open(file, 'rb')
files = dict(file=file)
resp = session.post(url, files=files)
Expand Down Expand Up @@ -86,20 +86,13 @@ def resize(self, width=None, height=None):
self.params['h'] = height
return self

def analyze(self):
url = '{}/analysis/{}'.format(config.API_URL, self.path)
resp = session.get(url, params=self.params)
if resp.status_code != 200:
raise APIError('GET {} {}'.format(url, resp.status_code))
return resp.json()

def list(self):
url = '{}/images'.format(config.API_URL)
def list(self, path=''):
url = '{}/images/{}'.format(config.API_URL, path)
resp = session.get(url)
if resp.status_code != 200:
raise APIError('GET {} {}'.format(url, resp.status_code))
files = resp.json()['files']
return files
resp = resp.json()
return resp['files'], resp['folders']

def delete(self, path):
url = '{}/images/{}'.format(config.API_URL, path)
Expand All @@ -108,6 +101,20 @@ def delete(self, path):
raise APIError('DELETE {} {}'.format(url, resp.status_code))
return resp.json()

def analyze(self):
url = '{}/analysis/{}'.format(config.API_URL, self.path)
resp = session.get(url, params=self.params)
if resp.status_code != 200:
raise APIError('GET {} {}'.format(url, resp.status_code))
return resp.json()

def aesthetics(self):
url = '{}/aesthetics/{}'.format(config.API_URL, self.path)
resp = session.get(url, params=self.params)
if resp.status_code != 200:
raise APIError('GET {} {}'.format(url, resp.status_code))
return resp.json()


class APIError(Exception):
def __init__(self, message):
Expand Down
Binary file modified images/cropped.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified images/optimized.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified images/resized.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
39 changes: 28 additions & 11 deletions scripts/abraia
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -100,22 +100,28 @@ def process_analyze(args):
print(result)


def process_list():
files = abraia.list()
files = [(f['date'], f['size'], f['name']) for f in files]
txt = '\n'.join(['{} {:>7} {}'.format(
datetime.fromtimestamp(f[0]), *f[1:]) for f in files])
def process_aesthetics(args):
result = abraia.from_file(args['path']).aesthetics()
print(result)


def process_list(path):
files, folders = abraia.list(path=path)
txt = '\n'.join(['{:>28} {}/'.format(
'', f['name']) for f in folders]) + '\n'
txt += '\n'.join(['{} {:>7} {}'.format(
datetime.fromtimestamp(f['date']), f['size'], f['name']) for f in files])
txt += '\ntotal {}'.format(len(files))
print(txt)


def process_remove(args):
print(abraia.remove(args['path']))
def process_remove(path):
print(abraia.remove(path))


def parse_input():
parser = argparse.ArgumentParser(description='Abraia image optimization tool')
parser.add_argument('-V', '--version', action='version', version='0.2.13')
parser.add_argument('-V', '--version', action='version', version='0.3.0')
subparser = parser.add_subparsers(dest='command')
subparser.add_parser('configure', help='configure the access keys')
parser_optimize = subparser.add_parser('optimize', help='optimize an image or a directory of images')
Expand All @@ -126,9 +132,12 @@ def parse_input():
parser_optimize.add_argument('dest', nargs='?', help='destination directory or image path')
parser_analyze = subparser.add_parser('analyze', help='analyze an image or a diretory of images')
parser_analyze.add_argument('path', nargs='?', help='image path or directory to process')
parser_aesthetics = subparser.add_parser('aesthetics', help='predict aesthetics of an image or a diretory of images')
parser_aesthetics.add_argument('path', nargs='?', help='image path or directory to process')
parser_store = subparser.add_parser('store', help='work with the cloud stored files')
subparser_store = parser_store.add_subparsers(dest='subcommand')
subparser_store.add_parser('ls', help='list stored files')
parser_list = subparser_store.add_parser('ls', help='list stored files')
parser_list.add_argument('path', nargs='?', help='folder path to list')
parser_remove = subparser_store.add_parser('rm', help='remove a stored file')
parser_remove.add_argument('path', nargs='?', help='image path to remove')
args = vars(parser.parse_args())
Expand All @@ -144,6 +153,10 @@ def parse_input():
if args['path'] is None:
parser_analyze.print_help()
sys.exit()
elif args['command'] == 'aesthetics':
if args['path'] is None:
parser_aesthetics.print_help()
sys.exit()
elif args['command'] == 'store':
if args['subcommand'] is None:
parser_store.print_help()
Expand All @@ -162,11 +175,15 @@ def process_input(args):
process_batch(args)
elif args['command'] == 'analyze':
process_analyze(args)
elif args['command'] == 'aesthetics':
process_aesthetics(args)
elif args['command'] == 'store':
if args['subcommand'] == 'ls':
process_list()
path = args.get('path')
path = '' if path is None else path
process_list(path)
elif args['subcommand'] == 'rm':
process_remove(args)
process_remove(args['path'])


if __name__ == "__main__":
Expand Down
37 changes: 23 additions & 14 deletions tests/test_abraia.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@
from abraia import abraia


def test_list():
"""Test an API call to list stored files and folders"""
files, folders = abraia.list()
assert isinstance(files, list)
assert isinstance(folders, list)


def test_from_file():
"""Tests an API call to upload a local file"""
source = abraia.from_file(os.path.join(
Expand Down Expand Up @@ -32,12 +39,23 @@ def test_resize():
output = os.path.join(
os.path.dirname(__file__), '../images/resized.jpg')
source = abraia.from_file(os.path.join(
os.path.dirname(__file__), '../images/tiger.jpg'))
os.path.dirname(__file__), '../images/lion.jpg'))
resized = source.resize(width=500)
resized.to_file(output)
assert os.path.isfile(output)


def test_smartcrop():
"""Test an API call to smartcrop an image"""
output = os.path.join(
os.path.dirname(__file__), '../images/cropped.jpg')
source = abraia.from_file(os.path.join(
os.path.dirname(__file__), '../images/lion.jpg'))
cropped = source.resize(width=333, height=333)
cropped.to_file(output)
assert os.path.isfile(output)


def test_analyze():
"""Test an API call to analyze an image"""
source = abraia.from_file(os.path.join(
Expand All @@ -46,21 +64,12 @@ def test_analyze():
assert isinstance(json, dict)


def test_list():
"""Test an API call to list stored files"""
files = abraia.list()
assert isinstance(files, list)


def test_smartcrop():
"""Test an API call to smartcrop an image"""
output = os.path.join(
os.path.dirname(__file__), '../images/cropped.jpg')
def test_aesthetics():
"""Test an API call to predict image aeshetics"""
source = abraia.from_file(os.path.join(
os.path.dirname(__file__), '../images/lion.jpg'))
cropped = source.resize(width=333, height=333)
cropped.to_file(output)
assert os.path.isfile(output)
json = source.aesthetics()
assert isinstance(json, dict)


# def test_exception():
Expand Down

0 comments on commit f10f72d

Please sign in to comment.