#!/usr/bin/env python3 """ compress_static.py — Pre-compress all compressible static assets. Generates .br (Brotli, quality=11) and .gz (Gzip, level=9) sibling files for every qualifying asset under src/static/. Run after: - make build-css (rebuilds tailwind.min.css) - updating any vendor JS/CSS file - adding new static assets The FastAPI _StaticCacheMiddleware in factory.py will automatically serve .br or .gz to browsers that send Accept-Encoding: br / gzip headers. Usage: python3 scripts/compress_static.py # or via Makefile: make compress-static """ import gzip import os import pathlib import sys import time try: import brotli except ImportError: print("ERROR: brotli package not found. Run: pip install brotli") sys.exit(1) # ── Configuration ────────────────────────────────────────────────────────────── STATIC_DIR = pathlib.Path(__file__).parent.parent / "src" / "static" MIN_SIZE_BYTES = 8_192 # Skip files smaller than 8 KB BROTLI_QUALITY = 11 # Maximum Brotli compression (slowest, best ratio) GZIP_LEVEL = 9 # Maximum Gzip compression COMPRESSIBLE_EXTENSIONS = { ".js", ".css", ".svg", ".json", ".html", ".woff", ".ttf", } SKIP_EXTENSIONS = {".br", ".gz", ".map", ".woff2"} # already compressed / skip def format_size(n: int) -> str: if n >= 1_048_576: return f"{n / 1_048_576:.1f}MB" return f"{n // 1_024}KB" def compress_file(path: pathlib.Path) -> tuple[int, int, int]: """Compress a single file. Returns (original, gz_size, br_size) in bytes.""" raw = path.read_bytes() gz_path = path.with_suffix(path.suffix + ".gz") gz_data = gzip.compress(raw, compresslevel=GZIP_LEVEL) gz_path.write_bytes(gz_data) br_path = path.with_suffix(path.suffix + ".br") br_data = brotli.compress(raw, quality=BROTLI_QUALITY) br_path.write_bytes(br_data) return len(raw), len(gz_data), len(br_data) def main() -> None: if not STATIC_DIR.exists(): print(f"ERROR: static dir not found: {STATIC_DIR}") sys.exit(1) start = time.time() total_orig = total_gz = total_br = 0 count = 0 print(f"Scanning {STATIC_DIR} …") print(f"{'File':<50} {'Orig':>7} {'Gzip':>7} {'Brotli':>7} {'Save':>6}") print("─" * 82) for root, dirs, files in os.walk(STATIC_DIR): dirs[:] = sorted(d for d in dirs if not d.startswith("__")) for fname in sorted(files): path = pathlib.Path(root) / fname if path.suffix in SKIP_EXTENSIONS: continue if path.suffix not in COMPRESSIBLE_EXTENSIONS: continue if path.stat().st_size < MIN_SIZE_BYTES: continue orig, gz_size, br_size = compress_file(path) saving = 100 - (br_size / orig * 100) if orig else 0 rel = str(path.relative_to(STATIC_DIR)) total_orig += orig total_gz += gz_size total_br += br_size count += 1 print(f" {rel:<48} {format_size(orig):>7} {format_size(gz_size):>7}" f" {format_size(br_size):>7} {saving:>5.0f}%") elapsed = time.time() - start print("─" * 82) if count: total_saving = 100 - (total_br / total_orig * 100) print(f" {'TOTAL (' + str(count) + ' files)':<48} {format_size(total_orig):>7}" f" {format_size(total_gz):>7} {format_size(total_br):>7} {total_saving:>5.0f}%") print(f"\n✅ Done in {elapsed:.1f}s — Brotli saves {total_saving:.0f}% vs raw") print(" Serving: factory.py _StaticCacheMiddleware auto-selects .br or .gz") else: print(" No files needed compression.") if __name__ == "__main__": main()