391 lines
9.3 KiB
Python
Executable File
391 lines
9.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import re
|
|
import sys
|
|
import xml.etree.ElementTree as ET
|
|
from pathlib import Path
|
|
|
|
|
|
SVG_NS = "http://www.w3.org/2000/svg"
|
|
XLINK_NS = "http://www.w3.org/1999/xlink"
|
|
|
|
ET.register_namespace("", SVG_NS)
|
|
|
|
|
|
# -----------------------------------------------------------------------------
|
|
# Configuration
|
|
# -----------------------------------------------------------------------------
|
|
|
|
REMOVE_ATTRIBUTES = {
|
|
"style",
|
|
"id",
|
|
}
|
|
|
|
REMOVE_ROOT_ATTRIBUTES = {
|
|
f"{{http://www.w3.org/2000/xmlns/}}xlink",
|
|
"version",
|
|
}
|
|
|
|
REMOVE_TAGS = {
|
|
"style",
|
|
"defs",
|
|
}
|
|
|
|
# Convert verbose color spellings to compact stable forms.
|
|
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+)$")
|
|
|
|
|
|
# -----------------------------------------------------------------------------
|
|
# 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 numeric values where safe.
|
|
|
|
Examples:
|
|
305px -> 305
|
|
305.0 -> 305
|
|
0.5000 -> .5
|
|
-0.500 -> -.5
|
|
"""
|
|
value = value.strip()
|
|
|
|
# draw.io commonly emits px on root dimensions.
|
|
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:
|
|
value = value.strip()
|
|
|
|
if value in COLOR_REPLACEMENTS:
|
|
return COLOR_REPLACEMENTS[value]
|
|
|
|
return value
|
|
|
|
|
|
def clean_attributes(element: ET.Element, *, is_root: bool = False) -> None:
|
|
"""
|
|
Remove draw.io-specific styling and normalize simple attributes.
|
|
"""
|
|
attrs = dict(element.attrib)
|
|
|
|
for name in list(attrs):
|
|
lname = local_name(name)
|
|
|
|
if lname in REMOVE_ATTRIBUTES:
|
|
element.attrib.pop(name, None)
|
|
continue
|
|
|
|
if is_root and name in REMOVE_ROOT_ATTRIBUTES:
|
|
element.attrib.pop(name, None)
|
|
continue
|
|
|
|
# Normalize dimensions.
|
|
for name in ("width", "height", "x", "y"):
|
|
if name in element.attrib:
|
|
element.attrib[name] = strip_number(element.attrib[name])
|
|
|
|
# Normalize direct color attributes.
|
|
for name in ("fill", "stroke", "color"):
|
|
if name in element.attrib:
|
|
element.attrib[name] = normalize_color(element.attrib[name])
|
|
|
|
# Remove redundant draw.io defaults.
|
|
if element.attrib.get("stroke-miterlimit") == "10":
|
|
# Keep this for paths/groups where it could matter.
|
|
pass
|
|
|
|
if element.attrib.get("fill") == "none":
|
|
# Keep explicit fill="none": it is semantically important.
|
|
pass
|
|
|
|
|
|
def remove_unwanted_elements(parent: ET.Element) -> None:
|
|
"""Remove <style> and empty/unneeded <defs> blocks 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.
|
|
|
|
Typical form:
|
|
<rect fill="#ffffff"
|
|
width="100%"
|
|
height="100%"
|
|
x="0"
|
|
y="0"/>
|
|
"""
|
|
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_single_child_groups(element: ET.Element) -> None:
|
|
"""
|
|
Recursively unwrap useless <g> elements.
|
|
|
|
A group is considered useless when:
|
|
- it has no attributes
|
|
- it contains children
|
|
"""
|
|
for child in list(element):
|
|
unwrap_single_child_groups(child)
|
|
|
|
children = list(element)
|
|
|
|
for index, child in reversed(list(enumerate(children))):
|
|
if local_name(child.tag) != "g":
|
|
continue
|
|
|
|
if child.attrib:
|
|
continue
|
|
|
|
grandchildren = list(child)
|
|
|
|
if not grandchildren:
|
|
element.remove(child)
|
|
continue
|
|
|
|
insertion_index = list(element).index(child)
|
|
element.remove(child)
|
|
|
|
for grandchild in reversed(grandchildren):
|
|
element.insert(insertion_index, grandchild)
|
|
|
|
|
|
def normalize_tree(root: ET.Element) -> None:
|
|
for element in root.iter():
|
|
clean_attributes(element, is_root=(element is root))
|
|
|
|
|
|
def set_default_black_fill(root: ET.Element) -> None:
|
|
"""
|
|
Put fill="black" on the root.
|
|
|
|
Individual shapes with fill="none" still override this.
|
|
"""
|
|
root.set("fill", "black")
|
|
|
|
|
|
def remove_white_shape_fills(root: ET.Element) -> None:
|
|
"""
|
|
Replace explicit white shape fills with inherited root fill.
|
|
|
|
This is useful for monochrome Ravenous-style icons.
|
|
|
|
NOTE:
|
|
This deliberately changes white geometry to black.
|
|
"""
|
|
for element in root.iter():
|
|
if element is root:
|
|
continue
|
|
|
|
fill = element.attrib.get("fill")
|
|
|
|
if fill in {"#fff", "#ffffff", "white"}:
|
|
element.attrib.pop("fill", None)
|
|
|
|
|
|
def remove_redundant_black_fills(root: ET.Element) -> None:
|
|
"""
|
|
Since root has fill='black', explicit black fills are unnecessary.
|
|
"""
|
|
for element in root.iter():
|
|
if element is root:
|
|
continue
|
|
|
|
fill = element.attrib.get("fill")
|
|
|
|
if fill in {"#000", "#000000", "black"}:
|
|
element.attrib.pop("fill", None)
|
|
|
|
|
|
def remove_redundant_none_strokes(root: ET.Element) -> None:
|
|
"""
|
|
stroke='none' is normally the SVG default, so remove it.
|
|
"""
|
|
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:
|
|
"""
|
|
Basic pretty printer 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 i, child in enumerate(children):
|
|
indent(child, level + 1)
|
|
|
|
if i == len(children) - 1:
|
|
child.tail = prefix
|
|
else:
|
|
child.tail = child_prefix
|
|
|
|
elif level and (not element.tail or not element.tail.strip()):
|
|
element.tail = prefix
|
|
|
|
|
|
# -----------------------------------------------------------------------------
|
|
# Main conversion
|
|
# -----------------------------------------------------------------------------
|
|
|
|
def clean_svg(
|
|
source: Path,
|
|
destination: Path,
|
|
*,
|
|
monochrome: bool = True,
|
|
unwrap_groups: bool = True,
|
|
) -> None:
|
|
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)
|
|
normalize_tree(root)
|
|
|
|
if monochrome:
|
|
set_default_black_fill(root)
|
|
remove_white_shape_fills(root)
|
|
remove_redundant_black_fills(root)
|
|
remove_redundant_none_strokes(root)
|
|
|
|
if unwrap_groups:
|
|
unwrap_single_child_groups(root)
|
|
|
|
indent(root)
|
|
|
|
tree.write(
|
|
destination,
|
|
encoding="unicode",
|
|
xml_declaration=False,
|
|
short_empty_elements=True,
|
|
)
|
|
|
|
|
|
def output_path(source: Path, output: Path | None) -> Path:
|
|
if output is not None:
|
|
return output
|
|
|
|
return source.with_name(source.stem + ".clean.svg")
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(
|
|
description="Clean draw.io SVG exports into simple static SVG files."
|
|
)
|
|
|
|
parser.add_argument(
|
|
"input",
|
|
type=Path,
|
|
help="Input SVG file",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"-o",
|
|
"--output",
|
|
type=Path,
|
|
help="Output SVG file. Default: <input>.clean.svg",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--keep-colors",
|
|
action="store_true",
|
|
help="Do not force the SVG to monochrome black.",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--keep-groups",
|
|
action="store_true",
|
|
help="Do not unwrap empty draw.io <g> wrappers.",
|
|
)
|
|
|
|
args = parser.parse_args()
|
|
|
|
source = args.input
|
|
destination = output_path(source, args.output)
|
|
|
|
if not source.is_file():
|
|
print(f"error: file does not exist: {source}", file=sys.stderr)
|
|
return 1
|
|
|
|
try:
|
|
clean_svg(
|
|
source,
|
|
destination,
|
|
monochrome=not args.keep_colors,
|
|
unwrap_groups=not args.keep_groups,
|
|
)
|
|
except (ET.ParseError, ValueError) as exc:
|
|
print(f"error: {exc}", file=sys.stderr)
|
|
return 1
|
|
|
|
print(f"{source} -> {destination}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|