From 25eeccec594a4027ddf51c978406b1cf9bd9f0b9 Mon Sep 17 00:00:00 2001 From: Victor Mylle Date: Tue, 7 Mar 2023 12:41:56 +0000 Subject: [PATCH] Trying out new cache system --- backend/src/routers/signvideo.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/backend/src/routers/signvideo.py b/backend/src/routers/signvideo.py index c38a6f5..7784cf4 100644 --- a/backend/src/routers/signvideo.py +++ b/backend/src/routers/signvideo.py @@ -26,12 +26,12 @@ from src.utils.cryptography import verify_password # Create a Memory object that caches data to the specified directory cache_dir = settings.CACHE_PATH -memory = Memory(location=cache_dir, verbose=0) - -@memory.cache -def extract_thumbnail(video_path): - proc = subprocess.run(["ffmpeg", "-i", video_path, "-ss", "00:00:02.000", "-vframes", "1", "-f", "image2pipe", "-"], stdout=subprocess.PIPE) - byte_data = proc.stdout +async def extract_thumbnail(video_path): + proc = await asyncio.create_subprocess_exec( + "ffmpeg", "-i", video_path, "-ss", "00:00:02.000", "-vframes", "1", "-f", "image2pipe", "-" + , stdout=subprocess.PIPE, + ) + byte_data = await proc.stdout.read() return byte_data router = APIRouter(prefix="/signs/{sign_id}/video") @@ -109,8 +109,17 @@ async def sign_video_thumbnail( if not os.path.exists(f"{settings.DATA_PATH}/{sign_video.path}"): raise BaseException("Video not found") + # check if the thumbnail exists in the cache folder + if os.path.exists(f"{settings.CACHE_PATH}/{sign_video.path}.jpg"): + # return the thumbnail and make it cacheable for 60 days + return FileResponse(f"{settings.CACHE_PATH}/{sign_video.path}.jpg", media_type="image/jpeg", headers={"Cache-Control": "max-age=5184000"}) + # extract the thumbnail from the video - bytes = extract_thumbnail(f"{settings.DATA_PATH}/{sign_video.path}") + bytes = await extract_thumbnail(f"{settings.DATA_PATH}/{sign_video.path}") + + # save the thumbnail in the cache folder + with open(f"{settings.CACHE_PATH}/{sign_video.path}.jpg", 'wb') as f: + f.write(bytes) # return the thumbnail and make it cacheable for 60 days return StreamingResponse(io.BytesIO(bytes), media_type="image/jpeg", headers={"Cache-Control": "max-age=5184000"})