From 8e69f70cf3b66db919aea4453ba5d2e4d5505291 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Sat, 28 Apr 2018 21:27:31 +0200 Subject: [PATCH] Implement processing of images on multiple threads at once --- imgrate.py | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/imgrate.py b/imgrate.py index 1fc127b..9ae7aa0 100755 --- a/imgrate.py +++ b/imgrate.py @@ -51,9 +51,11 @@ if __name__ == '__main__': from os import remove from sys import exit from signal import signal, SIGINT + from multiprocessing import Pool, cpu_count signal(SIGINT, lambda a, b: exit('\nExiting!')) + def parse_arguments(): ap = ArgumentParser(description='Find the best quality one among similar images.' 'Note: image dimensions should match!') @@ -65,21 +67,38 @@ if __name__ == '__main__': def run(args): - try: - ratings = {image: getattr(imgrate(image), args.method) for image in args.images} - except AttributeError: + if not hasattr(imgrate, args.method): exit('Invalid --method option!') + + ratings = calculate_all_ratings(args.images, args.method) maximum = max(ratings, key=ratings.get) - for rating in ratings.keys(): - if args.quiet: - print(ratings[rating]) - else: - maxmark = '*' if rating == maximum and len(ratings) > 1 else ' ' - print('{}imgrate("{}") = {}'.format(maxmark, rating, ratings[rating])) + fancy_print_ratings(ratings, args.quiet, maximum) if args.delete: [remove(image) for image in ratings if image != maximum] + def calculate_all_ratings(images, method): + ratings = [] + with Pool(processes=cpu_count()) as pool: + for image in images: + ratings.append((image, pool.apply_async(calculate_rating, (image, method)))) + + return {image: promise.get() for image, promise in ratings} + + + def calculate_rating(image, method): + return getattr(imgrate(image), method) + + + def fancy_print_ratings(ratings, quiet, maximum): + for rating in ratings.keys(): + if quiet: + print(ratings[rating]) + else: + maxmark = '*' if rating == maximum and len(ratings) > 1 else ' ' + print('{}imgrate("{}") = {}'.format(maxmark, rating, ratings[rating])) + + run(parse_arguments())