From 4ca0ba29dcf70bc7882ae761ac8a90bd716b6e90 Mon Sep 17 00:00:00 2001 From: palewire Date: Sat, 23 Jul 2022 05:10:46 -0700 Subject: [PATCH] Output a JSON of the images in a mosaic JPG. For potential future use in #199 --- newshomepages/mosaic.py | 12 ++++++++++-- newshomepages/utils.py | 7 +++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/newshomepages/mosaic.py b/newshomepages/mosaic.py index 4c63be7239c..5e02c4ae39e 100644 --- a/newshomepages/mosaic.py +++ b/newshomepages/mosaic.py @@ -1,3 +1,4 @@ +import json import math import random from pathlib import Path @@ -22,7 +23,10 @@ def jpg(input_dir: str, output_dir: str): # Get a list of images input_path = Path(input_dir) input_path.mkdir(parents=True, exist_ok=True) - image_paths = sorted(list(input_path.glob("*.jpg"))) + image_list = list(input_path.glob("*.jpg")) + image_paths = sorted( + image_list, key=lambda x: utils.get_site(x.stem)["name"].lower() + ) click.echo(f"{len(image_paths)} images discovered in {input_path}") # Set the output path @@ -34,7 +38,7 @@ def jpg(input_dir: str, output_dir: str): for i in range(slide_count): selected_images = [] for _x in range(n * n): - selected_images.append(image_paths.pop()) + selected_images.append(image_paths.pop(0)) size = (600, 388) shape = (n, n) @@ -62,6 +66,10 @@ def jpg(input_dir: str, output_dir: str): click.echo(f"Writing mosiac {i+1} to {output_path}") image.save(output_path / f"{i+1}.jpg", "JPEG") + # Write a JSON file out with the names of the images, for use in alt text, etc. + name_list = [utils.get_site(h.stem)["name"] for h in selected_images] + json.dump(name_list, open(output_path / f"{i+1}.json", "w"), indent=2) + @cli.command() @click.option("-i", "--input-dir", "input_dir", default="./latest-screenshots") diff --git a/newshomepages/utils.py b/newshomepages/utils.py index 1ecb7b3a3f1..585e1e59120 100644 --- a/newshomepages/utils.py +++ b/newshomepages/utils.py @@ -67,7 +67,7 @@ def get_bundle_list() -> typing.List[typing.Dict]: return bundle_list -def get_site(handle: typing.AnyStr) -> typing.Dict: +def get_site(handle: str) -> typing.Dict: """Get the metadata for the provided site. Args: @@ -76,7 +76,10 @@ def get_site(handle: typing.AnyStr) -> typing.Dict: Returns a dictionary. """ site_list = get_site_list() - return next(d for d in site_list if d["handle"].lower() == handle.lower()) + try: + return next(d for d in site_list if d["handle"].lower() == handle.lower()) + except StopIteration: + raise ValueError(f"The handle {handle} could not be found") def get_bundle(slug: str) -> typing.Dict: