Motion-SVG-Vector / validator.py
dodoyy's picture
Restore pre-Arrow SVG validation
bf353ec verified
Raw History Blame Contribute Delete
8.59 kB
import math
import re
from xml.etree import ElementTree as ET
from defusedxml import ElementTree as safe_xml
from defusedxml.common import DefusedXmlException
SVG_NS = "http://www.w3.org/2000/svg"
NS = f"{{{SVG_NS}}}"
MAX_SVG_BYTES = 100_000
ET.register_namespace("", SVG_NS)
NUMBER = r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?"
ID = r"[A-Za-z_][\w.:-]*"
LOCAL_URL = re.compile(rf"url\(\s*#{ID}\s*\)")
COLOR = re.compile(r"#[0-9a-fA-F]{3,8}|[A-Za-z]+|(?:rgb|hsl)a?\([0-9.,% +/\-]+\)")
CLOCK = re.compile(r"(\d+(?:\.\d+)?|\.\d+)(ms|s)")
PAINT = {"fill", "stroke", "color", "stop-color"}
PRESENTATION = PAINT | {
"fill-opacity", "fill-rule", "stroke-opacity", "stroke-width",
"stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-dasharray",
"stroke-dashoffset", "opacity", "transform", "clip-path", "clip-rule",
"vector-effect", "font-family", "font-size", "font-weight",
"text-anchor", "dominant-baseline",
}
ELEMENTS = {
"svg": {"viewBox", "width", "height", "preserveAspectRatio", "version"},
"g": set(),
"path": {"d", "pathLength"},
"rect": {"x", "y", "width", "height", "rx", "ry", "pathLength"},
"circle": {"cx", "cy", "r", "pathLength"},
"ellipse": {"cx", "cy", "rx", "ry", "pathLength"},
"line": {"x1", "y1", "x2", "y2", "pathLength"},
"polyline": {"points", "pathLength"},
"polygon": {"points", "pathLength"},
"text": {"x", "y", "dx", "dy", "rotate"},
"tspan": {"x", "y", "dx", "dy", "rotate"},
"defs": set(),
"linearGradient": {"x1", "y1", "x2", "y2", "gradientUnits", "gradientTransform", "spreadMethod"},
"radialGradient": {"cx", "cy", "r", "fx", "fy", "fr", "gradientUnits", "gradientTransform", "spreadMethod"},
"stop": {"offset", "stop-opacity"},
"clipPath": {"clipPathUnits"},
"title": set(),
"desc": set(),
}
TIMING = {
"attributeName", "values", "from", "to", "by", "dur", "begin",
"repeatCount", "fill", "calcMode", "keyTimes", "keySplines",
}
ANIMATIONS = {
"animate": TIMING,
"animateTransform": TIMING | {"type"},
"animateMotion": (TIMING - {"attributeName"}) | {"path", "rotate", "keyPoints"},
}
ANIMATABLE = PAINT | {
"opacity", "fill-opacity", "stroke-opacity", "stroke-width", "stroke-dashoffset",
"stop-opacity", "offset", "x", "y", "width", "height", "cx", "cy", "r", "rx",
"ry", "x1", "x2", "y1", "y2", "d", "points",
}
GRAPHICS = {
"g", "path", "rect", "circle", "ellipse", "line", "polyline",
"polygon", "text", "tspan",
}
class SVGError(ValueError):
"""The source SVG is invalid or outside the supported subset."""
def seconds(value: str) -> float:
match = CLOCK.fullmatch(value)
if match is None:
raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ μ‹œκ°„μ— s λ˜λŠ” ms λ‹¨μœ„λ₯Ό μ‚¬μš©ν•΄ μ£Όμ„Έμš”.")
amount, unit = match.groups()
number = float(amount) / (1000 if unit == "ms" else 1)
if not math.isfinite(number):
raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ μ‹œκ°„μ„ 확인해 μ£Όμ„Έμš”.")
return number
def view_box(root: ET.Element) -> tuple[float, float, float, float]:
raw = root.get("viewBox")
if raw is None:
dimensions = [root.get(axis, "") for axis in ("width", "height")]
raw = "0 0 " + " ".join(d.removesuffix("px") for d in dimensions)
parts = re.split(r"[\s,]+", raw.strip())
if len(parts) != 4 or any(re.fullmatch(NUMBER, part) is None for part in parts):
raise SVGError("SVG에 μ˜¬λ°”λ₯Έ viewBox λ˜λŠ” ν”½μ…€ λ‹¨μœ„ λ„ˆλΉ„μ™€ 높이λ₯Ό λ„£μ–΄ μ£Όμ„Έμš”.")
x, y, width, height = map(float, parts)
if not all(math.isfinite(n) and abs(n) <= 100_000 for n in (x, y, width, height)):
raise SVGError("SVG의 viewBox λ²”μœ„λ₯Ό 확인해 μ£Όμ„Έμš”.")
if width <= 0 or height <= 0:
raise SVGError("SVG의 λ„ˆλΉ„μ™€ λ†’μ΄λŠ” μ–‘μˆ˜μ—¬μ•Ό ν•©λ‹ˆλ‹€.")
return x, y, width, height
def _validate_animation(element: ET.Element, kind: str, parent: str | None) -> None:
target = element.get("attributeName", "")
if parent not in (GRAPHICS | {"svg", "stop"}):
raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜μ€ 움직일 λ„ν˜• μ•ˆμ— λ„£μ–΄ μ£Όμ„Έμš”.")
if kind == "animate" and target not in ANIMATABLE:
raise SVGError(f"μ§€μ›ν•˜μ§€ μ•ŠλŠ” μ• λ‹ˆλ©”μ΄μ…˜ μ†μ„±μž…λ‹ˆλ‹€ ({target}).")
if kind == "animateTransform" and (
target != "transform"
or element.get("type") not in {"translate", "scale", "rotate", "skewX", "skewY"}
):
raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜μ˜ transform μœ ν˜•μ„ 확인해 μ£Όμ„Έμš”.")
if not 0.001 <= seconds(element.get("dur", "")) <= 600:
raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ κΈΈμ΄λŠ” 1ms 이상 600초 μ΄ν•˜μ—¬μ•Ό ν•©λ‹ˆλ‹€.")
begin = element.get("begin")
if begin is not None and begin != "0" and not 0 <= seconds(begin) <= 600:
raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ μ‹œμž‘ μ‹œκ°„μ„ 확인해 μ£Όμ„Έμš”.")
repeat = element.get("repeatCount", "1")
if repeat != "indefinite" and not (
re.fullmatch(NUMBER, repeat) and 0 < float(repeat) <= 100
):
raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ 반볡 횟수λ₯Ό 확인해 μ£Όμ„Έμš”.")
if element.get("fill", "remove") not in {"freeze", "remove"}:
raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ μ’…λ£Œ μƒνƒœλ₯Ό 확인해 μ£Όμ„Έμš”.")
value_attrs = {"values", "from", "to", "by"}
if kind == "animateMotion":
value_attrs.add("path")
if not any(element.get(name) for name in value_attrs):
raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜μ— μ›€μ§μž„ 값이 ν•„μš”ν•©λ‹ˆλ‹€.")
if target in PAINT:
for name in value_attrs:
if name in element.attrib and any(
not COLOR.fullmatch(value.strip()) for value in element.attrib[name].split(";")
):
raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ 색상 값을 확인해 μ£Όμ„Έμš”.")
def parse_svg(source: str, *, require_animation: bool = False) -> ET.Element:
if len(source.encode("utf-8")) > MAX_SVG_BYTES:
raise SVGError("SVGλŠ” 100 KB μ΄ν•˜μ—¬μ•Ό ν•©λ‹ˆλ‹€.")
try:
root = safe_xml.fromstring(source.strip(), forbid_dtd=True)
except (ET.ParseError, DefusedXmlException) as exc:
raise SVGError("μ˜¬λ°”λ₯Έ SVG XML을 읽을 수 μ—†μŠ΅λ‹ˆλ‹€.") from exc
if root.tag not in {"svg", NS + "svg"}:
raise SVGError("SVG 파일 λ˜λŠ” SVG μ½”λ“œκ°€ ν•„μš”ν•©λ‹ˆλ‹€.")
view_box(root)
# Rebuild the namespace and accept only standalone SVG drawing primitives.
stack = [(root, None, 0)]
ids = set()
has_animation = False
has_graphics = False
count = 0
while stack:
node, parent, depth = stack.pop()
kind = node.tag.removeprefix(NS)
count += 1
if depth > 35 or count > 1200:
raise SVGError("SVG에 λ„ˆλ¬΄ λ§Žμ€ λ„ν˜• λ˜λŠ” 쀑첩이 μžˆμŠ΅λ‹ˆλ‹€.")
if kind in ANIMATIONS:
allowed = ANIMATIONS[kind]
_validate_animation(node, kind, parent)
has_animation = True
elif kind in ELEMENTS and (kind != "svg" or parent is None):
allowed = ELEMENTS[kind] | PRESENTATION
has_graphics |= kind in GRAPHICS - {"g", "tspan"}
else:
raise SVGError(f"μ§€μ›ν•˜μ§€ μ•ŠλŠ” SVG μš”μ†Œμž…λ‹ˆλ‹€ ({kind}).")
for attr, value in node.attrib.items():
if attr == "id":
if not re.fullmatch(ID, value) or value in ids:
raise SVGError("SVG μš”μ†Œ IDκ°€ 잘λͺ»λ˜μ—ˆκ±°λ‚˜ μ€‘λ³΅λ©λ‹ˆλ‹€.")
ids.add(value)
elif attr not in allowed:
raise SVGError(f"μ§€μ›ν•˜μ§€ μ•ŠλŠ” SVG μ†μ„±μž…λ‹ˆλ‹€ ({attr}).")
elif kind not in ANIMATIONS and attr in PAINT:
if not (COLOR.fullmatch(value) or LOCAL_URL.fullmatch(value)):
raise SVGError("SVG μƒ‰μƒμ—λŠ” 색상 κ°’ λ˜λŠ” λ‚΄λΆ€ ID만 μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.")
elif attr == "clip-path" and value != "none" and not LOCAL_URL.fullmatch(value):
raise SVGError("clip-pathμ—λŠ” SVG λ‚΄λΆ€ ID만 μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.")
node.tag = NS + kind
stack.extend((child, kind, depth + 1) for child in node)
if not has_graphics:
raise SVGError("SVG에 ν‘œμ‹œν•  λ„ν˜•μ΄ ν•„μš”ν•©λ‹ˆλ‹€.")
if require_animation and not has_animation:
raise SVGError("SVG에 SMIL μ• λ‹ˆλ©”μ΄μ…˜μ΄ ν•„μš”ν•©λ‹ˆλ‹€.")
if root.get("viewBox") is None:
root.set("viewBox", " ".join(f"{value:g}" for value in view_box(root)))
return root
def svg_text(root: ET.Element) -> str:
return ET.tostring(root, encoding="unicode")