SVG-Compress hinzugefügt via svg-polish python module

This commit is contained in:
2026-06-10 10:17:36 +02:00
parent b880c4f03a
commit 0cec37eecd
4 changed files with 310 additions and 75 deletions
+126 -36
View File
@@ -1,16 +1,11 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PPTX Grafik-Komprimier-Tool (nur CaesiumCLT, Multi-Thread, Batch, sauberes Cleanup)
Version: 1.1.7
PPTX Raster & Vector Komprimier-Tool (Raster-Iamges: via CaesiumCLT, Vector-Images: via python Module svg_polish)
Version: 1.1.8
Highlights:
- Caesium-Scratch außerhalb des PPTX-Arbeitsverzeichnisses -> keine Tempfiles in finaler PPTX
- Safety-Cleanup: entfernt 'caesium*' Ordner und '*.tmp' in ppt/media, bevor gezippt wird
- Overwrite Policy: -O bigger
- Log: image_name,size_before,size_after,saving,saving_percent,in_slide_number,image_type_changed
- Summary inkl. Zeit benötigt
Änderungen in 1.1.8:
- SVG Files werden bei Vorhandensein von svg_polish anhand von 2 Profilen optimiert: balanced|agressive
Änderungen in 1.1.7:
- PNG->JPG Fallback für große PNGs hinzugefügt (wenn nach Kompression weiterhin > 500 KB)
@@ -21,6 +16,7 @@ Highlights:
"""
import argparse
import importlib
import inspect
import os
import re
@@ -42,7 +38,7 @@ from typing import Callable, List, Optional
__version__ = "1.1.7"
__version__ = "1.1.8"
RASTER_EXT = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
VECTOR_EXT = {".svg"}
@@ -51,8 +47,11 @@ PROGRESS_BAR_LEN = 40
TEMP_PREFIX = "pptx_compress_"
DEFAULT_MIN_SAVINGS = "2%"
PNG_TO_JPEG_THRESHOLD_BYTES = 500 * 1024
SVGO_CLI_RELATIVE_PATH = Path("bin") / "svgo-client" / "svgo.cmd"
SVG_POLISH_MODULE_NAME = "svg_polish"
SVG_PROFILE_BALANCED = "balanced"
SVG_PROFILE_AGGRESSIVE = "aggressive"
SVG_PROFILE_DEFAULT = SVG_PROFILE_AGGRESSIVE
@dataclass
class DeckResult:
@@ -151,13 +150,13 @@ def compress_with_caesium(
min_savings: str,
output_format: str = "original",
) -> Path | None:
ext = original.suffix.lower()
if ext not in RASTER_EXT:
return None
exe = which("caesiumclt")
if not exe:
raise RuntimeError("[ERROR] 'caesiumclt' wurde nicht gefunden. Bitte CaesiumCLT installieren und in PATH verfügbar machen.")
out_dir.mkdir(parents=True, exist_ok=True)
ext = original.suffix.lower()
if ext not in ALLOWED_EXT:
return None
cmd = [
exe,
"-q",
@@ -239,44 +238,126 @@ def compress_raster_image(
)
def get_svgo_executable_path() -> Path:
return Path(__file__).resolve().parent / SVGO_CLI_RELATIVE_PATH
def import_svg_polish_module() -> object | None:
try:
return importlib.import_module(SVG_POLISH_MODULE_NAME)
except Exception:
return None
def compress_svg_with_svgo(
def build_svg_polish_options(svg_polish_module: object, profile: str = SVG_PROFILE_DEFAULT) -> object | None:
options_type = getattr(svg_polish_module, "OptimizeOptions", None)
if not callable(options_type):
return None
try:
if profile == SVG_PROFILE_BALANCED:
return options_type(
digits=3,
style_to_xml=True,
group_collapse=True,
simple_colors=True,
indent_type="none",
newlines=False,
strip_xml_prolog=True,
strip_comments=True,
remove_metadata=True,
remove_titles=True,
remove_descriptions=True,
)
return options_type(
digits=2,
style_to_xml=True,
group_collapse=True,
simple_colors=True,
indent_type="none",
newlines=False,
strip_xml_prolog=True,
strip_comments=True,
remove_metadata=True,
remove_titles=True,
remove_descriptions=True,
remove_descriptive_elements=True,
strip_ids=True,
shorten_ids=True,
renderer_workaround=False,
)
except Exception:
return None
def call_svg_polish_callable(fn: Callable[..., object], options: object | None, *args: object) -> object:
if options is not None:
try:
return fn(*args, options=options)
except TypeError:
return fn(*args)
return fn(*args)
def optimize_svg_content_with_module(svg_polish_module: object, original: Path, svg_profile: str = SVG_PROFILE_DEFAULT) -> str | None:
options = build_svg_polish_options(svg_polish_module, svg_profile)
optimize_path = getattr(svg_polish_module, "optimize_path", None)
if callable(optimize_path):
result = call_svg_polish_callable(optimize_path, options, original)
if isinstance(result, str):
return result
optimize_file = getattr(svg_polish_module, "optimize_file", None)
if callable(optimize_file):
result = call_svg_polish_callable(optimize_file, options, str(original))
if isinstance(result, str):
return result
svg_text = original.read_text(encoding="utf-8")
optimize = getattr(svg_polish_module, "optimize", None)
if callable(optimize):
result = call_svg_polish_callable(optimize, options, svg_text)
if isinstance(result, str):
return result
optimize_string = getattr(svg_polish_module, "optimize_string", None)
if callable(optimize_string):
result = call_svg_polish_callable(optimize_string, options, svg_text)
if isinstance(result, str):
return result
polish = getattr(svg_polish_module, "polish", None)
if callable(polish):
result = polish(svg_text)
if isinstance(result, str):
return result
return None
def compress_svg_with_svg_polish(
original: Path,
out_dir: Path,
svg_profile: str = SVG_PROFILE_DEFAULT,
) -> Path | None:
if original.suffix.lower() not in VECTOR_EXT:
return None
svgo_exe = get_svgo_executable_path()
if not svgo_exe.exists() or not svgo_exe.is_file():
svg_polish_module = import_svg_polish_module()
if svg_polish_module is None:
sys.stderr.write(f"[svg_polish] Modul '{SVG_POLISH_MODULE_NAME}' nicht verfügbar für {original.name}\n")
return None
out_dir.mkdir(parents=True, exist_ok=True)
out_file = out_dir / original.name
cmd = [
str(svgo_exe),
str(original),
"-o",
str(out_file),
]
try:
r = subprocess.run(cmd, capture_output=True, text=True)
if r.returncode != 0:
sys.stderr.write(f"[svgo] Fehler bei {original.name}:{r.stderr}")
optimized_svg = optimize_svg_content_with_module(svg_polish_module, original, svg_profile)
if not isinstance(optimized_svg, str):
return None
return out_file if out_file.exists() else None
out_file.write_text(optimized_svg, encoding="utf-8")
if out_file.stat().st_size >= original.stat().st_size:
return None
return out_file
except Exception as ex:
sys.stderr.write(f"[svgo] Ausnahme bei {original.name}: {ex}")
sys.stderr.write(f"[svg_polish] Ausnahme bei {original.name}: {ex}")
return None
def compress_vector_image(
original: Path,
out_dir: Path,
svg_profile: str = SVG_PROFILE_DEFAULT,
) -> Path | None:
if original.suffix.lower() == ".svg":
return compress_svg_with_svgo(original=original, out_dir=out_dir)
return compress_svg_with_svg_polish(original=original, out_dir=out_dir, svg_profile=svg_profile)
return None
@@ -287,10 +368,10 @@ def compress_image_with_routing(
caesium_threads: int | None,
quality: int,
min_savings: str,
svg_profile: str = SVG_PROFILE_DEFAULT,
) -> Path | None:
vector_out = compress_vector_image(original=original, out_dir=out_dir)
if vector_out is not None:
return vector_out
if original.suffix.lower() in VECTOR_EXT:
return compress_vector_image(original=original, out_dir=out_dir, svg_profile=svg_profile)
return compress_raster_image(
compressor=compressor,
original=original,
@@ -394,6 +475,7 @@ def process_image_file(
quality: int,
min_savings: str,
compressor: Callable[..., Path | None],
svg_profile: str = SVG_PROFILE_DEFAULT,
) -> ImageProcessResult:
orig_size = img_path.stat().st_size
chosen_size = orig_size
@@ -411,6 +493,7 @@ def process_image_file(
caesium_threads=caesium_threads,
quality=quality,
min_savings=min_savings,
svg_profile=svg_profile,
)
if caesium_out and caesium_out.exists():
compressed_size = caesium_out.stat().st_size
@@ -463,6 +546,7 @@ def process_single_deck(
threads: int,
quality: int,
min_savings: str,
svg_profile: str = SVG_PROFILE_DEFAULT,
compressor: Callable[..., Path | None] = compress_with_caesium,
) -> DeckResult:
start_time = time.perf_counter()
@@ -522,6 +606,7 @@ def process_single_deck(
quality=quality,
min_savings=min_savings,
compressor=compressor,
svg_profile=svg_profile,
)
with lock:
@@ -660,6 +745,9 @@ def main():
print("[ERROR] 'caesiumclt' nicht gefunden. Bitte installieren und in PATH verfügbar machen.")
sys.exit(3)
if import_svg_polish_module() is None:
print("[WARN] 'svg-polish' nicht gefunden. SVG-Dateien werden nicht komprimiert. Installation: python -m pip install svg-polish")
overall_before = 0
overall_after = 0
successes = 0
@@ -675,7 +763,7 @@ def main():
failures += 1
continue
dst = out_dir / f"{src.stem}_compressed.pptx"
res = process_single_deck(src, dst, args.threads, args.quality, args.min_savings)
res = process_single_deck(src, dst, args.threads, args.quality, args.min_savings, args.svg_profile)
if res.ok:
successes += 1
overall_before += res.size_before
@@ -748,9 +836,11 @@ def extractParserArguments():
parser.add_argument('-t','--threads', type=int, default=16, help='Anzahl paralleler Threads pro Datei')
parser.add_argument('-q','--quality', type=int, default=90, help='Qualität für caesiumclt (0..100), höher = bessere Qualität / größere Datei')
parser.add_argument('--min-savings', default=DEFAULT_MIN_SAVINGS, help="Mindestersparnis für caesiumclt (z. B. 2%%, 100KB, 1MB oder Bytes als Zahl)")
parser.add_argument('--svg-profile', choices=[SVG_PROFILE_BALANCED, SVG_PROFILE_AGGRESSIVE], default=SVG_PROFILE_DEFAULT, help='Optimierungsprofil für SVG-Kompression')
parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}', help="Zeigt die Versionsnummer an" )
args = parser.parse_args()
return parser,args