-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathneofetch_print.py
More file actions
307 lines (250 loc) · 9.81 KB
/
Copy pathneofetch_print.py
File metadata and controls
307 lines (250 loc) · 9.81 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
#!/usr/bin/env python3
"""Print a neofetch-style system info card on the S01 thermal printer.
Gathers Windows system information from the standard library (winreg, ctypes,
shutil, platform) -- no extra dependencies -- and lays it out neofetch-style:
a Windows logo on the left, key/value specs on the right, and a dithered
"palette" strip at the bottom as a nod to neofetch's colour blocks.
Examples:
python neofetch_print.py
python neofetch_print.py --no-print
"""
from __future__ import annotations
import argparse
import ctypes
import getpass
import os
from pathlib import Path
import platform
import shutil
import socket
import subprocess
import sys
from PIL import Image, ImageDraw, ImageFont
ROOT = Path(__file__).resolve().parent
WIDTH = 384
BOLD_TTF = "C:/Windows/Fonts/consolab.ttf"
REG_TTF = "C:/Windows/Fonts/consola.ttf"
BAYER4 = [[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]]
def font(path: str, size: int):
try:
return ImageFont.truetype(path, size)
except OSError:
return ImageFont.load_default()
def gib(n: int) -> float:
return n / (1024 ** 3)
# --- system info collection (all best-effort) ---
def reg_value(root, key: str, name: str):
import winreg
with winreg.OpenKey(root, key) as handle:
return winreg.QueryValueEx(handle, name)[0]
def os_name() -> str:
import winreg
try:
cv = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion"
product = reg_value(winreg.HKEY_LOCAL_MACHINE, cv, "ProductName")
build = int(reg_value(winreg.HKEY_LOCAL_MACHINE, cv, "CurrentBuild"))
if build >= 22000 and "Windows 10" in product: # MS never updated the key
product = product.replace("Windows 10", "Windows 11")
try:
disp = reg_value(winreg.HKEY_LOCAL_MACHINE, cv, "DisplayVersion")
return f"{product} ({disp})"
except OSError:
return product
except Exception: # noqa: BLE001
return f"{platform.system()} {platform.release()}"
def cpu_name() -> str:
import winreg
try:
name = reg_value(
winreg.HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\CentralProcessor\0",
"ProcessorNameString",
).strip()
except Exception: # noqa: BLE001
name = platform.processor() or "Unknown CPU"
return f"{name} ({os.cpu_count()}c)"
def gpu_name() -> str | None:
try:
out = subprocess.run(
["powershell", "-NoProfile", "-Command",
"(Get-CimInstance Win32_VideoController).Name"],
capture_output=True, text=True, timeout=8,
)
names = [ln.strip() for ln in out.stdout.splitlines() if ln.strip()]
return names[0] if names else None
except Exception: # noqa: BLE001
return None
def uptime() -> str:
ms = ctypes.windll.kernel32.GetTickCount64()
secs = ms // 1000
d, rem = divmod(secs, 86400)
h, rem = divmod(rem, 3600)
m = rem // 60
parts = []
if d:
parts.append(f"{d}d")
if h:
parts.append(f"{h}h")
parts.append(f"{m}m")
return " ".join(parts)
def memory() -> str:
class MSEX(ctypes.Structure):
_fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong),
("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong),
("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong),
("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong),
("ullAvailExtendedVirtual", ctypes.c_ulonglong)]
m = MSEX()
m.dwLength = ctypes.sizeof(m)
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m))
used = m.ullTotalPhys - m.ullAvailPhys
return f"{gib(used):.1f} / {gib(m.ullTotalPhys):.1f} GiB ({m.dwMemoryLoad}%)"
def disk() -> str:
drive = os.environ.get("SystemDrive", "C:") + "\\"
total, used, _free = shutil.disk_usage(drive)
return f"{drive[:2]} {gib(used):.0f} / {gib(total):.0f} GiB"
def resolution() -> str:
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
return f"{user32.GetSystemMetrics(0)}x{user32.GetSystemMetrics(1)}"
def shell_name() -> str:
if os.environ.get("WT_SESSION"):
term = "Windows Terminal"
else:
term = None
ps = "PowerShell" if os.environ.get("PSModulePath") else Path(os.environ.get("COMSPEC", "cmd.exe")).stem
return f"{ps} / {term}" if term else ps
def collect(skip_gpu: bool) -> tuple[str, list[tuple[str, str]]]:
user = getpass.getuser()
host = platform.node() or socket.gethostname()
info: list[tuple[str, str]] = [
("OS", os_name()),
("Host", host),
("Kernel", platform.version()),
("Uptime", uptime()),
("Shell", shell_name()),
("Res", resolution()),
("CPU", cpu_name()),
]
if not skip_gpu:
gpu = gpu_name()
if gpu:
info.append(("GPU", gpu))
info += [
("Memory", memory()),
("Disk", disk()),
("Python", platform.python_version()),
]
return f"{user}@{host}", info
# --- rendering ---
def draw_logo(canvas: Image.Image, x: int, y: int, size: int) -> None:
"""Modern Windows 4-pane logo."""
d = ImageDraw.Draw(canvas)
gap = max(2, size // 14)
half = (size - gap) // 2
for r in range(2):
for c in range(2):
px = x + c * (half + gap)
py = y + r * (half + gap)
d.rectangle((px, py, px + half - 1, py + half - 1), fill=0)
def swatch(d: ImageDraw.ImageDraw, x: int, y: int, size: int, density: float) -> None:
threshold = density * 16
for dy in range(size):
for dx in range(size):
if BAYER4[dy % 4][dx % 4] < threshold:
d.point((x + dx, y + dy), fill=0)
d.rectangle((x, y, x + size - 1, y + size - 1), outline=0)
def wrap(draw, text, fnt, max_w, max_lines=2):
lines, current = [], ""
for word in text.split():
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(text.split()) and lines:
last = lines[-1]
while last and draw.textlength(last + "...", font=fnt) > max_w:
last = last[:-1]
lines[-1] = last + "..."
return lines
def render(title: str, info: list[tuple[str, str]], out: Path, bottom_feed: int, scale: float) -> None:
s = scale
title_f = font(BOLD_TTF, round(22 * s))
key_f = font(BOLD_TTF, round(15 * s))
val_f = font(BOLD_TTF, round(15 * s)) # bold values for thermal legibility
tiny_f = font(REG_TTF, round(11 * s))
line_h = round(21 * s)
logo_size = round(78 * s)
pad = 14
canvas = Image.new("L", (WIDTH, 1800), 255)
d = ImageDraw.Draw(canvas)
# --- logo (top centre) + title ---
draw_logo(canvas, (WIDTH - logo_size) // 2, 14, logo_size)
y = 14 + logo_size + 12
tw = d.textlength(title, font=title_f)
d.text((WIDTH / 2 - tw / 2, y), title, fill=0, font=title_f)
y += round(26 * s)
d.line((pad, y, WIDTH - pad, y), fill=0, width=2)
y += round(8 * s)
# --- full-width key / value rows ---
info_x = pad
key_col = max(d.textlength(k, font=key_f) for k, _ in info) + 12
val_w = WIDTH - pad - (info_x + key_col)
for key, value in info:
d.text((info_x, y), key, fill=0, font=key_f)
vlines = wrap(d, value, val_f, val_w, max_lines=3)
d.text((info_x + key_col, y), vlines[0], fill=0, font=val_f)
y += line_h
for extra in vlines[1:]:
d.text((info_x + key_col, y), extra, fill=0, font=val_f)
y += line_h
y += round(6 * s)
# --- palette strip (nod to neofetch colour blocks) ---
d.line((pad, y, WIDTH - pad, y), fill=0, width=1)
y += round(8 * s)
n = 8
sw_size = round(20 * s)
spacing = sw_size + round(5 * s)
total = n * spacing - round(5 * s)
sx = (WIDTH - total) // 2
for i in range(n):
swatch(d, sx + i * spacing, y, sw_size, i / (n - 1))
y += sw_size + round(8 * s)
content_h = y + 4
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 neofetch-style system card on the S01 thermal printer.")
parser.add_argument("--no-gpu", action="store_true", help="Skip the (slower) GPU lookup.")
parser.add_argument("--scale", type=float, default=1.3, help="Overall size of the card (1.0 = compact).")
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)
parser.add_argument("--no-print", action="store_true")
args = parser.parse_args()
print("Collecting system info ...")
title, info = collect(args.no_gpu)
for key, value in info:
print(f" {key}: {value}")
out = args.out or ROOT / "neofetch.png"
render(title, info, 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())