import os from PIL import Image from pathlib import Path BASE_DIR = Path("/home/andre/coden/Orchestrator/privat/CV/andreknie.de") DIRS_TO_PROCESS = [ BASE_DIR / "public/images", BASE_DIR / "public/logos" ] def optimize_images(): for img_dir in DIRS_TO_PROCESS: if not img_dir.exists(): continue # Process files directly in this directory (not recursive to avoid processing kniepunkt again) for img_path in img_dir.iterdir(): if img_path.is_file() and img_path.suffix.lower() in [".png", ".jpg", ".jpeg"]: if img_path.name == "favicon.png": continue try: with Image.open(img_path) as img: # Convert to RGB if necessary if img.mode in ("RGBA", "P"): img = img.convert("RGBA") elif img.mode != "RGB": img = img.convert("RGB") # Resize if overly large if img.width > 2000: ratio = 2000 / img.width new_size = (2000, int(img.height * ratio)) img = img.resize(new_size, Image.Resampling.LANCZOS) webp_path = img_path.with_suffix(".webp") img.save(webp_path, "WEBP", quality=80) img_path.unlink() print(f"Optimized: {img_path.name} -> {webp_path.name}") except Exception as e: print(f"Error processing {img_path}: {e}") def update_references(): import glob # Search all jsx, css, yaml, md files extensions = ["jsx", "css", "yaml", "yml", "md"] search_dirs = [ BASE_DIR / "src", BASE_DIR / "content" ] # Also update index.html if needed (though favicon.png is excluded from conversion) for d in search_dirs: for root, _, files in os.walk(d): for file in files: ext = file.split('.')[-1].lower() if ext in extensions: filepath = Path(root) / file try: content = filepath.read_text(encoding="utf-8") # Replace .png, .jpg, .jpeg with .webp # But be careful not to replace favicon.png if it's there if "favicon.png" not in content: new_content = content.replace(".png", ".webp").replace(".jpg", ".webp").replace(".jpeg", ".webp") if new_content != content: filepath.write_text(new_content, encoding="utf-8") print(f"Updated references in: {filepath.name}") else: # Do a safe replace (not touching favicon.png) lines = content.split('\n') new_lines = [] changed = False for line in lines: if "favicon.png" not in line: nl = line.replace(".png", ".webp").replace(".jpg", ".webp").replace(".jpeg", ".webp") if nl != line: changed = True new_lines.append(nl) else: new_lines.append(line) if changed: filepath.write_text('\n'.join(new_lines), encoding="utf-8") print(f"Updated references in: {filepath.name} (safe mode)") except Exception as e: pass if __name__ == "__main__": optimize_images() update_references() print("Optimization complete!")