Added photos compression

This commit is contained in:
Profitroll 2022-12-20 22:24:35 +01:00
parent 653688b376
commit 7291faede5
2 changed files with 29 additions and 4 deletions

View File

@ -2,10 +2,11 @@ import re
import pickle import pickle
from secrets import token_urlsafe from secrets import token_urlsafe
from magic import Magic from magic import Magic
from datetime import datetime from datetime import datetime, timedelta
from os import makedirs, path, remove from os import makedirs, path, remove, system
from classes.models import Photo, SearchResults from classes.models import Photo, SearchResults
from modules.hasher import get_phash, get_duplicates from modules.hasher import get_phash, get_duplicates
from modules.scheduler import scheduler
from modules.security import User, get_current_active_user from modules.security import User, get_current_active_user
from modules.app import app from modules.app import app
from modules.database import col_photos, col_albums, col_tokens 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 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 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") @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: 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.") 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} ) 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( return UJSONResponse(
{ {
"id": uploaded.inserted_id.__str__(), "id": uploaded.inserted_id.__str__(),

View File

@ -5,4 +5,5 @@ scipy~=1.9.3
python-magic~=0.4.27 python-magic~=0.4.27
opencv-python~=4.6.0.66 opencv-python~=4.6.0.66
python-jose[cryptography]~=3.3.0 python-jose[cryptography]~=3.3.0
passlib~=1.7.4 passlib~=1.7.4
apscheduler~=3.9.1.post1