vectorbench 0.0.0-stage → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,638 @@
1
+ #!/usr/bin/env python3
2
+ """The sandbox's own commands, installed as `view`, `zoom`, `compare`,
3
+ `frames`, `render`, `check`, `weigh`, `shrink` and `submit` (one file, nine
4
+ names).
5
+
6
+ view FILE [SIZE] Show yourself an image. An SVG is drawn the way
7
+ voters will see it: put through the site's own
8
+ check, then drawn by Chromium in an <img> tag
9
+ on a white square frame SIZE pixels wide
10
+ (default 1024). PNG, JPEG, GIF and WebP files
11
+ are shown as they are.
12
+ zoom FILE.svg X Y W H [SIZE] Show yourself one region of the drawing, close
13
+ up: the part of its viewBox from (X, Y), W wide
14
+ and H high, drawn SIZE pixels wide (default
15
+ 1024), the same way `view` draws it.
16
+ compare FILE FILE... [SIZE] Show up to four images side by side, each SIZE
17
+ pixels wide, to see two versions together.
18
+ frames FILE.svg [SECONDS...] Show an animated drawing at several moments side
19
+ by side: four across its longest loop, or up to
20
+ six moments named in seconds. Each is the
21
+ drawing's own clock (SMIL and CSS) stopped at
22
+ that time, drawn by Chromium.
23
+ render IN.svg OUT.png [SIZE] Draw an SVG the same way and save the PNG, to
24
+ crop, enlarge or measure with other tools.
25
+ check FILE.svg Say whether the site would accept the file, and
26
+ why not if it wouldn't.
27
+ weigh FILE.svg Say where the file's bytes go: by element, by
28
+ part, in path data and in repeated shapes.
29
+ shrink IN.svg OUT.svg [DIGITS]
30
+ Make the file smaller with SVGO without
31
+ changing the picture: says how much smaller,
32
+ and how much the drawing changed, if at all.
33
+ submit [drawing.svg] Hand in /work/drawing.svg. Refused, with the
34
+ reason, if the site would not accept it.
35
+
36
+ `view`, `zoom`, `compare` and `frames` do not print the picture: they leave it in a
37
+ spool folder, and the harness attaches whatever is there to the command's
38
+ result as an image (`collect`, which the harness runs after every command,
39
+ empties the folder).
40
+ """
41
+
42
+ import base64
43
+ import json
44
+ import os
45
+ import re
46
+ import shutil
47
+ import signal
48
+ import subprocess
49
+ import sys
50
+ import tempfile
51
+ from collections import Counter, defaultdict
52
+ from pathlib import Path
53
+
54
+ STATE = Path.home() / ".vb"
55
+ SPOOL = STATE / "spool"
56
+ SUBMITTED = STATE / "submitted"
57
+ ENTRY = Path("/work/drawing.svg")
58
+ MAX_SIZE = 2048
59
+ MAX_BYTES = 1_500_000 # past this a PNG is sent as a JPEG instead
60
+ MIME = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp"}
61
+ SVG_NS = "{http://www.w3.org/2000/svg}"
62
+ LABEL_FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
63
+
64
+
65
+ def fail(message):
66
+ print(message, file=sys.stderr)
67
+ sys.exit(1)
68
+
69
+
70
+ def size_from(argument, name="size"):
71
+ try:
72
+ size = int(argument)
73
+ except ValueError:
74
+ fail(f"The {name} has to be a whole number of pixels, not {argument!r}.")
75
+ if not 16 <= size <= MAX_SIZE:
76
+ fail(f"The {name} has to be between 16 and {MAX_SIZE} pixels.")
77
+ return size
78
+
79
+
80
+ def number_from(argument, name):
81
+ try:
82
+ return float(argument)
83
+ except ValueError:
84
+ fail(f"{name} has to be a number, not {argument!r}.")
85
+
86
+
87
+ def existing(argument):
88
+ path = Path(argument)
89
+ if not path.is_file():
90
+ fail(f"There is no file {path}.")
91
+ return path
92
+
93
+
94
+ def checked(path, cleaned):
95
+ """The site's verdict on a file: (accepted, sentence). The file as the
96
+ site would store it is written to `cleaned` when it is accepted."""
97
+ done = subprocess.run(["node", "/opt/vb/check.mjs", str(path), str(cleaned)], capture_output=True, text=True, timeout=60)
98
+ try:
99
+ verdict = json.loads(done.stdout)
100
+ except json.JSONDecodeError:
101
+ fail(f"The check itself failed on {path}:\n{done.stderr.strip()[-2000:]}")
102
+ if not verdict["ok"]:
103
+ return False, f"{path} would not be accepted: {verdict['message']}"
104
+ # The site's check reads text, not XML: a file a browser can't parse draws nothing.
105
+ from lxml import etree
106
+
107
+ try:
108
+ etree.parse(str(cleaned))
109
+ except etree.XMLSyntaxError as error:
110
+ return False, f"{path} would not be accepted: it is not well-formed XML, so a browser will not draw it ({error})."
111
+ return True, f"{path} is accepted: {verdict['kb']} KB of the {verdict['limit']} KB allowed."
112
+
113
+
114
+ # Headless Chromium draws nothing in a window under about 150 pixels, so the
115
+ # page is always at least this big, the picture is laid out at its exact
116
+ # size in the top left corner, and the screenshot is cut down to it.
117
+ MIN_WINDOW = 512
118
+ BROWSER_SECONDS = 100
119
+ _browser = None
120
+
121
+
122
+ def _stop_browser(*_):
123
+ """Kills the browser and everything it started (it runs in its own process group)."""
124
+ # The whole group, even when its leader has already exited: its helpers may not have.
125
+ if _browser:
126
+ try:
127
+ os.killpg(_browser.pid, signal.SIGKILL)
128
+ except (ProcessLookupError, PermissionError):
129
+ pass
130
+
131
+
132
+ def _stopped(number, _frame):
133
+ # The harness stops a command that runs too long; take the browser with it.
134
+ _stop_browser()
135
+ sys.exit(128 + number)
136
+
137
+
138
+ def screenshot(html, png, width, height, extra=()):
139
+ """Draws a page whose picture fills the top left `width` x `height`
140
+ pixels and saves just those pixels. One browser at a time: several at
141
+ once on two cores only make each other time out."""
142
+ global _browser
143
+ import fcntl
144
+
145
+ STATE.mkdir(parents=True, exist_ok=True)
146
+ with open(STATE / "browser.lock", "w") as lock, tempfile.TemporaryDirectory() as scratch:
147
+ fcntl.flock(lock, fcntl.LOCK_EX)
148
+ page = Path(scratch, "frame.html")
149
+ page.write_text(html)
150
+ shot = Path(scratch, "shot.png")
151
+ for number in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
152
+ signal.signal(number, _stopped)
153
+ _browser = subprocess.Popen(
154
+ [
155
+ "chromium", "--headless", "--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage",
156
+ "--hide-scrollbars", "--force-device-scale-factor=1", f"--user-data-dir={scratch}/profile",
157
+ *extra, f"--window-size={max(width, MIN_WINDOW)},{max(height, MIN_WINDOW)}",
158
+ f"--screenshot={shot}", page.as_uri(),
159
+ ],
160
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, start_new_session=True,
161
+ )
162
+ try:
163
+ _, errors = _browser.communicate(timeout=BROWSER_SECONDS)
164
+ except subprocess.TimeoutExpired:
165
+ _stop_browser()
166
+ fail(f"The browser took more than {BROWSER_SECONDS} seconds to draw this, and was stopped. Heavy filters (large blurs, turbulence, lighting) over big areas are the usual cause.")
167
+ finally:
168
+ _stop_browser()
169
+ if _browser.returncode != 0 or not shot.exists():
170
+ fail(f"The browser could not draw it:\n{(errors or '').strip()[-2000:]}")
171
+ from PIL import Image
172
+
173
+ Image.open(shot).crop((0, 0, width, height)).save(png)
174
+
175
+
176
+ def draw(svg, png, width, height=None):
177
+ """The site's frame: a white box with the drawing fitted inside an <img>."""
178
+ height = height or width
179
+ screenshot(
180
+ '<!doctype html><meta charset="utf-8">'
181
+ "<style>html,body{margin:0;background:#fff}"
182
+ f"img{{display:block;width:{width}px;height:{height}px;object-fit:contain}}</style>"
183
+ f'<img src="{svg.resolve().as_uri()}">',
184
+ png, width, height,
185
+ )
186
+
187
+
188
+ def as_voters_get_it(source, cleaned):
189
+ """Writes the file as the site would store it to `cleaned`. A file the site
190
+ refuses is copied as written, if a browser can read it at all. Returns the
191
+ verdict."""
192
+ accepted, verdict = checked(source, cleaned)
193
+ if not accepted:
194
+ from lxml import etree
195
+
196
+ try:
197
+ etree.parse(str(source))
198
+ except etree.XMLSyntaxError:
199
+ fail(verdict)
200
+ shutil.copy(source, cleaned)
201
+ verdict += " It is drawn here as written."
202
+ return verdict
203
+
204
+
205
+ def draw_as_voters_see(source, png, size):
206
+ """Draws the file as the site would store it. Returns the verdict."""
207
+ with tempfile.TemporaryDirectory() as scratch:
208
+ cleaned = Path(scratch, "cleaned.svg")
209
+ verdict = as_voters_get_it(source, cleaned)
210
+ draw(cleaned, png, size)
211
+ return verdict
212
+
213
+
214
+ def spool(image, note):
215
+ """Leaves a picture for the harness to attach to this command's result."""
216
+ data, suffix = image.read_bytes(), image.suffix.lower()
217
+ if len(data) > MAX_BYTES:
218
+ from PIL import Image
219
+
220
+ with tempfile.TemporaryDirectory() as scratch:
221
+ smaller = Path(scratch, "view.jpg")
222
+ Image.open(image).convert("RGB").save(smaller, quality=92)
223
+ data, suffix = smaller.read_bytes(), ".jpg"
224
+ SPOOL.mkdir(parents=True, exist_ok=True)
225
+ number = len(list(SPOOL.iterdir())) + 1
226
+ (SPOOL / f"{number:03d}{suffix}").write_bytes(data)
227
+ print(f"[image attached: {note}]")
228
+
229
+
230
+ def view(args):
231
+ if len(args) not in (1, 2):
232
+ fail("Usage: view FILE [SIZE]")
233
+ source = existing(args[0])
234
+ if source.suffix.lower() == ".svg":
235
+ size = size_from(args[1]) if len(args) == 2 else 1024
236
+ with tempfile.TemporaryDirectory() as scratch:
237
+ png = Path(scratch, "view.png")
238
+ verdict = draw_as_voters_see(source, png, size)
239
+ spool(png, f"{source} at {size}x{size}, as a browser shows it in an <img> tag on a white frame")
240
+ print(verdict)
241
+ elif source.suffix.lower() in MIME:
242
+ spool(source, str(source))
243
+ else:
244
+ fail(f"view shows .svg, .png, .jpg, .gif and .webp files; {source} is none of those.")
245
+
246
+
247
+ def view_box(root):
248
+ """The drawing's own coordinates: (x, y, width, height), or None."""
249
+ box = root.get("viewBox")
250
+ if box:
251
+ parts = re.split(r"[\s,]+", box.strip())
252
+ try:
253
+ values = [float(p) for p in parts]
254
+ except ValueError:
255
+ return None
256
+ if len(values) == 4 and values[2] > 0 and values[3] > 0:
257
+ return tuple(values)
258
+ try:
259
+ return (0.0, 0.0, float(root.get("width", "").rstrip("px")), float(root.get("height", "").rstrip("px")))
260
+ except ValueError:
261
+ return None
262
+
263
+
264
+ def zoom(args):
265
+ if len(args) not in (5, 6):
266
+ fail("Usage: zoom FILE.svg X Y W H [SIZE] (X Y W H in the drawing's own viewBox coordinates)")
267
+ source = existing(args[0])
268
+ if source.suffix.lower() != ".svg":
269
+ fail("zoom shows a region of an .svg file; for a PNG, crop it with ImageMagick or Pillow and `view` the result.")
270
+ x, y, w, h = (number_from(a, n) for a, n in zip(args[1:5], "XYWH"))
271
+ if w <= 0 or h <= 0:
272
+ fail("W and H have to be more than 0.")
273
+ width = size_from(args[5]) if len(args) == 6 else 1024
274
+ height = round(width * h / w)
275
+ if not 16 <= height <= MAX_SIZE:
276
+ fail(f"At {width} pixels wide that region would be {height} high; keep it between 16 and {MAX_SIZE} (choose another SIZE or a less elongated region).")
277
+ from lxml import etree
278
+
279
+ with tempfile.TemporaryDirectory() as scratch:
280
+ cleaned = Path(scratch, "cleaned.svg")
281
+ verdict = as_voters_get_it(source, cleaned)
282
+ tree = etree.parse(str(cleaned))
283
+ root = tree.getroot()
284
+ whole = view_box(root)
285
+ root.set("viewBox", f"{x:g} {y:g} {w:g} {h:g}")
286
+ root.set("preserveAspectRatio", "xMidYMid meet")
287
+ for attribute in ("width", "height"):
288
+ root.attrib.pop(attribute, None)
289
+ region = Path(scratch, "region.svg")
290
+ tree.write(str(region), xml_declaration=False, encoding="utf-8")
291
+ png = Path(scratch, "zoom.png")
292
+ draw(region, png, width, height)
293
+ note = f"{source}, the region x {x:g}–{x + w:g}, y {y:g}–{y + h:g} at {width}x{height}"
294
+ if whole:
295
+ magnified = (width / w) / (1024 / max(whole[2], whole[3]))
296
+ note += f", {magnified:.1f} times as large as in `view` at 1024"
297
+ spool(png, note)
298
+ print(verdict)
299
+
300
+
301
+ def compare(args):
302
+ sizes = [a for a in args if re.fullmatch(r"\d+", a)]
303
+ files = [a for a in args if not re.fullmatch(r"\d+", a)]
304
+ if len(sizes) > 1 or not 2 <= len(files) <= 4:
305
+ fail("Usage: compare FILE FILE [FILE [FILE]] [SIZE] (two to four .svg or image files, each drawn SIZE pixels wide)")
306
+ gap = 12
307
+ size = size_from(sizes[0]) if sizes else min(1024, (2048 - gap * (len(files) - 1)) // len(files))
308
+ from PIL import Image, ImageDraw, ImageFont
309
+
310
+ try:
311
+ font = ImageFont.truetype(LABEL_FONT, 18)
312
+ except OSError:
313
+ font = ImageFont.load_default()
314
+ label = 30
315
+ with tempfile.TemporaryDirectory() as scratch:
316
+ tiles, verdicts = [], []
317
+ for number, name in enumerate(files):
318
+ source = existing(name)
319
+ if source.suffix.lower() == ".svg":
320
+ png = Path(scratch, f"{number}.png")
321
+ verdicts.append(draw_as_voters_see(source, png, size))
322
+ tile = Image.open(png).convert("RGB")
323
+ elif source.suffix.lower() in MIME:
324
+ tile = Image.open(source).convert("RGB")
325
+ tile.thumbnail((size, size))
326
+ else:
327
+ fail(f"compare shows .svg, .png, .jpg, .gif and .webp files; {source} is none of those.")
328
+ tiles.append((name, tile))
329
+ height = max(tile.height for _, tile in tiles) + label
330
+ sheet = Image.new("RGB", (sum(tile.width for _, tile in tiles) + gap * (len(tiles) - 1), height), "#7f7f7f")
331
+ pen = ImageDraw.Draw(sheet)
332
+ left = 0
333
+ for name, tile in tiles:
334
+ sheet.paste(tile, (left, label))
335
+ pen.rectangle([left, 0, left + tile.width - 1, label - 1], fill="#202020")
336
+ pen.text((left + 8, 5), name, fill="#ffffff", font=font)
337
+ left += tile.width + gap
338
+ out = Path(scratch, "compare.png")
339
+ sheet.save(out)
340
+ spool(out, f"{', '.join(files)} side by side, left to right, each {size} pixels wide")
341
+ for verdict in verdicts:
342
+ print(verdict)
343
+
344
+
345
+ CLOCK = re.compile(r"^\s*(?:(\d+):)?(\d+):(\d+(?:\.\d+)?)\s*$|^\s*(\d*\.?\d+)\s*(h|min|s|ms)?\s*$")
346
+
347
+
348
+ def seconds(value):
349
+ """An SVG clock value ("2s", "1.5", "500ms", "0:00:02") in seconds, or None."""
350
+ found = CLOCK.match(value or "")
351
+ if not found:
352
+ return None
353
+ hours, minutes, secs, number, unit = found.groups()
354
+ if secs is not None:
355
+ return int(hours or 0) * 3600 + int(minutes) * 60 + float(secs)
356
+ return float(number) * {"h": 3600, "min": 60, "s": 1, "ms": 0.001, None: 1}[unit]
357
+
358
+
359
+ def loop_length(text):
360
+ """The longest animation in a drawing, in seconds: SMIL dur and CSS animation durations. None if it has none."""
361
+ found = [seconds(v) for v in re.findall(r"\bdur\s*=\s*[\"']([^\"']+)[\"']", text)]
362
+ for declaration in re.findall(r"animation(?:-duration)?\s*:\s*([^;}\"']+)", text):
363
+ # In the shorthand the first time is the duration (the second is a delay).
364
+ for part in declaration.split(","):
365
+ first = re.search(r"(\d*\.?\d+)(ms|s)\b", part)
366
+ if first:
367
+ found.append(float(first.group(1)) * (0.001 if first.group(2) == "ms" else 1))
368
+ found = [f for f in found if f and f > 0]
369
+ return max(found) if found else None
370
+
371
+
372
+ def draw_at(svg_text, png, size, moment):
373
+ """Draws a drawing with its clocks stopped at `moment` seconds, inline in a page."""
374
+ body = re.sub(r"^\s*<\?xml[^>]*\?>", "", svg_text)
375
+ screenshot(
376
+ '<!doctype html><meta charset="utf-8">'
377
+ "<style>html,body{margin:0;background:#fff;overflow:hidden}"
378
+ f"#f{{width:{size}px;height:{size}px}}#f>svg{{display:block;width:100%;height:100%}}</style>"
379
+ f'<div id="f">{body}</div>'
380
+ "<script>"
381
+ f"const t={moment};"
382
+ "function freeze(){const s=document.querySelector('#f>svg');"
383
+ "if(s&&s.pauseAnimations){s.pauseAnimations();s.setCurrentTime(t);}"
384
+ "for(const a of document.getAnimations()){a.pause();a.currentTime=t*1000;}}"
385
+ "freeze();addEventListener('load',()=>{freeze();requestAnimationFrame(()=>{freeze();requestAnimationFrame(freeze);});});"
386
+ "</script>",
387
+ png, size, size, extra=("--virtual-time-budget=3000",),
388
+ )
389
+
390
+
391
+ def frames(args):
392
+ if not args:
393
+ fail("Usage: frames FILE.svg [SECONDS...] (no SECONDS: four moments across the drawing's longest loop)")
394
+ source = existing(args[0])
395
+ if source.suffix.lower() != ".svg":
396
+ fail("frames shows an .svg file at several moments.")
397
+ moments = []
398
+ for value in args[1:]:
399
+ moment = seconds(value)
400
+ if moment is None or moment < 0:
401
+ fail(f"{value!r} is not a time; give seconds, such as 0, 0.5 or 2.25.")
402
+ moments.append(moment)
403
+ if len(moments) > 6:
404
+ fail("Name at most six moments.")
405
+ from PIL import Image, ImageDraw, ImageFont
406
+
407
+ with tempfile.TemporaryDirectory() as scratch:
408
+ cleaned = Path(scratch, "cleaned.svg")
409
+ verdict = as_voters_get_it(source, cleaned)
410
+ text = cleaned.read_text(encoding="utf-8", errors="replace")
411
+ loop = loop_length(text)
412
+ if not moments:
413
+ span = min(loop or 2.0, 20.0)
414
+ moments = [round(span * i / 4, 3) for i in range(4)]
415
+ gap, label = 12, 30
416
+ size = min(1024, (2048 - gap * (len(moments) - 1)) // len(moments))
417
+ try:
418
+ font = ImageFont.truetype(LABEL_FONT, 18)
419
+ except OSError:
420
+ font = ImageFont.load_default()
421
+ tiles = []
422
+ for number, moment in enumerate(moments):
423
+ png = Path(scratch, f"{number}.png")
424
+ draw_at(text, png, size, moment)
425
+ tiles.append((moment, Image.open(png).convert("RGB")))
426
+ sheet = Image.new("RGB", (sum(t.width for _, t in tiles) + gap * (len(tiles) - 1), size + label), "#7f7f7f")
427
+ pen = ImageDraw.Draw(sheet)
428
+ left = 0
429
+ for moment, tile in tiles:
430
+ sheet.paste(tile, (left, label))
431
+ pen.rectangle([left, 0, left + tile.width - 1, label - 1], fill="#202020")
432
+ pen.text((left + 8, 5), f"{moment:g} s", fill="#ffffff", font=font)
433
+ left += tile.width + gap
434
+ out = Path(scratch, "frames.png")
435
+ sheet.save(out)
436
+ spool(out, f"{source} at {', '.join(f'{m:g} s' for m in moments)}, left to right, each {size} pixels wide")
437
+ if loop is None:
438
+ print(f"{source} has no SMIL or CSS animation, so every moment is the same picture.")
439
+ else:
440
+ print(f"The longest animation in {source} lasts {loop:g} s.")
441
+ print(verdict)
442
+
443
+
444
+ def render(args):
445
+ if len(args) not in (2, 3):
446
+ fail("Usage: render IN.svg OUT.png [SIZE]")
447
+ source, target = existing(args[0]), Path(args[1])
448
+ size = size_from(args[2]) if len(args) == 3 else 1024
449
+ verdict = draw_as_voters_see(source, target, size)
450
+ print(f"Drew {source} at {size}x{size} into {target}.")
451
+ print(verdict)
452
+
453
+
454
+ def check(args):
455
+ if len(args) != 1:
456
+ fail("Usage: check FILE.svg")
457
+ source = existing(args[0])
458
+ with tempfile.TemporaryDirectory() as scratch:
459
+ accepted, verdict = checked(source, Path(scratch, "cleaned.svg"))
460
+ print(verdict)
461
+ sys.exit(0 if accepted else 1)
462
+
463
+
464
+ def kb(count):
465
+ return f"{count / 1024:.1f} KB"
466
+
467
+
468
+ NUMBER = re.compile(r"-?(?:\d+\.\d+|\.\d+|\d+)(?:[eE][-+]?\d+)?")
469
+
470
+
471
+ def weigh(args):
472
+ if len(args) != 1:
473
+ fail("Usage: weigh FILE.svg")
474
+ source = existing(args[0])
475
+ from lxml import etree
476
+
477
+ text = source.read_text(encoding="utf-8", errors="replace")
478
+ try:
479
+ root = etree.fromstring(text.encode("utf-8"))
480
+ except etree.XMLSyntaxError as error:
481
+ fail(f"{source} is not well-formed XML ({error}).")
482
+ with tempfile.TemporaryDirectory() as scratch:
483
+ _, verdict = checked(source, Path(scratch, "cleaned.svg"))
484
+ total = len(text.encode("utf-8"))
485
+ print(verdict)
486
+ print(f"The file is {kb(total)} ({total} bytes).")
487
+
488
+ def name(element):
489
+ tag = element.tag.replace(SVG_NS, "") if isinstance(element.tag, str) else "comment"
490
+ return tag
491
+
492
+ def own(element):
493
+ """The element's own markup, without its children."""
494
+ if not isinstance(element.tag, str):
495
+ return len(etree.tostring(element))
496
+ return len(name(element)) + 3 + sum(len(k) + len(v) + 4 for k, v in element.attrib.items()) + len((element.text or "").strip())
497
+
498
+ by_tag = defaultdict(lambda: [0, 0])
499
+ for element in root.iter():
500
+ entry = by_tag[name(element)]
501
+ entry[0] += 1
502
+ entry[1] += own(element)
503
+ print("\nBy element (own markup, children not included):")
504
+ for tag, (count, size) in sorted(by_tag.items(), key=lambda item: -item[1][1])[:12]:
505
+ print(f" {tag:<18} {count:>6} × {kb(size):>9} {100 * size / total:5.1f}%")
506
+
507
+ print("\nThe largest parts (an element with everything inside it):")
508
+ parts = []
509
+ for element in root:
510
+ parts.append((element, 1))
511
+ if name(element) in ("g", "defs") and len(element) > 1:
512
+ parts.extend((child, 2) for child in element)
513
+ for element, depth in sorted(parts, key=lambda part: -len(etree.tostring(part[0])))[:12]:
514
+ size = len(etree.tostring(element))
515
+ label = name(element)
516
+ for attribute in ("id", "class", "transform", "fill", "filter", "clip-path"):
517
+ if element.get(attribute):
518
+ label += f' {attribute}="{element.get(attribute)[:40]}"'
519
+ break
520
+ inside = sum(1 for _ in element.iter()) - 1
521
+ print(f" {' ' * (depth - 1)}{label[:70]:<70} {kb(size):>9} {inside} inside")
522
+
523
+ paths = [element.get("d") for element in root.iter(f"{SVG_NS}path") if element.get("d")]
524
+ numbers = [n for d in paths for n in NUMBER.findall(d)]
525
+ d_bytes = sum(len(d) for d in paths)
526
+ print(f"\nPath data: {kb(d_bytes)} in {len(paths)} paths, {len(numbers)} numbers.")
527
+ if numbers:
528
+ long = [n for n in numbers if "." in n and len(n.split(".")[1].split("e")[0].split("E")[0]) >= 2]
529
+ print(f" {100 * len(long) / len(numbers):.0f}% of the numbers have two or more decimals.")
530
+
531
+ def rounded(digits):
532
+ def fix(match):
533
+ value = round(float(match.group()), digits)
534
+ out = f"{value:.{digits}f}".rstrip("0").rstrip(".") if digits else str(int(value))
535
+ out = re.sub(r"^(-?)0\.", r"\1.", out)
536
+ return "0" if out in ("-0", "", "-") else out
537
+
538
+ return sum(len(NUMBER.sub(fix, d)) for d in paths)
539
+
540
+ for digits in (1, 0):
541
+ saved = d_bytes - rounded(digits)
542
+ if saved > 1024:
543
+ print(f" Rounding every path coordinate to {digits} decimal{'s' if digits != 1 else ''} would save about {kb(saved)}.")
544
+
545
+ shapes = Counter(d for d in paths if len(d) >= 80)
546
+ repeated = [(d, n) for d, n in shapes.items() if n > 1]
547
+ if repeated:
548
+ waste = sum(len(d) * (n - 1) for d, n in repeated)
549
+ print(f" {len(repeated)} identical path shapes are written out more than once; drawing each once in <defs> and placing the copies with <use> would save about {kb(waste)}.")
550
+ print("\n`shrink` tries SVGO's safe optimisations and tells you whether the picture changed.")
551
+
552
+
553
+ def difference(first, second):
554
+ """How far apart two renders are: (mean change in 0–255, share of pixels visibly changed)."""
555
+ import numpy as np
556
+ from PIL import Image
557
+
558
+ a = np.asarray(Image.open(first).convert("RGB"), dtype=np.int16)
559
+ b = np.asarray(Image.open(second).convert("RGB"), dtype=np.int16)
560
+ if a.shape != b.shape:
561
+ return 255.0, 1.0
562
+ change = np.abs(a - b).max(axis=2)
563
+ return float(change.mean()), float((change > 12).mean())
564
+
565
+
566
+ def shrink(args):
567
+ if len(args) not in (2, 3):
568
+ fail("Usage: shrink IN.svg OUT.svg [DIGITS] (DIGITS: decimals kept in numbers, default 2)")
569
+ source, target = existing(args[0]), Path(args[1])
570
+ digits = 2
571
+ if len(args) == 3:
572
+ if not re.fullmatch(r"[0-5]", args[2]):
573
+ fail("DIGITS is how many decimals to keep in numbers, from 0 to 5.")
574
+ digits = int(args[2])
575
+ with tempfile.TemporaryDirectory() as scratch:
576
+ out = Path(scratch, "shrunk.svg")
577
+ done = subprocess.run(
578
+ ["svgo", "--multipass", "--quiet", "-p", str(digits), "-i", str(source), "-o", str(out)],
579
+ capture_output=True, text=True, timeout=100,
580
+ )
581
+ if done.returncode != 0 or not out.exists():
582
+ fail(f"SVGO could not shrink {source}:\n{(done.stderr or done.stdout).strip()[-2000:]}")
583
+ before, after = source.stat().st_size, out.stat().st_size
584
+ old_png, new_png = Path(scratch, "before.png"), Path(scratch, "after.png")
585
+ draw_as_voters_see(source, old_png, 1024)
586
+ shutil.copy(out, target)
587
+ verdict = draw_as_voters_see(target, new_png, 1024)
588
+ mean, share = difference(old_png, new_png)
589
+ print(f"Wrote {target}: {kb(after)}, down from {kb(before)} ({100 * (before - after) / before:.0f}% smaller), keeping {digits} decimal{'s' if digits != 1 else ''}.")
590
+ if share < 0.0005 and mean < 0.2:
591
+ print("Drawn at 1024, it looks the same as before.")
592
+ else:
593
+ print(f"Drawn at 1024 it is not quite the same: {100 * share:.2f}% of the pixels changed visibly (mean change {mean:.2f} of 255). `compare {source} {target}` and `zoom` show where.")
594
+ print(verdict.replace(" It is drawn here as written.", ""))
595
+
596
+
597
+ def submit(args):
598
+ if len(args) > 1:
599
+ fail("Usage: submit (it hands in /work/drawing.svg)")
600
+ if args and Path(args[0]).resolve() != ENTRY:
601
+ fail(f"submit hands in {ENTRY} and nothing else. To enter {args[0]}, copy it there first: cp {args[0]} {ENTRY} && submit")
602
+ if not ENTRY.is_file():
603
+ fail(f"Not submitted: there is no {ENTRY}.")
604
+ with tempfile.TemporaryDirectory() as scratch:
605
+ accepted, verdict = checked(ENTRY, Path(scratch, "cleaned.svg"))
606
+ if not accepted:
607
+ fail(f"Not submitted. {verdict}")
608
+ STATE.mkdir(parents=True, exist_ok=True)
609
+ SUBMITTED.write_text("1")
610
+ print(f"Submitted. {verdict} Nothing can be changed now.")
611
+
612
+
613
+ def collect(_args):
614
+ """For the harness: the pictures `view` left since the last command, and
615
+ whether the drawing has been handed in. Also stops any browser a command
616
+ left behind (one run in the background, say), so it can't slow the next."""
617
+ subprocess.run(["pkill", "-KILL", "-x", "chromium"], capture_output=True)
618
+ images = []
619
+ if SPOOL.is_dir():
620
+ for image in sorted(SPOOL.iterdir()):
621
+ if image.suffix.lower() in MIME:
622
+ images.append({"mime": MIME[image.suffix.lower()], "data": base64.b64encode(image.read_bytes()).decode()})
623
+ image.unlink()
624
+ json.dump({"images": images, "submitted": SUBMITTED.exists()}, sys.stdout)
625
+
626
+
627
+ if __name__ == "__main__":
628
+ os.environ.setdefault("HOME", tempfile.gettempdir())
629
+ commands = {
630
+ "view": view, "zoom": zoom, "compare": compare, "frames": frames, "render": render, "check": check,
631
+ "weigh": weigh, "shrink": shrink, "submit": submit, "collect": collect,
632
+ }
633
+ name, rest = Path(sys.argv[0]).name, sys.argv[1:]
634
+ if name not in commands and rest:
635
+ name, rest = rest[0], rest[1:]
636
+ if name not in commands:
637
+ fail("Usage: view | zoom | compare | frames | render | check | weigh | shrink | submit")
638
+ commands[name](rest)