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}
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Optimize cached covers: WebP previews and a size limit.
|
||||
|
||||
Examples:
|
||||
python tools/optimize_covers.py
|
||||
python tools/optimize_covers.py --prune --max-mb 500
|
||||
python tools/optimize_covers.py --stats
|
||||
|
||||
WebP requires Pillow. Without it the script only reports statistics and can
|
||||
still prune the cache; the server keeps serving the original images.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(BASE, "tools"))
|
||||
|
||||
import covers
|
||||
import steam_source
|
||||
|
||||
CACHE_DIR = os.path.join(BASE, "cache", "covers")
|
||||
SOURCE_NAMES = tuple(steam_source.COVER_ORDER) + ("header.jpg", "header.png")
|
||||
|
||||
|
||||
def app_dirs(cache_dir):
|
||||
if not os.path.isdir(cache_dir):
|
||||
return []
|
||||
return sorted(os.path.join(cache_dir, name) for name in os.listdir(cache_dir)
|
||||
if name.isdigit() and os.path.isdir(os.path.join(cache_dir, name)))
|
||||
|
||||
|
||||
def best_source(app_dir):
|
||||
for name in SOURCE_NAMES:
|
||||
path = os.path.join(app_dir, name)
|
||||
if os.path.isfile(path):
|
||||
return path
|
||||
for dirpath, _dirs, names in os.walk(app_dir):
|
||||
for name in names:
|
||||
if name.lower().endswith((".jpg", ".jpeg", ".png")):
|
||||
return os.path.join(dirpath, name)
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Optimize cover cache")
|
||||
ap.add_argument("--webp", action="store_true", help="create WebP previews")
|
||||
ap.add_argument("--prune", action="store_true", help="delete oldest files over the limit")
|
||||
ap.add_argument("--max-mb", type=float, default=500, help="cache size limit in MB")
|
||||
ap.add_argument("--stats", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
before = covers.cache_stats(CACHE_DIR)
|
||||
if args.stats:
|
||||
print(f"files: {before['files']} | previews: {before['previews']} | "
|
||||
f"size: {before['bytes'] / (1024 * 1024):.1f} MB")
|
||||
return
|
||||
|
||||
make_webp = args.webp or not args.prune
|
||||
if make_webp:
|
||||
if not covers.can_optimize():
|
||||
print("Pillow is not installed: WebP previews are skipped")
|
||||
else:
|
||||
made = skipped = failed = 0
|
||||
for app_dir in app_dirs(CACHE_DIR):
|
||||
preview = os.path.join(app_dir, covers.PREVIEW_NAME)
|
||||
if os.path.isfile(preview):
|
||||
skipped += 1
|
||||
continue
|
||||
source = best_source(app_dir)
|
||||
if not source:
|
||||
continue
|
||||
if covers.make_preview(source, preview):
|
||||
made += 1
|
||||
else:
|
||||
failed += 1
|
||||
print(f"webp: created={made} existing={skipped} failed={failed}")
|
||||
|
||||
if args.prune:
|
||||
result = covers.prune_cache(CACHE_DIR, int(args.max_mb * 1024 * 1024))
|
||||
print(f"prune: removed={result['removed']} "
|
||||
f"freed={result['freed'] / (1024 * 1024):.1f} MB "
|
||||
f"left={result['bytes'] / (1024 * 1024):.1f} MB")
|
||||
|
||||
after = covers.cache_stats(CACHE_DIR)
|
||||
print(f"cache: {after['files']} files, {after['previews']} previews, "
|
||||
f"{after['bytes'] / (1024 * 1024):.1f} MB")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user