forked from phuryn/claude-usage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
323 lines (271 loc) · 10.1 KB
/
cli.py
File metadata and controls
323 lines (271 loc) · 10.1 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
"""
cli.py - Command-line interface for the Claude Code usage dashboard.
Commands:
scan - Scan JSONL files and update the database
today - Print today's usage summary
stats - Print all-time usage statistics
dashboard - Scan + open browser + start dashboard server
"""
import os
import sys
import sqlite3
from pathlib import Path
from datetime import datetime, date
DB_PATH = Path.home() / ".claude" / "usage.db"
PRICING = {
"claude-opus-4-6": {"input": 5.00, "output": 25.00},
"claude-opus-4-5": {"input": 5.00, "output": 25.00},
"claude-sonnet-4-6": {"input": 3.00, "output": 15.00},
"claude-sonnet-4-5": {"input": 3.00, "output": 15.00},
"claude-haiku-4-5": {"input": 1.00, "output": 5.00},
"claude-haiku-4-6": {"input": 1.00, "output": 5.00},
}
def get_pricing(model):
if not model:
return None
if model in PRICING:
return PRICING[model]
for key in PRICING:
if model.startswith(key):
return PRICING[key]
# Substring fallback: match model family by keyword
m = model.lower()
if "opus" in m:
return PRICING["claude-opus-4-6"]
if "sonnet" in m:
return PRICING["claude-sonnet-4-6"]
if "haiku" in m:
return PRICING["claude-haiku-4-5"]
return None
def calc_cost(model, inp, out, cache_read, cache_creation):
p = get_pricing(model)
if not p:
return 0.0
return (
inp * p["input"] / 1_000_000 +
out * p["output"] / 1_000_000 +
cache_read * p["input"] * 0.10 / 1_000_000 +
cache_creation * p["input"] * 1.25 / 1_000_000
)
def fmt(n):
if n >= 1_000_000:
return f"{n/1_000_000:.2f}M"
if n >= 1_000:
return f"{n/1_000:.1f}K"
return str(n)
def fmt_cost(c):
return f"${c:.4f}"
def hr(char="-", width=60):
print(char * width)
def require_db():
if not DB_PATH.exists():
print("Database not found. Run: python cli.py scan")
sys.exit(1)
return sqlite3.connect(DB_PATH)
# ── Commands ──────────────────────────────────────────────────────────────────
def cmd_scan(projects_dir=None):
from scanner import scan
scan(projects_dir=Path(projects_dir) if projects_dir else None)
def cmd_today():
conn = require_db()
conn.row_factory = sqlite3.Row
today = date.today().isoformat()
rows = conn.execute("""
SELECT
COALESCE(model, 'unknown') as model,
SUM(input_tokens) as inp,
SUM(output_tokens) as out,
SUM(cache_read_tokens) as cr,
SUM(cache_creation_tokens) as cc,
COUNT(*) as turns
FROM turns
WHERE substr(timestamp, 1, 10) = ?
GROUP BY model
ORDER BY inp + out DESC
""", (today,)).fetchall()
sessions = conn.execute("""
SELECT COUNT(DISTINCT session_id) as cnt
FROM turns
WHERE substr(timestamp, 1, 10) = ?
""", (today,)).fetchone()
print()
hr()
print(f" Today's Usage ({today})")
hr()
if not rows:
print(" No usage recorded today.")
print()
return
total_inp = total_out = total_cr = total_cc = total_turns = 0
total_cost = 0.0
for r in rows:
cost = calc_cost(r["model"], r["inp"] or 0, r["out"] or 0, r["cr"] or 0, r["cc"] or 0)
total_cost += cost
total_inp += r["inp"] or 0
total_out += r["out"] or 0
total_cr += r["cr"] or 0
total_cc += r["cc"] or 0
total_turns += r["turns"]
print(f" {r['model']:<30} turns={r['turns']:<4} in={fmt(r['inp'] or 0):<8} out={fmt(r['out'] or 0):<8} cost={fmt_cost(cost)}")
hr()
print(f" {'TOTAL':<30} turns={total_turns:<4} in={fmt(total_inp):<8} out={fmt(total_out):<8} cost={fmt_cost(total_cost)}")
print()
print(f" Sessions today: {sessions['cnt']}")
print(f" Cache read: {fmt(total_cr)}")
print(f" Cache creation: {fmt(total_cc)}")
hr()
print()
conn.close()
def cmd_stats():
conn = require_db()
conn.row_factory = sqlite3.Row
# Session-level info (count, date range)
session_info = conn.execute("""
SELECT
COUNT(*) as sessions,
MIN(first_timestamp) as first,
MAX(last_timestamp) as last
FROM sessions
""").fetchone()
# All-time totals from turns (more accurate — per-turn model attribution)
totals = conn.execute("""
SELECT
SUM(input_tokens) as inp,
SUM(output_tokens) as out,
SUM(cache_read_tokens) as cr,
SUM(cache_creation_tokens) as cc,
COUNT(*) as turns
FROM turns
""").fetchone()
# By model from turns (each turn has the actual model used)
by_model = conn.execute("""
SELECT
COALESCE(model, 'unknown') as model,
SUM(input_tokens) as inp,
SUM(output_tokens) as out,
SUM(cache_read_tokens) as cr,
SUM(cache_creation_tokens) as cc,
COUNT(*) as turns,
COUNT(DISTINCT session_id) as sessions
FROM turns
GROUP BY model
ORDER BY inp + out DESC
""").fetchall()
# Top 5 projects from turns (join with sessions for project name)
top_projects = conn.execute("""
SELECT
COALESCE(s.project_name, 'unknown') as project_name,
SUM(t.input_tokens) as inp,
SUM(t.output_tokens) as out,
COUNT(*) as turns,
COUNT(DISTINCT t.session_id) as sessions
FROM turns t
LEFT JOIN sessions s ON t.session_id = s.session_id
GROUP BY s.project_name
ORDER BY inp + out DESC
LIMIT 5
""").fetchall()
# Daily average (last 30 days)
daily_avg = conn.execute("""
SELECT
AVG(daily_inp) as avg_inp,
AVG(daily_out) as avg_out,
AVG(daily_cost) as avg_cost
FROM (
SELECT
substr(timestamp, 1, 10) as day,
SUM(input_tokens) as daily_inp,
SUM(output_tokens) as daily_out,
0.0 as daily_cost
FROM turns
WHERE timestamp >= datetime('now', '-30 days')
GROUP BY day
)
""").fetchone()
# Build total cost across all models
total_cost = sum(
calc_cost(r["model"], r["inp"] or 0, r["out"] or 0, r["cr"] or 0, r["cc"] or 0)
for r in by_model
)
print()
hr("=")
print(" Claude Code Usage - All-Time Statistics")
hr("=")
first_date = (session_info["first"] or "")[:10]
last_date = (session_info["last"] or "")[:10]
print(f" Period: {first_date} to {last_date}")
print(f" Total sessions: {session_info['sessions'] or 0:,}")
print(f" Total turns: {fmt(totals['turns'] or 0)}")
print()
print(f" Input tokens: {fmt(totals['inp'] or 0):<12} (raw prompt tokens)")
print(f" Output tokens: {fmt(totals['out'] or 0):<12} (generated tokens)")
print(f" Cache read: {fmt(totals['cr'] or 0):<12} (90% cheaper than input)")
print(f" Cache creation: {fmt(totals['cc'] or 0):<12} (25% premium on input)")
print()
print(f" Est. total cost: ${total_cost:.4f}")
hr()
print(" By Model:")
for r in by_model:
cost = calc_cost(r["model"], r["inp"] or 0, r["out"] or 0, r["cr"] or 0, r["cc"] or 0)
print(f" {r['model']:<30} sessions={r['sessions']:<4} turns={fmt(r['turns'] or 0):<6} "
f"in={fmt(r['inp'] or 0):<8} out={fmt(r['out'] or 0):<8} cost={fmt_cost(cost)}")
hr()
print(" Top Projects:")
for r in top_projects:
print(f" {(r['project_name'] or 'unknown'):<40} sessions={r['sessions']:<3} "
f"turns={fmt(r['turns'] or 0):<6} tokens={fmt((r['inp'] or 0)+(r['out'] or 0))}")
if daily_avg["avg_inp"]:
hr()
print(" Daily Average (last 30 days):")
print(f" Input: {fmt(int(daily_avg['avg_inp'] or 0))}")
print(f" Output: {fmt(int(daily_avg['avg_out'] or 0))}")
hr("=")
print()
conn.close()
def cmd_dashboard(projects_dir=None):
import webbrowser
import threading
import time
print("Running scan first...")
cmd_scan(projects_dir=projects_dir)
print("\nStarting dashboard server...")
from dashboard import serve
host = os.environ.get("HOST", "localhost")
port = int(os.environ.get("PORT", "8080"))
def open_browser():
time.sleep(1.0)
webbrowser.open(f"http://{host}:{port}")
t = threading.Thread(target=open_browser, daemon=True)
t.start()
serve(host=host, port=port)
# ── Entry point ───────────────────────────────────────────────────────────────
USAGE = """
Claude Code Usage Dashboard
Usage:
python cli.py scan [--projects-dir PATH] Scan JSONL files and update database
python cli.py today Show today's usage summary
python cli.py stats Show all-time statistics
python cli.py dashboard [--projects-dir PATH] Scan + start dashboard
"""
COMMANDS = {
"scan": cmd_scan,
"today": cmd_today,
"stats": cmd_stats,
"dashboard": cmd_dashboard,
}
def parse_projects_dir(args):
"""Extract --projects-dir value from argument list."""
for i, arg in enumerate(args):
if arg == "--projects-dir" and i + 1 < len(args):
return args[i + 1]
return None
if __name__ == "__main__":
if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS:
print(USAGE)
sys.exit(0)
command = sys.argv[1]
projects_dir = parse_projects_dir(sys.argv[2:])
if command in ("scan", "dashboard") and projects_dir:
COMMANDS[command](projects_dir=projects_dir)
else:
COMMANDS[command]()