Created
November 16, 2020 21:46
-
-
Save cnovel/040469800bbbcc15956eccc5c8ad72fa to your computer and use it in GitHub Desktop.
Continuous compression script for CaesiumCLT using Python
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
import time | |
import datetime | |
import logging | |
import subprocess | |
import os | |
# --- Parameters for the compression --- | |
path_to_caesiumclt_exe = "D:\\Documents\\Caesium\\caesiumclt.exe" | |
folder_to_watch = "D:\\Images\\ToCompress" | |
compress_existing_images = False # Can be True or False | |
compression_factor = 80 # 0 = lossless, 80 most common | |
wait_time_between_checks = 30 # seconds | |
# --- Don't modify anything beyond this point --- | |
logging.getLogger().setLevel(logging.INFO) | |
log_format = "(%(asctime)s)[%(levelname)s] %(message)s" | |
logging.basicConfig(format=log_format) | |
logging.captureWarnings(True) | |
def compress_images(pics_to_compress): | |
for f in pics_to_compress: | |
cmd_line = '{} -q {} -e -o "{}" "{}"'.format(path_to_caesiumclt_exe, compression_factor, folder_to_watch, f) | |
logging.info("Compressing {}...".format(f)) | |
res = subprocess.run(cmd_line, capture_output=True) | |
logging.info(res.stdout.decode()) | |
if res.returncode != 0: | |
logging.error("Compression of {} failed with code {}".format(f, res.returncode)) | |
else: | |
logging.info("Compression successful!") | |
def get_images_since(last_mod_time): | |
imgs = [] | |
for f in os.listdir(folder_to_watch): | |
full_path = os.path.join(folder_to_watch, f) | |
if full_path.lower().endswith('jpg')\ | |
and full_path not in last_compressed_pics \ | |
and datetime.datetime.fromtimestamp(os.stat(full_path).st_ctime) > last_mod_time: | |
imgs.append(full_path) | |
return imgs | |
def compress_all_images_in_folder(): | |
logging.info("Compressing all images in {}".format(folder_to_watch)) | |
images = [] | |
for f in os.listdir(folder_to_watch): | |
if f.lower().endswith('jpg'): | |
full_path = os.path.join(folder_to_watch, f) | |
images.append(full_path) | |
compress_images(images) | |
return images | |
first_pass = True | |
last_update = datetime.datetime.now() | |
last_compressed_pics = [] | |
while True: | |
if first_pass and compress_existing_images: | |
now = datetime.datetime.now() | |
last_compressed_pics = compress_all_images_in_folder() | |
first_pass = False | |
continue | |
now = datetime.datetime.now() | |
files = get_images_since(last_update) | |
logging.info("{} images to compress".format(len(files))) | |
compress_images(files) | |
last_compressed_pics = files | |
last_update = now | |
time.sleep(wait_time_between_checks) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment