Skip to content

Commit

Permalink
Images optimizer : tient compte du dossier de sortie (#223)
Browse files Browse the repository at this point in the history
  • Loading branch information
Guts authored Jul 2, 2024
2 parents b7176b5 + fb65e48 commit cd0c939
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 19 deletions.
34 changes: 23 additions & 11 deletions geotribu_cli/images/images_optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ def parser_images_optimizer(
subparser.add_argument(
"-o",
"--output-path",
dest="output_path",
help="Fichier de sortie. Par défaut, stocke dans le dossier de travail local "
"de Geotribu.",
dest="output_path",
)

subparser.add_argument(
Expand Down Expand Up @@ -110,6 +110,10 @@ def run(args: argparse.Namespace):
args (argparse.Namespace): arguments passed to the subcommand
"""
logger.debug(f"Running {args.command} with {args}")
# dossier de sortie
output_folder = Path(
args.output_path
) or defaults_settings.geotribu_working_folder.joinpath("images/optim/")

# liste l'image ou les images à optimiser
if check_path(
Expand All @@ -120,10 +124,12 @@ def run(args: argparse.Namespace):
must_exists=True,
raise_error=False,
):
logger.info(f"Dossier d'images passé : {args.image_path}")
input_images_folder = Path(args.image_path).resolve()
logger.info(f"Dossier d'images passé : {input_images_folder}")
logger.info(f"Dossier en sortie : {output_folder}")
li_images = [
image.resolve()
for image in Path(args.image_path).glob("*")
for image in input_images_folder.glob("*")
if image.suffix.lower() in defaults_settings.images_body_extensions
]
if not li_images:
Expand All @@ -133,7 +139,7 @@ def run(args: argparse.Namespace):
sys.exit(0)
else:
logger.debug(f"Image unique passée : {args.image_path}")
li_images = [args.image_path]
li_images = [Path(args.image_path)]

# Utilise l'outil d'optimisation
if args.tool_to_use == "tinypng":
Expand All @@ -159,7 +165,9 @@ def run(args: argparse.Namespace):
for img in li_images:
try:
optimized_image = optimize_with_tinify(
image_path_or_url=img, image_type=args.image_type
image_path_or_url=img,
image_type=args.image_type,
output_folder=output_folder,
)
console.print(
f":clamp: L'image {img} a été redimensionnée et "
Expand Down Expand Up @@ -187,7 +195,9 @@ def run(args: argparse.Namespace):
count_optim_error = 0
for img in li_images:
try:
optimized_image = pil_redimensionner_image(image_path_or_url=img)
optimized_image = pil_redimensionner_image(
image_path_or_url=img, output_folder=output_folder
)
console.print(
f":clamp: L'image {img} a été redimensionnée et "
f"compressée avec {args.tool_to_use} : {optimized_image}"
Expand All @@ -200,10 +210,12 @@ def run(args: argparse.Namespace):
)
count_optim_error += 1

# report
console.print(
f":white_check_mark: {count_optim_success} image(s) correctement redimensionnée(s)\n"
f":cross_mark: {count_optim_error} image(s) non redimensionnée(s)"
)

# open output folder if success and not disabled
if args.opt_auto_open_disabled and count_optim_success > 0:
open_uri(
in_filepath=defaults_settings.geotribu_working_folder.joinpath(
"images/optim"
)
)
open_uri(in_filepath=output_folder)
6 changes: 4 additions & 2 deletions geotribu_cli/images/optim_pillow.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@

def pil_redimensionner_image(
image_path_or_url: Path,
output_folder: Path,
largeur_max_paysage: int = 1000,
hauteur_max_portrait: int = 600,
) -> Optional[Path]:
Expand All @@ -44,6 +45,7 @@ def pil_redimensionner_image(
Args:
image_path_or_url: chemin ou URL vers l'image
output_folder: chemin du dossier de sortie
largeur_max_paysage: largeur maximum pour une image orientée paysage.
Defaults to 1000.
hauteur_max_portrait: hauteur maximum pour une image orientée portrait.
Expand Down Expand Up @@ -83,8 +85,8 @@ def pil_redimensionner_image(
new_img = contain(img, nouvelle_taille)

# sauvegarder l'image
output_filepath = defaults_settings.geotribu_working_folder.joinpath(
f"images/optim/{image_path_or_url.stem}_resized_{new_img.width}x"
output_filepath = output_folder.joinpath(
f"{image_path_or_url.stem}_resized_{new_img.width}x"
f"{new_img.height}{image_path_or_url.suffix}"
)
output_filepath.parent.mkdir(parents=True, exist_ok=True)
Expand Down
10 changes: 4 additions & 6 deletions geotribu_cli/images/optim_tinify.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import sys
from os import getenv
from pathlib import Path
from typing import Union
from typing import Optional, Union
from urllib.parse import unquote, urlsplit

# 3rd party
Expand Down Expand Up @@ -59,8 +59,8 @@ def tinify_check_api_limit() -> int:


def optimize_with_tinify(
image_path_or_url: Union[str, Path], image_type: str = "body"
) -> Path:
image_path_or_url: Union[str, Path], output_folder: Path, image_type: str = "body"
) -> Optional[Path]:
"""Optimize image using Tinify API (tinypng.com).
Args:
Expand Down Expand Up @@ -110,9 +110,7 @@ def optimize_with_tinify(
)

# prepare output path
output_filepath = defaults_settings.geotribu_working_folder.joinpath(
f"images/optim/{img_filename}"
)
output_filepath = output_folder.joinpath(f"{img_filename}")
output_filepath.parent.mkdir(parents=True, exist_ok=True)

# save output
Expand Down

0 comments on commit cd0c939

Please sign in to comment.