From 4921d4bd6f285bd816b2841d3ec8f50109b51a64 Mon Sep 17 00:00:00 2001 From: OleSTEEP Date: Thu, 2 Oct 2025 23:09:00 +0300 Subject: [PATCH] backend: convert input images to webp --- .gitignore | 4 ++-- backend/api.py | 6 ++---- backend/db.py | 4 +++- backend/utils.py | 25 +++++++++++++++++++++++++ backend/hmm.txt => hmm.txt | 0 5 files changed, 32 insertions(+), 7 deletions(-) create mode 100644 backend/utils.py rename backend/hmm.txt => hmm.txt (100%) diff --git a/.gitignore b/.gitignore index 1c8319a..fe7243c 100644 --- a/.gitignore +++ b/.gitignore @@ -3,5 +3,5 @@ venv/ __pycache__/ .idea/ .DS_Store -vn_database.db -screens/ \ No newline at end of file +*.db +store/ \ No newline at end of file diff --git a/backend/api.py b/backend/api.py index 0c20ee7..affd950 100644 --- a/backend/api.py +++ b/backend/api.py @@ -4,6 +4,7 @@ from fastapi.middleware.cors import CORSMiddleware from pathlib import Path from vntypes import Novel, Mark +from utils import * from db import VNDB app = FastAPI() @@ -42,7 +43,4 @@ async def novel_thumb(thumb: Annotated[bytes, File()], filename: str): @app.post("/api/screenshot") async def screenshot(scrshot: Annotated[bytes, File()], filename: str): - Path("screens/").mkdir(exist_ok=True) - with open(Path("screens", filename), "wb") as file: - file.write(scrshot) - return {"file_size": len(scrshot)} \ No newline at end of file + return {"file_size": save_image(scrshot, "screens", filename)} \ No newline at end of file diff --git a/backend/db.py b/backend/db.py index 473b7cb..998ef60 100644 --- a/backend/db.py +++ b/backend/db.py @@ -1,8 +1,10 @@ import sqlite3 +from utils import asset + class VNDB: - def __init__(self, db_name='vn_database.db'): + def __init__(self, db_name=asset('vn_database.db')): self.__db_name = db_name connection = sqlite3.connect(self.__db_name) cursor = connection.cursor() diff --git a/backend/utils.py b/backend/utils.py new file mode 100644 index 0000000..b50b648 --- /dev/null +++ b/backend/utils.py @@ -0,0 +1,25 @@ +from PIL import Image, UnidentifiedImageError +from pathlib import Path +import io + +def asset(path: str) -> Path: + return Path("store", path) + + +def image_normalize(img: bytes) -> bytes: + try: + byte_arr = io.BytesIO() + img = Image.open(io.BytesIO(img)) + img.save(byte_arr, format='WEBP') + return byte_arr.getvalue() + except UnidentifiedImageError: + return 0 + +def save_image(img: bytes, dir: str, name: str) -> int: + path = asset(dir) + path.mkdir(exist_ok=True) + img = image_normalize(img) + if img: + with open(Path(path, name+'.webp'), "wb") as file: + file.write(img) + return len(img) \ No newline at end of file diff --git a/backend/hmm.txt b/hmm.txt similarity index 100% rename from backend/hmm.txt rename to hmm.txt