guetzli-recursively/guetzli_recursively.py

64 lines
1.9 KiB
Python
Raw Normal View History

2017-10-29 20:42:13 +01:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Libraries
import click
from os import path, walk, remove, rename
from imghdr import what
from subprocess import call
# Variables
TEMP_FILE = 'temp.jpg'
TYPES = ('jpeg',)
2018-01-05 16:28:24 +01:00
LIMIT_QUALITY = 84
2017-10-29 20:42:13 +01:00
@click.command()
2018-01-05 16:28:24 +01:00
@click.option(
'--quality',
default=100,
2018-01-05 16:57:04 +01:00
help='Quality >= {quality} [default 100].'.format(
2018-01-05 16:28:24 +01:00
quality=LIMIT_QUALITY
)
)
2017-10-29 20:42:13 +01:00
@click.argument('folder', type=click.Path(exists=True))
2018-01-05 16:28:24 +01:00
def run(quality, folder):
2017-10-29 20:42:13 +01:00
for dirpath, dirnames, files in walk(folder):
for name in files:
url = path.join(dirpath, name)
# Check type
2018-01-05 16:28:24 +01:00
if what(url) in TYPES or quality >= LIMIT_QUALITY:
2017-10-29 20:42:13 +01:00
# Get urls
click.echo(url)
url_out = path.join(folder, TEMP_FILE)
# Remove temp image
try:
remove(url_out)
except:
pass
# Execute guetzli
2018-01-05 16:28:24 +01:00
call(['guetzli', '--quality', str(quality), url, url_out])
2017-10-29 20:42:13 +01:00
# Print your have saved
size_source = path.getsize(url)
try:
size_out = path.getsize(url_out)
except:
size_out = size_source
size_acurate = 100 * size_out / size_source
# Check if it is cost effective to replace it
if size_acurate < 100:
# Remove source
try:
remove(url)
except:
pass
# Move temp to source
rename(url_out, url)
2018-01-05 16:28:24 +01:00
click.echo(
'Save ' + str(round(100 - size_acurate, 2)) + '%')
2017-10-29 20:42:13 +01:00
else:
click.echo('It is not necessary to optimize')
if __name__ == '__main__':
run()