From d97bffa4d2042e65e025752970b56e31d6173a09 Mon Sep 17 00:00:00 2001 From: Blondel MONDESIR Date: Sun, 23 Jul 2023 00:08:37 -0400 Subject: [PATCH] feat: make covers square --- cps/editbooks.py | 14 +++++++++++++- cps/uploader.py | 24 +++++++++++++++++------- 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/cps/editbooks.py b/cps/editbooks.py index a0ddb050..c6ef3031 100755 --- a/cps/editbooks.py +++ b/cps/editbooks.py @@ -21,8 +21,10 @@ # along with this program. If not, see . import os +import smartcrop from datetime import datetime import json +from PIL import Image from shutil import copyfile from uuid import uuid4 from markupsafe import escape # dependency of flask @@ -752,9 +754,19 @@ def move_coverfile(meta, db_book): else: cover_file = os.path.join(constants.STATIC_DIR, 'generic_cover.jpg') new_cover_path = os.path.join(config.config_calibre_dir, db_book.path) + try: os.makedirs(new_cover_path, exist_ok=True) - copyfile(cover_file, os.path.join(new_cover_path, "cover.jpg")) + image = Image.open(cover_file) + + # crop image to square 150x150 using smartcrop + cropper = smartcrop.SmartCrop() + result = cropper.crop(image, 150, 150) + x, y, width, height = result['top_crop']['x'], result['top_crop']['y'], \ + result['top_crop']['width'], result['top_crop']['height'] + cropped_image = image.crop((x, y, x + width, y + height)) + cropped_image.save(os.path.join(new_cover_path, "cover.jpg")) + if meta.cover: os.unlink(meta.cover) except OSError as e: diff --git a/cps/uploader.py b/cps/uploader.py index 871449aa..2dd6a149 100644 --- a/cps/uploader.py +++ b/cps/uploader.py @@ -19,7 +19,7 @@ import os import hashlib import shutil -import subprocess +from subprocess import run from tempfile import gettempdir from flask_babel import gettext as _ @@ -262,15 +262,25 @@ def video_metadata(tmp_file_path, original_file_name, original_file_extension): pubdate="", identifiers=[]) return meta - + + def video_cover(tmp_file_path): - """ generate cover image from video using ffmpeg """ + """generate cover image from video using ffmpeg""" ffmpeg_executable = os.getenv('FFMPEG_PATH', 'ffmpeg') + ffmpeg_output_file = os.path.splitext(tmp_file_path)[0] + '.cover.jpg' + ffmpeg_args = [ + ffmpeg_executable, + '-i', tmp_file_path, + '-vframes', '1', + '-y', ffmpeg_output_file + ] + try: - subprocess.call([ffmpeg_executable, '-i', tmp_file_path, '-vframes', '1', '-y', os.path.splitext(tmp_file_path)[0] + '.cover.jpg']) - return None - except Exception as ex: - log.warning('Cannot extract cover image, using default: %s', ex) + ffmpeg_result = run(ffmpeg_args, capture_output=True, check=True) + log.debug(f"ffmpeg output: {ffmpeg_result.stdout}") + + except Exception as e: + log.warning(f"ffmpeg failed: {e}") return None