yonsen_language/data/svg/unclean/clean_drawio_svg.py

624 lines
15 KiB
Python
Executable File

#!/usr/bin/env python3
from __future__ import annotations
import argparse
import os
import re
import sys
import tempfile
import xml.etree.ElementTree as ET
from pathlib import Path
SVG_NS = "http://www.w3.org/2000/svg"
ET.register_namespace("", SVG_NS)
# =============================================================================
# Configuration
# =============================================================================
REMOVE_ATTRIBUTES = {
"style",
"id",
}
REMOVE_TAGS = {
"style",
"defs",
}
COLOR_REPLACEMENTS = {
"#000000": "#000",
"#ffffff": "#fff",
"rgb(0, 0, 0)": "#000",
"rgb(255, 255, 255)": "#fff",
}
NUMBER_RE = re.compile(r"^-?(?:\d+\.\d+|\d+|\.\d+)$")
# =============================================================================
# SVG helpers
# =============================================================================
def local_name(tag: str) -> str:
"""Strip an XML namespace from a tag name."""
return tag.rsplit("}", 1)[-1]
def strip_number(value: str) -> str:
"""
Simplify basic numeric values.
Examples:
305px -> 305
305.0 -> 305
0.5000 -> .5
-0.500 -> -.5
"""
value = value.strip()
if value.endswith("px"):
value = value[:-2]
if not NUMBER_RE.match(value):
return value
try:
number = float(value)
except ValueError:
return value
if number == int(number):
return str(int(number))
result = f"{number:.12f}".rstrip("0").rstrip(".")
if result.startswith("0."):
result = result[1:]
elif result.startswith("-0."):
result = "-" + result[2:]
return result
def normalize_color(value: str) -> str:
return COLOR_REPLACEMENTS.get(value.strip(), value.strip())
def clean_attributes(element: ET.Element) -> None:
"""Remove Draw.io-specific styling and normalize attributes."""
for name in list(element.attrib):
if local_name(name) in REMOVE_ATTRIBUTES:
element.attrib.pop(name, None)
for name in ("width", "height", "x", "y"):
if name in element.attrib:
element.attrib[name] = strip_number(element.attrib[name])
for name in ("fill", "stroke", "color"):
if name in element.attrib:
element.attrib[name] = normalize_color(element.attrib[name])
def remove_unwanted_elements(parent: ET.Element) -> None:
"""Remove Draw.io style/defs nodes recursively."""
for child in list(parent):
if local_name(child.tag) in REMOVE_TAGS:
parent.remove(child)
continue
remove_unwanted_elements(child)
def remove_background_rect(root: ET.Element) -> None:
"""Remove Draw.io's generated full-canvas background rectangle."""
for child in list(root):
if local_name(child.tag) != "rect":
continue
width = child.attrib.get("width")
height = child.attrib.get("height")
x = child.attrib.get("x", "0")
y = child.attrib.get("y", "0")
if width == "100%" and height == "100%" and x == "0" and y == "0":
root.remove(child)
def unwrap_groups(element: ET.Element) -> None:
"""
Remove groups with no attributes.
Groups carrying transforms, data-cell-id, etc. are preserved.
"""
for child in list(element):
unwrap_groups(child)
for child in list(element):
if local_name(child.tag) != "g":
continue
if child.attrib:
continue
children = list(child)
if not children:
element.remove(child)
continue
index = list(element).index(child)
element.remove(child)
for grandchild in reversed(children):
element.insert(index, grandchild)
def set_default_black_fill(root: ET.Element) -> None:
root.set("fill", "black")
def remove_white_shape_fills(root: ET.Element) -> None:
"""White Draw.io geometry becomes inherited black geometry."""
for element in root.iter():
if element is root:
continue
if element.attrib.get("fill") in {
"#fff",
"#ffffff",
"white",
}:
element.attrib.pop("fill", None)
def remove_redundant_black_fills(root: ET.Element) -> None:
"""Root already supplies fill=black."""
for element in root.iter():
if element is root:
continue
if element.attrib.get("fill") in {
"#000",
"#000000",
"black",
}:
element.attrib.pop("fill", None)
def remove_redundant_none_strokes(root: ET.Element) -> None:
"""stroke=none is the SVG default."""
for element in root.iter():
if element.attrib.get("stroke") == "none":
element.attrib.pop("stroke", None)
def indent(element: ET.Element, level: int = 0) -> None:
"""Pretty-print XML without external dependencies."""
prefix = "\n" + " " * level
child_prefix = "\n" + " " * (level + 1)
children = list(element)
if children:
if not element.text or not element.text.strip():
element.text = child_prefix
for index, child in enumerate(children):
indent(child, level + 1)
if index == len(children) - 1:
child.tail = prefix
else:
child.tail = child_prefix
# =============================================================================
# Cleaning
# =============================================================================
def clean_svg_tree(
source: Path,
*,
monochrome: bool = True,
unwrap: bool = True,
) -> ET.ElementTree:
tree = ET.parse(source)
root = tree.getroot()
if local_name(root.tag) != "svg":
raise ValueError(f"{source}: root element is not <svg>")
remove_unwanted_elements(root)
remove_background_rect(root)
for element in root.iter():
clean_attributes(element)
if monochrome:
set_default_black_fill(root)
remove_white_shape_fills(root)
remove_redundant_black_fills(root)
remove_redundant_none_strokes(root)
if unwrap:
unwrap_groups(root)
indent(root)
return tree
def write_svg_atomic(tree: ET.ElementTree, destination: Path) -> None:
"""
Write to a temporary file first, then atomically replace destination.
"""
destination.parent.mkdir(parents=True, exist_ok=True)
fd, temporary_name = tempfile.mkstemp(
prefix=f".{destination.name}.",
suffix=".tmp",
dir=destination.parent,
)
os.close(fd)
temporary = Path(temporary_name)
try:
tree.write(
temporary,
encoding="unicode",
xml_declaration=False,
short_empty_elements=True,
)
os.replace(temporary, destination)
except Exception:
temporary.unlink(missing_ok=True)
raise
# =============================================================================
# Input/output resolution
# =============================================================================
def backup_path(source: Path) -> Path:
"""
foo.svg -> foo.svg.bkp
foo.svg.bkp -> foo.svg.bkp
"""
if source.suffix == ".bkp":
return source
return source.with_name(source.name + ".bkp")
def backup_output_path(source: Path) -> Path:
"""
foo.svg:
source renamed to foo.svg.bkp
output becomes foo.svg
foo.svg.bkp:
source remains foo.svg.bkp
output becomes foo.svg
"""
if source.suffix == ".bkp":
stripped = source.with_suffix("")
if stripped.suffix.lower() == ".svg":
return stripped
return stripped.with_suffix(".svg")
return source
def default_output_path(source: Path) -> Path:
"""foo.svg -> foo.clean.svg"""
if source.suffix == ".bkp":
source = source.with_suffix("")
if source.suffix.lower() == ".svg":
return source.with_name(source.stem + ".clean.svg")
return source.with_suffix(".clean.svg")
def output_directory_path(source: Path, directory: Path) -> Path:
"""
foo.svg -> DIR/foo.svg
foo.svg.bkp -> DIR/foo.svg
"""
name = source.name
if name.endswith(".bkp"):
name = name[:-4]
path = Path(name)
if path.suffix.lower() != ".svg":
path = path.with_suffix(".svg")
return directory / path.name
# =============================================================================
# Per-file processing
# =============================================================================
def process_file(
source: Path,
*,
replace: bool,
backup: bool,
output_directory: Path | None,
monochrome: bool,
unwrap: bool,
) -> Path:
if not source.is_file():
raise FileNotFoundError(f"file does not exist: {source}")
tree = clean_svg_tree(
source,
monochrome=monochrome,
unwrap=unwrap,
)
if backup:
destination = backup_output_path(source)
backup_file = backup_path(source)
if source != backup_file:
if backup_file.exists():
raise FileExistsError(
f"backup already exists: {backup_file}"
)
source.rename(backup_file)
write_svg_atomic(tree, destination)
return destination
if replace:
write_svg_atomic(tree, source)
return source
if output_directory is not None:
destination = output_directory_path(
source,
output_directory,
)
write_svg_atomic(tree, destination)
return destination
destination = default_output_path(source)
write_svg_atomic(tree, destination)
return destination
# =============================================================================
# CLI
# =============================================================================
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Clean Draw.io SVG exports into simple, static SVG files.\n\n"
"By default, each input is preserved and the cleaned version is\n"
"written next to it using the '.clean.svg' suffix."
),
epilog="""
OUTPUT MODES
------------
Default:
icon.svg
-> icon.clean.svg
The original file is preserved.
--replace:
icon.svg
-> icon.svg
The original file is erased and replaced by the cleaned SVG.
--backup:
icon.svg
-> icon.svg.bkp original Draw.io SVG
-> icon.svg cleaned SVG
The original input is considered disposable/generated, but is retained
as a .bkp file before the cleaned SVG takes its name.
If the input is already a backup:
icon.svg.bkp
-> icon.svg.bkp remains unchanged
-> icon.svg cleaned SVG
A '.bkp.bkp' file is never created.
If icon.svg.bkp already exists when processing icon.svg, the operation
fails instead of overwriting the existing backup.
--output DIR:
icon.svg
-> DIR/icon.svg
foo.svg bar.svg
-> DIR/foo.svg
-> DIR/bar.svg
Input files are left untouched. DIR is created automatically if needed.
MULTIPLE INPUTS
---------------
Any number of SVGs may be supplied:
clean_drawio_svg.py foo.svg bar.svg baz.svg
Output modes apply independently to every input:
clean_drawio_svg.py --replace *.svg
clean_drawio_svg.py --backup sword.svg shield.svg armor.svg
clean_drawio_svg.py --output build/icons *.svg
MUTUALLY EXCLUSIVE OPTIONS
--------------------------
--replace, --backup and --output cannot be combined.
EXAMPLES
--------
# Preserve original and create icon.clean.svg
clean_drawio_svg.py icon.svg
# Clean several files
clean_drawio_svg.py sword.svg shield.svg armor.svg
# Replace generated SVGs directly
clean_drawio_svg.py --replace *.svg
# Preserve Draw.io originals as *.svg.bkp
clean_drawio_svg.py --backup *.svg
# Put cleaned files in another directory
clean_drawio_svg.py --output generated *.svg
# Keep the original colors
clean_drawio_svg.py --replace --keep-colors icon.svg
# Preserve otherwise redundant SVG groups
clean_drawio_svg.py --replace --keep-groups icon.svg
""",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"inputs",
metavar="SVG",
nargs="+",
type=Path,
help="one or more SVG or SVG.bkp files to clean",
)
output_mode = parser.add_mutually_exclusive_group()
output_mode.add_argument(
"--replace",
action="store_true",
help=(
"replace each input with its cleaned version "
"(original is permanently discarded)"
),
)
output_mode.add_argument(
"--backup",
action="store_true",
help=(
"rename original foo.svg to foo.svg.bkp and write the "
"cleaned result as foo.svg"
),
)
output_mode.add_argument(
"-o",
"--output",
type=Path,
metavar="DIR",
help=(
"write cleaned SVGs into DIR without modifying the inputs"
),
)
parser.add_argument(
"--keep-colors",
action="store_true",
help=(
"preserve explicit SVG colors instead of converting "
"the image to monochrome black"
),
)
parser.add_argument(
"--keep-groups",
action="store_true",
help=(
"preserve otherwise redundant empty SVG <g> wrappers"
),
)
return parser.parse_args()
def main() -> int:
args = parse_args()
if args.output is not None:
args.output.mkdir(parents=True, exist_ok=True)
if not args.output.is_dir():
print(
f"error: output is not a directory: {args.output}",
file=sys.stderr,
)
return 2
failures = 0
for source in args.inputs:
try:
destination = process_file(
source,
replace=args.replace,
backup=args.backup,
output_directory=args.output,
monochrome=not args.keep_colors,
unwrap=not args.keep_groups,
)
print(f"{source} -> {destination}")
except (
ET.ParseError,
ValueError,
FileNotFoundError,
FileExistsError,
OSError,
) as exc:
print(
f"error: {source}: {exc}",
file=sys.stderr,
)
failures += 1
if failures:
print(
f"{failures} file(s) failed",
file=sys.stderr,
)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())