SILICON
Loading...
Searching...
No Matches
normalize.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""Select SVG elements and assign Silicon palette colors in a local browser."""
3
4import argparse
5import io
6import json
7import re
8import secrets
9import shutil
10import subprocess
11import sys
12import tempfile
13import webbrowser
14import xml.etree.ElementTree as ET
15import zipfile
16from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
17from pathlib import Path
18from urllib.parse import urlsplit
19
20SVG_NS = "http://www.w3.org/2000/svg"
21SCRIPT_DIR = Path(__file__).resolve().parent
22PALETTE_PATH = SCRIPT_DIR.parents[1] / "resources/app/palette.json"
23DEFAULT_CONFIG = SCRIPT_DIR / "svgo.config.mjs"
24MAX_SVG_BYTES = 10 * 1024 * 1024
25MAX_REQUEST_BYTES = MAX_SVG_BYTES * 6 + 1024
26ET.register_namespace("", SVG_NS)
27ET.register_namespace("xlink", "http://www.w3.org/1999/xlink")
28
29
30class SVGTreeBuilder(ET.TreeBuilder):
31 def doctype(self, name, pubid, system):
32 # This is called even for UTF-16/32 input, unlike a byte search.
33 raise ValueError("DTD and entity declarations are forbidden")
34
35
36def parse_svg(data: bytes) -> ET.Element:
37 if len(data) > MAX_SVG_BYTES:
38 raise ValueError("SVG exceeds the 10 MiB size limit")
39 if b"<!DOCTYPE" in data.upper() or b"<!ENTITY" in data.upper():
40 raise ValueError("DTD and entity declarations are forbidden")
41 root = ET.fromstring(data, parser=ET.XMLParser(target=SVGTreeBuilder()))
42 if root.tag != f"{{{SVG_NS}}}svg":
43 raise ValueError("Not an SVG document")
44 return root
45
46
47def load_palette(path: Path = PALETTE_PATH) -> dict:
48 palette = json.loads(path.read_text(encoding="utf-8"))
49 if not isinstance(palette, dict) or set(palette) != {"light", "dark"}:
50 raise ValueError("Palette must contain light and dark themes")
51 for theme, colors in palette.items():
52 if not isinstance(colors, dict) or not colors:
53 raise ValueError(f"{theme}: expected a nonempty palette")
54 for token, color in colors.items():
55 if not re.fullmatch(r"SILICON_[A-Z][A-Z0-9_]*", token):
56 raise ValueError(f"Invalid palette token: {token}")
57 if not isinstance(color, str) or not re.fullmatch(r"#[0-9a-fA-F]{6}", color):
58 raise ValueError(f"{theme}.{token}: expected #RRGGBB")
59 if palette["light"].keys() != palette["dark"].keys():
60 raise ValueError("Light and dark palette tokens must match")
61 return palette
62
63
64def sanitize_svg(root: ET.Element) -> bool:
65 """Keep static SVG; the preview additionally blocks network loads with CSP."""
66 changed = False
67 forbidden = {"script", "foreignobject", "iframe", "object", "embed",
68 "animate", "animatemotion", "animatetransform", "set"}
69 for parent in list(root.iter()):
70 for child in list(parent):
71 if child.tag.rsplit("}", 1)[-1].lower() in forbidden:
72 parent.remove(child)
73 changed = True
74 for name, value in list(parent.attrib.items()):
75 local = name.rsplit("}", 1)[-1].lower()
76 unsafe_href = local == "href" and not (
77 value.strip().startswith("#")
78 or re.match(r"^data:image/(png|jpeg|gif|webp);base64,", value, re.I)
79 )
80 if local.startswith("on") or local == "base" or unsafe_href:
81 del parent.attrib[name]
82 changed = True
83 return changed
84
85
86def serialize(root: ET.Element) -> bytes:
87 return ET.tostring(root, encoding="utf-8", xml_declaration=True)
88
89
90def import_svg(data: bytes, config: Path = DEFAULT_CONFIG) -> dict:
91 root = parse_svg(data)
92 sanitized = sanitize_svg(root)
93 root = optimize_svg(root, config)
94 sanitized = sanitize_svg(root) or sanitized
95 return {"svg": serialize(root).decode("utf-8"), "sanitized": sanitized}
96
97
98def resolve_palette(root: ET.Element, colors: dict) -> None:
99 """Resolve annotations with the same inline-style precedence as Silicon."""
100 for element in root.iter():
101 for prop in ("fill", "stroke"):
102 color = colors.get(element.get(f"data-silicon-{prop}"))
103 if color is None:
104 continue
105 style = element.get("style", "")
106 pattern = re.compile(rf"(^|;)(\s*{prop}\s*:)[^;]*")
107 if pattern.search(style):
108 element.set("style", pattern.sub(
109 lambda m: m[1] + m[2] + color +
110 (" !important" if re.search(r"!\s*important\s*$", m[0]) else ""), style))
111 else:
112 element.set(prop, color)
113
114
115def optimize(source: bytes, config: Path) -> bytes:
116 if not shutil.which("svgo"):
117 raise ValueError("SVGO is required to open SVGs. Install it with 'npm install -g svgo' "
118 "or run this tool in 'nix-shell -p svgo'.")
119 if not config.is_file():
120 raise ValueError(f"SVGO configuration not found: {config}")
121 with tempfile.TemporaryDirectory(prefix="silicon-svg-") as directory:
122 input_file = Path(directory) / "input.svg"
123 output_file = Path(directory) / "output.svg"
124 input_file.write_bytes(source)
125 try:
126 subprocess.run(
127 ["svgo", "--config", str(config.resolve()), "--input", str(input_file),
128 "--output", str(output_file)],
129 check=True, capture_output=True, text=True, timeout=60,
130 )
131 except subprocess.CalledProcessError as error:
132 raise ValueError(f"SVGO failed: {(error.stderr or error.stdout).strip()}") from error
133 except subprocess.TimeoutExpired as error:
134 raise ValueError("SVGO timed out after 60 seconds; the SVG was not opened") from error
135 return output_file.read_bytes()
136
137
138def optimize_svg(root: ET.Element, config: Path) -> ET.Element:
139 # A custom SVGO configuration must not silently lose or combine mappings.
140 guard = "data-normalize-" + secrets.token_hex(12)
141 expected = {}
142 for element in root.iter():
143 mappings = {p: element.get(f"data-silicon-{p}") for p in ("fill", "stroke")}
144 if any(mappings.values()):
145 key = str(len(expected))
146 expected[key] = mappings
147 element.set(guard, key)
148 result = parse_svg(optimize(serialize(root), config))
149 actual = {}
150 for element in result.iter():
151 key = element.attrib.pop(guard, None)
152 mappings = {p: element.get(f"data-silicon-{p}") for p in ("fill", "stroke")}
153 if key is not None:
154 if key in actual:
155 raise ValueError("SVGO duplicated a palette mapping; use the bundled configuration")
156 actual[key] = mappings
157 elif any(mappings.values()):
158 raise ValueError("SVGO moved a palette mapping; use the bundled configuration")
159 if actual != expected:
160 raise ValueError("SVGO removed or changed palette mappings; use the bundled configuration")
161 return result
162
163
164def export_svg(source: bytes, palette: dict) -> bytes:
165 """Serialize edits to an already optimized document without running SVGO."""
166 root = parse_svg(source)
167 sanitize_svg(root)
168 resolve_palette(root, palette["light"])
169 return serialize(root)
170
171
172def process_file(source: Path, destination: Path, config: Path) -> None:
173 """Noninteractive helper; writes only after successful optimization."""
174 imported = import_svg(source.read_bytes(), config)
175 destination.write_bytes(export_svg(imported["svg"].encode("utf-8"), load_palette()))
176
177
178def export_name(source: str, used: set, overwrite: bool = False, reserved=None) -> str:
179 """Match browser naming, keeping archive paths and duplicate names out."""
180 stem = re.sub(r"\.svg$", "", source, flags=re.I)
181 stem = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "-", stem).rstrip(". ") or "document"
182 base = stem if overwrite else f"{stem}.normalized"
183 extension = re.search(r"\.svg$", source, flags=re.I) if overwrite else None
184 extension = extension[0] if extension else ".svg"
185 first = f"{base}{extension}"
186 name, suffix = first, 2
187 while name.lower() in used or (name != first and name.lower() in (reserved or set())):
188 name = f"{base}-{suffix}{extension}"
189 suffix += 1
190 used.add(name.lower())
191 return name
192
193
194def export_archive(files: list, palette: dict, overwrite: bool = False) -> bytes:
195 if not isinstance(files, list) or not files:
196 raise ValueError("Expected a nonempty list of SVG files")
197 if not isinstance(overwrite, bool):
198 raise ValueError("Overwrite must be true or false")
199 for item in files:
200 if (not isinstance(item, dict) or not isinstance(item.get("name"), str)
201 or not isinstance(item.get("svg"), str)):
202 raise ValueError("Each file must contain a name and SVG string")
203 archive = io.BytesIO()
204 used = set()
205 reserved = {export_name(item["name"], set(), overwrite=True).lower() for item in files}
206 with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED) as output:
207 for item in files:
208 name = export_name(item["name"], used, overwrite, reserved)
209 try:
210 result = export_svg(item["svg"].encode("utf-8"), palette)
211 except (ValueError, ET.ParseError, OSError) as error:
212 raise ValueError(f'{item["name"]}: {error}') from error
213 output.writestr(name, result)
214 return archive.getvalue()
215
216
217def make_server(sources: list[dict], palette: dict, config: Path, port: int = 0):
218 token = secrets.token_urlsafe(32)
219 assets = {"/": ("editor.html", "text/html; charset=utf-8"),
220 "/editor.js": ("editor.js", "text/javascript; charset=utf-8"),
221 "/editor.css": ("editor.css", "text/css; charset=utf-8")}
222
223 class Handler(BaseHTTPRequestHandler):
224 def log_message(self, format, *args):
225 pass # Do not log the session token in the URL.
226
227 def reply(self, status, body, content_type="application/json; charset=utf-8"):
228 self.send_response(status)
229 self.send_header("Content-Type", content_type)
230 self.send_header("Content-Length", str(len(body)))
231 self.send_header("Cache-Control", "no-store")
232 self.send_header("X-Content-Type-Options", "nosniff")
233 self.send_header("Referrer-Policy", "no-referrer")
234 self.send_header("Content-Security-Policy", "default-src 'none'; script-src 'self'; "
235 "style-src 'self' 'unsafe-inline'; connect-src 'self'; "
236 "frame-src 'self'; img-src data:; base-uri 'none'; frame-ancestors 'none'")
237 self.end_headers()
238 self.wfile.write(body)
239
240 def error(self, status, message):
241 self.reply(status, json.dumps({"error": message}).encode())
242
243 def authorized(self):
244 origin = f"http://127.0.0.1:{self.server.server_port}"
245 if self.headers.get("Host") != origin.removeprefix("http://"):
246 self.error(403, "Invalid host")
247 return False
248 if self.headers.get("Origin", origin) != origin:
249 self.error(403, "Invalid origin")
250 return False
251 if not secrets.compare_digest(self.headers.get("X-Normalize-Token", ""), token):
252 self.error(403, "Invalid session; open the URL printed by normalize.py")
253 return False
254 return True
255
256 def do_GET(self):
257 path = urlsplit(self.path).path
258 if path in assets:
259 filename, content_type = assets[path]
260 self.reply(200, (SCRIPT_DIR / filename).read_bytes(), content_type)
261 elif path == "/api/state" and self.authorized():
262 self.reply(200, json.dumps({"palette": palette, "files": sources,
263 "svgo": bool(shutil.which("svgo"))}).encode())
264 elif path != "/api/state":
265 self.error(404, "Not found")
266
267 def do_POST(self):
268 if not self.authorized():
269 return
270 path = urlsplit(self.path).path
271 if path not in {"/api/import", "/api/export", "/api/export-all"}:
272 self.error(404, "Not found")
273 return
274 try:
275 length = int(self.headers.get("Content-Length", "0"))
276 if not 0 < length <= MAX_REQUEST_BYTES:
277 raise ValueError("Request exceeds the 60 MiB limit; save large documents individually")
278 data = json.loads(self.rfile.read(length))
279 if path == "/api/export-all":
280 if not isinstance(data, dict):
281 raise ValueError("Expected a list of SVG files")
282 self.reply(200, export_archive(data.get("files"), palette,
283 data.get("overwrite", False)), "application/zip")
284 return
285 if not isinstance(data, dict) or not isinstance(data.get("svg"), str):
286 raise ValueError("Expected an SVG string")
287 source = data["svg"].encode("utf-8")
288 if path == "/api/import":
289 self.reply(200, json.dumps(import_svg(source, config)).encode())
290 else:
291 self.reply(200, export_svg(source, palette), "image/svg+xml")
292 except (ValueError, ET.ParseError, OSError) as error:
293 self.error(400, str(error))
294
295 server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
296 server.daemon_threads = True
297 return server, f"http://127.0.0.1:{server.server_port}/?token={token}"
298
299
300def main() -> int:
301 parser = argparse.ArgumentParser(description=__doc__)
302 parser.add_argument("sources", type=Path, nargs="*", help="SVG files or directories to preload")
303 parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG, help="SVGO configuration")
304 parser.add_argument("--port", type=int, default=0, help="Local port (default: choose a free port)")
305 parser.add_argument("--no-browser", action="store_true", help="Print the URL without opening it")
306 args = parser.parse_args()
307 try:
308 palette = load_palette()
309 if not args.config.is_file():
310 raise ValueError(f"SVGO configuration not found: {args.config}")
311 sources, seen = [], set()
312 for path in args.sources:
313 for source in sorted(path.rglob("*.svg")) if path.is_dir() else [path]:
314 if source.resolve() in seen:
315 continue
316 seen.add(source.resolve())
317 try:
318 sources.append({"name": source.name, **import_svg(source.read_bytes(), args.config)})
319 except (OSError, ValueError, ET.ParseError) as error:
320 print(f"Skipping {source}: {error}", file=sys.stderr)
321 server, url = make_server(sources, palette, args.config, args.port)
322 except (OSError, ValueError) as error:
323 print(f"normalize.py: {error}", file=sys.stderr)
324 return 1
325 print(f"SVG palette editor: {url}", flush=True)
326 print("Press Ctrl+C to stop. SVGs are optimized with SVGO when opened.", flush=True)
327 if not shutil.which("svgo"):
328 print("SVGO is missing: install it before opening SVGs (npm install -g svgo).", file=sys.stderr)
329 if not args.no_browser:
330 webbrowser.open(url)
331 try:
332 server.serve_forever()
333 except KeyboardInterrupt:
334 pass
335 finally:
336 server.server_close()
337 return 0
338
339
340if __name__ == "__main__":
341 sys.exit(main())
doctype(self, name, pubid, system)
Definition normalize.py:31
dict load_palette(Path path=PALETTE_PATH)
Definition normalize.py:47
ET.Element parse_svg(bytes data)
Definition normalize.py:36
ET.Element optimize_svg(ET.Element root, Path config)
Definition normalize.py:138
bytes export_svg(bytes source, dict palette)
Definition normalize.py:164
bytes optimize(bytes source, Path config)
Definition normalize.py:115
str export_name(str source, set used, bool overwrite=False, reserved=None)
Definition normalize.py:178
bool sanitize_svg(ET.Element root)
Definition normalize.py:64
int main()
Definition normalize.py:300
None resolve_palette(ET.Element root, dict colors)
Definition normalize.py:98
bytes export_archive(list files, dict palette, bool overwrite=False)
Definition normalize.py:194
make_server(list[dict] sources, dict palette, Path config, int port=0)
Definition normalize.py:217
dict import_svg(bytes data, Path config=DEFAULT_CONFIG)
Definition normalize.py:90
bytes serialize(ET.Element root)
Definition normalize.py:86
None process_file(Path source, Path destination, Path config)
Definition normalize.py:172