Spaces:
Running on Zero
Running on Zero
File size: 8,593 Bytes
29e1b52 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | 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")
|