-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdraw_contributions.py
241 lines (201 loc) · 8.38 KB
/
draw_contributions.py
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
import requests
from typing import Dict, Tuple, List, Generator
import itertools
from icecream import ic
from bs4 import BeautifulSoup
from datetime import date
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from datetime import date, timedelta
def get_contributions(username: str, year: int) -> Dict[date, int]:
# get request to the following url with appropriate parameters
# https://github.com/users/mahdihasnat/contributions?from=2022-12-01&to=2022-12-31
url = f"https://github.com/users/{username}/contributions?from={year}-01-01&to={year}-12-31"
ic(url)
response = requests.get(url)
if response.status_code != 200:
raise Exception(f"Failed to fetch contributions: {response.status_code}")
soup = BeautifulSoup(response.text, "html.parser")
contributions = {}
# Locate the contribution calendar table
table = soup.find("table", {"class": "js-calendar-graph-table"})
if not table:
raise Exception("Could not find contribution graph in the response")
ic(len(table))
table_datas = table.find_all("td", {"class": "ContributionCalendar-day"})
ic(len(table_datas))
tool_tips = table.find_all("tool-tip")
ic(len(tool_tips))
if len(table_datas) != len(tool_tips):
raise Exception("Number of table data and tool tips do not match")
def parseContribution(text: str) -> int:
# No contributions on January 2nd.
# 1 contribution on January 23rd.
# 2 contributions on January 24th.
text = text.strip()
text = text.split("contribution")[0]
text = text.strip()
if text == "No":
return 0
else:
return int(text)
contributions_for_data_ids = {}
for tool_tip in tool_tips:
contributions_for_data_ids[tool_tip["for"]] = parseContribution(tool_tip.contents[0])
for table_data in table_datas:
date_str = table_data["data-date"]
date_obj = date.fromisoformat(date_str)
contributions[date_obj] = contributions_for_data_ids[table_data["id"]]
return contributions
def get_labels(contributions: Dict[date, int]) -> Dict[date, int]:
max_contribution = max(contributions.values())
def get_label(contribution) -> int :
if contribution == 0:
return 0
max_contribution = max(contributions.values())
segment_size = max_contribution // 4
segments = [segment_size, segment_size, segment_size, segment_size]
reminder = max_contribution % 4
if reminder > 0:
segments[3] += 1
reminder -= 1
if reminder > 1:
segments[2] += 1
reminder -= 1
if reminder > 0:
segments[1] += 1
reminder -= 1
assert reminder == 0
for i, segment in enumerate(segments):
if contribution <= segment:
return i + 1
contribution -= segment
assert False
return -1
labels = {}
for date, contribution in contributions.items():
labels[date] = get_label(contribution)
return labels
# Define the color mapping for data labels
colors = {
0: "#161b22",
1: "#0e4429",
2: "#006d32",
3: "#26a641",
4: "#39d353",
}
# Function to generate a 7x52 grid based on input data
def draw_contribution_chart(contributions: Dict[date, int], year):
labels = get_labels(contributions)
# Create a 7x52 grid filled with zeros (default data-label 0)
grid = np.zeros((7, 54), dtype=int)
# Find the first Sunday of the year
start_date = date(year, 1, 1)
end_date = date(year, 12, 31)
current_date = start_date
current_column = 0
# Fill the grid with data-labels from the contributions
while current_date <= end_date:
current_row = current_date.isoweekday() % 7
grid[current_row][current_column] = labels.get(current_date, (0, 0))
if current_row == 6:
current_column += 1
current_date += timedelta(days=1)
# Create a custom colormap
cmap = mcolors.ListedColormap([colors[i] for i in range(5)])
bounds = [-0.5, 0.5, 1.5, 2.5, 3.5, 4.5]
norm = mcolors.BoundaryNorm(bounds, cmap.N)
# Plot the heatmap
fig, ax = plt.subplots(figsize=(15, 4))
ax.imshow(grid, cmap=cmap, norm=norm, aspect="equal")
# Customize the chart
ax.set_yticks(range(7))
ax.set_yticklabels(["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"])
ax.set_xticks(range(0, 52, 4)) # Add ticks every 4 weeks
ax.set_xticklabels([f"Week {i}" for i in range(0, 52, 4)])
ax.set_title("Contribution Chart")
ax.grid(False)
# Hide spines and ticks
ax.spines[:].set_visible(False)
ax.tick_params(left=False, bottom=False)
plt.show()
plt.savefig(f"contribution_chart_{year}.png")
def apply_art(contributions: Dict[date, int], year: int, art: List[str]) -> Dict[date, int]:
max_conttribution = max(contributions.values())
start_date = date(year, 1, 1)
end_date = date(year, 12, 31)
current_date = start_date
current_column = 0
updated_contributions = {}
# Fill the grid with data-labels from the contributions
while current_date <= end_date:
current_row = current_date.isoweekday() % 7
if art[current_row][current_column] == '#':
updated_contributions[current_date] = 1 if max_conttribution == 0 else 4 * max_conttribution
else:
updated_contributions[current_date] = 0 if contributions[current_date] == 0 else max_conttribution
if current_row == 6:
current_column += 1
current_date += timedelta(days=1)
return updated_contributions
def generate_extra_commits(contributions: Dict[date, int], updated_contributions: Dict[date, int]) -> Generator:
all_dates = set(contributions.keys()).union(updated_contributions.keys())
for date in all_dates:
existing_contribution = contributions.get(date, 0)
updated_contribution = updated_contributions.get(date, 0)
extra_contribution = updated_contribution - existing_contribution
assert extra_contribution >= 0
for i in range(extra_contribution):
date_str = date.strftime('%Y-%m-%d %H:%M:%S')
commit_msg = f'Commit {existing_contribution + i + 1} for day {date_str}'
env_vars = f'GIT_AUTHOR_DATE="{date_str}" GIT_COMMITTER_DATE="{date_str}"'
yield f'{env_vars} git commit --allow-empty -m "{commit_msg}"\n'
year = 2024
contributions = get_contributions("mahdihasnat", year)
ic(len(contributions))
# Draw the chart
# draw_contribution_chart(contributions, year)
target_art = [
#......................................................;
'......#.....#..######..#.......#.........###.........',
'......#.....#..#.......#.......#........#...#........',
'......#.....#..#.......#.......#.......#.....#........',
'......#######..####....#.......#.......#.....#........',
'......#.....#..#.......#.......#.......#.....#........',
'......#.....#..#.......#.......#........#...#........',
'......#.....#..######..######..######....###..........',
]
ic(target_art)
updated_contributions = apply_art(contributions, year, target_art)
# draw_contribution_chart(updated_contributions, year)
commit_gen1 = generate_extra_commits(contributions, updated_contributions)
target_art = [
#......................................................;
'......#.....#....###.....####....#.......#####........',
'......#.....#...#...#...#....#...#.......#....#.......',
'......#.....#..#.....#..#...#....#.......#.....#......',
'......#..#..#..#.....#..####.....#.......#.....#......',
'......#.#.#.#..#.....#..#...#....#.......#.....#......',
'......##...##...#...#...#....#...#.......#....#.......',
'......#.....#....###....#.....#..######..#####........',
]
year = 2023
contributions = get_contributions("mahdihasnat", year)
ic(len(contributions))
# Draw the chart
# draw_contribution_chart(contributions, year)
updated_contributions = apply_art(contributions, year, target_art)
# draw_contribution_chart(updated_contributions, year)
commit_gen2 = generate_extra_commits(contributions, updated_contributions)
commit_gen = itertools.chain(commit_gen1, commit_gen2)
with open('commits.sh', 'w') as f:
commits_to_push = 0
for commit in commit_gen:
f.write(commit)
commits_to_push += 1
if commits_to_push == 1000:
f.write('git push\n')
commits_to_push = 0
if commits_to_push > 0:
f.write('git push\n')