Repository navigation
Expand file tree
/
Copy pathProject.py
More file actions
229 lines (179 loc) · 7.33 KB
/
Copy pathProject.py
File metadata and controls
229 lines (179 loc) · 7.33 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
# --- GitHub Profile Analyzer ---
# This script fetches data from a GitHub user's profile using the GitHub REST API.
# It generates a detailed report including user info, repositories, languages used, and more.
#importing modules
import requests
import matplotlib.pyplot as plt
import seaborn as sns
# Base URL for GitHub API
BASE_URL = "https://api.github.com"
def get_user_data(username):
"""
Fetches basic user information from GitHub API.
Returns a dictionary with user details or None if user not found.
"""
url = f"{BASE_URL}/users/{username}"
response = requests.get(url)
if response.status_code == 200:
return response.json()
elif response.status_code == 404:
print(f"Error: User '{username}' not found.")
return None
elif response.status_code == 403:
print("Error: API rate limit exceeded. Try again later or use a GitHub token.")
return None
else:
print(f"Error: Unable to fetch user data. Status code: {response.status_code}")
return None
def get_repositories(username):
"""
Fetches all public repositories for the user.
Handles pagination to get all repos.
Returns a list of repo dictionaries.
"""
repos = []
page = 1
per_page = 100 # Max per page
while True:
url = f"{BASE_URL}/users/{username}/repos?page={page}&per_page={per_page}"
response = requests.get(url)
if response.status_code != 200:
print(f"Error: Unable to fetch repositories. Status code: {response.status_code}")
break
page_repos = response.json()
if not page_repos:
break # No more repos
repos.extend(page_repos)
page += 1
return repos
def get_repo_languages(username, repo_name):
"""
Fetches the programming languages used in a specific repository.
Returns a dictionary of languages with their byte counts.
"""
url = f"{BASE_URL}/repos/{username}/{repo_name}/languages"
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
print(f"Warning: Could not fetch languages for {repo_name}. Status code: {response.status_code}")
return {}
def calculate_language_stats(repos, username):
"""
Aggregates language usage across all repositories.
Returns a dictionary of languages sorted by total bytes used.
"""
language_totals = {}
for repo in repos:
repo_name = repo['name']
languages = get_repo_languages(username, repo_name)
for lang, bytes_count in languages.items():
if lang in language_totals:
language_totals[lang] += bytes_count
else:
language_totals[lang] = bytes_count
# Sort by total bytes (descending)
sorted_languages = sorted(language_totals.items(), key=lambda x: x[1], reverse=True)
return dict(sorted_languages)
def calculate_total_stars(repos):
"""
Calculates the total number of stars across all repositories.
"""
return sum(repo['stargazers_count'] for repo in repos)
def generate_markdown_report(username, user_data, repos, language_stats, total_stars):
"""
Generates a markdown report file with all the analyzed data.
Saves it as '{username}_report.md'.
"""
filename = f"{username}_report.md"
with open(filename, 'w', encoding='utf-8') as file:
file.write(f"# --- GITHUB PROFILE REPORT ({username}) ---\n\n\n")
# User Info Section
file.write("## --USER INFORMATION--\n\n")
file.write(f"- **Name:** {user_data.get('name', 'N/A')}\n")
file.write(f"- **Bio:** {user_data.get('bio', 'N/A')}\n")
file.write(f"- **Location:** {user_data.get('location', 'N/A')}\n")
file.write(f"- **Followers:** {user_data.get('followers', 0)}\n")
file.write(f"- **Following:** {user_data.get('following', 0)}\n")
file.write(f"- **Public Repositories:** {user_data.get('public_repos', 0)}\n")
file.write(f"- **Profile URL:** {user_data.get('html_url', 'N/A')}\n\n\n")
# Repositories Section
file.write("## --REPOSITORIES--\n\n")
file.write(f"-**Total Public Repositories** : {len(repos)}\n\n")
for repo in repos:
file.write(f"- **{repo['name']}**: {repo['description'] or 'No description'}\n")
file.write(f" - Stars: {repo['stargazers_count']}\n")
file.write(f" - Language: {repo.get('language', 'N/A')}\n\n")
# Language Stats Section
file.write("## --Most Used Programming Languages--\n\n")
if language_stats:
for lang, bytes_count in language_stats.items():
file.write(f"- **{lang}**: {bytes_count} bytes\n")
else:
file.write("No language data available.")
file.write("\n\n")
# Total Stars Section
file.write("## --Total Stars Earned--\n\n")
file.write(f"- **Total stars earned through all repos**: {total_stars}\n\n\n")
# Footer
file.write("\nThank you for using the GitHub Profile Analyzer🧠.\n")
print(f"\nReport saved as {filename}")
def languages_plot(language_stats, top_n=10):
"""
Plots a horizontal bar chart of most used languages.
Only top_n languages are shown for readability.
"""
# Take top N languages
languages = list(language_stats.keys())[:top_n]
bytes_used = list(language_stats.values())[:top_n]
# Dynamic figure height based on number of languages
fig_height = max(5, len(languages)*0.5)
fig, ax = plt.subplots(figsize=(10, fig_height))
# Horizontal bar chart
sns.barplot(
y=languages,
x=bytes_used,
ax=ax,
color="#89EBE9",
orient="h"
)
# Add value labels at end of bars
for i, val in enumerate(bytes_used):
ax.text(val + max(bytes_used)*0.01, i, str(val), va="center", ha="left", fontsize=9)
# Titles and labels
ax.set_title(f"Top {top_n} Languages by Bytes of Code")
ax.set_xlabel("Bytes of Code")
ax.set_ylabel("Programming Languages")
fig.tight_layout()
plt.show()
def main():
"""
Main function to run the GitHub Profile Analyzer.
Prompts for username and generates the report.
"""
print("---Welcome to the GitHub Profile Analyzer🧠---\n")
print("This tool analyzes any public GitHub profile and generates a detailed report in Markdown(.md) format.\n")
username = input("Enter a GitHub username: ").strip()
if not username:
print("Error: Username cannot be empty.")
return
# Fetch user data
user_data = get_user_data(username)
if not user_data:
return
# Fetch repositories
repos = get_repositories(username)
if not repos:
print("No public repositories found.")
return
# Calculate language stats
language_stats = calculate_language_stats(repos, username)
# Calculate total stars
total_stars = calculate_total_stars(repos)
# Plot top languages
languages_plot(language_stats, top_n=10)
# Generate markdown report
generate_markdown_report(username, user_data, repos, language_stats, total_stars)
print("\n---Analysis complete!---")
if __name__ == "__main__":
main()