forked from vycdev/thermal-printer-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_print.py
More file actions
323 lines (265 loc) · 11.8 KB
/
Copy pathgithub_print.py
File metadata and controls
323 lines (265 loc) · 11.8 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
#!/usr/bin/env python3
"""Print a GitHub profile card -- avatar, stats, and contribution graph -- on the S01.
Pulls everything unauthenticated:
* profile fields from the REST API (name, bio, followers, repos, ...)
* the avatar image (Floyd-dithered into the card)
* the last-year contribution calendar scraped from the public contributions
fragment (per-day intensity levels 0-4)
The whole card is rendered bilevel (crisp black text/lines + a pre-dithered
avatar), so it prints sharp through the existing s1_print.py image path.
Examples:
python github_print.py octocat
python github_print.py octocat --no-print # just write the PNG
python github_print.py octocat --darkness 4
"""
from __future__ import annotations
import argparse
from datetime import datetime, timezone
from io import BytesIO
import json
from pathlib import Path
import re
import subprocess
import sys
import urllib.request
from PIL import Image, ImageDraw, ImageFont, ImageOps
ROOT = Path(__file__).resolve().parent
WIDTH = 384
UA = "Mozilla/5.0 (printer; github_print.py)"
# Contribution level -> fraction of the cell filled by a centred solid square.
# Level 0 is a single faint dot; weight grows monotonically with activity so a
# busy day always reads darker than a quiet one (no heavy empty-cell borders).
CELL_FILL = {0: 0.0, 1: 0.45, 2: 0.66, 3: 0.83, 4: 1.0}
BOLD_TTF = "C:/Windows/Fonts/consolab.ttf"
REG_TTF = "C:/Windows/Fonts/consola.ttf"
def font(path: str, size: int):
try:
return ImageFont.truetype(path, size)
except OSError:
return ImageFont.load_default()
class Fonts:
"""Font set sized for a given scale factor (1.0 = compact, larger = bigger card)."""
def __init__(self, scale: float) -> None:
s = scale
self.name = font(BOLD_TTF, round(22 * s))
self.sub = font(REG_TTF, round(15 * s))
self.bio = font(REG_TTF, round(15 * s))
self.stat_value = font(BOLD_TTF, round(21 * s))
self.stat_label = font(REG_TTF, round(13 * s))
self.meta = font(REG_TTF, round(15 * s))
self.title = font(BOLD_TTF, round(20 * s))
self.tiny = font(REG_TTF, round(12 * s))
def get(url: str, binary: bool = False):
req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/vnd.github+json"})
with urllib.request.urlopen(req, timeout=25) as resp:
data = resp.read()
return data if binary else data.decode("utf-8")
def fetch_profile(user: str) -> dict:
return json.loads(get(f"https://api.github.com/users/{user}"))
def fetch_avatar(url: str, size: int) -> Image.Image:
img = Image.open(BytesIO(get(url, binary=True))).convert("L")
img = ImageOps.fit(img, (size, size), Image.LANCZOS)
img = ImageOps.autocontrast(img, cutoff=1)
return img.convert("1") # Floyd-Steinberg is Pillow's default for "1"
def fetch_contributions(user: str) -> tuple[dict[str, int], int]:
html = get(f"https://github.com/users/{user}/contributions")
cells = re.findall(r'data-date="(\d{4}-\d{2}-\d{2})"[^>]*data-level="(\d)"', html)
levels = {date: int(level) for date, level in cells}
total_match = re.search(r"([\d,]+)\s+contributions", html)
total = int(total_match.group(1).replace(",", "")) if total_match else sum(1 for c in cells)
return levels, total
def wrap(draw: ImageDraw.ImageDraw, text: str, fnt, max_w: int, max_lines: int) -> list[str]:
words = text.split()
lines: list[str] = []
current = ""
for word in words:
trial = f"{current} {word}".strip()
if not current or draw.textlength(trial, font=fnt) <= max_w:
current = trial
else:
lines.append(current)
current = word
if len(lines) == max_lines:
current = ""
break
if current and len(lines) < max_lines:
lines.append(current)
placed = sum(len(line.split()) for line in lines)
if placed < len(words) and lines:
last = lines[-1]
while last and draw.textlength(last + " ...", font=fnt) > max_w:
last = last.rsplit(" ", 1)[0] if " " in last else last[:-1]
lines[-1] = last + " ..."
return lines
def lh(fnt) -> int:
"""Line height for a font (with a little leading)."""
return round(getattr(fnt, "size", 13) * 1.3)
def fill_cell(draw: ImageDraw.ImageDraw, x: int, y: int, size: int, level: int) -> None:
if level <= 0:
draw.point((x + size // 2, y + size // 2), fill=0)
return
side = max(2, round(size * CELL_FILL[level]))
off = (size - side) // 2
draw.rectangle((x + off, y + off, x + off + side - 1, y + off + side - 1), fill=0)
def draw_contributions(
draw: ImageDraw.ImageDraw,
levels: dict[str, int],
fonts: "Fonts",
top_y: int,
) -> int:
if not levels:
return top_y
parsed = {datetime.strptime(d, "%Y-%m-%d").date(): lvl for d, lvl in levels.items()}
start = min(parsed)
start_sunday = start.fromordinal(start.toordinal() - (start.weekday() + 1) % 7)
columns = max((d.toordinal() - start_sunday.toordinal()) // 7 for d in parsed) + 1
margin = 4
step = max(6, min(11, (WIDTH - 2 * margin) // columns))
cell = step - 1
grid_w = columns * step - 1
origin_x = (WIDTH - grid_w) // 2
months_y = top_y
grid_y = top_y + lh(fonts.tiny)
last_month = None
next_label_x = origin_x
for d, level in sorted(parsed.items()):
col = (d.toordinal() - start_sunday.toordinal()) // 7
row = (d.weekday() + 1) % 7
x = origin_x + col * step
y = grid_y + row * step
fill_cell(draw, x, y, cell, level)
if d.day <= 7 and d.month != last_month and row == 0:
last_month = d.month
label = d.strftime("%b")
label_w = draw.textlength(label, font=fonts.tiny)
if x >= next_label_x and x + label_w <= WIDTH - margin:
draw.text((x, months_y), label, fill=0, font=fonts.tiny)
next_label_x = x + label_w + 4
return grid_y + 7 * step
def draw_legend(draw: ImageDraw.ImageDraw, fonts: "Fonts", cy: int) -> None:
box = round(getattr(fonts.tiny, "size", 12) * 0.9)
gap = box + 3
swatches = gap * 5
label = "Less"
label_w = draw.textlength(label + " ", font=fonts.tiny)
total_w = label_w + swatches + 4 + draw.textlength(" More", font=fonts.tiny)
x = (WIDTH - total_w) / 2
draw.text((x, cy), label, fill=0, font=fonts.tiny)
bx = x + label_w
for level in range(5):
fill_cell(draw, round(bx), cy + 2, box, level)
bx += gap
draw.text((bx + 4, cy), "More", fill=0, font=fonts.tiny)
def stat_block(draw: ImageDraw.ImageDraw, fonts: "Fonts", cx: float, y: int, value: str, label: str) -> None:
vw = draw.textlength(value, font=fonts.stat_value)
draw.text((cx - vw / 2, y), value, fill=0, font=fonts.stat_value)
lw = draw.textlength(label, font=fonts.stat_label)
draw.text((cx - lw / 2, y + lh(fonts.stat_value)), label, fill=0, font=fonts.stat_label)
def human(n: int) -> str:
if n >= 1000:
return f"{n / 1000:.1f}k".replace(".0k", "k")
return str(n)
def render(profile: dict, levels: dict[str, int], total: int, out: Path, bottom_feed: int, scale: float) -> None:
fonts = Fonts(scale)
pad = 14
avatar_size = min(round(104 * scale), 168)
avatar = fetch_avatar(profile["avatar_url"], avatar_size)
canvas = Image.new("L", (WIDTH, 2000), 255)
d = ImageDraw.Draw(canvas)
login = profile["login"]
name = profile.get("name") or login
bio = (profile.get("bio") or "").strip()
location = profile.get("location")
blog = (profile.get("blog") or "").strip()
since = datetime.fromisoformat(profile["created_at"].replace("Z", "+00:00")).year
def divider(y: int) -> None:
d.line((pad - 4, y, WIDTH - pad + 3, y), fill=0, width=2)
# --- header: avatar + identity ---
d.text((pad, 8), "GITHUB", fill=0, font=fonts.tiny)
avatar_y = 8 + lh(fonts.tiny)
canvas.paste(avatar.convert("L"), (pad, avatar_y))
d.rectangle((pad, avatar_y, pad + avatar_size - 1, avatar_y + avatar_size - 1), outline=0)
text_x = pad + avatar_size + round(12 * scale)
text_w = WIDTH - text_x - pad
y = avatar_y + 2
d.text((text_x, y), name[:16], fill=0, font=fonts.name)
y += lh(fonts.name)
if name.lower() != login.lower():
d.text((text_x, y), f"@{login}", fill=0, font=fonts.sub)
y += lh(fonts.sub)
for line in wrap(d, bio, fonts.bio, text_w, 4) if bio else []:
d.text((text_x, y), line, fill=0, font=fonts.bio)
y += lh(fonts.bio)
y = max(y, avatar_y + avatar_size) + round(12 * scale)
# --- stats row ---
divider(y)
y += round(10 * scale)
quarters = [WIDTH * (i + 0.5) / 4 for i in range(4)]
stats = [
(human(profile["followers"]), "followers"),
(human(profile["following"]), "following"),
(human(profile["public_repos"]), "repos"),
(human(profile["public_gists"]), "gists"),
]
for cx, (value, label) in zip(quarters, stats):
stat_block(d, fonts, cx, y, value, label)
y += lh(fonts.stat_value) + lh(fonts.stat_label) + round(10 * scale)
# --- meta lines ---
divider(y)
y += round(8 * scale)
meta_lines = [v for v in (
f"Location: {location}" if location else None,
f"Web: {blog}" if blog else None,
f"On GitHub since {since}",
) if v]
for line in meta_lines:
d.text((pad, y), line, fill=0, font=fonts.meta)
y += lh(fonts.meta)
y += round(8 * scale)
# --- contribution graph ---
divider(y)
y += round(8 * scale)
d.text((pad, y), f"{total:,} contributions", fill=0, font=fonts.title)
y += lh(fonts.title) + 2
grid_bottom = draw_contributions(d, levels, fonts, y)
y = grid_bottom + round(8 * scale)
draw_legend(d, fonts, y)
y += lh(fonts.tiny) + round(8 * scale)
# --- footer ---
divider(y)
y += round(6 * scale)
d.text((pad, y), f"github.com/{login}", fill=0, font=fonts.tiny)
stamp = datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M")
sw = d.textlength(stamp, font=fonts.tiny)
d.text((WIDTH - pad - sw, y), stamp, fill=0, font=fonts.tiny)
y += lh(fonts.tiny)
content_h = y + round(8 * scale)
d.rectangle((0, 0, WIDTH - 1, content_h - 1), outline=0, width=2)
card = canvas.crop((0, 0, WIDTH, content_h + max(0, bottom_feed)))
card.convert("1").save(out)
def print_image(path: Path, darkness: int) -> int:
python = ROOT / ".venv" / "Scripts" / "python.exe"
python = python if python.exists() else Path(sys.executable)
command = [str(python), str(ROOT / "s1_print.py"), "image", str(path), "--darkness", str(darkness)]
return subprocess.call(command, cwd=ROOT)
def main() -> int:
parser = argparse.ArgumentParser(description="Print a GitHub profile card on the S01 thermal printer.")
parser.add_argument("user", nargs="?", default="octocat")
parser.add_argument("--out", type=Path, default=None)
parser.add_argument("--darkness", type=int, choices=range(1, 6), default=3)
parser.add_argument("--bottom-feed", type=int, default=24, help="Blank pixels after the card for tearing.")
parser.add_argument("--scale", type=float, default=1.35, help="Overall size of the card (1.0 = compact).")
parser.add_argument("--no-print", action="store_true")
args = parser.parse_args()
out = args.out or ROOT / f"github_{args.user}.png"
print(f"Fetching @{args.user} ...")
profile = fetch_profile(args.user)
levels, total = fetch_contributions(args.user)
print(f" {profile['followers']} followers, {profile['public_repos']} repos, {total:,} contributions")
render(profile, levels, total, out, args.bottom_feed, args.scale)
print(f"Wrote {out}")
if args.no_print:
return 0
return print_image(out, args.darkness)
if __name__ == "__main__":
raise SystemExit(main())