-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender_benchmark_chart.py
More file actions
841 lines (715 loc) · 25 KB
/
Copy pathrender_benchmark_chart.py
File metadata and controls
841 lines (715 loc) · 25 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
import re
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from PIL import Image, ImageDraw, ImageFont
BACKGROUND = "#070504"
PANEL = "#221715"
FOREGROUND = "#FDFBF0"
MUTED = "#EBD9AF"
ACCENT = "#FF5C01"
LINE = "#EBD9AF"
BEFORE_FILL = "#EBD9AF"
BEFORE_PATTERN = "#FDFBF0"
AFTER_FILL = ACCENT
INNER_TEXT = "#070504"
FONT_CANDIDATES = [
"/System/Library/Fonts/Menlo.ttc",
"/System/Library/Fonts/Courier.ttc",
"/System/Library/Fonts/Supplemental/Courier New.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
]
LATENCY_UNITS = {
"ns": ("time", 1e-9, "ns"),
"nanosecond": ("time", 1e-9, "ns"),
"nanoseconds": ("time", 1e-9, "ns"),
"us": ("time", 1e-6, "us"),
"microsecond": ("time", 1e-6, "us"),
"microseconds": ("time", 1e-6, "us"),
"µs": ("time", 1e-6, "us"),
"μs": ("time", 1e-6, "us"),
"ms": ("time", 1e-3, "ms"),
"millisecond": ("time", 1e-3, "ms"),
"milliseconds": ("time", 1e-3, "ms"),
"s": ("time", 1.0, "s"),
"sec": ("time", 1.0, "s"),
"secs": ("time", 1.0, "s"),
"second": ("time", 1.0, "s"),
"seconds": ("time", 1.0, "s"),
}
BYTE_RATE_UNITS = {
"b/s": ("byte_rate", 1.0, "B/s"),
"byte/s": ("byte_rate", 1.0, "B/s"),
"bytes/s": ("byte_rate", 1.0, "B/s"),
"kb/s": ("byte_rate", 1e3, "KB/s"),
"mb/s": ("byte_rate", 1e6, "MB/s"),
"gb/s": ("byte_rate", 1e9, "GB/s"),
"tb/s": ("byte_rate", 1e12, "TB/s"),
"kib/s": ("byte_rate", 1024.0, "KiB/s"),
"mib/s": ("byte_rate", 1024.0**2, "MiB/s"),
"gib/s": ("byte_rate", 1024.0**3, "GiB/s"),
"tib/s": ("byte_rate", 1024.0**4, "TiB/s"),
}
BYTE_SIZE_UNITS = {
"b": ("bytes", 1.0, "B"),
"byte": ("bytes", 1.0, "B"),
"bytes": ("bytes", 1.0, "B"),
"kb": ("bytes", 1e3, "KB"),
"mb": ("bytes", 1e6, "MB"),
"gb": ("bytes", 1e9, "GB"),
"tb": ("bytes", 1e12, "TB"),
"kib": ("bytes", 1024.0, "KiB"),
"mib": ("bytes", 1024.0**2, "MiB"),
"gib": ("bytes", 1024.0**3, "GiB"),
"tib": ("bytes", 1024.0**4, "TiB"),
}
COUNT_RATE_SUFFIXES = {
"op/s": "op/s",
"ops/s": "ops/s",
"req/s": "req/s",
"rps": "rps",
"qps": "qps",
"tps": "tps",
"txn/s": "txn/s",
"txns/s": "txns/s",
}
COUNT_RATE_PREFIXES = {
"": 1.0,
"k": 1e3,
"m": 1e6,
"g": 1e9,
}
@dataclass
class MeasurementValue:
value: float
units: str
normalized_value: float
dimension: str
label: str
@dataclass
class BarEntry:
name: str
measurement: MeasurementValue
@dataclass
class BenchmarkEntry:
name: str
bars: list[BarEntry]
@dataclass
class Payload:
title: str
description: str
workload: str
measurement: str
benchmarks: list[BenchmarkEntry]
dimension: str
def load_json(path: Path) -> dict[str, Any]:
with path.open("r", encoding="utf-8") as handle:
data = json.load(handle)
if not isinstance(data, dict):
raise ValueError("Input JSON must be an object.")
return data
def require_string(
data: dict[str, Any], key: str, *, default: str | None = None
) -> str:
value = data.get(key, default)
if not isinstance(value, str):
raise ValueError(f"'{key}' must be a string.")
return value.strip()
def normalize_unit(unit: str) -> str:
return unit.strip().lower().replace(" ", "")
def canonical_display_unit(unit: str) -> str:
normalized = normalize_unit(unit)
if normalized in LATENCY_UNITS:
return LATENCY_UNITS[normalized][2]
if normalized in BYTE_RATE_UNITS:
return BYTE_RATE_UNITS[normalized][2]
if normalized in BYTE_SIZE_UNITS:
return BYTE_SIZE_UNITS[normalized][2]
match = re.fullmatch(
r"([kmg]?)(op/s|ops/s|req/s|rps|qps|tps|txn/s|txns/s)", normalized
)
if match:
prefix, suffix = match.groups()
return f"{prefix}{COUNT_RATE_SUFFIXES[suffix]}"
return unit.strip()
def format_number(value: float) -> str:
if value == 0:
return "0"
if float(value).is_integer():
return str(int(value))
magnitude = abs(value)
if magnitude >= 100:
text = f"{value:.1f}"
elif magnitude >= 10:
text = f"{value:.1f}"
elif magnitude >= 1:
text = f"{value:.2f}"
elif magnitude >= 0.1:
text = f"{value:.3f}"
elif magnitude >= 0.01:
text = f"{value:.4f}"
else:
text = f"{value:.3g}"
return text.rstrip("0").rstrip(".")
def format_value_label(value: float, units: str) -> str:
return f"{format_number(value)}{canonical_display_unit(units)}"
def humanize_time(seconds: float) -> str:
units = [
(1.0, "s"),
(1e-3, "ms"),
(1e-6, "us"),
(1e-9, "ns"),
]
magnitude = abs(seconds)
for factor, suffix in units:
if magnitude >= factor or factor == 1e-9:
return f"{format_number(seconds / factor)}{suffix}"
return f"{format_number(seconds)}s"
def humanize_byte_rate(bytes_per_second: float) -> str:
units = [
(1e12, "TB/s"),
(1e9, "GB/s"),
(1e6, "MB/s"),
(1e3, "KB/s"),
(1.0, "B/s"),
]
magnitude = abs(bytes_per_second)
for factor, suffix in units:
if magnitude >= factor or factor == 1.0:
return f"{format_number(bytes_per_second / factor)}{suffix}"
return f"{format_number(bytes_per_second)}B/s"
def humanize_bytes(value: float) -> str:
units = [
(1024.0**4, "TiB"),
(1024.0**3, "GiB"),
(1024.0**2, "MiB"),
(1024.0, "KiB"),
(1.0, "B"),
]
magnitude = abs(value)
for factor, suffix in units:
if magnitude >= factor or factor == 1.0:
return f"{format_number(value / factor)}{suffix}"
return f"{format_number(value)}B"
def build_display_label(
value: float, units: str, normalized_value: float, dimension: str
) -> str:
if dimension == "time":
return humanize_time(normalized_value)
if dimension == "byte_rate":
return humanize_byte_rate(normalized_value)
if dimension == "bytes":
return humanize_bytes(normalized_value)
return format_value_label(value, units)
def parse_measurement_value(raw: Any, label: str) -> MeasurementValue:
if not isinstance(raw, dict):
raise ValueError(f"'{label}' must be an object with 'value' and 'units'.")
value = raw.get("value")
units = raw.get("units", raw.get("unit"))
if not isinstance(value, (int, float)):
raise ValueError(f"'{label}.value' must be a number.")
if not isinstance(units, str) or not units.strip():
raise ValueError(f"'{label}.units' must be a non-empty string.")
normalized = normalize_unit(units)
if normalized in LATENCY_UNITS:
dimension, factor, _ = LATENCY_UNITS[normalized]
normalized_value = float(value) * factor
return MeasurementValue(
float(value),
units.strip(),
normalized_value,
dimension,
build_display_label(float(value), units, normalized_value, dimension),
)
if normalized in BYTE_RATE_UNITS:
dimension, factor, _ = BYTE_RATE_UNITS[normalized]
normalized_value = float(value) * factor
return MeasurementValue(
float(value),
units.strip(),
normalized_value,
dimension,
build_display_label(float(value), units, normalized_value, dimension),
)
if normalized in BYTE_SIZE_UNITS:
dimension, factor, _ = BYTE_SIZE_UNITS[normalized]
normalized_value = float(value) * factor
return MeasurementValue(
float(value),
units.strip(),
normalized_value,
dimension,
build_display_label(float(value), units, normalized_value, dimension),
)
match = re.fullmatch(
r"([kmg]?)(op/s|ops/s|req/s|rps|qps|tps|txn/s|txns/s)", normalized
)
if match:
prefix, suffix = match.groups()
factor = COUNT_RATE_PREFIXES[prefix]
display_unit = f"{prefix}{COUNT_RATE_SUFFIXES[suffix]}"
normalized_value = float(value) * factor
return MeasurementValue(
float(value),
units.strip(),
normalized_value,
"count_rate",
build_display_label(
float(value), display_unit, normalized_value, "count_rate"
),
)
raise ValueError(f"Unsupported units '{units}'.")
def infer_allowed_dimensions(measurement: str) -> set[str] | None:
normalized = measurement.lower()
if "latency" in normalized or "duration" in normalized or "time" in normalized:
return {"time"}
if "throughput" in normalized or "bandwidth" in normalized or "rate" in normalized:
return {"count_rate", "byte_rate"}
return None
def parse_payload(raw: dict[str, Any]) -> Payload:
title = require_string(raw, "title")
description = require_string(raw, "description", default="")
workload = require_string(raw, "workload", default="")
measurement = require_string(raw, "measurement")
benchmarks_raw = raw.get("benchmarks", raw.get("benchmakrs"))
if not isinstance(benchmarks_raw, list) or not benchmarks_raw:
raise ValueError("'benchmarks' must be a non-empty array.")
allowed_dimensions = infer_allowed_dimensions(measurement)
parsed: list[BenchmarkEntry] = []
chart_dimension: str | None = None
for index, benchmark_raw in enumerate(benchmarks_raw):
if not isinstance(benchmark_raw, dict):
raise ValueError(f"'benchmarks[{index}]' must be an object.")
name = require_string(benchmark_raw, "name")
bars = parse_benchmark_bars(benchmark_raw, index)
benchmark_dimension: str | None = None
for bar in bars:
if (
allowed_dimensions is not None
and bar.measurement.dimension not in allowed_dimensions
):
raise ValueError(
f"Units for benchmark '{name}' do not match measurement '{measurement}'."
)
if benchmark_dimension is None:
benchmark_dimension = bar.measurement.dimension
elif bar.measurement.dimension != benchmark_dimension:
raise ValueError(
f"Benchmark '{name}' mixes incompatible units across bars."
)
if chart_dimension is None:
chart_dimension = bar.measurement.dimension
elif bar.measurement.dimension != chart_dimension:
raise ValueError(
"All benchmarks in one chart must use compatible units so the bars can share a scale."
)
parsed.append(BenchmarkEntry(name=name, bars=bars))
if chart_dimension is None:
raise ValueError("No benchmarks were provided.")
return Payload(
title=title,
description=description,
workload=workload,
measurement=measurement,
benchmarks=parsed,
dimension=chart_dimension,
)
def parse_benchmark_bars(
benchmark_raw: dict[str, Any], benchmark_index: int
) -> list[BarEntry]:
bars_raw = benchmark_raw.get("bars")
if bars_raw is None:
fallback_bars = []
if "before" in benchmark_raw:
fallback_bars.append(
BarEntry(
name="before",
measurement=parse_measurement_value(
benchmark_raw.get("before"),
f"benchmarks[{benchmark_index}].before",
),
)
)
if "after" in benchmark_raw:
fallback_bars.append(
BarEntry(
name="after",
measurement=parse_measurement_value(
benchmark_raw.get("after"),
f"benchmarks[{benchmark_index}].after",
),
)
)
if fallback_bars:
return fallback_bars
raise ValueError(
f"'benchmarks[{benchmark_index}]' must contain a non-empty 'bars' array."
)
if not isinstance(bars_raw, list) or not bars_raw:
raise ValueError(
f"'benchmarks[{benchmark_index}].bars' must be a non-empty array."
)
bars: list[BarEntry] = []
for bar_index, bar_raw in enumerate(bars_raw):
if not isinstance(bar_raw, dict):
raise ValueError(
f"'benchmarks[{benchmark_index}].bars[{bar_index}]' must be an object."
)
bars.append(
BarEntry(
name=require_string(bar_raw, "name"),
measurement=parse_measurement_value(
bar_raw,
f"benchmarks[{benchmark_index}].bars[{bar_index}]",
),
)
)
return bars
def load_font(size: int) -> Any:
for candidate in FONT_CANDIDATES:
path = Path(candidate)
if path.exists():
return ImageFont.truetype(str(path), size=size)
return ImageFont.load_default()
def text_size(draw: ImageDraw.ImageDraw, text: str, font: Any) -> tuple[int, int]:
left, top, right, bottom = draw.textbbox((0, 0), text, font=font)
return int(right - left), int(bottom - top)
def wrap_text(
draw: ImageDraw.ImageDraw, text: str, font: Any, max_width: int
) -> list[str]:
words = text.split()
if not words:
return []
lines: list[str] = []
current = words[0]
for word in words[1:]:
candidate = f"{current} {word}"
if text_size(draw, candidate, font)[0] <= max_width:
current = candidate
else:
lines.append(current)
current = word
lines.append(current)
return lines
def fit_text(draw: ImageDraw.ImageDraw, text: str, font: Any, max_width: int) -> str:
if text_size(draw, text, font)[0] <= max_width:
return text
shortened = text
while shortened and text_size(draw, f"{shortened}...", font)[0] > max_width:
shortened = shortened[:-1]
return f"{shortened}..." if shortened else "..."
def draw_patterned_bar(
draw: ImageDraw.ImageDraw,
x: int,
y: int,
width: int,
height: int,
*,
fill: str,
pattern: str | None = None,
) -> None:
if width <= 0:
return
draw.rectangle((x, y, x + width, y + height), fill=fill)
if pattern is None:
return
step = max(6, height // 5)
diagonal = height + max(6, height // 5)
for start in range(x - height, x + width, step):
draw.line((start, y, start + diagonal, y + height), fill=pattern, width=1)
def scaled_bar_width(value: float, scale: float) -> int:
if value <= 0 or scale <= 0:
return 0
return max(3, int(round(value * scale)))
def px(value: int | float, scale: float) -> int:
return max(1, int(round(value * scale)))
def draw_wrapped_lines(
draw: ImageDraw.ImageDraw,
x: int,
y: int,
lines: list[str],
font: Any,
fill: str,
line_gap: int,
) -> int:
current_y = y
for line in lines:
draw.text((x, current_y), line, font=font, fill=fill)
current_y += text_size(draw, line, font)[1] + line_gap
return current_y
def render_chart(
payload: Payload, output_path: Path, width: int, resolution_scale: float
) -> None:
canvas_width = px(width, resolution_scale)
all_bars = [bar for entry in payload.benchmarks for bar in entry.bars]
title_font = load_font(px(45, resolution_scale))
subtitle_font = load_font(px(28, resolution_scale))
header_font = load_font(px(26, resolution_scale))
row_font = load_font(px(24, resolution_scale))
label_font = load_font(px(25, resolution_scale))
value_font = load_font(px(25, resolution_scale))
probe = Image.new("RGB", (canvas_width, px(1000, resolution_scale)), BACKGROUND)
draw = ImageDraw.Draw(probe)
left_pad = px(28, resolution_scale)
right_pad = px(34, resolution_scale)
top_pad = px(20, resolution_scale)
chart_gap = px(52, resolution_scale)
row_gap = px(8, resolution_scale)
bar_height = px(28, resolution_scale)
group_gap = px(58, resolution_scale)
bottom_pad = px(34, resolution_scale)
meta_gap = px(24, resolution_scale)
workload_max_width = int((canvas_width - left_pad - right_pad) * 0.38)
title_lines = wrap_text(
draw, payload.title, title_font, canvas_width - left_pad - right_pad
)
workload_panel_width = 0
workload_lines: list[str] = []
if payload.workload:
available_width = canvas_width - left_pad - right_pad
workload_text_width = text_size(draw, payload.workload, subtitle_font)[0]
workload_panel_width = min(
max(workload_text_width, px(280, resolution_scale)),
workload_max_width,
)
workload_lines = wrap_text(
draw,
payload.workload,
subtitle_font,
workload_panel_width,
)
description_max_width = max(
available_width - workload_panel_width - meta_gap,
px(260, resolution_scale),
)
else:
description_max_width = canvas_width - left_pad - right_pad
description_lines = (
wrap_text(draw, payload.description, subtitle_font, description_max_width)
if payload.description
else []
)
title_height = sum(
text_size(draw, line, title_font)[1] for line in title_lines
) + max(len(title_lines) - 1, 0) * px(4, resolution_scale)
description_height = sum(
text_size(draw, line, subtitle_font)[1] for line in description_lines
) + max(len(description_lines) - 1, 0) * px(2, resolution_scale)
workload_height = sum(
text_size(draw, line, subtitle_font)[1] for line in workload_lines
) + max(len(workload_lines) - 1, 0) * px(2, resolution_scale)
meta_height = max(description_height, workload_height)
header_top = (
top_pad
+ title_height
+ (px(10, resolution_scale) if description_lines or workload_lines else 0)
+ meta_height
+ px(72, resolution_scale)
)
benchmark_header = "benchmark"
measurement_header = payload.measurement
line_y = (
header_top
+ text_size(draw, benchmark_header, header_font)[1]
+ px(24, resolution_scale)
)
max_name_width = max(
text_size(draw, entry.name, row_font)[0] for entry in payload.benchmarks
)
max_bar_name_width = max(
text_size(draw, bar.name, label_font)[0] for bar in all_bars
)
left_column_width = min(
max(px(290, resolution_scale), max_name_width + px(24, resolution_scale)),
int(canvas_width * 0.36),
)
label_block_width = max(
px(112, resolution_scale), max_bar_name_width + px(28, resolution_scale)
)
bar_origin_x = left_pad + left_column_width + chart_gap + label_block_width
max_value_label_width = max(
text_size(draw, bar.measurement.label, value_font)[0] for bar in all_bars
)
bar_max_width = (
canvas_width
- right_pad
- bar_origin_x
- max_value_label_width
- px(18, resolution_scale)
)
if bar_max_width < px(240, resolution_scale):
raise ValueError(
"Image width is too small for the current labels. Increase --width."
)
content_top = line_y + px(34, resolution_scale)
groups_height = (
sum(
(len(entry.bars) * bar_height)
+ (max(len(entry.bars) - 1, 0) * row_gap)
+ px(34, resolution_scale)
for entry in payload.benchmarks
)
+ max(len(payload.benchmarks) - 1, 0) * group_gap
)
height = content_top + groups_height + bottom_pad
image = Image.new("RGB", (canvas_width, height), BACKGROUND)
draw = ImageDraw.Draw(image)
draw.rectangle(
(0, 0, canvas_width - 1, height - 1),
outline=PANEL,
width=px(4, resolution_scale),
)
current_y = top_pad
current_y = draw_wrapped_lines(
draw,
left_pad,
current_y,
title_lines,
title_font,
FOREGROUND,
px(4, resolution_scale),
)
if description_lines:
current_y += px(10, resolution_scale)
meta_y = current_y
draw_wrapped_lines(
draw,
left_pad,
meta_y,
description_lines,
subtitle_font,
MUTED,
px(2, resolution_scale),
)
current_y = meta_y + meta_height
elif workload_lines:
current_y += px(10, resolution_scale)
current_y += meta_height
if workload_lines:
text_y = top_pad + title_height + px(10, resolution_scale)
for line in workload_lines:
line_width, line_height = text_size(draw, line, subtitle_font)
text_x = canvas_width - right_pad - line_width
draw.text((text_x, text_y), line, font=subtitle_font, fill=MUTED)
text_y += line_height + px(2, resolution_scale)
benchmark_header_x = left_pad + max(
(left_column_width - text_size(draw, benchmark_header, header_font)[0]) // 2, 0
)
measurement_header_x = left_pad + left_column_width + chart_gap
header_y = header_top
draw.text(
(benchmark_header_x, header_y),
benchmark_header,
font=header_font,
fill=MUTED,
)
draw.text(
(measurement_header_x, header_y),
measurement_header,
font=header_font,
fill=MUTED,
)
draw.line(
(left_pad, line_y, left_pad + left_column_width, line_y),
fill=LINE,
width=px(3, resolution_scale),
)
draw.line(
(measurement_header_x, line_y, canvas_width - right_pad, line_y),
fill=LINE,
width=px(3, resolution_scale),
)
max_value = max(bar.measurement.normalized_value for bar in all_bars)
scale = bar_max_width / max_value if max_value > 0 else 0
group_y = content_top
for entry in payload.benchmarks:
bars_block_height = (len(entry.bars) * bar_height) + (
max(len(entry.bars) - 1, 0) * row_gap
)
group_height = bars_block_height + px(34, resolution_scale)
first_bar_y = group_y + px(4, resolution_scale)
label_y = (
first_bar_y
+ bars_block_height // 2
- text_size(draw, entry.name, row_font)[1] // 2
)
name_text = fit_text(draw, entry.name, row_font, left_column_width)
name_width, _ = text_size(draw, name_text, row_font)
name_x = left_pad + max((left_column_width - name_width) // 2, 0)
draw.text((name_x, label_y), name_text, font=row_font, fill=FOREGROUND)
for bar_index, bar in enumerate(entry.bars):
bar_y = first_bar_y + bar_index * (bar_height + row_gap)
bar_width = scaled_bar_width(bar.measurement.normalized_value, scale)
bar_fill = BEFORE_FILL if bar_index == 0 else AFTER_FILL
draw.text(
(
left_pad + left_column_width + chart_gap,
bar_y - px(2, resolution_scale),
),
bar.name,
font=label_font,
fill=MUTED,
)
draw_patterned_bar(
draw,
bar_origin_x,
bar_y,
bar_width,
bar_height,
fill=bar_fill,
pattern=None,
)
draw.text(
(
bar_origin_x + bar_width + px(12, resolution_scale),
bar_y - px(1, resolution_scale),
),
bar.measurement.label,
font=value_font,
fill=FOREGROUND,
)
group_y += group_height + group_gap
output_path.parent.mkdir(parents=True, exist_ok=True)
image.save(output_path, dpi=(300, 300))
def parse_args(argv: list[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Render a before/after benchmark chart PNG from JSON input."
)
parser.add_argument("input", help="Path to the input JSON payload.")
parser.add_argument("output", help="Path to write the PNG image.")
parser.add_argument(
"--width",
type=int,
default=1600,
help="Logical chart width before resolution scaling (default: 1600).",
)
parser.add_argument(
"--scale",
type=float,
default=2.0,
help="Resolution multiplier for the PNG output (default: 2.0).",
)
return parser.parse_args(argv)
def main(argv: list[str]) -> int:
args = parse_args(argv)
input_path = Path(args.input)
output_path = Path(args.output)
try:
if args.scale <= 0:
raise ValueError("'--scale' must be greater than zero.")
payload = parse_payload(load_json(input_path))
render_chart(
payload, output_path, width=args.width, resolution_scale=args.scale
)
except Exception as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
print(f"Wrote chart to {output_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))