Repository navigation
Expand file tree
/
Copy pathgithub_data_scraper.py
More file actions
364 lines (317 loc) · 15.1 KB
/
Copy pathgithub_data_scraper.py
File metadata and controls
364 lines (317 loc) · 15.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
"""
GitHub Data-Tools Market Scan
=============================
Collects public repository data for popular data-analysis topics from the
GitHub REST API, cleans it, and exports an analysis-ready Excel report.
Demonstrates:
- API pagination and rate-limit handling (waits for reset, retries on errors)
- Data cleaning: de-duplication, type conversion, missing values, text cleanup
- Excel reporting: formatted data table, live formula summary, charts,
data dictionary and run log
Usage:
pip install requests pandas openpyxl
python github_data_scraper.py
# optional: set GITHUB_TOKEN for higher rate limits
For Contributions:
- Please submit a GitHub issue or pull request if you have suggestions or
improvements. (https://github.com/talalondata/github-data-tools-scraper/)
"""
import logging
import os
import re
import time
from datetime import datetime, timezone
import pandas as pd
import requests
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.table import Table, TableStyleInfo
# ---------------------------------------------------------------- settings
TOPICS = ["pandas", "web-scraping", "data-visualization", "data-cleaning", "etl"]
PAGES_PER_TOPIC = 2 # 100 repos per page
PER_PAGE = 100
OUTPUT_XLSX = "github_data_tools_report.xlsx"
OUTPUT_CSV = "github_data_tools_clean.csv"
API_URL = "https://api.github.com/search/repositories"
MAX_RETRIES = 4
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("scraper")
# ---------------------------------------------------------------- extract
def make_session() -> requests.Session:
s = requests.Session()
s.headers.update({"Accept": "application/vnd.github+json",
"User-Agent": "portfolio-data-scraper"})
token = os.getenv("GITHUB_TOKEN")
if token:
s.headers["Authorization"] = f"Bearer {token}"
return s
def get_page(session, topic, page):
"""Fetch one page of results, waiting out rate limits and retrying errors."""
params = {"q": f"topic:{topic}", "sort": "stars", "order": "desc",
"per_page": PER_PAGE, "page": page}
for attempt in range(1, MAX_RETRIES + 1):
try:
r = session.get(API_URL, params=params, timeout=30)
except requests.RequestException as e:
wait = 2 ** attempt
log.warning("Network error (%s); retrying in %ss", e, wait)
time.sleep(wait)
continue
remaining = int(r.headers.get("X-RateLimit-Remaining", 1))
if r.status_code == 200:
if remaining == 0: # pre-emptively wait before the next call
_sleep_until(r.headers.get("X-RateLimit-Reset"))
return r.json().get("items", [])
if r.status_code in (403, 429):
log.warning("Rate limited on %s p%s; waiting for reset", topic, page)
_sleep_until(r.headers.get("X-RateLimit-Reset"))
continue
if r.status_code >= 500:
time.sleep(2 ** attempt)
continue
log.error("HTTP %s for %s p%s: %s", r.status_code, topic, page, r.text[:200])
return []
log.error("Gave up on %s p%s after %s attempts", topic, page, MAX_RETRIES)
return []
def _sleep_until(reset_header):
reset = int(reset_header or time.time() + 60)
wait = max(reset - int(time.time()), 0) + 2
log.info("Sleeping %ss for rate-limit reset", wait)
time.sleep(wait)
def extract(session):
rows, run_log = [], []
for topic in TOPICS:
for page in range(1, PAGES_PER_TOPIC + 1):
items = get_page(session, topic, page)
log.info("%-20s page %s -> %s repos", topic, page, len(items))
run_log.append({"Topic": topic, "Page": page, "Records": len(items)})
for it in items:
rows.append({
"repo_id": it.get("id"),
"full_name": it.get("full_name"),
"owner_type": (it.get("owner") or {}).get("type"),
"description": it.get("description"),
"language": it.get("language"),
"stars": it.get("stargazers_count"),
"forks": it.get("forks_count"),
"open_issues": it.get("open_issues_count"),
"license": (it.get("license") or {}).get("spdx_id"),
"created_at": it.get("created_at"),
"pushed_at": it.get("pushed_at"),
"archived": it.get("archived"),
"url": it.get("html_url"),
"source_topic": topic,
})
if len(items) < PER_PAGE:
break
return pd.DataFrame(rows), pd.DataFrame(run_log)
# ---------------------------------------------------------------- clean
def clean(raw: pd.DataFrame):
stats = {"Raw records": len(raw)}
df = raw.copy()
# Repos tagged with several topics appear more than once: keep one row,
# and record every matching topic.
topics = df.groupby("repo_id")["source_topic"].apply(lambda s: ", ".join(sorted(set(s))))
df = df.drop_duplicates("repo_id").drop(columns="source_topic")
df["matched_topics"] = df["repo_id"].map(topics)
stats["Duplicates removed"] = stats["Raw records"] - len(df)
# Text cleanup: strip emoji/control chars, collapse whitespace, fill blanks
def tidy(text):
if not isinstance(text, str) or not text.strip():
return "(no description)"
text = re.sub(r"[^\x20-\x7E\u00A0-\u024F]", "", text)
return re.sub(r"\s+", " ", text).strip()[:250] or "(no description)"
stats["Missing descriptions filled"] = int(df["description"].isna().sum())
df["description"] = df["description"].map(tidy)
stats["Missing language filled"] = int(df["language"].isna().sum())
df["language"] = df["language"].fillna("Unspecified")
df["license"] = df["license"].replace({"NOASSERTION": "Other"}).fillna("None")
df["owner_type"] = df["owner_type"].fillna("Unknown")
# Types
for col in ("stars", "forks", "open_issues"):
df[col] = pd.to_numeric(df[col], errors="coerce").fillna(0).astype(int)
for col in ("created_at", "pushed_at"):
df[col] = pd.to_datetime(df[col], utc=True).dt.tz_localize(None).dt.date
df["archived"] = df["archived"].map({True: "Yes", False: "No"}).fillna("No")
# Derived fields
today = datetime.now(timezone.utc).date()
df["days_since_push"] = df["pushed_at"].map(lambda d: (today - d).days)
df["status"] = pd.cut(df["days_since_push"], [-1, 90, 365, 10**6],
labels=["Active", "Slowing", "Stale"]).astype(str)
df.loc[df["archived"] == "Yes", "status"] = "Archived"
df = df.sort_values("stars", ascending=False).reset_index(drop=True)
stats["Clean records"] = len(df)
return df, stats
# ---------------------------------------------------------------- report
HEADERS = {
"full_name": ("Repository", "owner/name on GitHub"),
"description": ("Description", "Repo description; emoji removed, blanks filled with '(no description)'"),
"language": ("Language", "Main language; 'Unspecified' when GitHub reports none"),
"stars": ("Stars", "Stargazer count at time of collection"),
"forks": ("Forks", "Fork count"),
"open_issues": ("Open Issues", "Open issues + pull requests"),
"license": ("License", "SPDX licence id; 'None' if absent, 'Other' if unrecognised"),
"owner_type": ("Owner Type", "User or Organization"),
"created_at": ("Created", "Date the repo was created"),
"pushed_at": ("Last Push", "Date of the most recent push"),
"days_since_push": ("Days Since Push", "Days between last push and collection date"),
"status": ("Status", "Active <=90 days, Slowing <=365, Stale >365, or Archived"),
"matched_topics": ("Matched Topics", "Which searched topics returned this repo (de-duplicated)"),
"url": ("URL", "Link to the repository"),
}
FONT = "Arial"
HEAD_FILL = PatternFill("solid", fgColor="1F4E79")
HEAD_FONT = Font(name=FONT, bold=True, color="FFFFFF")
BODY = Font(name=FONT, size=10)
TITLE = Font(name=FONT, size=16, bold=True, color="1F4E79")
THIN = Border(bottom=Side(style="thin", color="BFBFBF"))
def write_report(df, stats, run_log, path):
wb = Workbook()
summary = wb.active
summary.title = "Summary"
data = wb.create_sheet("Repositories")
dictionary = wb.create_sheet("Data Dictionary")
logsheet = wb.create_sheet("Run Log")
# ---- Repositories sheet (Excel table)
cols = list(HEADERS)
data.append([HEADERS[c][0] for c in cols])
for rec in df[cols].itertuples(index=False):
data.append(list(rec))
n = len(df) + 1
last_col = get_column_letter(len(cols))
tbl = Table(displayName="Repos", ref=f"A1:{last_col}{n}")
tbl.tableStyleInfo = TableStyleInfo(name="TableStyleMedium2", showRowStripes=True)
data.add_table(tbl)
widths = [34, 60, 14, 10, 10, 11, 14, 13, 12, 12, 14, 11, 40, 45]
for i, w in enumerate(widths, 1):
data.column_dimensions[get_column_letter(i)].width = w
for row in data.iter_rows(min_row=2, max_row=n):
for c in row:
c.font = BODY
for col in ("D", "E", "F", "K"):
for c in data[col][1:]:
c.number_format = "#,##0"
for col in ("I", "J"):
for c in data[col][1:]:
c.number_format = "yyyy-mm-dd"
for c in data["N"][1:]:
c.hyperlink = c.value
data.freeze_panes = "B2"
# ---- Summary sheet (formulas point at the Repositories sheet)
R = f"Repositories!$%s$2:$%s${n}"
rng = {k: R % (v, v) for k, v in
{"name": "A", "lang": "C", "stars": "D", "forks": "E", "status": "L", "lic": "G"}.items()}
summary["A1"] = "GitHub Data-Tools Market Scan"
summary["A1"].font = TITLE
summary["A2"] = (f"Topics: {', '.join(TOPICS)} | Collected "
f"{datetime.now(timezone.utc):%Y-%m-%d} via GitHub REST API")
summary["A2"].font = Font(name=FONT, size=10, italic=True, color="595959")
def header(row, labels):
for j, lab in enumerate(labels):
c = summary.cell(row=row, column=1 + j, value=lab)
c.font, c.fill = HEAD_FONT, HEAD_FILL
header(4, ["Key metric", "Value"])
kpis = [
("Repositories analysed", f"=COUNTA({rng['name']})", "#,##0"),
("Total stars", f"=SUM({rng['stars']})", "#,##0"),
("Median stars", f"=MEDIAN({rng['stars']})", "#,##0"),
("Total forks", f"=SUM({rng['forks']})", "#,##0"),
("Share actively maintained", f'=COUNTIF({rng["status"]},"Active")/B5', "0.0%"),
("Share with no licence", f'=COUNTIF({rng["lic"]},"None")/B5', "0.0%"),
]
for i, (lab, f, fmt) in enumerate(kpis, start=5):
summary.cell(row=i, column=1, value=lab).font = BODY
c = summary.cell(row=i, column=2, value=f)
c.font, c.number_format = Font(name=FONT, size=10, bold=True), fmt
for col in (1, 2):
summary.cell(row=i, column=col).border = THIN
# Language table (top 8 by repo count, labels from Python, numbers by formula)
top_lang = df["language"].value_counts().head(8).index.tolist()
header(12, ["Language", "Repos", "Total stars", "Avg stars"])
for i, lang in enumerate(top_lang, start=13):
summary.cell(row=i, column=1, value=lang)
summary.cell(row=i, column=2, value=f"=COUNTIF({rng['lang']},A{i})")
summary.cell(row=i, column=3, value=f"=SUMIF({rng['lang']},A{i},{rng['stars']})")
summary.cell(row=i, column=4, value=f"=IFERROR(C{i}/B{i},0)")
for col in range(1, 5):
c = summary.cell(row=i, column=col)
c.font, c.border = BODY, THIN
if col > 1:
c.number_format = "#,##0"
lang_end = 12 + len(top_lang)
# Status table
st_start = lang_end + 2
header(st_start, ["Maintenance status", "Repos", "Share"])
for k, s in enumerate(["Active", "Slowing", "Stale", "Archived"], start=1):
r = st_start + k
summary.cell(row=r, column=1, value=s)
summary.cell(row=r, column=2, value=f"=COUNTIF({rng['status']},A{r})")
summary.cell(row=r, column=3, value=f"=B{r}/$B$5")
for col in range(1, 4):
c = summary.cell(row=r, column=col)
c.font, c.border = BODY, THIN
summary.cell(row=r, column=3).number_format = "0.0%"
st_end = st_start + 4
# Cleaning stats
cl_start = st_end + 2
header(cl_start, ["Data cleaning step", "Count"])
for k, (lab, val) in enumerate(stats.items(), start=1):
summary.cell(row=cl_start + k, column=1, value=lab).font = BODY
c = summary.cell(row=cl_start + k, column=2, value=val)
c.font, c.number_format = BODY, "#,##0"
summary.cell(row=cl_start + len(stats) + 1, column=1,
value="Counts are hardcoded outputs of the cleaning script.").font = \
Font(name=FONT, size=9, italic=True, color="7F7F7F")
for col, w in zip("ABCD", (32, 16, 14, 12)):
summary.column_dimensions[col].width = w
# Charts
ch = BarChart()
ch.type, ch.title, ch.style = "bar", "Repositories by language", 10
ch.add_data(Reference(summary, min_col=2, min_row=12, max_row=lang_end), titles_from_data=True)
ch.set_categories(Reference(summary, min_col=1, min_row=13, max_row=lang_end))
ch.legend, ch.height, ch.width = None, 8, 14
ch.y_axis.majorGridlines = None
summary.add_chart(ch, "F4")
ch2 = BarChart()
ch2.title, ch2.style = "Maintenance status", 10
ch2.add_data(Reference(summary, min_col=2, min_row=st_start, max_row=st_end), titles_from_data=True)
ch2.set_categories(Reference(summary, min_col=1, min_row=st_start + 1, max_row=st_end))
ch2.legend, ch2.height, ch2.width = None, 7, 14
summary.add_chart(ch2, "F21")
# ---- Data dictionary
dictionary.append(["Column", "Meaning / cleaning rule"])
for c in cols:
dictionary.append(list(HEADERS[c]))
dictionary.column_dimensions["A"].width = 18
dictionary.column_dimensions["B"].width = 80
for c in dictionary[1]:
c.font, c.fill = HEAD_FONT, HEAD_FILL
for row in dictionary.iter_rows(min_row=2):
for c in row:
c.font = BODY
# ---- Run log
logsheet.append(["Topic", "Page", "Records"])
for rec in run_log.itertuples(index=False):
logsheet.append(list(rec))
for c in logsheet[1]:
c.font, c.fill = HEAD_FONT, HEAD_FILL
logsheet.column_dimensions["A"].width = 22
for ws in (summary, dictionary, logsheet):
ws.sheet_view.showGridLines = False
wb.save(path)
# ---------------------------------------------------------------- main
def main():
session = make_session()
raw, run_log = extract(session)
if raw.empty:
raise SystemExit("No data collected - check network or rate limits.")
df, stats = clean(raw)
df.to_csv(OUTPUT_CSV, index=False)
write_report(df, stats, run_log, OUTPUT_XLSX)
log.info("Done: %s clean rows -> %s, %s", len(df), OUTPUT_XLSX, OUTPUT_CSV)
for k, v in stats.items():
log.info(" %-28s %s", k, v)
if __name__ == "__main__":
main()