From 5984370a72d448b07d62ed8f7e20b4dffe30339a Mon Sep 17 00:00:00 2001 From: Brad Spencer Date: Sat, 4 Jun 2022 23:15:41 -0300 Subject: [PATCH] Add a --preview option You can use this option to see if you like the output before you spend time computing the actual prime number. --- src/primify/base.py | 37 ++++++++++++++++++++++++------------- src/primify/cli.py | 9 ++++++++- 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/src/primify/base.py b/src/primify/base.py index 5134da60..f0b08dab 100644 --- a/src/primify/base.py +++ b/src/primify/base.py @@ -146,7 +146,10 @@ def quantized_image_to_number(image: Image.Image) -> ImageNumber: return ImageNumber(value=int(digits), image_width=image.width) - def get_prime(self) -> ImageNumber: + def get_prime( + self, + preview: False + ) -> ImageNumber: with console.status(f"Converting {self.image_path} into number."): quantized_image = PrimeImage.quantize_image(self.im) @@ -165,23 +168,31 @@ def get_prime(self) -> ImageNumber: with console.status("Searching for a similar looking prime."): - # initiate helping prime finder. Much faster than just using nextprime() - n_processes = max( - 1, mp.cpu_count() - 1 - ) # at least one core should remain free + # are we actually going to search? + if not preview: - console.log( - f"Initializing multi-process prime finder with {n_processes} workers." - ) - prime_finder = NextPrimeFinder( - value=image_number.value, n_workers=n_processes - ) - next_prime = prime_finder.find_next_prime() + # initiate helping prime finder. Much faster than just using nextprime() + n_processes = max( + 1, mp.cpu_count() - 1 + ) # at least one core should remain free + + console.log( + f"Initializing multi-process prime finder with {n_processes} workers." + ) + prime_finder = NextPrimeFinder( + value=image_number.value, n_workers=n_processes + ) + next_prime = prime_finder.find_next_prime() + + else: + # just use the original image number as a preview if we aren't + # searching for a prime + next_prime = image_number.value # turn result back into a formated number result = ImageNumber(next_prime, image_number.image_width) console.print(str(result), style="black on white") self.output_file_path.write_text(str(result)) - console.log(f"Saved prime to {self.output_file_path}!") + console.log(f"Saved {'preview' if preview else 'prime'} to {self.output_file_path}!") return result diff --git a/src/primify/cli.py b/src/primify/cli.py index 99c87795..3b19db3b 100644 --- a/src/primify/cli.py +++ b/src/primify/cli.py @@ -56,6 +56,13 @@ def parse_args(args): dest="output_file", ) + parser.add_argument( + "--preview", + "-n", + action="store_true", + help="Emit a preview number that is not prime." + ) + return parser.parse_args(args) @@ -73,7 +80,7 @@ def main(args): output_file_path=args.output_file, ) - a.get_prime() + a.get_prime(preview=args.preview) def run():