Fix output path bug with cbz-format: use path instead of std pathlib.

This commit is contained in:
Sekun 2024-08-27 11:08:53 +02:00
parent 6fc74ef755
commit cb5d71fd22

View file

@ -15,16 +15,17 @@ Test this program simply with pipx:
# dependencies = [ # dependencies = [
# "pillow>=10.4,<10.5", # "pillow>=10.4,<10.5",
# "structlog>=24.4,<24.5", # "structlog>=24.4,<24.5",
# "path",
# ] # ]
# /// # ///
import argparse import argparse
import pathlib
import re import re
import shutil import shutil
import tempfile import tempfile
import structlog import structlog
from path import Path
from PIL import Image from PIL import Image
logger = structlog.get_logger(__name__) logger = structlog.get_logger(__name__)
@ -56,7 +57,7 @@ def parse_args():
parser.add_argument( parser.add_argument(
"-q", "--quality", type=int, default=75, help="Quality of generated jpeg images" "-q", "--quality", type=int, default=75, help="Quality of generated jpeg images"
) )
parser.add_argument("files", nargs="+", type=pathlib.Path, help="Path of cbz files") parser.add_argument("files", nargs="+", type=Path, help="Path of cbz files")
return parser.parse_args() return parser.parse_args()
@ -65,12 +66,13 @@ def operate_cbz(cbz_path, quality=75, max_size=None, inplace=False):
logger.error(f"File {cbz_path} doesn't exist") logger.error(f"File {cbz_path} doesn't exist")
return return
with tempfile.TemporaryDirectory() as tmp_dir_: with tempfile.TemporaryDirectory() as tmp_dir_, tempfile.TemporaryDirectory() as zip_tmp_dir_:
tmp_dir = pathlib.Path(tmp_dir_) tmp_dir = Path(tmp_dir_)
zip_tmp_dir = Path(zip_tmp_dir_)
shutil.unpack_archive(cbz_path, tmp_dir, "zip") shutil.unpack_archive(cbz_path, tmp_dir, "zip")
for img_path in tmp_dir.iterdir(): for img_path in tmp_dir.iterdir():
if not img_path.is_file() or not re.match( if not img_path.is_file() or not re.match(
r".*\.(png|webp|jpe?g)$", str(img_path), re.I r".*\.(png|webp|jpe?g)$", img_path, re.I
): ):
continue continue
with Image.open(img_path) as im: with Image.open(img_path) as im:
@ -84,13 +86,20 @@ def operate_cbz(cbz_path, quality=75, max_size=None, inplace=False):
optimize=True, optimize=True,
quality=quality, quality=quality,
) )
if not img_path.endswith(".jpg"):
img_path.unlink() img_path.unlink()
output_path_stem = str(tmp_dir.parent / cbz_path.stem)
shutil.make_archive(zip_tmp_dir / "output", "zip", tmp_dir, ".")
output_zip = zip_tmp_dir / "output.zip"
if not inplace: if not inplace:
output_path_stem += "_copy" output_cbz = cbz_path.with_stem(cbz_path.name + "_copy")
shutil.make_archive(output_path_stem, "zip", tmp_dir) else:
pathlib.Path(output_path_stem + ".zip").rename(output_path_stem + ".cbz") cbz_path.unlink()
logger.info(f"Created {output_path_stem + ".cbz"} file") output_cbz = cbz_path
output_zip.copy(output_cbz)
logger.info(f"Created {output_cbz} file")
def main(): def main():