tokstats 0.2.0__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.
- tokstats/__init__.py +3 -0
- tokstats/__main__.py +5 -0
- tokstats/archive.py +288 -0
- tokstats/card.py +195 -0
- tokstats/cli.py +298 -0
- tokstats/github.py +113 -0
- tokstats/hook.py +103 -0
- tokstats/parse.py +241 -0
- tokstats/paths.py +80 -0
- tokstats/report.py +605 -0
- tokstats/schedule.py +130 -0
- tokstats/store.py +98 -0
- tokstats-0.2.0.dist-info/METADATA +270 -0
- tokstats-0.2.0.dist-info/RECORD +18 -0
- tokstats-0.2.0.dist-info/WHEEL +5 -0
- tokstats-0.2.0.dist-info/entry_points.txt +2 -0
- tokstats-0.2.0.dist-info/licenses/LICENSE +21 -0
- tokstats-0.2.0.dist-info/top_level.txt +1 -0
tokstats/__init__.py
ADDED
tokstats/__main__.py
ADDED
tokstats/archive.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""Copy Claude Code transcripts into the tokstats archive.
|
|
2
|
+
|
|
3
|
+
The archive keeps a gzip copy of every transcript, for each host:
|
|
4
|
+
|
|
5
|
+
~/.tokstats/archive/<host>/projects/<project>/<session>.jsonl.gz
|
|
6
|
+
~/.tokstats/archive/<host>/manifest.json sizes of the copied files
|
|
7
|
+
~/.tokstats/archive/<host>/stats-history.json daily rows of stats-cache.json, merged
|
|
8
|
+
~/.tokstats/archive/<host>/host.json settings and the time of the last copy
|
|
9
|
+
|
|
10
|
+
The archive only adds and updates files. When Claude Code deletes an old
|
|
11
|
+
transcript, the archived copy stays.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import gzip
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import subprocess
|
|
20
|
+
import tarfile
|
|
21
|
+
import time
|
|
22
|
+
from pathlib import Path, PurePosixPath
|
|
23
|
+
from typing import Any, Dict, Iterable, Optional, Tuple
|
|
24
|
+
|
|
25
|
+
from . import paths
|
|
26
|
+
|
|
27
|
+
DEFAULT_CLEANUP_DAYS = 30
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# ---------------------------------------------------------------- helpers
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _archive_path(hdir: Path, rel: str) -> Path:
|
|
34
|
+
return hdir / "projects" / (rel + ".gz")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _valid_rel(rel: str) -> bool:
|
|
38
|
+
p = PurePosixPath(rel)
|
|
39
|
+
return (
|
|
40
|
+
not p.is_absolute()
|
|
41
|
+
and ".." not in p.parts
|
|
42
|
+
and p.suffix == ".jsonl"
|
|
43
|
+
and len(p.parts) >= 2
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _write_gz_from(dest: Path, src_fh) -> int:
|
|
48
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
49
|
+
tmp = dest.with_name(dest.name + ".tmp")
|
|
50
|
+
copied = 0
|
|
51
|
+
with gzip.open(tmp, "wb", compresslevel=6) as out:
|
|
52
|
+
while True:
|
|
53
|
+
chunk = src_fh.read(1 << 20)
|
|
54
|
+
if not chunk:
|
|
55
|
+
break
|
|
56
|
+
out.write(chunk)
|
|
57
|
+
copied += len(chunk)
|
|
58
|
+
os.replace(tmp, dest)
|
|
59
|
+
return copied
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def merge_stats_cache(hdir: Path, stats_cache: Optional[Dict[str, Any]]) -> int:
|
|
63
|
+
"""Merge the daily rows of a ``stats-cache.json`` into the host's history.
|
|
64
|
+
|
|
65
|
+
Claude Code keeps daily totals in this file even after it deletes the
|
|
66
|
+
transcripts of those days. The history keeps every day it ever saw.
|
|
67
|
+
Returns the number of days in the history.
|
|
68
|
+
"""
|
|
69
|
+
hist_path = hdir / "stats-history.json"
|
|
70
|
+
hist = paths.read_json(hist_path, {"days": {}})
|
|
71
|
+
days = hist.setdefault("days", {})
|
|
72
|
+
if isinstance(stats_cache, dict):
|
|
73
|
+
computed = str(stats_cache.get("lastComputedDate") or "")
|
|
74
|
+
for row in stats_cache.get("dailyActivity") or []:
|
|
75
|
+
date = row.get("date")
|
|
76
|
+
if not date:
|
|
77
|
+
continue
|
|
78
|
+
day = days.setdefault(date, {})
|
|
79
|
+
if computed >= day.get("computed", ""):
|
|
80
|
+
day["activity"] = {
|
|
81
|
+
"messages": int(row.get("messageCount") or 0),
|
|
82
|
+
"sessions": int(row.get("sessionCount") or 0),
|
|
83
|
+
"tool_calls": int(row.get("toolCallCount") or 0),
|
|
84
|
+
}
|
|
85
|
+
day["computed"] = computed
|
|
86
|
+
for row in stats_cache.get("dailyModelTokens") or []:
|
|
87
|
+
date = row.get("date")
|
|
88
|
+
if not date:
|
|
89
|
+
continue
|
|
90
|
+
day = days.setdefault(date, {})
|
|
91
|
+
if computed >= day.get("tokens_computed", ""):
|
|
92
|
+
day["tokens"] = {k: int(v or 0) for k, v in (row.get("tokensByModel") or {}).items()}
|
|
93
|
+
day["tokens_computed"] = computed
|
|
94
|
+
hist["last_computed"] = max(computed, hist.get("last_computed", ""))
|
|
95
|
+
paths.write_json(hist_path, hist)
|
|
96
|
+
return len(days)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _cleanup_days(settings: Optional[Dict[str, Any]]) -> int:
|
|
100
|
+
if isinstance(settings, dict) and settings.get("cleanupPeriodDays") is not None:
|
|
101
|
+
try:
|
|
102
|
+
return int(settings["cleanupPeriodDays"])
|
|
103
|
+
except (TypeError, ValueError):
|
|
104
|
+
pass
|
|
105
|
+
return DEFAULT_CLEANUP_DAYS
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _write_host_meta(hdir: Path, source: str, settings: Optional[Dict[str, Any]], stats_cache) -> None:
|
|
109
|
+
meta = paths.read_json(hdir / "host.json", {})
|
|
110
|
+
meta.update(
|
|
111
|
+
{
|
|
112
|
+
"source": source,
|
|
113
|
+
"last_copy": time.time(),
|
|
114
|
+
"cleanup_period_days": _cleanup_days(settings),
|
|
115
|
+
"stats_cache_last_computed": (stats_cache or {}).get("lastComputedDate")
|
|
116
|
+
if isinstance(stats_cache, dict)
|
|
117
|
+
else None,
|
|
118
|
+
}
|
|
119
|
+
)
|
|
120
|
+
paths.write_json(hdir / "host.json", meta)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# ---------------------------------------------------------------- local host
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def collect_local(host: Optional[str] = None) -> Dict[str, Any]:
|
|
127
|
+
"""Copy new and changed local transcripts into the archive."""
|
|
128
|
+
host = paths.safe_name(host or paths.local_host_name())
|
|
129
|
+
hdir = paths.host_dir(host)
|
|
130
|
+
cdir = paths.claude_dir()
|
|
131
|
+
src_root = cdir / "projects"
|
|
132
|
+
manifest = paths.read_json(hdir / "manifest.json", {})
|
|
133
|
+
|
|
134
|
+
copied = 0
|
|
135
|
+
seen = 0
|
|
136
|
+
if src_root.is_dir():
|
|
137
|
+
for path in sorted(src_root.rglob("*.jsonl")):
|
|
138
|
+
if not path.is_file():
|
|
139
|
+
continue
|
|
140
|
+
rel = path.relative_to(src_root).as_posix()
|
|
141
|
+
if not _valid_rel(rel):
|
|
142
|
+
continue
|
|
143
|
+
seen += 1
|
|
144
|
+
st = path.stat()
|
|
145
|
+
old = manifest.get(rel)
|
|
146
|
+
if old and old.get("size") == st.st_size and old.get("mtime") == int(st.st_mtime):
|
|
147
|
+
continue
|
|
148
|
+
try:
|
|
149
|
+
with open(path, "rb") as fh:
|
|
150
|
+
size = _write_gz_from(_archive_path(hdir, rel), fh)
|
|
151
|
+
except OSError:
|
|
152
|
+
continue
|
|
153
|
+
manifest[rel] = {"size": size, "mtime": int(st.st_mtime)}
|
|
154
|
+
copied += 1
|
|
155
|
+
paths.write_json(hdir / "manifest.json", manifest)
|
|
156
|
+
|
|
157
|
+
stats_cache = paths.read_json(cdir / "stats-cache.json", None)
|
|
158
|
+
settings = paths.read_json(cdir / "settings.json", None)
|
|
159
|
+
days = merge_stats_cache(hdir, stats_cache)
|
|
160
|
+
_write_host_meta(hdir, "local", settings, stats_cache)
|
|
161
|
+
return {"host": host, "files": seen, "copied": copied, "archived": len(manifest), "stats_days": days}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
# ---------------------------------------------------------------- remote host over SSH
|
|
165
|
+
|
|
166
|
+
_REMOTE_DIR = 'cd "${CLAUDE_CONFIG_DIR:-$HOME/.claude}" || exit 3'
|
|
167
|
+
_MARK = "__TOKSTATS_SECTION__"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _ssh(ssh_host: str, command: str, stdin: Optional[bytes] = None, timeout: int = 120) -> bytes:
|
|
171
|
+
proc = subprocess.run(
|
|
172
|
+
["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=15", ssh_host, command],
|
|
173
|
+
input=stdin,
|
|
174
|
+
stdout=subprocess.PIPE,
|
|
175
|
+
stderr=subprocess.PIPE,
|
|
176
|
+
timeout=timeout,
|
|
177
|
+
)
|
|
178
|
+
if proc.returncode != 0:
|
|
179
|
+
raise RuntimeError(
|
|
180
|
+
"ssh %s failed (exit %d): %s" % (ssh_host, proc.returncode, proc.stderr.decode(errors="replace").strip())
|
|
181
|
+
)
|
|
182
|
+
return proc.stdout
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _remote_inventory(ssh_host: str) -> Tuple[Dict[str, int], Optional[dict], Optional[dict]]:
|
|
186
|
+
"""Return {relative path: size}, settings.json and stats-cache.json of a remote host."""
|
|
187
|
+
cmd = (
|
|
188
|
+
_REMOTE_DIR
|
|
189
|
+
+ "; [ -d projects ] && find projects -type f -name '*.jsonl' -exec wc -c {} + ; "
|
|
190
|
+
+ "echo %s; cat settings.json 2>/dev/null; echo %s; cat stats-cache.json 2>/dev/null; true" % (_MARK, _MARK)
|
|
191
|
+
)
|
|
192
|
+
out = _ssh(ssh_host, cmd).decode("utf-8", errors="replace")
|
|
193
|
+
parts = out.split(_MARK + "\n")
|
|
194
|
+
listing = parts[0] if parts else ""
|
|
195
|
+
sizes: Dict[str, int] = {}
|
|
196
|
+
for line in listing.splitlines():
|
|
197
|
+
line = line.strip()
|
|
198
|
+
if not line:
|
|
199
|
+
continue
|
|
200
|
+
num, _, name = line.partition(" ")
|
|
201
|
+
name = name.strip()
|
|
202
|
+
if not num.isdigit() or not name.startswith("projects/"):
|
|
203
|
+
continue # also drops the "total" lines of wc
|
|
204
|
+
rel = name[len("projects/"):]
|
|
205
|
+
if _valid_rel(rel):
|
|
206
|
+
sizes[rel] = int(num)
|
|
207
|
+
|
|
208
|
+
def _json(text: str):
|
|
209
|
+
try:
|
|
210
|
+
return json.loads(text)
|
|
211
|
+
except ValueError:
|
|
212
|
+
return None
|
|
213
|
+
|
|
214
|
+
settings = _json(parts[1]) if len(parts) > 1 else None
|
|
215
|
+
stats_cache = _json(parts[2]) if len(parts) > 2 else None
|
|
216
|
+
return sizes, settings, stats_cache
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _fetch_files(ssh_host: str, rels: Iterable[str], hdir: Path, manifest: Dict[str, Any]) -> int:
|
|
220
|
+
rels = list(rels)
|
|
221
|
+
if not rels:
|
|
222
|
+
return 0
|
|
223
|
+
names = "".join("projects/%s\n" % r for r in rels).encode()
|
|
224
|
+
proc = subprocess.Popen(
|
|
225
|
+
["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=15", ssh_host, _REMOTE_DIR + "; tar -czf - -T -"],
|
|
226
|
+
stdin=subprocess.PIPE,
|
|
227
|
+
stdout=subprocess.PIPE,
|
|
228
|
+
stderr=subprocess.PIPE,
|
|
229
|
+
)
|
|
230
|
+
assert proc.stdin and proc.stdout
|
|
231
|
+
proc.stdin.write(names)
|
|
232
|
+
proc.stdin.close()
|
|
233
|
+
copied = 0
|
|
234
|
+
wanted = set(rels)
|
|
235
|
+
with tarfile.open(fileobj=proc.stdout, mode="r|gz") as tar:
|
|
236
|
+
for member in tar:
|
|
237
|
+
if not member.isfile() or not member.name.startswith("projects/"):
|
|
238
|
+
continue
|
|
239
|
+
rel = member.name[len("projects/"):]
|
|
240
|
+
if rel not in wanted or not _valid_rel(rel):
|
|
241
|
+
continue
|
|
242
|
+
fh = tar.extractfile(member)
|
|
243
|
+
if fh is None:
|
|
244
|
+
continue
|
|
245
|
+
size = _write_gz_from(_archive_path(hdir, rel), fh)
|
|
246
|
+
manifest[rel] = {"size": size, "mtime": int(member.mtime)}
|
|
247
|
+
copied += 1
|
|
248
|
+
err = proc.stderr.read().decode(errors="replace") if proc.stderr else ""
|
|
249
|
+
if proc.wait() != 0 and copied == 0:
|
|
250
|
+
raise RuntimeError("could not copy files from %s: %s" % (ssh_host, err.strip()))
|
|
251
|
+
return copied
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def pull_remote(ssh_host: str, name: Optional[str] = None) -> Dict[str, Any]:
|
|
255
|
+
"""Copy new and changed transcripts of a remote host through SSH."""
|
|
256
|
+
host = paths.safe_name(name or ssh_host)
|
|
257
|
+
if host == paths.local_host_name():
|
|
258
|
+
raise RuntimeError("the name %r is the name of this host; use --as to give the remote host a different name" % host)
|
|
259
|
+
hdir = paths.host_dir(host)
|
|
260
|
+
manifest = paths.read_json(hdir / "manifest.json", {})
|
|
261
|
+
sizes, settings, stats_cache = _remote_inventory(ssh_host)
|
|
262
|
+
changed = [rel for rel, size in sorted(sizes.items()) if (manifest.get(rel) or {}).get("size") != size]
|
|
263
|
+
copied = 0
|
|
264
|
+
batch = 200
|
|
265
|
+
for i in range(0, len(changed), batch):
|
|
266
|
+
copied += _fetch_files(ssh_host, changed[i : i + batch], hdir, manifest)
|
|
267
|
+
paths.write_json(hdir / "manifest.json", manifest)
|
|
268
|
+
paths.write_json(hdir / "manifest.json", manifest)
|
|
269
|
+
days = merge_stats_cache(hdir, stats_cache)
|
|
270
|
+
_write_host_meta(hdir, "ssh:" + ssh_host, settings, stats_cache)
|
|
271
|
+
meta = paths.read_json(hdir / "host.json", {})
|
|
272
|
+
meta["ssh"] = ssh_host
|
|
273
|
+
paths.write_json(hdir / "host.json", meta)
|
|
274
|
+
return {"host": host, "files": len(sizes), "copied": copied, "archived": len(manifest), "stats_days": days}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def archived_files(host: str):
|
|
278
|
+
"""Yield (relative path, archive path) for every archived transcript of a host."""
|
|
279
|
+
root = paths.host_dir(host) / "projects"
|
|
280
|
+
if not root.is_dir():
|
|
281
|
+
return
|
|
282
|
+
for path in sorted(root.rglob("*.jsonl.gz")):
|
|
283
|
+
yield path.relative_to(root).as_posix()[: -len(".gz")], path
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def archive_size(host: str) -> int:
|
|
287
|
+
root = paths.host_dir(host)
|
|
288
|
+
return sum(p.stat().st_size for p in root.rglob("*") if p.is_file()) if root.is_dir() else 0
|
tokstats/card.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Draw an SVG card with the main numbers, for a GitHub profile README or a CV."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import date, timedelta
|
|
6
|
+
from typing import Any, Dict, List, Optional
|
|
7
|
+
from xml.sax.saxutils import escape
|
|
8
|
+
|
|
9
|
+
from .report import fmt_n
|
|
10
|
+
|
|
11
|
+
W = 720
|
|
12
|
+
PAD = 24
|
|
13
|
+
CELL = 10
|
|
14
|
+
STEP = 12
|
|
15
|
+
WEEKS = 53
|
|
16
|
+
|
|
17
|
+
THEMES = {
|
|
18
|
+
"light": {
|
|
19
|
+
"bg": "#ffffff", "border": "#d0d7de", "text": "#1f2328", "muted": "#59636e",
|
|
20
|
+
"levels": ["#ebedf0", "#f6d5c2", "#efa57c", "#dd7444", "#b84c22"],
|
|
21
|
+
},
|
|
22
|
+
"dark": {
|
|
23
|
+
"bg": "#0d1117", "border": "#30363d", "text": "#e6edf3", "muted": "#9198a1",
|
|
24
|
+
"levels": ["#161b22", "#4b2a1b", "#7f3f21", "#c0592a", "#ee8a55"],
|
|
25
|
+
},
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
LANGUAGE_COLORS = {
|
|
29
|
+
"Python": "#3572A5", "JavaScript": "#f1e05a", "TypeScript": "#3178c6", "Rust": "#dea584",
|
|
30
|
+
"Go": "#00ADD8", "Java": "#b07219", "Kotlin": "#A97BFF", "Swift": "#F05138", "C": "#555555",
|
|
31
|
+
"C++": "#f34b7d", "C/C++": "#f34b7d", "C#": "#178600", "Ruby": "#701516", "PHP": "#4F5D95",
|
|
32
|
+
"HTML": "#e34c26", "CSS": "#663399", "Shell": "#89e051", "SQL": "#e38c00", "Vue": "#41b883",
|
|
33
|
+
"Svelte": "#ff3e00", "Dart": "#00B4AB", "Scala": "#c22d40", "Elixir": "#6e4a7e", "Lua": "#000080",
|
|
34
|
+
"CUDA": "#3A4E3A", "Jupyter": "#DA5B0B", "Terraform": "#7B42BC", "Dockerfile": "#384d54",
|
|
35
|
+
"Haskell": "#5e5086", "Zig": "#ec915c", "Julia": "#a270ba", "R": "#198CE7", "Objective-C": "#438eff",
|
|
36
|
+
}
|
|
37
|
+
OTHER_COLOR = "#8b949e"
|
|
38
|
+
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _short_tokens(n: float) -> str:
|
|
42
|
+
"""Three significant digits at most: 19.02B -> 19B, 4.56M -> 4.56M, 345.6k -> 346k."""
|
|
43
|
+
for size, suffix in ((1e12, "T"), (1e9, "B"), (1e6, "M"), (1e3, "k")):
|
|
44
|
+
if n >= size:
|
|
45
|
+
v = n / size
|
|
46
|
+
text = "%.0f" % v if v >= 10 else ("%.1f" % v).rstrip("0").rstrip(".")
|
|
47
|
+
return text + suffix
|
|
48
|
+
return str(int(n))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _level(minutes: Optional[int]) -> int:
|
|
52
|
+
if minutes is None:
|
|
53
|
+
return 2 # active, but only stats-cache.json knows the day: no minutes
|
|
54
|
+
if minutes <= 0:
|
|
55
|
+
return 0
|
|
56
|
+
if minutes <= 30:
|
|
57
|
+
return 1
|
|
58
|
+
if minutes <= 120:
|
|
59
|
+
return 2
|
|
60
|
+
if minutes <= 300:
|
|
61
|
+
return 3
|
|
62
|
+
return 4
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _month_label(iso: Optional[str]) -> str:
|
|
66
|
+
if not iso:
|
|
67
|
+
return "-"
|
|
68
|
+
return "%s %s" % (MONTHS[int(iso[5:7]) - 1], iso[:4])
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _style(theme: str) -> str:
|
|
72
|
+
def rules(t: Dict[str, Any]) -> str:
|
|
73
|
+
lv = "".join(".l%d{fill:%s}" % (i, c) for i, c in enumerate(t["levels"]))
|
|
74
|
+
return (".bg{fill:%s;stroke:%s}.t{fill:%s}.m{fill:%s}%s"
|
|
75
|
+
% (t["bg"], t["border"], t["text"], t["muted"], lv))
|
|
76
|
+
base = ("text{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif}"
|
|
77
|
+
".b{font-weight:600}")
|
|
78
|
+
if theme == "auto":
|
|
79
|
+
return base + rules(THEMES["light"]) + "@media (prefers-color-scheme:dark){%s}" % rules(THEMES["dark"])
|
|
80
|
+
return base + rules(THEMES[theme])
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def render_card(s: Dict[str, Any], theme: str = "auto", title: Optional[str] = None,
|
|
84
|
+
today: Optional[date] = None) -> str:
|
|
85
|
+
if theme not in ("auto", "light", "dark"):
|
|
86
|
+
raise ValueError("theme must be auto, light or dark")
|
|
87
|
+
o, a, t = s["outcomes"], s["activity"], s["tokens"]
|
|
88
|
+
today = today or date.today()
|
|
89
|
+
login = o.get("github_login")
|
|
90
|
+
title = title or ("%s · AI coding with Claude Code" % login if login else "AI coding with Claude Code")
|
|
91
|
+
period = "%s – %s" % (_month_label(s["period"]["from"]), _month_label(s["period"]["to"]))
|
|
92
|
+
|
|
93
|
+
if o.get("merged_prs_verified") is not None:
|
|
94
|
+
pr_value, pr_label = fmt_n(o["merged_prs_verified"]), "merged PRs, verified"
|
|
95
|
+
else:
|
|
96
|
+
pr_value, pr_label = fmt_n(o["prs_worked_on"]), "PRs"
|
|
97
|
+
total_tokens = t["total"] + t.get("only_in_stats_cache_estimate", 0)
|
|
98
|
+
approx = "~" if t.get("only_in_stats_cache_estimate") else ""
|
|
99
|
+
stats = [
|
|
100
|
+
(pr_value, pr_label),
|
|
101
|
+
(fmt_n(a["active_days"]), "active days"),
|
|
102
|
+
("%d days" % a["longest_streak_days"], "longest streak"),
|
|
103
|
+
(approx + _short_tokens(total_tokens), "tokens"),
|
|
104
|
+
]
|
|
105
|
+
|
|
106
|
+
out: List[str] = []
|
|
107
|
+
add = out.append
|
|
108
|
+
|
|
109
|
+
# Heatmap: 53 weeks that end with the week of today, Sunday first.
|
|
110
|
+
end = today
|
|
111
|
+
start = end - timedelta(days=(end.weekday() + 1) % 7 + 7 * (WEEKS - 1))
|
|
112
|
+
daily = a.get("daily_minutes") or {}
|
|
113
|
+
hx = PAD + (W - 2 * PAD - WEEKS * STEP + (STEP - CELL)) // 2
|
|
114
|
+
hy = 160
|
|
115
|
+
cells = []
|
|
116
|
+
month_labels = []
|
|
117
|
+
last_month = None
|
|
118
|
+
year_days = 0
|
|
119
|
+
for week in range(WEEKS):
|
|
120
|
+
for wd in range(7):
|
|
121
|
+
d = start + timedelta(days=week * 7 + wd)
|
|
122
|
+
if d > end:
|
|
123
|
+
break
|
|
124
|
+
iso = d.isoformat()
|
|
125
|
+
lvl = _level(daily[iso]) if iso in daily else 0
|
|
126
|
+
if lvl:
|
|
127
|
+
year_days += 1
|
|
128
|
+
cells.append('<rect x="%d" y="%d" width="%d" height="%d" rx="2" class="l%d"><title>%s%s</title></rect>'
|
|
129
|
+
% (hx + week * STEP, hy + wd * STEP, CELL, CELL, lvl, iso,
|
|
130
|
+
"" if iso not in daily else (": active" if daily[iso] is None
|
|
131
|
+
else ": %d min" % daily[iso])))
|
|
132
|
+
if wd == 0 and d.month != last_month and d.day <= 7:
|
|
133
|
+
if week < WEEKS - 2:
|
|
134
|
+
month_labels.append('<text x="%d" y="%d" font-size="10" class="m">%s</text>'
|
|
135
|
+
% (hx + week * STEP, hy - 6, MONTHS[d.month - 1]))
|
|
136
|
+
last_month = d.month
|
|
137
|
+
|
|
138
|
+
# Languages.
|
|
139
|
+
langs = o.get("languages") or []
|
|
140
|
+
shown = langs[:5]
|
|
141
|
+
other = max(0.0, 100.0 - sum(p for _n, _c, p in shown))
|
|
142
|
+
segments = [(n, p, LANGUAGE_COLORS.get(n, OTHER_COLOR)) for n, _c, p in shown]
|
|
143
|
+
if other >= 1:
|
|
144
|
+
segments.append(("Other", other, OTHER_COLOR))
|
|
145
|
+
|
|
146
|
+
height = 352 if segments else 300
|
|
147
|
+
add('<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d" viewBox="0 0 %d %d" '
|
|
148
|
+
'role="img" aria-label="%s">' % (W, height, W, height, escape(title, {'"': """})))
|
|
149
|
+
add("<title>%s</title>" % escape(title))
|
|
150
|
+
add("<style>%s</style>" % _style(theme))
|
|
151
|
+
add('<rect x="0.5" y="0.5" width="%d" height="%d" rx="10" class="bg"/>' % (W - 1, height - 1))
|
|
152
|
+
add('<text x="%d" y="40" font-size="17" class="t b">%s</text>' % (PAD, escape(title)))
|
|
153
|
+
add('<text x="%d" y="40" font-size="12" text-anchor="end" class="m">%s</text>' % (W - PAD, escape(period)))
|
|
154
|
+
|
|
155
|
+
col = (W - 2 * PAD) / 4.0
|
|
156
|
+
for i, (value, label) in enumerate(stats):
|
|
157
|
+
x = PAD + i * col
|
|
158
|
+
add('<text x="%d" y="94" font-size="30" class="t b">%s</text>' % (x, escape(value)))
|
|
159
|
+
add('<text x="%d" y="116" font-size="12" class="m">%s</text>' % (x, escape(label)))
|
|
160
|
+
|
|
161
|
+
out.extend(month_labels)
|
|
162
|
+
out.extend(cells)
|
|
163
|
+
ly = hy + 7 * STEP + 16
|
|
164
|
+
add('<text x="%d" y="%d" font-size="11" class="m">%s active days in the last 12 months</text>'
|
|
165
|
+
% (hx, ly, fmt_n(year_days)))
|
|
166
|
+
lx = hx + WEEKS * STEP - (STEP - CELL) - 5 * STEP - 34
|
|
167
|
+
add('<text x="%d" y="%d" font-size="11" text-anchor="end" class="m">Less</text>' % (lx - 6, ly))
|
|
168
|
+
for i in range(5):
|
|
169
|
+
add('<rect x="%d" y="%d" width="%d" height="%d" rx="2" class="l%d"/>' % (lx + i * STEP, ly - 9, CELL, CELL, i))
|
|
170
|
+
add('<text x="%d" y="%d" font-size="11" class="m">More</text>' % (lx + 5 * STEP + 4, ly))
|
|
171
|
+
|
|
172
|
+
if segments:
|
|
173
|
+
by = ly + 28
|
|
174
|
+
bw = W - 2 * PAD
|
|
175
|
+
add('<clipPath id="lang"><rect x="%d" y="%d" width="%d" height="8" rx="4"/></clipPath>' % (PAD, by, bw))
|
|
176
|
+
x = float(PAD)
|
|
177
|
+
add('<g clip-path="url(#lang)">')
|
|
178
|
+
total = sum(p for _n, p, _c in segments) or 1
|
|
179
|
+
for _n, p, c in segments:
|
|
180
|
+
w = bw * p / total
|
|
181
|
+
add('<rect x="%.1f" y="%d" width="%.1f" height="8" fill="%s"/>' % (x, by, w + 0.5, c))
|
|
182
|
+
x += w
|
|
183
|
+
add("</g>")
|
|
184
|
+
x = float(PAD)
|
|
185
|
+
for n, p, c in segments:
|
|
186
|
+
label = "%s %d%%" % (n, round(p))
|
|
187
|
+
add('<circle cx="%.1f" cy="%d" r="4" fill="%s"/>' % (x + 4, by + 25, c))
|
|
188
|
+
add('<text x="%.1f" y="%d" font-size="12" class="t">%s</text>' % (x + 13, by + 29, escape(label)))
|
|
189
|
+
x += 13 + 7.2 * len(label) + 18
|
|
190
|
+
|
|
191
|
+
add('<text x="%d" y="%d" font-size="10" class="m">tokstats · tokens counted once per API response'
|
|
192
|
+
'%s · github.com/muradyan/tokstats</text>'
|
|
193
|
+
% (PAD, height - 14, " · PRs verified on GitHub" if o.get("merged_prs_verified") is not None else ""))
|
|
194
|
+
add("</svg>")
|
|
195
|
+
return "\n".join(out) + "\n"
|