Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update bulk image conversion script to support multiple formats #226

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 73 additions & 38 deletions scripts/hooks/convert_images_hook.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,56 @@
#!/usr/bin/env python3
"""Convert png images within the repository."""

"""Convert png and other images within the repository."""

import argparse
import os
import sys
from PIL import Image

from scripts.utils.image_utils import convert_image, get_size_in_kb, get_size_reduction
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
Anushlinux marked this conversation as resolved.
Show resolved Hide resolved
from utils.image_utils import get_size_in_kb, get_size_reduction

def convert_image(input_path, output_path, output_format):
with Image.open(input_path) as img:
if output_format == 'JPG':
output_format = 'JPEG'
img.save(output_path, output_format)

def convert_images_in_tree(args):
filenames = args.get("filenames", None)
trigger_size = args.get("trigger_size", None)
def bulk_convert(input_dir, output_dir, output_format, trigger_size):
os.makedirs(output_dir, exist_ok=True)
converted_count = 0
for image_path in filenames:
old_size = get_size_in_kb(image_path)
if old_size <= trigger_size:
continue

# Note: the pre-commit hook takes care of ensuring only image files are passed here.
new_image_path = convert_image(image_path)
new_size = get_size_in_kb(new_image_path)
if new_size <= old_size:
print(
f"Converted png to jpg: {image_path}: {new_size:.2f}KB {get_size_reduction(old_size, new_size)}"
)
converted_count += 1
else:
print(
f"Skipping conversion for {image_path} as size is more than before ({new_size:.2f} KB > {old_size:.2f} KB)"
)
os.remove(new_image_path)

return converted_count
for root, _, files in os.walk(input_dir):
for filename in files:
input_path = os.path.join(root, filename)
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.tif')):
old_size = get_size_in_kb(input_path)

name, ext = os.path.splitext(filename)
output_path = os.path.join(output_dir, f"{name}.{output_format.lower()}")

convert_image(input_path, output_path, output_format.upper())
new_size = get_size_in_kb(output_path)

if old_size > trigger_size and new_size <= old_size:
print(
f"Converted {filename} to {output_format.upper()}: {new_size:.2f}KB "
f"{get_size_reduction(old_size, new_size)}"
)
converted_count += 1
elif old_size <= trigger_size:
print(
f"Converted {filename} to {output_format.upper()}: {new_size:.2f}KB"
)
else:
print(
f"Skipping conversion for {filename} as size increased "
f"({new_size:.2f} KB > {old_size:.2f} KB)"
)
# os.remove(output_path)

return converted_count

def parse_args():
# construct the argument parse and parse the arguments
argparser = argparse.ArgumentParser()

argparser.add_argument(
Expand All @@ -46,31 +61,51 @@ def parse_args():
dest="trigger_size",
help="Specify minimum file size to trigger the hook.",
)
argparser.add_argument(
Anushlinux marked this conversation as resolved.
Show resolved Hide resolved
"--input-dir",
default=None,
required=False,
help="Specify the input directory for bulk conversion.",
)
argparser.add_argument(
"--output-dir",
default=None,
required=True,
help="Specify the output directory for converted files.",
)
argparser.add_argument(
"--format",
choices=['jpg', 'jpeg', 'png'],
default='jpeg',
help="Specify the output format (default: jpeg).",
)
argparser.add_argument("filenames", nargs="*", help="Files to optimize.")

(
args,
unknown,
) = argparser.parse_known_args()

args = vars(args)
args, unknown = argparser.parse_known_args()

if len(unknown) > 0:
argparser.print_help()
raise Exception(f"\nError: Unknown arguments: {unknown}")
return args

return vars(args)

if __name__ == "__main__":
args = parse_args()

converted_count = convert_images_in_tree(args)
trigger_size = args["trigger_size"]
output_dir = args["output_dir"]
output_format = args["format"]

if args.get("input_dir"):
converted_count = bulk_convert(args["input_dir"], output_dir, output_format, trigger_size)
else:
print("No input directory specified. Please provide an input directory.")
exit(1)

if converted_count > 0:
print(
f"Note: {converted_count} png images above {trigger_size}KB were converted to jpg.\nPlease manually remove the png files and add your commit again."
f"Note: {converted_count} images above {trigger_size}KB were converted to {output_format.upper()}.\n"
)
exit(1)
else:
# print("All sample images are jpgs. Commit accepted.")
exit(0)
print("All images are optimized. Commit accepted.")
exit(0)