Skip to content

Commit

Permalink
Update cli commands and options
Browse files Browse the repository at this point in the history
  • Loading branch information
jrrodri committed Nov 23, 2024
1 parent 80bc9b9 commit cba42bd
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 95 deletions.
68 changes: 35 additions & 33 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,73 +137,75 @@ show_image(img)

The Abraia CLI provides access to the Abraia Cloud Platform through the command line. It makes simple to manage your files and enables bulk image editing capabilities. It provides and easy way to resize, convert, and compress your images - JPEG, WebP, or PNG -, and get them ready to publish on the web. Moreover, you can automatically remove the background, upscale, or anonymize your images in bulk.

To compress an image you just need to specify the input and output paths for the image:
### Remove background

Automatically remove images background and make them transparent in bulk.

```sh
abraia convert images/birds.jpg images/birds_o.jpg
abraia editing removebg "*.jpg"
```

![Image compressed from url](https://github.com/abraia/abraia-multiple/raw/master/images/birds_o.jpg)
![bolt transparent background](https://github.com/abraia/abraia-multiple/raw/master/images/usain-bolt.png)

### Upscale images

To resize and optimize and image maintaining the aspect ratio is enough to specify the `width` or the `height` of the new image:
Scale up and enhance images in bulk, doubling the size and preserving quality.

```sh
abraia convert --width 500 images/usain-bolt.jpeg images/usaint-bolt_500.jpeg
abraia editing upscale "*.jpg"
```

![Usain Bolt resized](https://github.com/abraia/abraia-multiple/raw/master/images/usain-bolt_500.jpeg)
![upscaled cat](https://github.com/abraia/abraia-multiple/raw/master/images/cat-upscaled.jpg)

You can also automatically change the aspect ratio specifying both `width` and `height` parameters and setting the resize `mode` (pad, crop, thumb):
### Anonymize images

Anonymize images in bulk, automatically blurring faces, car license plates, and removing metadata.

```sh
abraia convert --width 333 --height 333 --mode pad images/lion.jpg images/lion_333x333.jpg
abraia convert --width 333 --height 333 images/lion.jpg images/lion_333x333.jpg
```
abraia editing anonymize "*.jpg"
````

![Image lion smart cropped](https://github.com/abraia/abraia-multiple/raw/master/images/lion_333x333_pad.jpg)
![Image lion smart cropped](https://github.com/abraia/abraia-multiple/raw/master/images/lion_333x333.jpg)
![people and car anonymized](https://github.com/abraia/abraia-multiple/raw/master/images/people-car-anonymized.jpg)

So, you can automatically resize all the images in a specific folder preserving the aspect ration of each image just specifying the target `width` or `height`:
### Convert images

Compress images in bulk specifying the input glob pattern or folder:

```sh
abraia convert --width 300 [path] [dest]
abraia editing convert "images/bird*.jpg"
```

Or, automatically pad or crop all the images contained in the folder specifying both `width` and `height`:
![Image compressed from url](https://github.com/abraia/abraia-multiple/raw/master/images/birds_o.jpg)

Resize and optimize images maintaining the aspect ratio just specifying the `width` or the `height` of the new image:

```sh
abraia convert --width 300 --height 300 --mode crop [path] [dest]
abraia editing convert images/usain-bolt.jpeg --width 500
```

### Remove background
![Usain Bolt resized](https://github.com/abraia/abraia-multiple/raw/master/images/usain-bolt_500.jpeg)

Automatically remove images background and make them transparent in bulk.
You can also automatically change the aspect ratio specifying both `width` and `height` parameters and setting the resize `mode` (pad, crop, thumb):

```sh
abraia editing "*.jpg" --mode removebg
abraia editing convert images/lion.jpg --width 333 --height 333 --mode pad
abraia editing convert images/lion.jpg --width 333 --height 333
```

![bolt transparent background](https://github.com/abraia/abraia-multiple/raw/master/images/usain-bolt.png)

### Upscale images
![Image lion smart cropped](https://github.com/abraia/abraia-multiple/raw/master/images/lion_333x333_pad.jpg)
![Image lion smart cropped](https://github.com/abraia/abraia-multiple/raw/master/images/lion_333x333.jpg)

Scale up and enhance images in bulk, doubling the size and preserving quality.
So, you can automatically resize all the images in a specific folder preserving the aspect ration of each image just specifying the target `width` or `height`:

```sh
abraia editing "*.jpg" --mode upscale
abraia editing convert [src] --width 300
```

![upscaled cat](https://github.com/abraia/abraia-multiple/raw/master/images/cat-upscaled.jpg)

### Anonymize images

Anonymize images in bulk, automatically blurring faces, car license plates, and removing metadata.
Or, automatically pad or crop all the images contained in the folder specifying both `width` and `height`:

```sh
abraia editing "*.jpg" --mode anonymize
````

![people and car anonymized](https://github.com/abraia/abraia-multiple/raw/master/images/people-car-anonymized.jpg)
abraia editing convert [src] --width 300 --height 300 --mode crop
```

## Hyperspectral image analysis toolbox

Expand Down
2 changes: 2 additions & 0 deletions abraia/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
from dotenv import load_dotenv
load_dotenv()

__version__ = '0.20.0'

from . import config
from .client import Abraia, APIError

Expand Down
Binary file modified images/screenshot.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
134 changes: 73 additions & 61 deletions scripts/abraia
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ from concurrent.futures import ProcessPoolExecutor
from abraia import config
from abraia import Abraia
from abraia import APIError
from abraia import __version__


abraia = Abraia()
Expand Down Expand Up @@ -46,17 +47,18 @@ def input_files(src):


@click.group('abraia')
@click.version_option('0.19.1')
@click.version_option(__version__)
def cli():
"""Abraia CLI tool"""
pass


@cli.command()
def configure():
"""Configure the abraia api key"""
"""Configure the abraia api key."""
# click.echo('Go to [' + click.style('https://abraia.me/console/', fg='green') + '] to see your account information\n')
click.echo('Go to [' + click.style('https://abraia.me/console/', fg='green') + '] to get your user id and key\n')
try:
click.echo('Go to [' + click.style('https://abraia.me/console/', fg='green') + '] to get your user id and key\n')
abraia_id, abraia_key = config.load()
abraia_id = click.prompt('Abraia Id', default=abraia_id)
abraia_key = click.prompt('Abraia Key', default=abraia_key)
Expand All @@ -65,13 +67,6 @@ def configure():
pass


@cli.command()
def info():
"""Show user account information"""
click.echo('abraia, version 0.1890\n')
click.echo('Go to [' + click.style('https://abraia.me/console/', fg='green') + '] to see your account information\n')


def convert_file(src, dest, args):
if src.startswith('http'):
path, args['url'] = src, src
Expand All @@ -81,31 +76,6 @@ def convert_file(src, dest, args):
return dest


@cli.command()
@click.option('--width', help='Resize to specified width', type=int)
@click.option('--height', help='Resize to specified height', type=int)
@click.option('--mode', help='Select the resize mode', type=click.Choice(['pad', 'crop', 'thumb']))
@click.option('--format', help='Convert to specified image format', type=click.Choice(['jpeg', 'png', 'webp']))
@click.option('--action', help='Apply an action template', type=click.Path())
@click.argument('src')
def convert(src, width, height, mode, format, action):
"""Convert an image or set of images"""
try:
args = {'width': width, 'height': height, 'mode': mode, 'format': format, 'action': action, 'quality': 'auto'}
filenames = input_files(src)
dests = []
dirname = src if os.path.isdir(src) else os.path.dirname(src)
for filename in filenames:
if filename.startswith('http'):
filename = os.path.basename(urlparse(filename).path) or 'screenshot.png'
path, ext = os.path.splitext(os.path.relpath(filename, dirname))
oext = format if format is not None else (ext and ext[1:])
dests.append(os.path.join('output', f"{path}.{oext}"))
process_map(convert_file, filenames, dests, itertools.repeat(args), desc="Converting")
except APIError as error:
echo_error(error)


def editing_file(src, dest, mode):
output = f"export/{os.path.basename(dest)}"
path = abraia.upload_file(src, 'batch/')
Expand All @@ -118,46 +88,72 @@ def editing_file(src, dest, mode):
return abraia.download_file(output, dest)


@cli.command()
@click.option('--mode', help='Select the edit mode', type=click.Choice(['removebg', 'upscale', 'anonymize']), default='removebg')
@click.argument('src')
def editing(src, mode):
"""Edit an image or set of images"""
def editing_files(src, mode, desc="Editing"):
try:
inputs = input_files(src)
ext = 'png' if mode == 'removebg' else 'jpg'
dirname = src if os.path.isdir(src) else os.path.dirname(src)
paths = [os.path.splitext(os.path.relpath(src, dirname))[0] for src in inputs]
outputs = [os.path.join('output', f"{path}.{ext}") for path in paths]
process_map(editing_file, inputs, outputs, itertools.repeat(mode), desc="Editing")
process_map(editing_file, inputs, outputs, itertools.repeat(mode), desc=desc)
except APIError as error:
echo_error(error)


@cli.command()
@click.option('--remove', help='Remove file metadata', is_flag=True)
@cli.group('editing')
def cli_editing():
"""Convert and edit images in bulk."""
pass


@cli_editing.command()
@click.option('--width', help='Resize to specified width', type=int)
@click.option('--height', help='Resize to specified height', type=int)
@click.option('--mode', help='Select the resize mode', type=click.Choice(['pad', 'crop', 'thumb']))
@click.option('--format', help='Convert to specified image format', type=click.Choice(['jpeg', 'png', 'webp']))
@click.argument('src')
def metadata(src, remove):
"""Load and remove file metadata"""
def convert(src, width, height, mode, format):
"""Convert, resize, and optimize images in bulk."""
try:
path = abraia.upload_file(src, 'batch/')
if remove:
print(abraia.remove_metadata(path))
buffer = abraia.download_file(path)
with open(src+'.output', 'wb') as f:
f.write(buffer.getvalue())
else:
meta = abraia.load_metadata(path)
# metadata = abraia.load_metadata('usain.jpg')
# abraia.save_json('usain.json', metadata)
click.echo(json.dumps(meta, indent=2))
args = {'width': width, 'height': height, 'mode': mode, 'format': format, 'quality': 'auto'}
filenames = input_files(src)
dests = []
dirname = src if os.path.isdir(src) else os.path.dirname(src)
for filename in filenames:
if filename.startswith('http'):
filename = os.path.basename(urlparse(filename).path) or 'screenshot.png'
path, ext = os.path.splitext(os.path.relpath(filename, dirname))
oext = format if format is not None else (ext and ext[1:])
dests.append(os.path.join('output', f"{path}.{oext}"))
process_map(convert_file, filenames, dests, itertools.repeat(args), desc="Converting")
except APIError as error:
echo_error(error)


@cli_editing.command()
@click.argument('src')
def removebg(src):
"""Remove the images background to make them transparent."""
editing_files(src, 'removebg', desc="Removing")


@cli_editing.command()
@click.argument('src')
def upscale(src):
"""Upscale and enhance images increasing the resolution."""
editing_files(src, 'upscale', desc="Upscaling")


@cli_editing.command()
@click.argument('src')
def anonymize(src, ):
"""Anonymize image blurring faces and car license plates."""
editing_files(src, 'anonymize', desc="Anonymizing")


@cli.group('files')
def cli_files():
"""Commands related to cloud storage"""
"""Commands related to cloud storage."""
pass


Expand All @@ -184,7 +180,7 @@ def format_output(files, folders=[]):
@cli_files.command()
@click.argument('folder', required=False, default='')
def list(folder):
"""List files in abraia"""
"""List files in abraia."""
try:
files, folders = abraia.list_files(folder)
click.echo(format_output(files, folders))
Expand All @@ -196,7 +192,7 @@ def list(folder):
@click.argument('src', type=click.Path())
@click.argument('folder', required=False, default='')
def upload(src, folder):
"""Upload files to abraia"""
"""Upload files to abraia."""
try:
files = input_files(src)
process_map(upload_file, files, itertools.repeat(folder), desc="Uploading")
Expand All @@ -208,7 +204,7 @@ def upload(src, folder):
@click.argument('path')
@click.argument('folder', required=False, default='')
def download(path, folder):
"""Download files from abraia"""
"""Download files from abraia."""
try:
files = abraia.list_files(path)[0]
paths = [file['path'] for file in files]
Expand All @@ -220,7 +216,7 @@ def download(path, folder):
@cli_files.command()
@click.argument('path')
def remove(path):
"""Remove files from abraia"""
"""Remove files from abraia."""
try:
files = abraia.list_files(path)[0]
click.echo(format_output(files))
Expand All @@ -231,6 +227,22 @@ def remove(path):
echo_error(error)


@cli_files.command()
@click.option('--remove', help='Remove file metadata', is_flag=True)
@click.argument('path')
def metadata(path, remove):
"""Load or remove file metadata."""
try:
if remove:
abraia.remove_metadata(path)
meta = abraia.load_metadata(path)
# metadata = abraia.load_metadata('usain.jpg')
# abraia.save_json('usain.json', metadata)
click.echo(json.dumps(meta, indent=2))
except APIError as error:
echo_error(error)


if __name__ == '__main__':
if not abraia.userid:
configure()
Expand Down
4 changes: 3 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

from setuptools import setup, find_packages

from abraia import __version__

with open('README.md') as f:
long_description = f.read()

Expand All @@ -17,7 +19,7 @@

setup(
name='abraia',
version='0.19.1',
version=__version__,
description='Abraia Python SDK',
long_description=long_description,
long_description_content_type='text/markdown',
Expand Down

0 comments on commit cba42bd

Please sign in to comment.