This commit is contained in:
1 parent
b2ab347129
commit
adc832c042
14 files changed
+336
-24
No files matched your search
@@ -0,0 +1,82 @@
|
||||
"""Cover cache helpers: optional WebP previews and size pruning."""
|
||||
|
||||
import os
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
except Exception:
|
||||
Image = None
|
||||
|
||||
PREVIEW_NAME = "preview.webp"
|
||||
|
||||
|
||||
def can_optimize():
|
||||
return Image is not None
|
||||
|
||||
|
||||
def make_preview(src, dst, max_width=360, quality=80):
|
||||
"""Create a small WebP preview; returns False when Pillow is unavailable."""
|
||||
if Image is None:
|
||||
return False
|
||||
try:
|
||||
with Image.open(src) as image:
|
||||
if image.mode not in ("RGB", "RGBA"):
|
||||
image = image.convert("RGBA")
|
||||
if image.width > max_width:
|
||||
height = round(image.height * max_width / image.width)
|
||||
image = image.resize((max_width, height), Image.Resampling.LANCZOS)
|
||||
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
||||
image.save(dst, "WEBP", quality=quality, method=6)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def cache_stats(cache_dir):
|
||||
files = 0
|
||||
previews = 0
|
||||
total = 0
|
||||
if not os.path.isdir(cache_dir):
|
||||
return {"files": 0, "previews": 0, "bytes": 0}
|
||||
for dirpath, _dirs, names in os.walk(cache_dir):
|
||||
for name in names:
|
||||
path = os.path.join(dirpath, name)
|
||||
try:
|
||||
total += os.path.getsize(path)
|
||||
except OSError:
|
||||
continue
|
||||
files += 1
|
||||
if name == PREVIEW_NAME:
|
||||
previews += 1
|
||||
return {"files": files, "previews": previews, "bytes": total}
|
||||
|
||||
|
||||
def prune_cache(cache_dir, max_bytes):
|
||||
"""Delete oldest cached files until the directory is under max_bytes."""
|
||||
entries = []
|
||||
if not os.path.isdir(cache_dir):
|
||||
return {"removed": 0, "freed": 0, "bytes": 0}
|
||||
for dirpath, _dirs, names in os.walk(cache_dir):
|
||||
for name in names:
|
||||
if name == ".missing":
|
||||
continue
|
||||
path = os.path.join(dirpath, name)
|
||||
try:
|
||||
stat = os.stat(path)
|
||||
except OSError:
|
||||
continue
|
||||
entries.append((stat.st_mtime, stat.st_size, path))
|
||||
entries.sort()
|
||||
total = sum(size for _mtime, size, _path in entries)
|
||||
removed = freed = 0
|
||||
for _mtime, size, path in entries:
|
||||
if total <= max_bytes:
|
||||
break
|
||||
try:
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
continue
|
||||
total -= size
|
||||
freed += size
|
||||
removed += 1
|
||||
return {"removed": removed, "freed": freed, "bytes": total}
|
||||
Reference in new issue
Block a user