Last active
August 21, 2022 13:42
-
-
Save Miss-Inputs/0c2228629b967a4ec83fb6e72ba5cb43 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Copyright 2022 Megan Leet | |
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | |
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
import shutil | |
import subprocess | |
import sys | |
import tempfile | |
from collections.abc import Collection | |
from datetime import timedelta | |
from pathlib import Path | |
from time import perf_counter | |
from typing import Optional | |
from zipfile import ZipFile | |
import py7zr | |
from wand.exceptions import CorruptImageError, ImageError, WandRuntimeError, MissingDelegateError | |
from wand.image import Image # Supports more formats than Pillow | |
class DidNotOptimizeException(Exception): | |
pass | |
class OptimizationError(Exception): | |
pass | |
def format_byte_size(b: int) -> str: | |
if b > (1024 ** 3): | |
return f'{b / (1024 ** 3):.3g} GiB' | |
if b > (1024 ** 2): | |
return f'{b / (1024 ** 2):.3g} MiB' | |
if b > (1024): | |
return f'{b / 1024:.3g} KiB' | |
return f'{b} bytes' | |
def report(old_size: int, new_size: int) -> None: | |
print(f'Old size = {format_byte_size(old_size)}, new size = {format_byte_size(new_size)}') | |
print(f'Reduction: By {format_byte_size(old_size - new_size)}, to {new_size/old_size:.3%} of original') | |
def run_png_compression(path: Path, old_size: int, old_path: Optional[Path]=None, print_stuff: bool=True) -> int: | |
time_started = perf_counter() | |
#Since we are going to check the new size ourselves anyway, might as well suppress the messages | |
temp_optipng_path = Path(tempfile.gettempdir(), path.stem + '.optipng.png') | |
subprocess.check_call(['optipng', '-quiet', '-o7', '-fix', '-out', temp_optipng_path, path]) | |
optipng_size = temp_optipng_path.stat().st_size | |
if not optipng_size: | |
temp_optipng_path.unlink(missing_ok=True) | |
if old_path: #if we were converting a different format, never mind the converted file we're creating | |
path.unlink(missing_ok=True) | |
raise OptimizationError('New size was zero somehow') | |
#subprocess.check_call(['advpng', '-z4', path], stdout=subprocess.DEVNULL) #Not sure that one is worth doing actually | |
new_path = temp_optipng_path | |
new_size = optipng_size | |
temp_pngcrush_path = Path(tempfile.gettempdir(), path.stem + '.pngcrush.png') | |
try: | |
subprocess.check_call(['pngcrush', '-fix', '-brute', temp_optipng_path, temp_pngcrush_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) | |
#This seems to fail a bit too often, so if that happens just stick with optipng | |
pngcrush_size = temp_pngcrush_path.stat().st_size | |
except FileNotFoundError: | |
pngcrush_size = 0 | |
if not pngcrush_size: | |
temp_pngcrush_path.unlink(missing_ok=True) | |
else: | |
temp_optipng_path.unlink(missing_ok=True) | |
new_path = temp_pngcrush_path | |
new_size = pngcrush_size | |
if new_size >= old_size: | |
temp_optipng_path.unlink(missing_ok=True) | |
temp_pngcrush_path.unlink(missing_ok=True) | |
if old_path: | |
path.unlink(missing_ok=True) | |
raise DidNotOptimizeException(f'Old size was {format_byte_size(old_size)} but new size is {format_byte_size(new_size)}') | |
if print_stuff: | |
print(f'Optimized {path} in {timedelta(seconds=perf_counter() - time_started)}') | |
report(old_size, new_size) | |
path.unlink() | |
if old_path: | |
old_path.unlink() | |
shutil.move(new_path, path) | |
return new_size | |
def optimize_cbz(path: Path) -> int: | |
old_size = path.stat().st_size | |
time_started = perf_counter() | |
temp_dir = Path(tempfile.gettempdir(), path.name) | |
temp_dir.mkdir() | |
with ZipFile(path, 'r') as z: | |
#Flatten all inner subdirectories, so we don't use extractall | |
for info in z.infolist(): | |
basename = Path(info.filename).name | |
if info.is_dir() or basename == 'Thumbs.db': | |
continue | |
data = z.read(info) | |
temp_dir.joinpath(basename).write_bytes(data) | |
files = set(temp_dir.iterdir()) | |
count = len(files) | |
optimize_images(files, False) | |
new_path = path.with_suffix('.cb7') | |
with py7zr.SevenZipFile(new_path, 'w') as sevenzip: | |
#Well that's just fucking annoying, writeall() writes the directory | |
for f in files: | |
sevenzip.write(f, f.name) | |
#sevenzip.writeall(temp_dir) | |
shutil.rmtree(temp_dir, ignore_errors=True) | |
new_size = new_path.stat().st_size | |
if new_size >= old_size: | |
new_path.unlink(missing_ok=True) | |
raise DidNotOptimizeException(f'Old size was {format_byte_size(old_size)} but new size is {format_byte_size(new_size)}') | |
#Just want to _really_ make sure | |
with py7zr.SevenZipFile(new_path, 'r') as sevenzip: | |
new_count = len(sevenzip.files) | |
if new_count != count: | |
new_path.unlink(missing_ok=True) | |
raise OptimizationError(f'Something has gone wrong! cbz had {count} images but cb7 has {new_count}') | |
print(f'Optimized {path} to cb7 ({count} images) in {timedelta(seconds=perf_counter() - time_started)}') | |
report(old_size, new_size) | |
path.unlink(missing_ok=True) | |
return new_size | |
def optimize_image(path: Path, print_stuff: bool=True) -> int: | |
if path.is_dir(): | |
return optimize_images(set(path.iterdir()), print_stuff) | |
if path.suffix == '.cbz': | |
return optimize_cbz(path) | |
old_size = path.stat().st_size | |
with Image.ping(filename=path) as image: | |
image_format = image.format | |
if image_format in {'PSD', 'XCF', 'SVG', 'SVGZ', 'MVG', 'MSVG'}: | |
raise OptimizationError(f'Not messing with {image_format} even if we could') | |
if len(image.sequence) > 1: | |
raise OptimizationError(f'Not messing around with animated or multiple images (format = {image_format}, length = {len(image.sequence)}, animated = {image.animation})') | |
if image_format == 'JPEG': | |
if path.suffix not in {'.jpg', '.jpeg'}: | |
new_path = path.with_suffix('.jpg') | |
if new_path.exists(): | |
raise FileExistsError(f'Actually a JPEG, but not going to clobber {new_path}') | |
print(f'{path} is actually a JPEG, moving to {new_path}') | |
shutil.move(path, new_path) | |
path = new_path | |
#--stdout does not send an image if it does not result in a smaller image | |
time_started = perf_counter() | |
jpegopt_proc = subprocess.run(['jpegoptim', '-q', '--stdout', path], check=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) | |
new_image = jpegopt_proc.stdout | |
if new_image: | |
if print_stuff: | |
print(f'Optimized {path} in {timedelta(seconds=perf_counter() - time_started)}') | |
report(old_size, len(new_image)) | |
path.write_bytes(new_image) | |
return len(new_image) | |
raise DidNotOptimizeException('jpegoptim did not create a smaller image') | |
if image_format == 'PNG': | |
if path.suffix != '.png': | |
new_path = path.with_suffix('.png') | |
if new_path.exists(): | |
raise FileExistsError(f'Actually a PNG, but not going to clobber {new_path}') | |
print(f'{path} is actually a PNG, moving to {new_path}') | |
shutil.move(path, new_path) | |
path = new_path | |
return run_png_compression(path, old_size, print_stuff=print_stuff) | |
with Image(filename=path) as image: | |
with image.convert('png') as converted: | |
print(f'{path} is {image_format}, converting to PNG') | |
new_path = path.with_suffix('.png') | |
if new_path.exists(): | |
raise FileExistsError(f'Not going to clobber {new_path}') | |
converted.save(filename=new_path) | |
return run_png_compression(new_path, old_size, path, print_stuff=print_stuff) | |
def _get_size(path: Path) -> int: | |
return path.stat().st_size if path.is_file() else sum(_get_size(p) for p in path.iterdir()) | |
def optimize_images(paths: Collection[Path], print_stuff: bool=True) -> int: | |
time_started = perf_counter() | |
total_old_size = 0 | |
total_new_size = 0 | |
count = 0 | |
for path in paths: | |
old_size = _get_size(path) | |
total_old_size += old_size | |
count += 1 | |
try: | |
new_size = optimize_image(path, print_stuff) | |
if print_stuff: | |
print('-' * 10) | |
total_new_size += new_size | |
except DidNotOptimizeException: | |
total_new_size += old_size | |
except (OptimizationError, FileExistsError, CorruptImageError, WandRuntimeError, ImageError, MissingDelegateError, subprocess.CalledProcessError) as ex: | |
total_new_size += old_size | |
print(path, ex, file=sys.stderr) | |
if print_stuff: | |
print('-' * 10) | |
if print_stuff and total_old_size != total_new_size: | |
print(f'Optimized {count} images in {timedelta(seconds=perf_counter() - time_started)}') | |
report(total_old_size, total_new_size) | |
print('-' * 15) | |
return total_new_size | |
def main() -> None: | |
if len(sys.argv) == 2 and not Path(sys.argv[1]).is_dir(): | |
try: | |
optimize_image(Path(sys.argv[1])) | |
except DidNotOptimizeException: | |
sys.exit(1) | |
sys.exit(0) | |
paths = [Path(arg) for arg in sys.argv[1:]] | |
optimize_images(paths) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment