#!/usr/bin/env python3 """Генерация responsive-набора изображений и manifest со srcset.""" from __future__ import annotations import argparse import json import sys from pathlib import Path try: from PIL import Image, ImageOps except ImportError: sys.exit("Нужен Pillow: python3 -m pip install Pillow") EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".tif", ".tiff", ".bmp"} SUFFIX = {"webp": ".webp", "jpeg": ".jpg"} def parse_widths(value: str) -> list[int]: try: widths = sorted({int(item.strip()) for item in value.split(",") if item.strip()}) except ValueError as error: raise argparse.ArgumentTypeError("ширины нужны через запятую: 480,768,1024") from error if not widths or any(width < 32 for width in widths): raise argparse.ArgumentTypeError("каждая ширина должна быть не меньше 32") return widths def collect(root: Path, recursive: bool) -> list[Path]: pattern = "**/*" if recursive else "*" return sorted( path for path in root.glob(pattern) if path.is_file() and path.suffix.lower() in EXTENSIONS ) def flatten(image: Image.Image) -> Image.Image: if image.mode in ("RGBA", "LA") or (image.mode == "P" and "transparency" in image.info): rgba = image.convert("RGBA") canvas = Image.new("RGB", rgba.size, (255, 255, 255)) canvas.paste(rgba, mask=rgba.getchannel("A")) return canvas if image.mode != "RGB": return image.convert("RGB") return image def main() -> int: parser = argparse.ArgumentParser(description="Собрать responsive-набор для сайта") parser.add_argument("--dir", type=Path, required=True) parser.add_argument("--out", type=Path, required=True) parser.add_argument("--widths", type=parse_widths, default=[480, 768, 1024, 1600]) parser.add_argument("--format", choices=sorted(SUFFIX), default="webp") parser.add_argument("--quality", type=int, default=80) parser.add_argument("--recursive", action="store_true") parser.add_argument("--overwrite", action="store_true") args = parser.parse_args() if not 1 <= args.quality <= 100: parser.error("--quality должен быть от 1 до 100") root = args.dir.expanduser().resolve() if not root.is_dir(): parser.error(f"Папка не найдена: {root}") out_dir = args.out.expanduser().resolve() out_dir.mkdir(parents=True, exist_ok=True) files = collect(root, args.recursive) if not files: print("Изображения не найдены.") return 0 manifest = [] total = skipped = failed = 0 for path in files: try: with Image.open(path) as opened: image = ImageOps.exif_transpose(opened) if image.mode not in ("RGB", "RGBA", "L"): image = image.convert("RGBA" if "A" in image.getbands() else "RGB") variants = [] for width in [item for item in args.widths if item <= image.width] or [image.width]: height = max(1, round(image.height * width / image.width)) resized = image.resize((width, height), Image.Resampling.LANCZOS) name = f"{path.stem}-{width}w{SUFFIX[args.format]}" target = out_dir / name if target.exists() and not args.overwrite: skipped += 1 variants.append({"file": name, "width": width}) continue if args.format == "webp": resized.save(target, format="WEBP", quality=args.quality, method=6) else: flatten(resized).save( target, format="JPEG", quality=args.quality, optimize=True, progressive=True, ) total += 1 variants.append( {"file": name, "width": width, "bytes": target.stat().st_size} ) srcset = ", ".join(f"{item['file']} {item['width']}w" for item in variants) manifest.append({"source": str(path.relative_to(root)), "srcset": srcset, "variants": variants}) print(f"Готово: {path.name} ({len(variants)} вариантов)") except Exception as error: print(f"Ошибка {path}: {error}") failed += 1 (out_dir / "manifest.json").write_text( json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"Итог: {total} файлов, пропущено {skipped}, ошибок {failed}") print(f"Manifest: {out_dir / 'manifest.json'}") return 1 if failed else 0 if __name__ == "__main__": raise SystemExit(main())