File size: 628 Bytes
414dc55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
"""Tiny on-disk PNG cache keyed by content hash (path-independent, auto-named)."""

from __future__ import annotations

import hashlib
from collections.abc import Callable
from pathlib import Path

from PIL import Image


def _key_hash(parts: tuple[str, ...]) -> str:
    return hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()[:16]


def cached_png(cache_dir: Path, parts: tuple[str, ...], render: Callable[[], Image.Image]) -> Path:
    cache_dir.mkdir(parents=True, exist_ok=True)
    path = cache_dir / f"{_key_hash(parts)}.png"
    if not path.exists():
        render().save(path, format="PNG")
    return path