guetzli-recursively/guetzli_recursively.py

72 lines
2.2 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(
2020-07-14 23:39:09 +02:00
'--quality',
default=100,
help='Quality >= {quality} [default 100].'.format(
quality=LIMIT_QUALITY
)
)
@click.option(
'--memlimit',
default=28000,
help='Memory limit in MB. Guetzli will fail if unable to stay under the limit. Default is 28000 MB'
2018-01-05 16:28:24 +01:00
)
2017-10-29 20:42:13 +01:00
@click.argument('folder', type=click.Path(exists=True))
2020-07-14 23:39:09 +02:00
def run(quality, memlimit, 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
2020-07-14 23:39:09 +02:00
args = ['guetzli', '--quality',
str(quality), '--memlimit', str(memlimit), url, url_out]
print(' '.join(args))
call(args)
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(
2020-07-14 23:39:09 +02:00
'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()