From 7291faede549e0c66e90e4f9c03437989ca18a56 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Tue, 20 Dec 2022 22:24:35 +0100 Subject: [PATCH] Added photos compression --- extensions/photos.py | 30 +++++++++++++++++++++++++++--- requirements.txt | 3 ++- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/extensions/photos.py b/extensions/photos.py index 10cf68d..990af35 100644 --- a/extensions/photos.py +++ b/extensions/photos.py @@ -2,10 +2,11 @@ import re import pickle from secrets import token_urlsafe from magic import Magic -from datetime import datetime -from os import makedirs, path, remove +from datetime import datetime, timedelta +from os import makedirs, path, remove, system from classes.models import Photo, SearchResults from modules.hasher import get_phash, get_duplicates +from modules.scheduler import scheduler from modules.security import User, get_current_active_user from modules.app import app from modules.database import col_photos, col_albums, col_tokens @@ -16,8 +17,28 @@ from fastapi import HTTPException, UploadFile, Security from fastapi.responses import UJSONResponse, Response from starlette.status import HTTP_204_NO_CONTENT, HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED, HTTP_404_NOT_FOUND, HTTP_409_CONFLICT +from modules.utils import logWrite + +async def compress_image(image_path: str): + + image_type = Magic(mime=True).from_file(image_path) + + if image_type not in ["image/jpeg", "image/png"]: + logWrite(f"Not compressing {image_path} because its mime is '{image_type}'") + return + + size_before = path.getsize(image_path) / 1024 + + if image_type == "image/jpeg": + system(f"jpegoptim {image_path} -o --max=60 --strip-all") + elif image_type == "image/png": + system(f"optipng -o3 {image_path}") + + size_after = path.getsize(image_path) / 1024 + logWrite(f"Compressed '{path.split(image_path)[-1]}' from {size_before} Kb to {size_after} Kb") + @app.post("/albums/{album}/photos", response_class=UJSONResponse, response_model=Photo, description="Upload a photo to album") -async def photo_upload(file: UploadFile, album: str, ignore_duplicates: bool = False, current_user: User = Security(get_current_active_user, scopes=["photos.write"])): +async def photo_upload(file: UploadFile, album: str, ignore_duplicates: bool = False, compress: bool = True, current_user: User = Security(get_current_active_user, scopes=["photos.write"])): if col_albums.find_one( {"user": current_user.user, "name": album} ) is None: return HTTPException(status_code=HTTP_404_NOT_FOUND, detail=f"Provided album '{album}' does not exist.") @@ -51,6 +72,9 @@ async def photo_upload(file: UploadFile, album: str, ignore_duplicates: bool = F uploaded = col_photos.insert_one( {"user": current_user.user, "album": album, "hash": file_hash, "filename": filename} ) + if compress is True: + scheduler.add_job(compress_image, trigger="date", run_date=datetime.now()+timedelta(seconds=1), args=[path.join("data", "users", current_user.user, "albums", album, filename)]) + return UJSONResponse( { "id": uploaded.inserted_id.__str__(), diff --git a/requirements.txt b/requirements.txt index f62aea8..04a0283 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,4 +5,5 @@ scipy~=1.9.3 python-magic~=0.4.27 opencv-python~=4.6.0.66 python-jose[cryptography]~=3.3.0 -passlib~=1.7.4 \ No newline at end of file +passlib~=1.7.4 +apscheduler~=3.9.1.post1 \ No newline at end of file