motion-svg / validator.py
pdyoung's picture
Update validator.py
aa1973d verified
Raw History Blame Contribute Delete
9.91 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,
generated: 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}).")
# 모델이 인라인 스타일로 작성한 색상·선 속성을 SVG 속성으로 변환
if generated and kind in ELEMENTS and "style" in node.attrib:
inline_style = node.attrib.pop("style")
for declaration in inline_style.split(";"):
if not declaration.strip():
continue
name, separator, value = declaration.partition(":")
name = name.strip().lower()
value = value.strip()
if not separator or not value:
raise SVGError("SVG의 style 속성 형식이 올바르지 않습니다.")
if name in PAINT:
if not (COLOR.fullmatch(value) or LOCAL_URL.fullmatch(value)):
raise SVGError(f"지원하지 않는 색상 값입니다 ({name}).")
elif name in {"opacity", "fill-opacity", "stroke-opacity", "stroke-width"}:
if not re.fullmatch(NUMBER, value):
raise SVGError(f"숫자로 표현해야 하는 SVG 속성입니다 ({name}).")
else:
raise SVGError(f"개별 SVG 속성으로 작성해야 합니다 ({name}).")
node.set(name, value)
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")