| |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| from __future__ import annotations |
|
|
| import functools |
| import json |
| import logging |
| import os |
| import subprocess |
| import sys |
|
|
| from fnmatch import fnmatch |
| from colorama import Fore, Style |
| from concurrent.futures import Future |
| from concurrent.futures.thread import ThreadPoolExecutor |
| from hashlib import sha1 |
| from mkdocs import utils |
| from mkdocs.config.defaults import MkDocsConfig |
| from mkdocs.exceptions import PluginError |
| from mkdocs.plugins import BasePlugin |
| from mkdocs.structure.files import File |
| from shutil import which |
| try: |
| from PIL import Image |
| except ImportError: |
| pass |
|
|
| from .config import OptimizeConfig |
|
|
| |
| |
| |
|
|
| |
| class OptimizePlugin(BasePlugin[OptimizeConfig]): |
| supports_multiple_instances = True |
|
|
| |
| manifest: dict[str, str] = {} |
|
|
| |
| def __init__(self, *args, **kwargs): |
| super().__init__(*args, **kwargs) |
|
|
| |
| self.is_serve = False |
|
|
| |
| def on_startup(self, *, command, dirty): |
| self.is_serve = command == "serve" |
|
|
| |
| self.pool = ThreadPoolExecutor(self.config.concurrency) |
| self.pool_jobs: dict[str, Future] = {} |
|
|
| |
| def on_config(self, config): |
| if not self.config.enabled: |
| return |
|
|
| |
| |
| |
| |
| path = os.path.abspath(self.config.cache_dir) |
| if path != self.config.cache_dir: |
| self.config.cache_dir = os.path.join( |
| os.path.dirname(config.config_file_path), |
| os.path.normpath(self.config.cache_dir) |
| ) |
|
|
| |
| os.makedirs(self.config.cache_dir, exist_ok = True) |
|
|
| |
| self.manifest_file = os.path.join( |
| self.config.cache_dir, "manifest.json" |
| ) |
|
|
| |
| if os.path.isfile(self.manifest_file) and self.config.cache: |
| try: |
| with open(self.manifest_file) as f: |
| self.manifest = json.load(f) |
| except: |
| pass |
|
|
| |
| def on_env(self, env, *, config, files): |
| if not self.config.enabled: |
| return |
|
|
| |
| if not self.config.optimize: |
| return |
|
|
| |
| |
| |
| |
| for file in files.media_files(): |
| if self._is_excluded(file): |
| continue |
|
|
| |
| |
| path = os.path.join(self.config.cache_dir, file.src_path) |
| self.pool_jobs[file.abs_src_path] = self.pool.submit( |
| self._optimize_image, file, path, config |
| ) |
|
|
| |
| files.remove(file) |
|
|
| |
| def on_post_build(self, *, config): |
| if not self.config.enabled: |
| return |
|
|
| |
| if not self.config.optimize: |
| return |
|
|
| |
| |
| |
| |
| for path, future in self.pool_jobs.items(): |
| if future.exception(): |
| raise future.exception() |
| else: |
| file: File = future.result() |
| file.copy_file() |
|
|
| |
| if self.config.cache: |
| with open(self.manifest_file, "w") as f: |
| f.write(json.dumps(self.manifest, indent = 2, sort_keys = True)) |
|
|
| |
| if self.config.print_gain_summary: |
| print(Style.NORMAL) |
| print(f" Optimizations:") |
|
|
| |
| for seek in [".png", ".jpg"]: |
| size = size_opt = 0 |
| for path, future in self.pool_jobs.items(): |
| file: File = future.result() |
|
|
| |
| _, extension = os.path.splitext(path) |
| extension = ".jpg" if extension == ".jpeg" else extension |
| if extension != seek: |
| continue |
|
|
| |
| size += os.path.getsize(path) |
| size_opt += os.path.getsize(file.abs_dest_path) |
|
|
| |
| if size and size_opt: |
| gain_abs = size - size_opt |
| gain_rel = (1 - size_opt / size) * 100 |
|
|
| |
| print( |
| f" *{seek} {Fore.GREEN}{_size(size_opt)}" |
| f"{Fore.WHITE}{Style.DIM} ↓ " |
| f"{_size(gain_abs)} [{gain_rel:3.1f}%]" |
| f"{Style.RESET_ALL}" |
| ) |
|
|
| |
| print(Style.RESET_ALL) |
|
|
| |
| def on_shutdown(self): |
| if not self.config.enabled: |
| return |
|
|
| |
| |
| if sys.version_info >= (3, 9): |
| self.pool.shutdown(cancel_futures = True) |
| else: |
| self.pool.shutdown() |
|
|
| |
| if self.manifest and self.config.cache: |
| with open(self.manifest_file, "w") as f: |
| f.write(json.dumps(self.manifest, indent = 2, sort_keys = True)) |
|
|
| |
|
|
| |
| def _is_optimizable(self, file: File): |
|
|
| |
| if file.url.endswith((".png")): |
| return self.config.optimize_png |
|
|
| |
| if file.url.endswith((".jpg", ".jpeg")): |
| return self.config.optimize_jpg |
|
|
| |
| return False |
|
|
| |
| def _is_excluded(self, file: File): |
| if not self._is_optimizable(file): |
| return True |
|
|
| |
| path = file.src_path |
| if self.config.optimize_include: |
| for pattern in self.config.optimize_include: |
| if fnmatch(file.src_uri, pattern): |
| return False |
|
|
| |
| log.debug(f"Excluding file '{path}' due to inclusion patterns") |
| return True |
|
|
| |
| for pattern in self.config.optimize_exclude: |
| if fnmatch(file.src_uri, pattern): |
| log.debug(f"Excluding file '{path}' due to exclusion patterns") |
| return True |
|
|
| |
| return False |
|
|
| |
| def _optimize_image(self, file: File, path: str, config: MkDocsConfig): |
| with open(file.abs_src_path, "rb") as f: |
| data = f.read() |
| hash = sha1(data).hexdigest() |
|
|
| |
| prev = self.manifest.get(file.url, "") |
| if hash != prev or not os.path.isfile(path): |
| os.makedirs(os.path.dirname(path), exist_ok = True) |
|
|
| |
| if file.url.endswith((".png")): |
| self._optimize_image_png(file, path, config) |
|
|
| |
| if file.url.endswith((".jpg", ".jpeg")): |
| self._optimize_image_jpg(file, path, config) |
|
|
| |
| size = len(data) |
| size_opt = os.path.getsize(path) |
|
|
| |
| gain_abs = size - size_opt |
| gain_rel = (1 - size_opt / size) * 100 |
|
|
| |
| gain = "" |
| if gain_abs and self.config.print_gain: |
| gain += " ↓ " |
| gain += " ".join([_size(gain_abs), f"[{gain_rel:3.1f}%]"]) |
|
|
| |
| log.info( |
| f"Optimized media file: {file.src_uri} " |
| f"{Fore.GREEN}{_size(size_opt)}" |
| f"{Fore.WHITE}{Style.DIM}{gain}" |
| f"{Style.RESET_ALL}" |
| ) |
|
|
| |
| self.manifest[file.url] = hash |
|
|
| |
| root = os.path.dirname(config.config_file_path) |
|
|
| |
| file.abs_src_path = path |
| file.src_path = os.path.relpath(path, root) |
|
|
| |
| return file |
|
|
| |
| |
| |
| def _optimize_image_png(self, file: File, path: str, config: MkDocsConfig): |
|
|
| |
| |
| |
| |
| if not which("pngquant"): |
| docs = os.path.relpath(config.docs_dir) |
| path = os.path.relpath(file.abs_src_path, docs) |
| raise PluginError( |
| f"Couldn't optimize image '{path}' in '{docs}': 'pngquant' " |
| f"not found. Make sure 'pngquant' is installed and in your path" |
| ) |
|
|
| |
| args = ["pngquant", |
| "--force", "--skip-if-larger", |
| "--output", path, |
| "--speed", f"{self.config.optimize_png_speed}" |
| ] |
|
|
| |
| if self.config.optimize_png_strip: |
| args.append("--strip") |
|
|
| |
| |
| |
| |
| subprocess.run([*args, file.abs_src_path]) |
| if not os.path.isfile(path): |
| utils.copy_file(file.abs_src_path, path) |
|
|
| |
| def _optimize_image_jpg(self, file: File, path: str, config: MkDocsConfig): |
|
|
| |
| |
| |
| |
| if not _supports("Image"): |
| docs = os.path.relpath(config.docs_dir) |
| path = os.path.relpath(file.abs_src_path, docs) |
| raise PluginError( |
| f"Couldn't optimize image '{path}' in '{docs}': install " |
| f"required dependencies – pip install 'mkdocs-material[imaging]'" |
| ) |
|
|
| |
| image = Image.open(file.abs_src_path) |
| image.save(path, "jpeg", |
| quality = self.config.optimize_jpg_quality, |
| progressive = self.config.optimize_jpg_progressive |
| ) |
|
|
| |
| |
| |
|
|
| |
| @functools.lru_cache(maxsize = None) |
| def _supports(name: str): |
| return name in globals() |
|
|
| |
|
|
| |
| def _size(value): |
| for unit in ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB"]: |
| if abs(value) < 1000.0: |
| return f"{value:3.1f} {unit}" |
| value /= 1000.0 |
|
|
| |
| |
| |
|
|
| |
| log = logging.getLogger("mkdocs.material.optimize") |
|
|