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/poster.py ADDED
@@ -0,0 +1,992 @@
1
+ """Render a 1200x1600 shareable poster in the same paper/ink style as the HTML report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import threading
8
+ from datetime import date, timedelta
9
+ from pathlib import Path
10
+
11
+ from PIL import Image, ImageDraw, ImageFont
12
+
13
+ from .stats import (
14
+ ReportStats,
15
+ date_window,
16
+ fmt_int,
17
+ fmt_signed_pair,
18
+ language_breakdown,
19
+ parse_daily,
20
+ )
21
+
22
+ W, H = 1200, 1600
23
+ M = 64
24
+ SCALE = 2
25
+
26
+ PAPER = (244, 241, 232)
27
+ PAPER2 = (236, 234, 223)
28
+ INK = (23, 21, 18)
29
+ INK2 = (64, 60, 51)
30
+ MUTED = (111, 106, 94)
31
+ LINE = (217, 211, 194)
32
+ LINE2 = (200, 193, 172)
33
+ ACCENT = (212, 73, 31)
34
+ ACCENT2 = (178, 58, 21)
35
+
36
+ _FONT_PATHS: dict[str, list[str]] = {
37
+ "serif": [
38
+ "C:/Windows/Fonts/georgia.ttf",
39
+ "C:/Windows/Fonts/times.ttf",
40
+ "/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf",
41
+ "/System/Library/Fonts/Supplemental/Georgia.ttf",
42
+ ],
43
+ "serifcn": [
44
+ "C:/Windows/Fonts/simsun.ttc",
45
+ "C:/Windows/Fonts/simsun.ttf",
46
+ "C:/Windows/Fonts/STZHONGS.TTF",
47
+ "/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc",
48
+ "/System/Library/Fonts/Supplemental/Songti.ttc",
49
+ ],
50
+ "sans": [
51
+ "C:/Windows/Fonts/msyh.ttc",
52
+ "C:/Windows/Fonts/msyh.ttf",
53
+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
54
+ "/System/Library/Fonts/PingFang.ttc",
55
+ ],
56
+ "bold": [
57
+ "C:/Windows/Fonts/msyhbd.ttc",
58
+ "C:/Windows/Fonts/msyhbd.ttf",
59
+ "C:/Windows/Fonts/simhei.ttf",
60
+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc",
61
+ "/System/Library/Fonts/PingFang.ttc",
62
+ ],
63
+ "mono": [
64
+ "C:/Windows/Fonts/consola.ttf",
65
+ "C:/Windows/Fonts/consolab.ttf",
66
+ "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
67
+ ],
68
+ }
69
+ _FONT_CACHE: dict[tuple[int, str], ImageFont.FreeTypeFont] = {}
70
+
71
+ # Thread-local language state keeps the drawing helpers readable while
72
+ # remaining safe for concurrent multi-thread rendering.
73
+ _STATE = threading.local()
74
+ _MONTHS = [
75
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
76
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
77
+ ]
78
+
79
+
80
+ def _get_lang() -> str:
81
+ return getattr(_STATE, "lang", "zh")
82
+
83
+
84
+ def _set_lang(lang: str) -> None:
85
+ _STATE.lang = "en" if lang == "en" else "zh"
86
+
87
+
88
+ def _t(zh: str, en: str) -> str:
89
+ return en if _get_lang() == "en" else zh
90
+
91
+
92
+
93
+ def _font(size: int, kind: str = "sans") -> ImageFont.FreeTypeFont:
94
+ key = (size, kind)
95
+ if key in _FONT_CACHE:
96
+ return _FONT_CACHE[key]
97
+ for path in _FONT_PATHS.get(kind, []):
98
+ if os.path.exists(path):
99
+ try:
100
+ font = ImageFont.truetype(path, size * SCALE, index=0)
101
+ _FONT_CACHE[key] = font
102
+ return font
103
+ except OSError:
104
+ continue
105
+ font = ImageFont.load_default()
106
+ _FONT_CACHE[key] = font
107
+ return font
108
+
109
+
110
+ class _ScaledDraw:
111
+ """Draw in 1200x1600 design coordinates while rendering at 2x."""
112
+
113
+ def __init__(self, draw: ImageDraw.ImageDraw, scale: int):
114
+ self._d = draw
115
+ self.s = scale
116
+
117
+ def text(self, xy, text, *args, **kwargs):
118
+ self._d.text((xy[0] * self.s, xy[1] * self.s), text, *args, **kwargs)
119
+
120
+ def line(self, xy, *args, **kwargs):
121
+ if len(xy) == 4 and all(isinstance(v, (int, float)) for v in xy):
122
+ coords = tuple(v * self.s for v in xy)
123
+ else:
124
+ coords = [(x * self.s, y * self.s) for x, y in xy]
125
+ kwargs["width"] = max(1, int(kwargs.get("width", 1) * self.s))
126
+ self._d.line(coords, *args, **kwargs)
127
+
128
+ def rectangle(self, xy, *args, **kwargs):
129
+ if len(xy) == 4 and all(isinstance(v, (int, float)) for v in xy):
130
+ coords = tuple(v * self.s for v in xy)
131
+ else:
132
+ coords = [(x * self.s, y * self.s) for x, y in xy]
133
+ kwargs["width"] = max(1, int(kwargs.get("width", 1) * self.s))
134
+ self._d.rectangle(coords, *args, **kwargs)
135
+
136
+ def textlength(self, text, *args, **kwargs):
137
+ return self._d.textlength(text, *args, **kwargs) / self.s
138
+
139
+
140
+ def _ellipsize(draw: ImageDraw.ImageDraw, text: str, font, max_width: float) -> str:
141
+ if not text:
142
+ return text
143
+ if draw.textlength(text, font=font) <= max_width:
144
+ return text
145
+ ell = "…"
146
+ while text and draw.textlength(text + ell, font=font) > max_width:
147
+ text = text[:-1]
148
+ return text + ell
149
+
150
+
151
+ _TOKEN_RE = re.compile(r"[\u4e00-\u9fff]|[^\u4e00-\u9fff\s]+|\s+")
152
+
153
+
154
+ def _wrap(draw: ImageDraw.ImageDraw, text: str, font, max_width: float, max_lines: int) -> list[str]:
155
+ tokens = _TOKEN_RE.findall(text)
156
+ lines: list[str] = []
157
+ cur = ""
158
+ for tok in tokens:
159
+ if tok.isspace():
160
+ if cur:
161
+ cur += " "
162
+ continue
163
+ candidate = cur + tok
164
+ if draw.textlength(candidate, font=font) <= max_width:
165
+ cur = candidate
166
+ else:
167
+ if cur.strip():
168
+ lines.append(cur.strip())
169
+ cur = tok
170
+ if cur.strip():
171
+ lines.append(cur.strip())
172
+ if len(lines) > max_lines:
173
+ lines = lines[:max_lines]
174
+ lines[-1] = _ellipsize(draw, lines[-1] + "…", font, max_width)
175
+ return lines
176
+
177
+
178
+ def _big(n: int) -> str:
179
+ if _get_lang() == "en":
180
+ if n >= 1_000_000:
181
+ return f"{n / 1_000_000:.1f}m"
182
+ if n >= 10_000:
183
+ return f"{n / 1000:.0f}k"
184
+ return f"{n:,}"
185
+ if n >= 100_000_000:
186
+ return f"{n / 100_000_000:.1f}亿"
187
+ if n >= 10_000:
188
+ return f"{n / 10_000:.1f}万"
189
+ return f"{n:,}"
190
+
191
+
192
+ def _signed(insertions: int, deletions: int) -> str:
193
+ if _get_lang() == "en":
194
+ if max(insertions, deletions) >= 10_000:
195
+ return f"+{insertions / 1000:.0f}k / -{deletions / 1000:.0f}k"
196
+ return f"+{insertions:,} / -{deletions:,}"
197
+ return fmt_signed_pair(insertions, deletions)
198
+
199
+
200
+ def _spaced(draw: ImageDraw.ImageDraw, xy: tuple[int, int], text: str, font, fill,
201
+ spacing: int) -> None:
202
+ x, y = xy
203
+ for ch in text:
204
+ draw.text((x, y), ch, font=font, fill=fill)
205
+ x += draw.textlength(ch, font=font) + spacing
206
+
207
+
208
+ def _is_cjk(ch: str) -> bool:
209
+ return "\u4e00" <= ch <= "\u9fff" or ch in ",。:;!?、「」()—·"
210
+
211
+
212
+ def _draw_text(draw: ImageDraw.ImageDraw, xy: tuple[int, int], text: str, font, fill,
213
+ anchor: str = "la", cjk_font=None) -> None:
214
+ """Draw mixed mono + CJK text on one shared baseline (no tofu, no bobbing)."""
215
+ if cjk_font is None or not any(_is_cjk(ch) for ch in text):
216
+ draw.text(xy, text, font=font, fill=fill, anchor=anchor)
217
+ return
218
+ widths = [
219
+ draw.textlength(ch, font=(cjk_font if _is_cjk(ch) else font))
220
+ for ch in text
221
+ ]
222
+ total = sum(widths)
223
+ x, y = xy
224
+ if anchor.startswith("r"):
225
+ x -= total
226
+ elif anchor.startswith("m"):
227
+ x -= total / 2
228
+
229
+ ascent, descent = font.getmetrics()
230
+ ascent /= SCALE
231
+ descent /= SCALE
232
+ vertical = anchor[1:2]
233
+ if vertical == "m":
234
+ baseline = y + (ascent - descent) / 2
235
+ elif vertical == "s":
236
+ baseline = y
237
+ elif vertical == "b":
238
+ baseline = y - descent
239
+ else:
240
+ baseline = y + ascent
241
+
242
+ for ch, width in zip(text, widths):
243
+ glyph_font = cjk_font if _is_cjk(ch) else font
244
+ draw.text((x, baseline), ch, font=glyph_font, fill=fill, anchor="ls")
245
+ x += width
246
+
247
+
248
+ def _rule(draw: ImageDraw.ImageDraw, y: int, color=LINE) -> None:
249
+ draw.line((M, y, W - M, y), fill=color, width=1)
250
+
251
+
252
+ def _label(draw: ImageDraw.ImageDraw, xy: tuple[int, int], text: str) -> None:
253
+ _draw_text(draw, xy, text.upper(), _font(10, "mono"), MUTED,
254
+ cjk_font=_font(10, "sans"))
255
+
256
+
257
+ def _scope_line(stats: ReportStats) -> str:
258
+ parts = []
259
+ if stats.earliest_dt:
260
+ parts.append(_t(
261
+ f"最早提交 {stats.earliest_dt:%Y.%m}",
262
+ f"first commit {stats.earliest_dt:%Y.%m}",
263
+ ))
264
+ if stats.new_repos:
265
+ parts.append(_t(
266
+ f"今年新开 {stats.new_repos} 个仓库",
267
+ f"{stats.new_repos} new repositories",
268
+ ))
269
+ if stats.tags_in_year:
270
+ parts.append(_t(
271
+ f"{stats.tags_in_year} 个版本 tag",
272
+ f"{stats.tags_in_year} release tags",
273
+ ))
274
+ return " · ".join(parts)
275
+
276
+
277
+ def _header(draw: ImageDraw.ImageDraw, stats: ReportStats) -> None:
278
+ _spaced(draw, (M, 50), "CODEYEAR", _font(20, "mono"), ACCENT, 6)
279
+ draw.text((W - M, 56), _t("代码手账", "YEARBOOK"),
280
+ font=_font(15, "sans"), fill=MUTED, anchor="ra")
281
+
282
+ draw.text((M - 5, 76), str(stats.year), font=_font(150, "serif"), fill=INK, anchor="lt")
283
+
284
+ span = "—"
285
+ if stats.first_dt and stats.last_dt:
286
+ span = f"{stats.first_dt:%Y.%m.%d} — {stats.last_dt:%Y.%m.%d}"
287
+ meta = f"{stats.root} · {stats.repo_count} " + _t("个仓库", "repositories") + f" · {span}"
288
+ _draw_text(draw, (M, 262),
289
+ _ellipsize(draw, meta, _font(12, "mono"), W - 2 * M),
290
+ _font(12, "mono"), MUTED, cjk_font=_font(12, "sans"))
291
+ scope = _scope_line(stats)
292
+ if scope:
293
+ _draw_text(draw, (M, 282),
294
+ _ellipsize(draw, scope, _font(10, "mono"), W - 2 * M),
295
+ _font(10, "mono"), MUTED, cjk_font=_font(10, "sans"))
296
+ _rule(draw, 300)
297
+
298
+
299
+ def _persona(draw: ImageDraw.ImageDraw, stats: ReportStats) -> None:
300
+ _label(draw, (M, 322), "YOUR CODING YEAR")
301
+ title = _ellipsize(
302
+ draw, stats.persona.title_en if _get_lang() == "en" else stats.persona.title,
303
+ _font(42, "serif" if _get_lang() == "en" else "serifcn"), W - 2 * M,
304
+ )
305
+ draw.text((M - 2, 338), title,
306
+ font=_font(42, "serif" if _get_lang() == "en" else "serifcn"), fill=INK)
307
+
308
+ body = _font(15, "sans")
309
+ text = stats.persona.subtitle_en if _get_lang() == "en" else stats.persona.subtitle
310
+ lines = _wrap(draw, text, body, W - 2 * M, 2)
311
+ for i, line in enumerate(lines):
312
+ draw.text((M, 402 + i * 24), line, font=body, fill=INK2)
313
+
314
+
315
+ def _stats(draw: ImageDraw.ImageDraw, stats: ReportStats) -> None:
316
+ _rule(draw, 476)
317
+ if _get_lang() == "en":
318
+ labels = ["COMMITS", "LINES", "ACTIVE", "STREAK", "TOTAL"]
319
+ subs = [
320
+ f"{stats.repo_count} repos with commits",
321
+ _signed(stats.insertions, stats.deletions),
322
+ f"{stats.active_days / (366 if _is_leap(stats.year) else 365):.0%} of the year",
323
+ f"{stats.current_streak}-day current streak",
324
+ "all-time",
325
+ ]
326
+ else:
327
+ labels = ["COMMITS / 提交", "LINES / 行变更", "ACTIVE / 活跃天",
328
+ "STREAK / 最长连续", "TOTAL / 累计"]
329
+ subs = [
330
+ f"{stats.repo_count} 个有提交的仓库",
331
+ _signed(stats.insertions, stats.deletions),
332
+ f"占全年 {stats.active_days / (366 if _is_leap(stats.year) else 365):.0%}",
333
+ f"当前 {stats.current_streak} 天",
334
+ "仓库全历史",
335
+ ]
336
+ values = [
337
+ f"{stats.commit_count:,}",
338
+ _big(stats.lines_changed),
339
+ str(stats.active_days),
340
+ str(stats.longest_streak),
341
+ f"{stats.total_commits:,}",
342
+ ]
343
+ col_w = (W - 2 * M) / 5
344
+ for i, (label, value, sub) in enumerate(zip(labels, values, subs)):
345
+ x = int(M + i * col_w)
346
+ _draw_text(draw, (x, 494), label, _font(10, "mono"), MUTED,
347
+ cjk_font=_font(10, "sans"))
348
+ _draw_text(draw, (x - 1, 510), value, _font(36, "mono"), INK,
349
+ cjk_font=_font(30, "sans"))
350
+ _draw_text(draw, (x, 558),
351
+ _ellipsize(draw, sub, _font(10, "mono"), col_w - 18),
352
+ _font(10, "mono"), MUTED, cjk_font=_font(10, "sans"))
353
+ _rule(draw, 590)
354
+
355
+
356
+ def _is_leap(year: int) -> bool:
357
+ return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
358
+
359
+
360
+ def _monthly(draw: ImageDraw.ImageDraw, stats: ReportStats) -> None:
361
+ _label(draw, (M, 612), "MONTHLY RHYTHM")
362
+ max_v = max(stats.monthly) or 1
363
+ peak = stats.monthly.index(max_v) + 1
364
+ _draw_text(draw, (W - M, 612), _t(
365
+ f"峰值 {peak:02d} 月 · {max_v} 次",
366
+ f"Peak {_MONTHS[peak - 1]} · {max_v}",
367
+ ), _font(11, "mono"), ACCENT, anchor="ra", cjk_font=_font(11, "sans"))
368
+
369
+ baseline = 758
370
+ max_h = 104
371
+ gap = 10
372
+ bar_w = int((W - 2 * M - gap * 11) / 12)
373
+ for i, value in enumerate(stats.monthly):
374
+ x = M + i * (bar_w + gap)
375
+ h = max(int(value / max_v * max_h), 2)
376
+ draw.rectangle((x, baseline - h, x + bar_w, baseline),
377
+ fill=ACCENT if value == max_v and value > 0 else INK)
378
+ draw.line((M, baseline, W - M, baseline), fill=INK, width=1)
379
+ for i in range(12):
380
+ cx = M + i * (bar_w + gap) + bar_w / 2
381
+ draw.text((cx, baseline + 7), f"{i + 1:02d}", font=_font(9, "mono"),
382
+ fill=MUTED, anchor="ma")
383
+
384
+
385
+ def _clock(draw: ImageDraw.ImageDraw, stats: ReportStats) -> None:
386
+ _label(draw, (M, 800), "7 × 24 CLOCK")
387
+ flat = [v for row in stats.hour_weekday for v in row]
388
+ max_v = max(flat) or 1
389
+
390
+ def color(v: int) -> tuple[int, int, int]:
391
+ if v == 0:
392
+ return PAPER2
393
+ if v <= max_v * 0.15:
394
+ return (221, 214, 196)
395
+ if v <= max_v * 0.35:
396
+ return (168, 159, 136)
397
+ if v <= max_v * 0.6:
398
+ return (92, 85, 74)
399
+ return INK
400
+
401
+ days = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"]
402
+ label_w = 38
403
+ gap = 3
404
+ cell_w = 40
405
+ cell_h = 14
406
+ x0 = M + label_w
407
+ y0 = 842
408
+
409
+ for h in range(24):
410
+ if h % 3 == 0:
411
+ draw.text((x0 + h * (cell_w + gap) + cell_w / 2, 826), f"{h:02d}",
412
+ font=_font(8, "mono"), fill=MUTED, anchor="ma")
413
+
414
+ for wd, row in enumerate(stats.hour_weekday):
415
+ y = y0 + wd * (cell_h + 4)
416
+ draw.text((M, y + 2), days[wd], font=_font(8, "mono"), fill=MUTED)
417
+ for h, value in enumerate(row):
418
+ x = x0 + h * (cell_w + gap)
419
+ draw.rectangle((x, y, x + cell_w, y + cell_h), fill=color(value))
420
+
421
+ _rule(draw, 972)
422
+
423
+
424
+ def _languages(draw: ImageDraw.ImageDraw, stats: ReportStats) -> None:
425
+ _label(draw, (M, 992), _t(
426
+ f"LANGUAGES / 语言 · {stats.language_count} 种",
427
+ f"LANGUAGES · {stats.language_count}",
428
+ ))
429
+ rows, total = language_breakdown(stats.languages, limit=4, min_share=0.01)
430
+ if not rows:
431
+ draw.text((M, 1024), _t("没有可统计的代码文件", "No code files to count"),
432
+ font=_font(12, "sans"), fill=MUTED)
433
+ return
434
+
435
+ palette = [INK, ACCENT, (143, 134, 114), (179, 171, 151), (200, 193, 172)]
436
+ bar_x, bar_y, bar_w, bar_h = M, 1018, 500, 16
437
+ x = bar_x
438
+ for i, (_name, value) in enumerate(rows):
439
+ w = int(bar_w * value / total)
440
+ draw.rectangle((x, bar_y, x + w, bar_y + bar_h), fill=palette[i % len(palette)])
441
+ x += w
442
+ if x < bar_x + bar_w:
443
+ draw.rectangle((x, bar_y, bar_x + bar_w, bar_y + bar_h),
444
+ fill=palette[len(rows) % len(palette)])
445
+
446
+ for i, (name, value) in enumerate(rows):
447
+ y = 1048 + i * 25
448
+ draw.rectangle((M, y + 2, M + 8, y + 10), fill=palette[i % len(palette)])
449
+ label = "Other" if _get_lang() == "en" and name == "其他" else name
450
+ _draw_text(draw, (M + 18, y + 6), _ellipsize(draw, label, _font(11, "sans"), 300),
451
+ _font(11, "sans"), INK2, anchor="lm", cjk_font=_font(11, "sans"))
452
+ draw.text((M + 500, y + 6), f"{value / total * 100:.0f}%", font=_font(10, "mono"),
453
+ fill=MUTED, anchor="rm")
454
+
455
+
456
+ def _files(draw: ImageDraw.ImageDraw, stats: ReportStats) -> None:
457
+ x = 620
458
+ _label(draw, (x, 992), "MOST EDITED FILES")
459
+ rows = stats.top_files[:4]
460
+ if not rows:
461
+ draw.text((x, 1024), _t("暂无数据", "No data"),
462
+ font=_font(12, "sans"), fill=MUTED)
463
+ return
464
+ max_v = max(v for _, v in rows) or 1
465
+ for i, (path, lines) in enumerate(rows):
466
+ y = 1020 + i * 38
467
+ _draw_text(draw, (x, y + 5), f"{i + 1:02d}", _font(9, "mono"), ACCENT,
468
+ anchor="lm")
469
+ _draw_text(draw, (x + 24, y + 5),
470
+ _ellipsize(draw, path, _font(10, "mono"), 400),
471
+ _font(10, "mono"), INK2, anchor="lm", cjk_font=_font(10, "sans"))
472
+ draw.line((x + 24, y + 15, x + 24 + int(400 * lines / max_v), y + 15),
473
+ fill=INK, width=3)
474
+ _draw_text(draw, (W - M, y + 5), _big(lines), _font(9, "mono"), MUTED,
475
+ anchor="rm", cjk_font=_font(9, "sans"))
476
+
477
+
478
+ def _heatmap(draw: ImageDraw.ImageDraw, stats: ReportStats) -> None:
479
+ _rule(draw, 1200)
480
+ _label(draw, (M, 1216), _t(
481
+ f"CONTRIBUTION / {stats.active_days} 个活跃日",
482
+ f"CONTRIBUTION / {stats.active_days} active days",
483
+ ))
484
+
485
+ daily = parse_daily(stats.daily)
486
+ start, end = date_window(stats)
487
+ grid_start = start - timedelta(days=start.weekday())
488
+ grid_end = end + timedelta(days=6 - end.weekday())
489
+ cols = (grid_end - grid_start).days // 7 + 1
490
+
491
+ cell, gap = 14, 4
492
+ x0 = (W - (cols * cell + (cols - 1) * gap)) // 2
493
+ y0 = 1266
494
+
495
+ for month in range(1, 13):
496
+ col = (date(stats.year, month, 1) - grid_start).days // 7
497
+ draw.text((x0 + col * (cell + gap), 1246), f"{month:02d}",
498
+ font=_font(8, "mono"), fill=MUTED)
499
+
500
+ for col in range(cols):
501
+ for row in range(7):
502
+ day = grid_start + timedelta(days=col * 7 + row)
503
+ if day < start or day > end:
504
+ continue
505
+ count = daily.get(day, 0)
506
+ if count == 0:
507
+ fill = PAPER2
508
+ elif count == 1:
509
+ fill = (221, 214, 196)
510
+ elif count <= 3:
511
+ fill = (168, 159, 136)
512
+ elif count <= 6:
513
+ fill = (92, 85, 74)
514
+ else:
515
+ fill = INK
516
+ x = x0 + col * (cell + gap)
517
+ y = y0 + row * (cell + gap)
518
+ draw.rectangle((x, y, x + cell, y + cell), fill=fill)
519
+
520
+
521
+ def _closing(draw: ImageDraw.ImageDraw, stats: ReportStats) -> None:
522
+ quote = _t("「代码不会说谎,git 尤其不会。」",
523
+ "“Code doesn’t lie. Git especially doesn’t.”")
524
+ draw.text((M, 1424), quote,
525
+ font=_font(24, "serif" if _get_lang() == "en" else "serifcn"), fill=INK)
526
+ sub = _t(
527
+ f"LOCAL ONLY · 生成于 {stats.generated_at} · 代码从未离开这台电脑",
528
+ f"LOCAL ONLY · generated {stats.generated_at} · code never left this machine",
529
+ )
530
+ footer_label = "LOCAL-FIRST · NO DATA UPLOADED"
531
+ if stats.public_source:
532
+ sub = _t(
533
+ f"PUBLIC DATA · 生成于 {stats.generated_at} · 仅使用公开 GitHub 数据",
534
+ f"PUBLIC DATA · generated {stats.generated_at} · public GitHub data only",
535
+ )
536
+ footer_label = "PUBLIC DATA · GITHUB"
537
+ _draw_text(draw, (M, 1468), sub, _font(10, "mono"), MUTED,
538
+ cjk_font=_font(10, "sans"))
539
+
540
+ _rule(draw, 1520)
541
+ draw.text((M, 1534), footer_label,
542
+ font=_font(9, "mono"), fill=MUTED)
543
+ draw.text((W - M, 1534), f"CODEYEAR · {stats.year}",
544
+ font=_font(9, "mono"), fill=MUTED, anchor="ra")
545
+
546
+
547
+ def render(stats: ReportStats, out_path: str | Path, *, lang: str = "zh") -> Path:
548
+ _set_lang(lang)
549
+ img = Image.new("RGB", (W * SCALE, H * SCALE), PAPER)
550
+ draw = _ScaledDraw(ImageDraw.Draw(img), SCALE)
551
+
552
+ # Very light ledger grid.
553
+ for x in range(0, W, 48):
554
+ draw.line((x, 0, x, H), fill=(239, 236, 226), width=1)
555
+ for y in range(0, H, 48):
556
+ draw.line((0, y, W, y), fill=(239, 236, 226), width=1)
557
+
558
+ _header(draw, stats)
559
+ _persona(draw, stats)
560
+ _stats(draw, stats)
561
+ _monthly(draw, stats)
562
+ _clock(draw, stats)
563
+ _languages(draw, stats)
564
+ _files(draw, stats)
565
+ _heatmap(draw, stats)
566
+ _closing(draw, stats)
567
+
568
+ path = Path(out_path)
569
+ path.parent.mkdir(parents=True, exist_ok=True)
570
+ img.save(path, "PNG", optimize=True)
571
+ return path
572
+
573
+
574
+ # --------------------------------------------------------------------------
575
+ # Full-length "long image" version
576
+ # --------------------------------------------------------------------------
577
+
578
+ LONG_W = 1200
579
+ LONG_H = 4000
580
+
581
+
582
+ def _long_title(draw: ImageDraw.ImageDraw, y: int, no: str, cn: str, en: str) -> int:
583
+ _rule(draw, y - 18)
584
+ draw.text((M, y), f"{no} / {en}", font=_font(9, "mono"), fill=ACCENT)
585
+ heading = en if _get_lang() == "en" else cn
586
+ heading_font = "serif" if _get_lang() == "en" else "serifcn"
587
+ _draw_text(draw, (M, y + 16), heading, _font(26, heading_font), INK,
588
+ cjk_font=_font(26, "serifcn"))
589
+ return y + 54
590
+
591
+
592
+ def _long_header(draw: ImageDraw.ImageDraw, stats: ReportStats, y: int) -> int:
593
+ _spaced(draw, (M, y), "CODEYEAR", _font(18, "mono"), ACCENT, 5)
594
+ _draw_text(draw, (W - M, y + 3), _t(f"代码手账 · {stats.year}", f"Yearbook · {stats.year}"),
595
+ _font(13, "sans"), MUTED, anchor="ra", cjk_font=_font(13, "sans"))
596
+
597
+ draw.text((M - 4, y + 20), str(stats.year), font=_font(110, "serif"), fill=INK)
598
+ span = "—"
599
+ if stats.first_dt and stats.last_dt:
600
+ span = f"{stats.first_dt:%Y.%m.%d} — {stats.last_dt:%Y.%m.%d}"
601
+ meta = f"{stats.root} · {stats.repo_count} " + _t("个仓库", "repositories") + f" · {span}"
602
+ _draw_text(draw, (M, y + 158), _ellipsize(draw, meta, _font(11, "mono"), W - 2 * M),
603
+ _font(11, "mono"), MUTED, cjk_font=_font(11, "sans"))
604
+ scope = _scope_line(stats)
605
+ if scope:
606
+ _draw_text(draw, (M, y + 176), _ellipsize(draw, scope, _font(10, "mono"), W - 2 * M),
607
+ _font(10, "mono"), MUTED, cjk_font=_font(10, "sans"))
608
+
609
+ title = stats.persona.title_en if _get_lang() == "en" else stats.persona.title
610
+ title_font = "serif" if _get_lang() == "en" else "serifcn"
611
+ _draw_text(draw, (M, y + 196), title, _font(34, title_font), INK,
612
+ cjk_font=_font(34, "serifcn"))
613
+ subtitle = stats.persona.subtitle_en if _get_lang() == "en" else stats.persona.subtitle
614
+ lines = _wrap(draw, subtitle, _font(14, "sans"), W - 2 * M, 2)
615
+ for i, line in enumerate(lines):
616
+ draw.text((M, y + 242 + i * 22), line, font=_font(14, "sans"), fill=INK2)
617
+
618
+ _rule(draw, y + 300)
619
+ if _get_lang() == "en":
620
+ labels = ["COMMITS", "LINES", "ACTIVE", "STREAK", "TOTAL"]
621
+ subs = [f"{stats.repo_count} repos with commits",
622
+ _signed(stats.insertions, stats.deletions),
623
+ f"{stats.active_days / (366 if _is_leap(stats.year) else 365):.0%} of the year",
624
+ f"{stats.current_streak}-day current streak",
625
+ "all-time"]
626
+ else:
627
+ labels = ["COMMITS / 提交", "LINES / 行变更", "ACTIVE / 活跃天",
628
+ "STREAK / 最长连续", "TOTAL / 累计"]
629
+ subs = [f"{stats.repo_count} 个有提交的仓库",
630
+ _signed(stats.insertions, stats.deletions),
631
+ f"占全年 {stats.active_days / (366 if _is_leap(stats.year) else 365):.0%}",
632
+ f"当前 {stats.current_streak} 天",
633
+ "仓库全历史"]
634
+ values = [f"{stats.commit_count:,}", _big(stats.lines_changed),
635
+ str(stats.active_days), str(stats.longest_streak),
636
+ f"{stats.total_commits:,}"]
637
+ col_w = (W - 2 * M) / 5
638
+ for i, (label, value, sub) in enumerate(zip(labels, values, subs)):
639
+ x = int(M + i * col_w)
640
+ _draw_text(draw, (x, y + 318), label, _font(9, "mono"), MUTED,
641
+ cjk_font=_font(9, "sans"))
642
+ _draw_text(draw, (x, y + 332), value, _font(30, "mono"), INK,
643
+ cjk_font=_font(25, "sans"))
644
+ _draw_text(draw, (x, y + 370), _ellipsize(draw, sub, _font(9, "mono"), col_w - 18),
645
+ _font(9, "mono"), MUTED, cjk_font=_font(9, "sans"))
646
+ _rule(draw, y + 392)
647
+ return y + 416
648
+
649
+
650
+ def _long_records(draw: ImageDraw.ImageDraw, stats: ReportStats, y: int) -> int:
651
+ y0 = _long_title(draw, y, "01", "年度之最", "YEAR IN REVIEW")
652
+ records: list[tuple[str, str, str]] = []
653
+ if stats.busiest_day:
654
+ day, count = stats.busiest_day
655
+ records.append((_t("最忙的一天", "Busiest day"),
656
+ _t(f"{count} 次提交", f"{count} commits"),
657
+ day.replace("-", ".")))
658
+ if stats.busiest_week:
659
+ week, count = stats.busiest_week
660
+ records.append((_t("最忙的一周", "Busiest week"),
661
+ _t(f"{count} 次提交", f"{count} commits"),
662
+ _t(f"{week} · 起于 {stats.busiest_week_start or '—'}",
663
+ f"{week} · from {stats.busiest_week_start or '—'}")))
664
+ records.append((_t("最长连续", "Longest streak"),
665
+ _t(f"{stats.longest_streak} 天", f"{stats.longest_streak} days"),
666
+ _t(f"当前连续 {stats.current_streak} 天",
667
+ f"{stats.current_streak}-day current streak")))
668
+ if stats.longest_gap:
669
+ days, start, end = stats.longest_gap
670
+ records.append((_t("最长空窗", "Longest gap"),
671
+ _t(f"{days} 天", f"{days} days"),
672
+ f"{start} – {end}"))
673
+ if stats.largest_commit:
674
+ lc = stats.largest_commit
675
+ records.append((_t("最大单次提交", "Largest commit"),
676
+ _t(f"{fmt_int(lc['lines'])} 行", f"{fmt_int(lc['lines'])} lines"),
677
+ f"{lc['repo']} · {lc['date']}"))
678
+ records.append((_t("最长的 commit", "Longest message"),
679
+ _t(f"{len(stats.longest_subject)} 字符",
680
+ f"{len(stats.longest_subject)} chars"),
681
+ stats.longest_subject[:46]))
682
+
683
+ card_w, card_h = 344, 100
684
+ for i, (label, value, sub) in enumerate(records[:6]):
685
+ col, row = i % 3, i // 3
686
+ bx = M + col * (card_w + 20)
687
+ by = y0 + row * (card_h + 12)
688
+ draw.rectangle((bx, by, bx + card_w, by + card_h), outline=LINE)
689
+ _draw_text(draw, (bx + 14, by + 12), label, _font(9, "mono"), MUTED,
690
+ cjk_font=_font(9, "sans"))
691
+ _draw_text(draw, (bx + 14, by + 30), value, _font(21, "serifcn"), INK,
692
+ cjk_font=_font(21, "serifcn"))
693
+ _draw_text(draw, (bx + 14, by + 68), _ellipsize(draw, sub, _font(9, "mono"), card_w - 28),
694
+ _font(9, "mono"), MUTED, cjk_font=_font(9, "sans"))
695
+ return y0 + 2 * card_h + 12 + 8
696
+
697
+
698
+ def _long_monthly(draw: ImageDraw.ImageDraw, stats: ReportStats, y: int) -> int:
699
+ y0 = _long_title(draw, y, "02", "月度节奏", "MONTHLY RHYTHM")
700
+ max_v = max(stats.monthly) or 1
701
+ peak = stats.monthly.index(max_v) + 1
702
+ _draw_text(draw, (W - M, y0), _t(
703
+ f"峰值 {peak:02d} 月 · {max_v} 次",
704
+ f"Peak {_MONTHS[peak - 1]} · {max_v}",
705
+ ), _font(10, "mono"), ACCENT, anchor="ra", cjk_font=_font(10, "sans"))
706
+ baseline = y0 + 128
707
+ max_h = 92
708
+ gap = 8
709
+ bar_w = int((W - 2 * M - gap * 11) / 12)
710
+ for i, value in enumerate(stats.monthly):
711
+ x = M + i * (bar_w + gap)
712
+ h = max(int(value / max_v * max_h), 2)
713
+ draw.rectangle((x, baseline - h, x + bar_w, baseline),
714
+ fill=ACCENT if value == max_v and value > 0 else INK)
715
+ draw.line((M, baseline, W - M, baseline), fill=INK, width=1)
716
+ for i in range(12):
717
+ cx = M + i * (bar_w + gap) + bar_w / 2
718
+ draw.text((cx, baseline + 7), f"{i + 1:02d}", font=_font(9, "mono"),
719
+ fill=MUTED, anchor="ma")
720
+ return baseline + 30
721
+
722
+
723
+ def _long_clock(draw: ImageDraw.ImageDraw, stats: ReportStats, y: int) -> int:
724
+ y0 = _long_title(draw, y, "03", "7×24 提交时钟", "7 × 24 CLOCK")
725
+ flat = [v for row in stats.hour_weekday for v in row]
726
+ max_v = max(flat) or 1
727
+
728
+ def color(v: int) -> tuple[int, int, int]:
729
+ if v == 0:
730
+ return PAPER2
731
+ if v <= max_v * 0.15:
732
+ return (221, 214, 196)
733
+ if v <= max_v * 0.35:
734
+ return (168, 159, 136)
735
+ if v <= max_v * 0.6:
736
+ return (92, 85, 74)
737
+ return INK
738
+
739
+ days = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"]
740
+ label_w = 38
741
+ gap = 3
742
+ cell_w = 40
743
+ cell_h = 12
744
+ x0 = M + label_w
745
+ for h in range(24):
746
+ if h % 3 == 0:
747
+ draw.text((x0 + h * (cell_w + gap) + cell_w / 2, y0 - 2),
748
+ f"{h:02d}", font=_font(8, "mono"), fill=MUTED, anchor="ma")
749
+ for wd, row in enumerate(stats.hour_weekday):
750
+ yy = y0 + 12 + wd * (cell_h + 3)
751
+ draw.text((M, yy + 1), days[wd], font=_font(8, "mono"), fill=MUTED)
752
+ for h, value in enumerate(row):
753
+ x = x0 + h * (cell_w + gap)
754
+ draw.rectangle((x, yy, x + cell_w, yy + cell_h), fill=color(value))
755
+ _draw_text(draw, (W - M, y0 + 8), _t(
756
+ f"周末占 {stats.weekend_share:.0%} · 深夜占 {stats.night_share:.0%}",
757
+ f"weekend {stats.weekend_share:.0%} · late-night {stats.night_share:.0%}",
758
+ ), _font(9, "mono"), MUTED, anchor="ra", cjk_font=_font(9, "sans"))
759
+ return y0 + 12 + 7 * (cell_h + 3) + 14
760
+
761
+
762
+ def _long_bars(draw: ImageDraw.ImageDraw, x: int, y: int, w: int,
763
+ rows: list[tuple[str, int]], max_v: int, color=INK) -> int:
764
+ for i, (label, value) in enumerate(rows):
765
+ yy = y + i * 24
766
+ _draw_text(draw, (x, yy), _ellipsize(draw, label, _font(9, "mono"), 130),
767
+ _font(9, "mono"), INK2, cjk_font=_font(9, "sans"))
768
+ bx = x + 138
769
+ bw = w - 138 - 54
770
+ draw.rectangle((bx, yy - 7, bx + bw, yy - 1), outline=LINE)
771
+ if value > 0:
772
+ draw.rectangle((bx, yy - 7, bx + max(int(bw * value / max_v), 2), yy - 1),
773
+ fill=color)
774
+ draw.text((x + w, yy), f"{value:,}", font=_font(8, "mono"), fill=MUTED,
775
+ anchor="rm")
776
+ return y + len(rows) * 24
777
+
778
+
779
+ def _long_lang_files(draw: ImageDraw.ImageDraw, stats: ReportStats, y: int) -> int:
780
+ y0 = _long_title(draw, y, "04", "语言与文件", "LANGUAGES & FILES")
781
+ draw.text((M, y0), "LANGUAGES", font=_font(9, "mono"), fill=MUTED)
782
+ rows, total = language_breakdown(stats.languages, limit=4, min_share=0.01)
783
+ palette = [INK, ACCENT, (143, 134, 114), (179, 171, 151), (200, 193, 172)]
784
+ bar_w = 500
785
+ x = M
786
+ for i, (_name, value) in enumerate(rows):
787
+ w = int(bar_w * value / total)
788
+ draw.rectangle((x, y0 + 20, x + w, y0 + 34), fill=palette[i % len(palette)])
789
+ x += w
790
+ if x < M + bar_w:
791
+ draw.rectangle((x, y0 + 20, M + bar_w, y0 + 34),
792
+ fill=palette[len(rows) % len(palette)])
793
+ for i, (name, value) in enumerate(rows):
794
+ yy = y0 + 46 + i * 21
795
+ draw.rectangle((M, yy + 2, M + 8, yy + 10), fill=palette[i % len(palette)])
796
+ label = "Other" if _get_lang() == "en" and name == "其他" else name
797
+ _draw_text(draw, (M + 16, yy + 6), label, _font(10, "sans"), INK2,
798
+ anchor="lm", cjk_font=_font(10, "sans"))
799
+ draw.text((M + 500, yy + 6), f"{value / total * 100:.0f}%",
800
+ font=_font(9, "mono"), fill=MUTED, anchor="rm")
801
+
802
+ xr = 620
803
+ draw.text((xr, y0), "MOST EDITED FILES", font=_font(9, "mono"), fill=MUTED)
804
+ files = stats.top_files[:5]
805
+ max_v = max((v for _, v in files), default=1)
806
+ for i, (path, lines) in enumerate(files):
807
+ yy = y0 + 22 + i * 28
808
+ _draw_text(draw, (xr, yy), f"{i + 1:02d}", _font(8, "mono"), ACCENT)
809
+ _draw_text(draw, (xr + 22, yy),
810
+ _ellipsize(draw, path, _font(9, "mono"), 420),
811
+ _font(9, "mono"), INK2, cjk_font=_font(9, "sans"))
812
+ draw.line((xr + 22, yy + 14, xr + 22 + int(420 * lines / max_v), yy + 14),
813
+ fill=INK, width=3)
814
+ _draw_text(draw, (W - M, yy), _big(lines), _font(8, "mono"), MUTED,
815
+ anchor="ra", cjk_font=_font(8, "sans"))
816
+ return y0 + 172
817
+
818
+
819
+ def _long_sizes_types(draw: ImageDraw.ImageDraw, stats: ReportStats, y: int) -> int:
820
+ y0 = _long_title(draw, y, "05", "规模与类型", "SIZE & TYPES")
821
+ draw.text((M, y0), "COMMIT SIZE", font=_font(9, "mono"), fill=MUTED)
822
+ max_s = max((v for _, v in stats.size_buckets), default=1)
823
+ _long_bars(draw, M, y0 + 24, 500,
824
+ [(_t(f"{label} 行", f"{label} lines"), v)
825
+ for label, v in stats.size_buckets], max_s)
826
+
827
+ xr = 620
828
+ draw.text((xr, y0), "COMMIT TYPES", font=_font(9, "mono"), fill=MUTED)
829
+ types = stats.commit_types[:6]
830
+ max_t = max((v for _, v in types), default=1)
831
+ _long_bars(draw, xr, y0 + 24, 516, types, max_t)
832
+ _draw_text(draw, (W - M, y0 + 8),
833
+ _t(f"约定式 {stats.conventional_share:.0%}",
834
+ f"Conventional {stats.conventional_share:.0%}"),
835
+ _font(9, "mono"), ACCENT, anchor="ra", cjk_font=_font(9, "sans"))
836
+ return y0 + 176
837
+
838
+
839
+ def _long_msgs_sessions(draw: ImageDraw.ImageDraw, stats: ReportStats, y: int) -> int:
840
+ y0 = _long_title(draw, y, "06", "消息与节奏", "MESSAGES & SESSIONS")
841
+ draw.text((M, y0), "MESSAGE LENGTH", font=_font(9, "mono"), fill=MUTED)
842
+ max_m = max((v for _, v in stats.message_buckets), default=1)
843
+ _long_bars(draw, M, y0 + 24, 500,
844
+ [(_t(f"{label} 字符", f"{label} chars"), v)
845
+ for label, v in stats.message_buckets], max_m)
846
+
847
+ xr = 620
848
+ draw.text((xr, y0), "CODING SESSIONS", font=_font(9, "mono"), fill=MUTED)
849
+ s = stats.sessions
850
+ hours, mins = divmod(int(s.get("longest_minutes", 0)), 60)
851
+ items = [
852
+ (_t("会话次数", "Sessions"), f"{s.get('count', 0)}"),
853
+ (_t("最长会话", "Longest session"), f"{hours}h {mins:02d}m"),
854
+ (_t("最长会话提交", "Longest session commits"), f"{s.get('longest_commits', 0)}"),
855
+ (_t("平均会话", "Average session"), f"{s.get('avg_minutes', 0)}m"),
856
+ ]
857
+ for i, (label, value) in enumerate(items):
858
+ col, row = i % 2, i // 2
859
+ bx = xr + col * 258
860
+ by = y0 + 26 + row * 46
861
+ _draw_text(draw, (bx, by), label, _font(9, "mono"), MUTED,
862
+ cjk_font=_font(9, "sans"))
863
+ _draw_text(draw, (bx, by + 14), value, _font(20, "mono"), INK,
864
+ cjk_font=_font(16, "sans"))
865
+ _draw_text(draw, (xr, y0 + 140), _t(
866
+ f"间隔 ≤ 2 小时算同一会话 · 平均每条 {stats.avg_subject_len} 字符",
867
+ f"Sessions split at 2h gaps · avg {stats.avg_subject_len} chars per subject",
868
+ ), _font(9, "mono"), MUTED, cjk_font=_font(9, "sans"))
869
+ return y0 + 176
870
+
871
+
872
+ def _long_churn_dormant(draw: ImageDraw.ImageDraw, stats: ReportStats, y: int) -> int:
873
+ y0 = _long_title(draw, y, "07", "增删与墓园", "CHURN & DORMANT")
874
+ draw.text((M, y0), "ADD / DELETE", font=_font(9, "mono"), fill=MUTED)
875
+ total = max(stats.insertions + stats.deletions, 1)
876
+ draw.rectangle((M, y0 + 24, M + 500, y0 + 38), outline=INK)
877
+ draw.rectangle((M, y0 + 24, M + int(500 * stats.insertions / total), y0 + 38),
878
+ fill=INK)
879
+ draw.rectangle((M + int(500 * stats.insertions / total), y0 + 24,
880
+ M + 500, y0 + 38), fill=ACCENT)
881
+ _draw_text(draw, (M, y0 + 48),
882
+ _t(f"新增 {_signed(stats.insertions, stats.deletions)}",
883
+ f"Added {_signed(stats.insertions, stats.deletions)}"),
884
+ _font(9, "mono"), MUTED, cjk_font=_font(9, "sans"))
885
+ top_del = sorted(stats.repo_details, key=lambda d: -d["deleted"])[:3]
886
+ max_del = max((d["deleted"] for d in top_del), default=1)
887
+ _long_bars(draw, M, y0 + 80, 500,
888
+ [(d["name"], d["deleted"]) for d in top_del], max_del, color=ACCENT)
889
+
890
+ xr = 620
891
+ draw.text((xr, y0), "DORMANT REPOS", font=_font(9, "mono"), fill=MUTED)
892
+ if not stats.dormant:
893
+ draw.text((xr, y0 + 26),
894
+ _t("没有休眠超过 30 天的仓库",
895
+ "No repositories dormant for more than 30 days"),
896
+ font=_font(11, "sans"), fill=MUTED)
897
+ for i, repo in enumerate(stats.dormant[:5]):
898
+ yy = y0 + 24 + i * 26
899
+ _draw_text(draw, (xr, yy + 6), repo["name"], _font(9, "mono"), INK2,
900
+ anchor="lm", cjk_font=_font(9, "sans"))
901
+ draw.text((W - M, yy + 6), _t(f"{repo['days']} 天", f"{repo['days']} days"),
902
+ font=_font(9, "mono"), fill=ACCENT, anchor="rm")
903
+ return y0 + 186
904
+
905
+
906
+ def _long_heatmap(draw: ImageDraw.ImageDraw, stats: ReportStats, y: int) -> int:
907
+ y0 = _long_title(draw, y, "08", "全年热力图", "CONTRIBUTION")
908
+ daily = parse_daily(stats.daily)
909
+ start, end = date_window(stats)
910
+ grid_start = start - timedelta(days=start.weekday())
911
+ grid_end = end + timedelta(days=6 - end.weekday())
912
+ cols = (grid_end - grid_start).days // 7 + 1
913
+ cell, gap = 14, 4
914
+ x0 = (W - (cols * cell + (cols - 1) * gap)) // 2
915
+ y0 += 18
916
+ for month in range(1, 13):
917
+ col = (date(stats.year, month, 1) - grid_start).days // 7
918
+ draw.text((x0 + col * (cell + gap), y0 - 16), f"{month:02d}",
919
+ font=_font(8, "mono"), fill=MUTED)
920
+ for col in range(cols):
921
+ for row in range(7):
922
+ day = grid_start + timedelta(days=col * 7 + row)
923
+ if day < start or day > end:
924
+ continue
925
+ count = daily.get(day, 0)
926
+ if count == 0:
927
+ fill = PAPER2
928
+ elif count == 1:
929
+ fill = (221, 214, 196)
930
+ elif count <= 3:
931
+ fill = (168, 159, 136)
932
+ elif count <= 6:
933
+ fill = (92, 85, 74)
934
+ else:
935
+ fill = INK
936
+ x = x0 + col * (cell + gap)
937
+ yy = y0 + row * (cell + gap)
938
+ draw.rectangle((x, yy, x + cell, yy + cell), fill=fill)
939
+ _draw_text(draw, (W - M, y0 - 18), _t(
940
+ f"{stats.active_days} 个活跃日",
941
+ f"{stats.active_days} active days",
942
+ ), _font(9, "mono"), MUTED, anchor="ra", cjk_font=_font(9, "sans"))
943
+ return y0 + 7 * (cell + gap) + 18
944
+
945
+
946
+ def render_long(stats: ReportStats, out_path: str | Path, *, lang: str = "zh") -> Path:
947
+ _set_lang(lang)
948
+ img = Image.new("RGB", (LONG_W * SCALE, LONG_H * SCALE), PAPER)
949
+ draw = _ScaledDraw(ImageDraw.Draw(img), SCALE)
950
+ for x in range(0, LONG_W, 48):
951
+ draw.line((x, 0, x, LONG_H), fill=(239, 236, 226), width=1)
952
+ for yy in range(0, LONG_H, 48):
953
+ draw.line((0, yy, LONG_W, yy), fill=(239, 236, 226), width=1)
954
+
955
+ y = _long_header(draw, stats, 56)
956
+ y = _long_records(draw, stats, y + 20)
957
+ y = _long_monthly(draw, stats, y + 30)
958
+ y = _long_clock(draw, stats, y + 30)
959
+ y = _long_lang_files(draw, stats, y + 30)
960
+ y = _long_sizes_types(draw, stats, y + 30)
961
+ y = _long_msgs_sessions(draw, stats, y + 30)
962
+ y = _long_churn_dormant(draw, stats, y + 30)
963
+ y = _long_heatmap(draw, stats, y + 30)
964
+
965
+ draw.text((M, y + 24), _t("「代码不会说谎,git 尤其不会。」",
966
+ "“Code doesn’t lie. Git especially doesn’t.”"),
967
+ font=_font(22, "serif" if _get_lang() == "en" else "serifcn"), fill=INK)
968
+ sub = _t(
969
+ f"LOCAL ONLY · 生成于 {stats.generated_at} · 代码从未离开这台电脑",
970
+ f"LOCAL ONLY · generated {stats.generated_at} · code never left this machine",
971
+ )
972
+ footer_label = "LOCAL-FIRST · NO DATA UPLOADED"
973
+ if stats.public_source:
974
+ sub = _t(
975
+ f"PUBLIC DATA · 生成于 {stats.generated_at} · 仅使用公开 GitHub 数据",
976
+ f"PUBLIC DATA · generated {stats.generated_at} · public GitHub data only",
977
+ )
978
+ footer_label = "PUBLIC DATA · GITHUB"
979
+ _draw_text(draw, (M, y + 62), sub,
980
+ _font(9, "mono"), MUTED, cjk_font=_font(9, "sans"))
981
+ _rule(draw, y + 100)
982
+ draw.text((M, y + 112), footer_label,
983
+ font=_font(9, "mono"), fill=MUTED)
984
+ draw.text((W - M, y + 112), f"CODEYEAR · {stats.year}",
985
+ font=_font(9, "mono"), fill=MUTED, anchor="ra")
986
+
987
+ final_h = min(y + 150, LONG_H)
988
+ img = img.crop((0, 0, LONG_W * SCALE, final_h * SCALE))
989
+ path = Path(out_path)
990
+ path.parent.mkdir(parents=True, exist_ok=True)
991
+ img.save(path, "PNG", optimize=True)
992
+ return path