Files

36 lines
1.0 KiB
Python

"""Helpers shared by the route modules."""
import io
import os
from functools import lru_cache
from fastapi import HTTPException
from backend import projects as project_store
def project_or_404(project_id: int) -> dict:
project = project_store.get(project_id)
if project is None:
raise HTTPException(404, "No such project")
return project
@lru_cache(maxsize=512)
def _thumbnail_cached(path: str, width: int, mtime: float) -> bytes:
from PIL import Image
with Image.open(path) as image:
image = image.convert("RGB")
if image.width > width:
height = max(1, round(image.height * width / image.width))
image = image.resize((width, height), Image.BILINEAR)
buffer = io.BytesIO()
image.save(buffer, "JPEG", quality=72)
return buffer.getvalue()
def thumbnail(path: str, width: int) -> bytes:
# mtime is part of the key so a re-extracted frame never serves a stale one.
return _thumbnail_cached(path, width, os.path.getmtime(path))