codeyear 0.2.14__py3-none-any.whl

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.
codeyear/card.py ADDED
@@ -0,0 +1,720 @@
1
+ """Render a large, transparent SVG card for a GitHub profile README."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ from datetime import date, datetime, timedelta
7
+ from pathlib import Path
8
+
9
+ from .stats import (
10
+ ReportStats,
11
+ date_window,
12
+ fmt_human,
13
+ fmt_int,
14
+ fmt_signed_pair,
15
+ language_breakdown,
16
+ parse_daily,
17
+ )
18
+
19
+ W, H = 640, 1254
20
+ M = 28
21
+ RIGHT = W - M
22
+ COL2 = 278
23
+ MONO = "Consolas, 'SFMono-Regular', Menlo, monospace"
24
+ SANS = "-apple-system, 'Segoe UI', 'Microsoft YaHei', sans-serif"
25
+ SERIF = "Georgia, 'Songti SC', SimSun, serif"
26
+ NUM = "Cambria, 'Times New Roman', 'Songti SC', SimSun, serif"
27
+
28
+ LIGHT = {
29
+ "ink": "#141413",
30
+ "ink2": "#3d3d3a",
31
+ "muted": "#73726c",
32
+ "line": "#d9d7cd",
33
+ "accent": "#d97757",
34
+ "bar": "#cfcbbe",
35
+ "empty_opacity": "0.12",
36
+ "palette": ["#141413", "#d97757", "#8f8d84", "#b8b5aa", "#ddd9cc"],
37
+ "levels": ["#e7e4da", "#ddd8ca", "#b8b2a0", "#6f6a5e", "#d97757"],
38
+ }
39
+
40
+ DARK = {
41
+ "ink": "#f0eee6",
42
+ "ink2": "#d5d2c8",
43
+ "muted": "#9a978e",
44
+ "line": "#3a3936",
45
+ "accent": "#e08a68",
46
+ "bar": "#4a4843",
47
+ "empty_opacity": "0.2",
48
+ "palette": ["#f0eee6", "#e08a68", "#9a978e", "#7a7770", "#55534d"],
49
+ "levels": ["#262623", "#3a3936", "#5c5952", "#9a978e", "#e08a68"],
50
+ }
51
+
52
+ MONO_LIGHT = {
53
+ "ink": "#0a0a0a",
54
+ "ink2": "#2f2f2f",
55
+ "muted": "#707070",
56
+ "line": "#e4e4e4",
57
+ "accent": "#0a0a0a",
58
+ "bar": "#d4d4d4",
59
+ "empty_opacity": "0.12",
60
+ "palette": ["#0a0a0a", "#555555", "#999999", "#c4c4c4", "#e4e4e4"],
61
+ "levels": ["#ececec", "#d4d4d4", "#a3a3a3", "#5c5c5c", "#0a0a0a"],
62
+ }
63
+
64
+ MONO_DARK = {
65
+ "ink": "#f5f5f5",
66
+ "ink2": "#d4d4d4",
67
+ "muted": "#a3a3a3",
68
+ "line": "#333333",
69
+ "accent": "#f5f5f5",
70
+ "bar": "#4a4a4a",
71
+ "empty_opacity": "0.2",
72
+ "palette": ["#f5f5f5", "#bdbdbd", "#8a8a8a", "#5c5c5c", "#333333"],
73
+ "levels": ["#262626", "#3a3a3a", "#5c5c5c", "#9a9a9a", "#f5f5f5"],
74
+ }
75
+
76
+ FOREST_LIGHT = {
77
+ "ink": "#17261b",
78
+ "ink2": "#35463a",
79
+ "muted": "#6a7769",
80
+ "line": "#d3ddcd",
81
+ "accent": "#3f6b45",
82
+ "bar": "#c3d0bd",
83
+ "empty_opacity": "0.12",
84
+ "palette": ["#17261b", "#3f6b45", "#7f9179", "#a9b8a2", "#d3ddcd"],
85
+ "levels": ["#e6ece0", "#d3ddcd", "#a9b8a2", "#5c6f57", "#3f6b45"],
86
+ }
87
+
88
+ FOREST_DARK = {
89
+ "ink": "#e8efe4",
90
+ "ink2": "#cfd9c9",
91
+ "muted": "#9aa894",
92
+ "line": "#33402f",
93
+ "accent": "#8fbf8a",
94
+ "bar": "#43503e",
95
+ "empty_opacity": "0.2",
96
+ "palette": ["#e8efe4", "#8fbf8a", "#9aa894", "#6f7d68", "#43503e"],
97
+ "levels": ["#202a1d", "#33402f", "#4f5f48", "#7f9179", "#8fbf8a"],
98
+ }
99
+
100
+ OCEAN_LIGHT = {
101
+ "ink": "#0f1b2d",
102
+ "ink2": "#2b3d55",
103
+ "muted": "#647184",
104
+ "line": "#d6dee8",
105
+ "accent": "#2f6fb0",
106
+ "bar": "#c2d2e3",
107
+ "empty_opacity": "0.12",
108
+ "palette": ["#0f1b2d", "#2f6fb0", "#7c9cbf", "#a9c0d8", "#d6dee8"],
109
+ "levels": ["#e7eef6", "#d6e2ef", "#a9c0d8", "#5c7fa6", "#2f6fb0"],
110
+ }
111
+
112
+ OCEAN_DARK = {
113
+ "ink": "#e8eef6",
114
+ "ink2": "#cfd9e6",
115
+ "muted": "#93a1b5",
116
+ "line": "#2a3644",
117
+ "accent": "#6aa6e0",
118
+ "bar": "#3a4a5e",
119
+ "empty_opacity": "0.2",
120
+ "palette": ["#e8eef6", "#6aa6e0", "#93a1b5", "#627489", "#3a4a5e"],
121
+ "levels": ["#1b2430", "#2a3644", "#455a70", "#7c9cbf", "#6aa6e0"],
122
+ }
123
+
124
+ THEMES = {
125
+ "paper": (LIGHT, DARK),
126
+ "mono": (MONO_LIGHT, MONO_DARK),
127
+ "forest": (FOREST_LIGHT, FOREST_DARK),
128
+ "ocean": (OCEAN_LIGHT, OCEAN_DARK),
129
+ }
130
+
131
+
132
+ def _e(value: str) -> str:
133
+ return html.escape(str(value), quote=True)
134
+
135
+
136
+ def _en_human(n: int) -> str:
137
+ if n >= 1_000_000:
138
+ return f"{n / 1_000_000:.1f}m"
139
+ if n >= 10_000:
140
+ return f"{n / 1000:.0f}k"
141
+ return f"{n:,}"
142
+
143
+
144
+ def _en_signed_pair(insertions: int, deletions: int) -> str:
145
+ if max(insertions, deletions) >= 10_000:
146
+ return f"+{insertions / 1000:.0f}k / -{deletions / 1000:.0f}k"
147
+ return f"+{insertions:,} / -{deletions:,}"
148
+
149
+
150
+ def _truncate(text: str, limit: int) -> str:
151
+ text = (text or "").strip()
152
+ return text if len(text) <= limit else text[: limit - 1] + "…"
153
+
154
+
155
+ def _text(
156
+ x: float,
157
+ y: float,
158
+ text: str,
159
+ size: float,
160
+ fill: str,
161
+ *,
162
+ family: str = MONO,
163
+ anchor: str | None = None,
164
+ spacing: float | None = None,
165
+ ) -> str:
166
+ attrs = [
167
+ f'x="{x}"',
168
+ f'y="{y}"',
169
+ f'font-family="{family}"',
170
+ f'font-size="{size}"',
171
+ f'fill="{fill}"',
172
+ ]
173
+ if anchor:
174
+ attrs.append(f'text-anchor="{anchor}"')
175
+ if spacing is not None:
176
+ attrs.append(f'letter-spacing="{spacing}"')
177
+ return f'<text {" ".join(attrs)}>{_e(text)}</text>'
178
+
179
+
180
+ def _rule(y: float, color: str) -> str:
181
+ return f'<line x1="{M}" y1="{y}" x2="{RIGHT}" y2="{y}" stroke="{color}"/>'
182
+
183
+
184
+ def _metric(x: float, y: float, number: str, unit: str, c: dict,
185
+ size: float = 28, anchor: str | None = None) -> str:
186
+ """One hero number per insight, with a small muted unit."""
187
+ attrs = [
188
+ f'x="{x}"',
189
+ f'y="{y}"',
190
+ f'font-family="{NUM}"',
191
+ f'font-size="{size}"',
192
+ f'fill="{c["ink"]}"',
193
+ ]
194
+ if anchor:
195
+ attrs.append(f'text-anchor="{anchor}"')
196
+ head = f'<text {" ".join(attrs)}>{_e(number)}'
197
+ if not unit:
198
+ return head + "</text>"
199
+ dx = 1 if unit in {"%", ":1"} else 4
200
+ return (
201
+ head
202
+ + f'<tspan font-size="12.5" fill="{c["muted"]}" dx="{dx}">{_e(unit)}</tspan></text>'
203
+ )
204
+
205
+
206
+ def _heatmap(stats: ReportStats, c: dict, x0: float, y0: float,
207
+ cell: float = 9, gap: float = 2) -> str:
208
+ daily = parse_daily(stats.daily)
209
+ start, end = date_window(stats)
210
+ grid_start = start - timedelta(days=start.weekday())
211
+ grid_end = end + timedelta(days=6 - end.weekday())
212
+
213
+ rects = []
214
+ cursor = grid_start
215
+ while cursor <= grid_end:
216
+ if start <= cursor <= end:
217
+ col = (cursor - grid_start).days // 7
218
+ row = cursor.weekday()
219
+ count = daily.get(cursor, 0)
220
+ if count == 0:
221
+ level = 0
222
+ opacity = f' fill-opacity="{c["empty_opacity"]}"'
223
+ else:
224
+ if count == 1:
225
+ level = 1
226
+ elif count <= 3:
227
+ level = 2
228
+ elif count <= 6:
229
+ level = 3
230
+ else:
231
+ level = 4
232
+ opacity = ""
233
+ x = x0 + col * (cell + gap)
234
+ y = y0 + row * (cell + gap)
235
+ rects.append(
236
+ f'<rect x="{x}" y="{y}" width="{cell}" height="{cell}" '
237
+ f'fill="{c["levels"][level]}"{opacity}/>'
238
+ )
239
+ cursor += timedelta(days=1)
240
+ return "".join(rects)
241
+
242
+
243
+ MONTHS = [
244
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
245
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
246
+ ]
247
+
248
+
249
+ def build_svg(stats: ReportStats, *, dark: bool = False,
250
+ theme: str = "paper", lang: str = "zh") -> str:
251
+ light, dark_theme = THEMES.get(theme, THEMES["paper"])
252
+ c = dark_theme if dark else light
253
+ en = lang == "en"
254
+
255
+ def t(zh: str, english: str) -> str:
256
+ return english if en else zh
257
+
258
+ monthly = stats.monthly
259
+ peak = max(monthly) or 1
260
+ peak_month = monthly.index(peak) + 1 if peak else 1
261
+ peak_hour = stats.by_hour.index(max(stats.by_hour)) if any(stats.by_hour) else 0
262
+ owner = (stats.identity_label or "").split(" <")[0].strip()
263
+
264
+ if en:
265
+ lines_text = _en_human(stats.lines_changed)
266
+ signed_text = _en_signed_pair(stats.insertions, stats.deletions)
267
+ else:
268
+ lines_text = fmt_human(stats.lines_changed)
269
+ signed_text = fmt_signed_pair(stats.insertions, stats.deletions)
270
+
271
+ # ---- header -------------------------------------------------------
272
+ if en:
273
+ title = _truncate(stats.persona.title_en, 32)
274
+ sub_lines = [
275
+ f"{fmt_int(stats.commit_count)} commits across "
276
+ f"{stats.repo_count} repos · {lines_text} lines.",
277
+ f"{stats.night_share:.0%} late-night · {stats.language_count} languages "
278
+ f"· {stats.active_days} active days.",
279
+ ]
280
+ else:
281
+ title = _truncate(stats.persona.title, 24)
282
+ subtitle_parts = stats.persona.subtitle.split("。", 1)
283
+ sub_lines = [subtitle_parts[0] + ("。" if len(subtitle_parts) > 1 else "")]
284
+ if len(subtitle_parts) > 1:
285
+ sub_lines.append(subtitle_parts[1])
286
+
287
+ header = [
288
+ f'<rect x="0" y="0" width="{W}" height="3" fill="{c["accent"]}"/>',
289
+ _text(M, 30, f"CODEYEAR · {stats.year}", 9, c["accent"], spacing=2.4),
290
+ (
291
+ _text(RIGHT, 32, _truncate(owner, 26), 17, c["ink"], family=SERIF,
292
+ anchor="end")
293
+ if owner
294
+ else _text(RIGHT, 30, "LOCAL-FIRST", 9, c["muted"], anchor="end")
295
+ ),
296
+ _text(M - 1, 82, title, 36, c["ink"], family=SERIF),
297
+ ]
298
+ for i, line in enumerate(sub_lines[:2]):
299
+ header.append(_text(M, 108 + i * 20, line, 11.5, c["ink2"], family=SANS))
300
+ header.append(_rule(142, c["line"]))
301
+
302
+ # ---- six summary tiles (3 x 2) ------------------------------------
303
+ active_pct = stats.active_days / (366 if _is_leap(stats.year) else 365)
304
+ tiles = [
305
+ (t("COMMITS / 提交", "COMMITS"), fmt_int(stats.commit_count),
306
+ t("年度提交", "commits this year")),
307
+ (t("LINES / 行变更", "LINES"), lines_text, signed_text),
308
+ (t("ACTIVE / 活跃天", "ACTIVE"), str(stats.active_days),
309
+ t(f"占全年 {active_pct:.0%}", f"{active_pct:.0%} of the year")),
310
+ (t("STREAK / 最长连续", "STREAK"), str(stats.longest_streak),
311
+ t(f"当前 {stats.current_streak} 天",
312
+ f"{stats.current_streak}-day current streak")),
313
+ (t("REPOS / 仓库", "REPOS"), str(stats.repo_count),
314
+ t(f"今年新开 {stats.new_repos}",
315
+ f"{stats.new_repos} started this year")),
316
+ (t("TOTAL / 累计", "TOTAL"), fmt_int(stats.total_commits),
317
+ t("仓库全历史", "all-time")),
318
+ ]
319
+ tile_svg = []
320
+ for i, (label, value, sub) in enumerate(tiles):
321
+ row, col = divmod(i, 3)
322
+ x = M + col * 194.6
323
+ y = row * 88
324
+ tile_svg.append(_text(x, 164 + y, label, 10, c["muted"], spacing=0.6))
325
+ tile_svg.append(_text(x - 1, 208 + y, value, 36, c["ink"], family=NUM))
326
+ tile_svg.append(_text(x, 226 + y, sub, 10, c["muted"]))
327
+ tile_svg.append(_rule(332, c["line"]))
328
+
329
+ # ---- monthly rhythm ----------------------------------------------
330
+ bars = []
331
+ bar_w, gap = 40, 8
332
+ baseline = 430
333
+ for i, value in enumerate(monthly):
334
+ x = M + i * (bar_w + gap)
335
+ height = max(int(value / peak * 66), 2)
336
+ fill = c["accent"] if value == peak and value > 0 else c["ink"]
337
+ bars.append(
338
+ f'<rect x="{x}" y="{baseline - height}" width="{bar_w}" '
339
+ f'height="{height}" fill="{fill}"/>'
340
+ )
341
+ bars.append(_text(x + bar_w / 2, baseline + 14, f"{i + 1:02d}", 9.5,
342
+ c["muted"], anchor="middle"))
343
+
344
+ # ---- contribution calendar ---------------------------------------
345
+ cell, gap_h = 9, 2
346
+ grid_start = date(stats.year, 1, 1)
347
+ grid_start -= timedelta(days=grid_start.weekday())
348
+ grid_end = date(stats.year, 12, 31)
349
+ grid_end += timedelta(days=6 - grid_end.weekday())
350
+ grid_cols = (grid_end - grid_start).days // 7 + 1
351
+ grid_w = grid_cols * (cell + gap_h) - gap_h
352
+ grid_x = (W - grid_w) / 2
353
+
354
+ month_ticks = []
355
+ for month in range(1, 13):
356
+ col = (date(stats.year, month, 1) - grid_start).days // 7
357
+ mx = grid_x + col * (cell + gap_h)
358
+ month_ticks.append(_text(mx, 588, f"{month:02d}", 9.5, c["muted"]))
359
+
360
+ charts = [
361
+ _text(M, 350, "MONTHLY RHYTHM", 10, c["muted"], spacing=1),
362
+ _text(RIGHT, 350, t(
363
+ f"峰值 {peak_month:02d} 月 · {peak} 次",
364
+ f"Peak {MONTHS[peak_month - 1]} · {peak}",
365
+ ), 10, c["accent"], anchor="end"),
366
+ *bars,
367
+ _rule(462, c["line"]),
368
+ _text(M, 480, "CONTRIBUTION", 10, c["muted"], spacing=1),
369
+ _text(RIGHT, 480, t(
370
+ f"{stats.active_days} 个活跃日",
371
+ f"{stats.active_days} active days",
372
+ ), 10, c["muted"], anchor="end"),
373
+ _heatmap(stats, c, grid_x, 498, cell, gap_h),
374
+ *month_ticks,
375
+ _rule(602, c["line"]),
376
+ ]
377
+
378
+ # ---- derived insights ---------------------------------------------
379
+ cols2 = [M, M + 306]
380
+ top_repo = stats.repo_details[0] if stats.repo_details else None
381
+ if top_repo and stats.commit_count:
382
+ share = top_repo["commits"] / stats.commit_count
383
+ focus_num, focus_unit = f"{share * 100:.0f}", "%"
384
+ focus_sub = t(
385
+ f"大部分提交在 {_truncate(top_repo['name'], 16)}",
386
+ f"Most commits in {_truncate(top_repo['name'], 22)}",
387
+ )
388
+ else:
389
+ focus_num, focus_unit, focus_sub = "—", "", t("暂无数据", "No data")
390
+
391
+ night, weekend = stats.night_share, stats.weekend_share
392
+ rhythm_num, rhythm_unit = f"{peak_hour:02d}:00", ""
393
+ rhythm_sub = t(
394
+ f"深夜提交占 {night:.0%} · 周末 {weekend:.0%}",
395
+ f"{night:.0%} late-night · {weekend:.0%} weekend",
396
+ )
397
+
398
+ size_map = dict(stats.size_buckets)
399
+ size_total = sum(size_map.values()) or 1
400
+ small_share = (size_map.get("0–10", 0) + size_map.get("10–100", 0)) / size_total
401
+ large_share = (size_map.get("500–2k", 0) + size_map.get("2k+", 0)) / size_total
402
+ style_num, style_unit = f"{small_share * 100:.0f}", "%"
403
+ style_sub = t(
404
+ f"小改动为主 · 大改仅 {large_share:.0%}",
405
+ f"Mostly small changes · large {large_share:.0%}",
406
+ )
407
+
408
+ sessions = stats.sessions or {}
409
+ sess_count = int(sessions.get("count") or 0)
410
+ avg_min = int(sessions.get("avg_minutes") or 0)
411
+ long_min = int(sessions.get("longest_minutes") or 0)
412
+ if avg_min:
413
+ if avg_min >= 90:
414
+ pace_num, pace_unit = f"{avg_min / 60:.1f}", t("小时", "h")
415
+ else:
416
+ pace_num, pace_unit = str(avg_min), t("分钟", "min")
417
+ long_label = (
418
+ f"{long_min / 60:.0f}h" if long_min >= 90 else f"{long_min}min"
419
+ ) if en else (
420
+ f"{long_min / 60:.0f} 小时" if long_min >= 90 else f"{long_min} 分钟"
421
+ )
422
+ pace_sub = t(
423
+ f"{sess_count} 次连续写码 · 最长 {long_label}",
424
+ f"{sess_count} sessions · longest {long_label}",
425
+ )
426
+ else:
427
+ pace_num, pace_unit, pace_sub = "—", "", t("暂无会话", "No sessions")
428
+
429
+ churn_total = stats.insertions + stats.deletions
430
+ deletion_share = stats.deletions / churn_total if churn_total else 0
431
+ ratio = stats.insertions / stats.deletions if stats.deletions else 0
432
+ if deletion_share >= 0.5:
433
+ churn_kind = t("重构型", "Refactoring")
434
+ elif deletion_share >= 0.3:
435
+ churn_kind = t("平衡型", "Balanced")
436
+ else:
437
+ churn_kind = t("扩张型", "Expanding")
438
+ if ratio:
439
+ churn_num, churn_unit = f"{ratio:.1f}", ":1"
440
+ churn_sub = t(
441
+ f"每写 {ratio:.1f} 行才删 1 行",
442
+ f"{ratio:.1f} lines written per line deleted",
443
+ )
444
+ else:
445
+ churn_num, churn_unit = t("只增", "add-only"), ""
446
+ churn_sub = t(f"{churn_kind} · 没有删除", f"{churn_kind} · no deletions")
447
+
448
+ peak_share = peak / max(stats.commit_count, 1)
449
+ burst_num, burst_unit = f"{peak_share * 100:.0f}", "%"
450
+ peak_label = MONTHS[peak_month - 1]
451
+ if peak_share >= 0.5:
452
+ burst_sub = t(
453
+ f"{peak_month} 月占了全年 {peak_share:.0%} 的提交",
454
+ f"{peak_label} accounted for {peak_share:.0%} of the year",
455
+ )
456
+ elif peak_share >= 0.3:
457
+ burst_sub = t(
458
+ f"{peak_month} 月最忙,占全年 {peak_share:.0%}",
459
+ f"{peak_label} was busiest at {peak_share:.0%}",
460
+ )
461
+ elif peak_share >= 0.18:
462
+ burst_sub = t(
463
+ f"{peak_month} 月提交最多,占 {peak_share:.0%}",
464
+ f"{peak_label} had the most commits ({peak_share:.0%})",
465
+ )
466
+ else:
467
+ burst_sub = t(
468
+ f"全年分布比较平均,{peak_month} 月最多",
469
+ f"Fairly even across the year; {peak_label} was slightly ahead",
470
+ )
471
+
472
+ top2 = sum(repo["commits"] for repo in stats.repo_details[:2])
473
+ top2_share = top2 / max(stats.commit_count, 1)
474
+ breadth_num, breadth_unit = f"{top2_share * 100:.0f}", "%"
475
+ breadth_sub = t(
476
+ f"前 2 个项目拿走 {top2_share:.0%} 的提交",
477
+ f"Top 2 repos account for {top2_share:.0%} of commits",
478
+ )
479
+
480
+ msg_map = dict(stats.message_buckets)
481
+ msg_total = sum(msg_map.values()) or 1
482
+ mid_share = msg_map.get("40–80", 0) / msg_total
483
+ avg_subject = stats.avg_subject_len
484
+ msg_num, msg_unit = str(avg_subject), t("字", "chars")
485
+ if avg_subject >= 50:
486
+ msg_kind = t("说明很长", "Very detailed")
487
+ elif avg_subject >= 30:
488
+ msg_kind = t("说明较详细", "Detailed")
489
+ elif avg_subject >= 15:
490
+ msg_kind = t("长度适中", "Medium-length")
491
+ else:
492
+ msg_kind = t("标题偏短", "Short subjects")
493
+ if mid_share >= 0.15:
494
+ msg_sub = t(
495
+ f"{msg_kind} · {mid_share:.0%} 在 40–80 字",
496
+ f"{msg_kind} · {mid_share:.0%} at 40–80 chars",
497
+ )
498
+ else:
499
+ msg_sub = t(
500
+ f"{msg_kind} · 平均 {avg_subject} 字",
501
+ f"{msg_kind} · avg {avg_subject} chars",
502
+ )
503
+
504
+ insights = [
505
+ (t("主攻项目 / MAIN PROJECT", "MAIN PROJECT"),
506
+ focus_num, focus_unit, focus_sub),
507
+ (t("写码时段 / WHEN", "WHEN"), rhythm_num, rhythm_unit, rhythm_sub),
508
+ (t("改动大小 / COMMIT SIZE", "COMMIT SIZE"),
509
+ style_num, style_unit, style_sub),
510
+ (t("一次写多久 / SESSION", "SESSION"), pace_num, pace_unit, pace_sub),
511
+ (t("写删比例 / ADD VS DELETE", "ADD VS DELETE"),
512
+ churn_num, churn_unit, churn_sub),
513
+ (t("最忙月份 / BUSIEST MONTH", "BUSIEST MONTH"),
514
+ burst_num, burst_unit, burst_sub),
515
+ (t("精力集中吗 / FOCUS SPREAD", "FOCUS SPREAD"),
516
+ breadth_num, breadth_unit, breadth_sub),
517
+ (t("提交说明 / MESSAGE", "MESSAGE"), msg_num, msg_unit, msg_sub),
518
+ ]
519
+ insight_svg = [
520
+ _text(M, 618, t("INSIGHTS / 观察", "INSIGHTS"), 10, c["muted"], spacing=1),
521
+ f'<line x1="321" y1="618" x2="321" y2="894" stroke="{c["line"]}"/>',
522
+ ]
523
+ for i, (label, number, unit, sub) in enumerate(insights):
524
+ row, col = divmod(i, 2)
525
+ x = cols2[col]
526
+ top = 650 + row * 62
527
+ insight_svg.append(_text(x, top, label, 10, c["muted"], spacing=0.4))
528
+ insight_svg.append(_metric(x + COL2, top, number, unit, c, anchor="end"))
529
+ insight_svg.append(_text(x, top + 18, sub, 10.5, c["muted"]))
530
+ insight_svg.append(
531
+ f'<line x1="{x}" y1="{top + 36}" x2="{x + COL2}" y2="{top + 36}" '
532
+ f'stroke="{c["line"]}"/>'
533
+ )
534
+ insight_svg.append(_rule(894, c["line"]))
535
+
536
+ # ---- four detail blocks (2 x 2, wide) -----------------------------
537
+ left_x, right_x = M, M + 306
538
+ sections = []
539
+
540
+ lang_rows, lang_total = language_breakdown(stats.languages, limit=4, min_share=0.01)
541
+ lang_total = lang_total or 1
542
+ sections.append(_text(left_x, 912, t(
543
+ f"LANGUAGES · {stats.language_count} 种",
544
+ f"LANGUAGES · {stats.language_count}",
545
+ ), 10, c["muted"], spacing=0.6))
546
+ for i, (name, value) in enumerate(lang_rows[:5]):
547
+ y = 936 + i * 24
548
+ label = "Other" if en and name == "其他" else name
549
+ sections.append(_text(left_x, y, _truncate(label, 22), 11, c["ink2"]))
550
+ sections.append(_text(left_x + COL2 - 12, y, f"{value / lang_total * 100:.0f}%",
551
+ 10.5, c["muted"], anchor="end"))
552
+ track_w = COL2 - 12
553
+ width = int(track_w * value / lang_total)
554
+ sections.append(
555
+ f'<rect x="{left_x}" y="{y + 8}" width="{track_w}" height="2" '
556
+ f'fill="{c["line"]}"/>'
557
+ )
558
+ sections.append(
559
+ f'<rect x="{left_x}" y="{y + 8}" width="{width}" height="2" '
560
+ f'fill="{c["palette"][i % len(c["palette"])]}"/>'
561
+ )
562
+
563
+ type_rows = stats.commit_types[:5]
564
+ type_total = sum(value for _, value in stats.commit_types) or 1
565
+ sections.append(_text(right_x, 912, "COMMIT TYPES", 10, c["muted"], spacing=0.6))
566
+ for i, (name, value) in enumerate(type_rows[:5]):
567
+ y = 936 + i * 24
568
+ sections.append(_text(right_x, y, _truncate(name, 14), 11, c["ink2"]))
569
+ sections.append(_text(right_x + COL2 - 12, y, fmt_int(value), 10.5,
570
+ c["muted"], anchor="end"))
571
+ track_w = COL2 - 12
572
+ width = int(track_w * value / type_total)
573
+ sections.append(
574
+ f'<rect x="{right_x}" y="{y + 8}" width="{track_w}" height="2" '
575
+ f'fill="{c["line"]}"/>'
576
+ )
577
+ sections.append(
578
+ f'<rect x="{right_x}" y="{y + 8}" width="{width}" height="2" '
579
+ f'fill="{c["ink2"]}"/>'
580
+ )
581
+
582
+ repos = stats.repo_details[:4]
583
+ max_commits = max((r["commits"] for r in repos), default=1)
584
+ sections.append(_text(left_x, 1058, t(
585
+ f"TOP REPOS · {stats.repo_count} 个",
586
+ f"TOP REPOS · {stats.repo_count}",
587
+ ), 10, c["muted"], spacing=0.6))
588
+ for i, repo in enumerate(repos):
589
+ y = 1082 + i * 24
590
+ sections.append(_text(left_x, y, _truncate(repo["name"], 26), 11, c["ink2"]))
591
+ sections.append(_text(left_x + COL2 - 12, y, fmt_int(repo["commits"]), 10.5,
592
+ c["muted"], anchor="end"))
593
+ width = int((COL2 - 12) * repo["commits"] / max_commits)
594
+ sections.append(
595
+ f'<rect x="{left_x}" y="{y + 8}" width="{width}" height="2" '
596
+ f'fill="{c["ink2"]}"/>'
597
+ )
598
+
599
+ record_items: list[tuple[str, str]] = []
600
+ if stats.busiest_day:
601
+ day, count = stats.busiest_day
602
+ record_items.append((
603
+ t("最忙一天", "Busiest day"),
604
+ t(f"{count} 次 · {day[5:].replace('-', '.')}",
605
+ f"{count} commits · {day[5:].replace('-', '.')}"),
606
+ ))
607
+ if stats.busiest_week:
608
+ _week, count = stats.busiest_week
609
+ start_s = stats.busiest_week_start
610
+ if start_s:
611
+ start_d = datetime.strptime(start_s, "%Y.%m.%d").date()
612
+ end_d = start_d + timedelta(days=6)
613
+ span = f"{start_d:%m.%d}–{end_d:%m.%d}"
614
+ record_items.append((
615
+ t("最忙一周", "Busiest week"),
616
+ t(f"{count} 次 · {span}", f"{count} commits · {span}"),
617
+ ))
618
+ else:
619
+ record_items.append((
620
+ t("最忙一周", "Busiest week"),
621
+ t(f"{count} 次", f"{count} commits"),
622
+ ))
623
+ if stats.longest_gap:
624
+ days, start, end = stats.longest_gap
625
+ span = f"{start[5:]}–{end[5:]}".replace("-", ".")
626
+ record_items.append((
627
+ t("最长空窗", "Longest gap"),
628
+ t(f"{days} 天 · {span}", f"{days} days · {span}"),
629
+ ))
630
+ if stats.largest_commit:
631
+ record_items.append((
632
+ t("最大提交", "Largest commit"),
633
+ t(f"{fmt_int(stats.largest_commit['lines'])} 行",
634
+ f"{fmt_int(stats.largest_commit['lines'])} lines"),
635
+ ))
636
+ if stats.top_files:
637
+ path, _lines = stats.top_files[0]
638
+ record_items.append((
639
+ t("最常改文件", "Most edited"),
640
+ _truncate(path.split("/")[-1], 28),
641
+ ))
642
+ sections.append(_text(right_x, 1058, t("RECORDS / 年度之最", "RECORDS"),
643
+ 10, c["muted"], spacing=0.6))
644
+ for i, (label, value) in enumerate(record_items[:5]):
645
+ y = 1082 + i * 24
646
+ sections.append(_text(right_x, y, label, 10.5, c["muted"]))
647
+ sections.append(_text(right_x + COL2 - 12, y, value, 10.5, c["ink2"],
648
+ anchor="end"))
649
+
650
+ # ---- footer -------------------------------------------------------
651
+ meta_parts = []
652
+ if stats.earliest_dt:
653
+ meta_parts.append(t(
654
+ f"最早提交 {stats.earliest_dt:%Y.%m}",
655
+ f"First commit {stats.earliest_dt:%Y.%m}",
656
+ ))
657
+ if stats.tags_in_year:
658
+ meta_parts.append(t(
659
+ f"今年 {stats.tags_in_year} 个版本 tag",
660
+ f"{stats.tags_in_year} tags this year",
661
+ ))
662
+ previous = stats.previous or {}
663
+ if previous.get("commits_pct") is not None:
664
+ meta_parts.append(t(
665
+ f"同比 {previous['commits_pct']:+.0%} 提交",
666
+ f"{previous['commits_pct']:+.0%} commits YoY",
667
+ ))
668
+ meta_line = " · ".join(meta_parts)
669
+ right_footer = t(
670
+ f"生成于 {stats.generated_at.replace('-', '.')}",
671
+ f"Generated {stats.generated_at.replace('-', '.')}",
672
+ )
673
+ if stats.public_source:
674
+ source_line = t(
675
+ f"CODEYEAR · {stats.year} · 公开 GitHub 数据",
676
+ f"CODEYEAR · {stats.year} · public GitHub data",
677
+ )
678
+ source_badge = "PUBLIC · GITHUB"
679
+ else:
680
+ source_line = f"CODEYEAR · {stats.year} · generated locally · no data uploaded"
681
+ source_badge = "LOCAL ONLY"
682
+ footer = [
683
+ _rule(1202, c["line"]),
684
+ _text(M, 1218, meta_line, 10, c["muted"]),
685
+ _text(RIGHT, 1218, right_footer, 10, c["muted"], anchor="end"),
686
+ _text(M, 1236, source_line, 9.5, c["muted"]),
687
+ _text(RIGHT, 1236, source_badge, 9.5, c["accent"], anchor="end", spacing=1),
688
+ ]
689
+
690
+ label = f"{owner} · CodeYear {stats.year} · {title}" if owner else (
691
+ f"CodeYear {stats.year} · {title}"
692
+ )
693
+ return f"""<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}" role="img" aria-label="{_e(label)}">
694
+ <title>{_e(label)}</title>
695
+ {''.join(header)}
696
+ {''.join(tile_svg)}
697
+ {''.join(charts)}
698
+ {''.join(insight_svg)}
699
+ {''.join(sections)}
700
+ {''.join(footer)}
701
+ </svg>
702
+ """
703
+
704
+
705
+ def _is_leap(year: int) -> bool:
706
+ return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
707
+
708
+
709
+ def render(stats: ReportStats, out_path: str | Path, *,
710
+ theme: str = "paper", lang: str = "zh") -> list[Path]:
711
+ path = Path(out_path)
712
+ path.parent.mkdir(parents=True, exist_ok=True)
713
+ paths = [path]
714
+ path.write_text(build_svg(stats, theme=theme, lang=lang), encoding="utf-8")
715
+
716
+ dark_path = path.with_name(f"{path.stem}-dark{path.suffix}")
717
+ dark_path.write_text(
718
+ build_svg(stats, dark=True, theme=theme, lang=lang), encoding="utf-8")
719
+ paths.append(dark_path)
720
+ return paths