-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithubfetch.py
More file actions
277 lines (240 loc) · 9.39 KB
/
githubfetch.py
File metadata and controls
277 lines (240 loc) · 9.39 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
#!/usr/bin/python3
import requests
import subprocess
import sys
import os
from PIL import Image
from io import BytesIO
class Color:
def __init__(self):
self.red = "\x1b[38;5;1m"
self.green = "\x1b[38;5;2m"
self.yellow = "\x1b[38;5;3m"
self.light_blue = "\x1b[38;5;4m"
self.light_red = "\x1b[38;5;9m"
self.blue = "\x1b[38;5;21m"
self.reset = "\x1b[00m"
def color(self,color_name,text):
return f"{color_name}{text}{color.reset}"
color = Color()
def get_headers():
token = os.getenv("GITHUB_TOKEN")
if not token:
return {}
return {"Authorization": f"Bearer {token}"}
def get_user_data(username):
user_url = f"https://api.github.com/users/{username}"
response = requests.get(user_url, headers=get_headers())
if response.status_code != 200:
raise Exception(f"Error: {response.status_code} - {response.json().get('message')}")
return response.json()
def get_starred_count(username):
user_url = f"https://api.github.com/users/{username}/starred"
response = requests.get(user_url, headers=get_headers())
if response.status_code != 200:
return 0
return len(response.json())
def fetch_contributions(username):
url = "https://api.github.com/graphql"
headers = get_headers()
query = """
query($login:String!) {
user(login:$login) {
contributionsCollection {
contributionCalendar {
weeks {
contributionDays {
date
contributionCount
}
}
}
}
}
}"""
variables = {"login": username}
resp = requests.post(url, json={"query": query, "variables": variables}, headers=headers)
data = resp.json()
weeks_data = data["data"]["user"]["contributionsCollection"]["contributionCalendar"]["weeks"]
weeks = []
for week in weeks_data:
levels = []
for day in week["contributionDays"]:
count = day["contributionCount"]
levels.append(classify_level(count))
weeks.append(levels)
return weeks
def classify_level(count):
if count == 0:
return 0
elif count < 3:
return 1
elif count < 6:
return 2
elif count < 10:
return 3
else:
return 4
def display_contributions(weeks):
colors = {
0: "\x1b[48;5;232m", # dark gray
1: "\x1b[48;5;22m", # dark green
2: "\x1b[48;5;28m", # green
3: "\x1b[48;5;34m", # bright green
4: "\x1b[48;5;40m", # light green
}
reset = "\x1b[0m"
print("\n" + " " * 22 + "GitHub Contributions (Past Year):")
for row in range(7):
line = " " * 0
for week in weeks:
if row < len(week):
level = week[row]
color_block = f"{colors.get(level, colors[0])} {reset}"
line += color_block
else:
line += " "
print(line)
def display_avatar(image_url):
try:
subprocess.run([
"kitten", "icat", "--align",
"left", "--scale-up", "--place",
"20x20@0x2", image_url])
except FileNotFoundError:
print(color.red,"Kitty Terminal not installed!", color.reset)
sys.exit(1)
def display_user_info(data, starred_count, username):
github_url = f"{username}@github.com"
indent = " " * 22
elements = [
{"text":color.color(color.light_blue,"Username:"),"value":data.get('login')},
{"text":color.color(color.yellow,"Repos:"),"value":data.get('public_repos')},
{"text":color.color(color.green,"Bio:"),"value":data.get('bio','N/A') or 'N/A'},
{"text":color.color(color.red,"From:"),"value":data.get('location','Not Provided')},
{"text":color.color(color.light_red,"Followers:"),"value":data.get('followers')},
{"text":color.color(color.light_blue,"Following:"),"value":data.get('following')},
{"text":color.color(color.yellow,"Starred repos:"),"value":starred_count},
]
print(f"{indent} {github_url}")
print(f"{indent} {'-'*len(github_url)}")
for element in elements:
print(f"{indent} {element['text']} {element['value']}")
print("\n")
## Rending ASCII
use_ascii = True
align_bottom = False
def render_ascii(image_url, width=30, style='bold', use_color=True):
try:
# Dynamic style selection
styles = {
'bold': "@%#*+=-:. "[::-1],
'fine': ".,:;i1tfLCG08@"[::-1],
'block': " ░▒▓█"[::-1],
'retro': " .'`^\",:;Il!i><~+_-?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$"
}
chars = styles.get(style, styles['bold'])
response = requests.get(image_url)
image = Image.open(BytesIO(response.content)).convert('L')
# Auto-size to terminal
import os
max_width = os.get_terminal_size().columns - 10
width = min(width, max_width)
aspect_ratio = image.height / image.width
height = int(aspect_ratio * width * 0.55)
image = image.resize((width, height))
ascii_image = []
for y in range(height):
line = ""
for x in range(width):
pixel = image.getpixel((x, y))
char = chars[min(len(chars)-1, pixel * len(chars) // 256)]
if use_color:
color_code = f"\x1b[38;5;{232 + (pixel * 23 // 255)}m"
line += f"{color_code}{char}\x1b[0m"
else:
line += char
ascii_image.append(line)
return ascii_image
except Exception as e:
print(f"\x1b[31m[!] Error: {e}\x1b[0m", file=sys.stderr)
return []
## Render Layout
def render_layout(ascii_lines, info_lines, align='top'):
max_lines = max(len(ascii_lines), len(info_lines))
pad_ascii = max_lines - len(ascii_lines)
pad_info = max_lines - len(info_lines)
ascii_lines += [''] * pad_ascii
info_lines += [''] * pad_info
for a, b in zip(ascii_lines, info_lines):
print(f"{a:<45} {b}")
def get_user_info_lines(data, starred_count, username):
url = f"{username}@github.com"
lines = [
f"{color.color(color.blue, 'Username:')} {data.get('login')}",
f"{color.color(color.yellow, 'Repos:')} {data.get('public_repos')}",
f"{color.color(color.green, 'Bio:')} {data.get('bio') or 'N/A'}",
f"{color.color(color.red, 'From:')} {data.get('location') or 'Not Provided'}",
f"{color.color(color.light_red, 'Followers:')} {data.get('followers')}",
f"{color.color(color.light_blue, 'Following:')} {data.get('following')}",
f"{color.color(color.yellow, 'Starred repos:')} {starred_count}"
]
return [f"{' ' * 2}{url}", ' ' * 2 + '-' * len(url)] + lines
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: githubfetch <username> [--ascii[=style]] [--heatmap] [--nocolor]")
print("Available styles: bold, fine, block, sketch, invert, minimal, retro")
sys.exit(1)
if sys.argv[1] in ['--help', '-h']:
print("GitHub User Fetcher with Enhanced ASCII Art")
print("Usage: githubfetch <username> [options]")
print("\nOptions:")
print(" --ascii[=style] Show avatar as ASCII art (default: bold)")
print(" Available styles:")
print(" - bold: Thick characters (@%#*)")
print(" - fine: Thin characters (.,:;)")
print(" - block: Block characters (█▓▒░)")
print(" - retro: Classic terminal look")
print(" --nocolor Disable colored ASCII output")
print(" --heatmap Show contribution graph (requires GITHUB_TOKEN)")
print(" -h, --help Show this help message")
sys.exit(0)
username = sys.argv[1]
heatmap = '--heatmap' in sys.argv
use_color = '--nocolor' not in sys.argv
# Parse ASCII style
ascii_style = 'bold'
for arg in sys.argv:
if arg.startswith('--ascii='):
ascii_style = arg.split('=')[1].lower()
elif arg == '--ascii':
ascii_style = 'bold' # default
try:
user_data = get_user_data(username)
starred_count = get_starred_count(username)
if '--ascii' in sys.argv or any(a.startswith('--ascii=') for a in sys.argv):
ascii_block = render_ascii(
user_data.get('avatar_url'),
style=ascii_style,
use_color=use_color
)
info_block = get_user_info_lines(user_data, starred_count, username)
render_layout(ascii_block, info_block)
else:
if use_color:
display_avatar(user_data.get('avatar_url'))
else:
# Display grayscale avatar if --nocolor
img = Image.open(BytesIO(requests.get(user_data.get('avatar_url')).content).convert('L'))
img.show()
display_user_info(user_data, starred_count, username)
if heatmap:
token = os.getenv("GITHUB_TOKEN")
if not token:
print("\x1b[33mWarning: GITHUB_TOKEN not set. Skipping heatmap.\x1b[0m", file=sys.stderr)
else:
contributions = fetch_contributions(username)
display_contributions(contributions)
except Exception as e:
print(f"\x1b[31mError: {str(e)}\x1b[0m", file=sys.stderr)
sys.exit(1)