-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode_tracker.py
More file actions
175 lines (145 loc) · 4.9 KB
/
leetcode_tracker.py
File metadata and controls
175 lines (145 loc) · 4.9 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
"""
leetcode_tracker.py
-------------------
Fetches your LeetCode stats via the public GraphQL API
and saves a daily snapshot to data/stats_history.csv.
Run manually or set up a daily cron job / Task Scheduler.
Usage: python leetcode_tracker.py
"""
import requests
import pandas as pd
import os
from datetime import datetime
from dotenv import load_dotenv
# ── Config ────────────────────────────────────────────────────
load_dotenv()
USERNAME = os.getenv("LEETCODE_USERNAME") # set in .env file
if not USERNAME:
raise ValueError("LEETCODE_USERNAME not set in .env file")
DATA_DIR = "data"
STATS_FILE = os.path.join(DATA_DIR, "stats_history.csv")
# ── GraphQL queries ───────────────────────────────────────────
STATS_QUERY = """
query getUserStats($username: String!) {
matchedUser(username: $username) {
submitStats: submitStatsGlobal {
acSubmissionNum {
difficulty
count
}
}
profile {
ranking
reputation
starRating
}
}
}
"""
CALENDAR_QUERY = """
query getUserCalendar($username: String!) {
matchedUser(username: $username) {
userCalendar {
streak
totalActiveDays
submissionCalendar
}
}
}
"""
RECENT_QUERY = """
query getRecentSubmissions($username: String!, $limit: Int!) {
recentAcSubmissionList(username: $username, limit: $limit) {
title
titleSlug
timestamp
lang
}
}
"""
HEADERS = {
"Content-Type": "application/json",
"Referer": "https://leetcode.com",
"User-Agent": "Mozilla/5.0"
}
URL = "https://leetcode.com/graphql"
def fetch(query: str, variables: dict) -> dict:
"""Send a GraphQL query and return the parsed JSON response."""
response = requests.post(
URL,
json={"query": query, "variables": variables},
headers=HEADERS,
timeout=10
)
response.raise_for_status()
return response.json()
def get_stats(username: str) -> dict:
"""Fetch solve counts by difficulty and ranking."""
data = fetch(STATS_QUERY, {"username": username})
user = data["data"]["matchedUser"]
counts = {d["difficulty"]: d["count"]
for d in user["submitStats"]["acSubmissionNum"]}
return {
"easy": counts.get("Easy", 0),
"medium": counts.get("Medium", 0),
"hard": counts.get("Hard", 0),
"total": counts.get("All", 0),
"ranking": user["profile"]["ranking"],
}
def get_calendar(username: str) -> dict:
"""Fetch streak and total active days."""
data = fetch(CALENDAR_QUERY, {"username": username})
cal = data["data"]["matchedUser"]["userCalendar"]
return {
"streak": cal["streak"],
"active_days": cal["totalActiveDays"],
}
def get_recent(username: str, limit: int = 5) -> list[dict]:
"""Fetch the most recently accepted submissions."""
data = fetch(RECENT_QUERY, {"username": username, "limit": limit})
return data["data"]["recentAcSubmissionList"]
def save_snapshot(stats: dict, calendar: dict) -> None:
"""Append today's snapshot to the CSV history file."""
os.makedirs(DATA_DIR, exist_ok=True)
today = datetime.now().strftime("%Y-%m-%d")
row = {
"date": today,
"total": stats["total"],
"easy": stats["easy"],
"medium": stats["medium"],
"hard": stats["hard"],
"ranking": stats["ranking"],
"streak": calendar["streak"],
"active_days": calendar["active_days"],
}
if os.path.exists(STATS_FILE):
df = pd.read_csv(STATS_FILE)
# Don't add a duplicate entry for the same day
if today in df["date"].values:
print(f"[i] Snapshot for {today} already exists — skipping save.")
return
df = pd.concat([df, pd.DataFrame([row])], ignore_index=True)
else:
df = pd.DataFrame([row])
df.to_csv(STATS_FILE, index=False)
print(f"[+] Snapshot saved for {today}: {stats['total']} total solved.")
def main():
print(f"Fetching stats for: {USERNAME}")
try:
stats = get_stats(USERNAME)
calendar = get_calendar(USERNAME)
recent = get_recent(USERNAME)
print(f" Total : {stats['total']}")
print(f" Easy : {stats['easy']}")
print(f" Medium: {stats['medium']}")
print(f" Hard : {stats['hard']}")
print(f" Rank : #{stats['ranking']}")
print(f" Streak: {calendar['streak']} days")
print(f" Recent: {[r['title'] for r in recent]}")
save_snapshot(stats, calendar)
except requests.RequestException as e:
print(f"[!] Network error: {e}")
except (KeyError, TypeError) as e:
print(f"[!] Parse error — LeetCode may have changed their API: {e}")
if __name__ == "__main__":
main()