mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(generator): scaffold + move widgets/themes/models/utils/processor/config
- Add generator/requirements.txt and generator/pytest.ini - git mv src/widgets, themes, models, utils, data/processor.py, config.py into generator/src/ - Fix relative imports in processor.py (moved up one level: .. → .) - Append service-specific env vars (PORT, DB paths, FETCHER_URL, etc.) to generator/src/config.py - git rm retired src/db, src/data/__init__.py, src/__init__.py Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
cb3ace8dcd
commit
3525144aeb
@@ -0,0 +1,542 @@
|
||||
"""GitHub data processing and widget generation."""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from collections import defaultdict
|
||||
|
||||
from ..models import (
|
||||
GradeData,
|
||||
TagData,
|
||||
ImpactWeek,
|
||||
CollaboratorData,
|
||||
FocusCategory,
|
||||
LanguageData,
|
||||
)
|
||||
from ..widgets import (
|
||||
render_grade_widget,
|
||||
render_impact_widget,
|
||||
render_collaborators_widget,
|
||||
render_focus_widget,
|
||||
render_languages_widget,
|
||||
)
|
||||
|
||||
|
||||
def compute_grade(github_data: dict, custom_tags: list[str] = None) -> GradeData:
|
||||
"""
|
||||
Compute a developer grade from GitHub profile data.
|
||||
|
||||
Args:
|
||||
github_data: GitHub profile data dictionary
|
||||
custom_tags: Optional list of custom tags to include (e.g., ["open-source", "hackathon-winner"])
|
||||
"""
|
||||
user = github_data["user"]
|
||||
repos = github_data["repos"]
|
||||
events = github_data["events"]
|
||||
|
||||
# Use accurate contribution count (commits + PRs + issues + reviews) from GraphQL
|
||||
commits = github_data.get("total_commits", 0)
|
||||
|
||||
# Fallback to daily contribution data if aggregation didn't work
|
||||
if commits == 0:
|
||||
daily_contribs = github_data.get("commits", [])
|
||||
if daily_contribs and isinstance(daily_contribs, list) and len(daily_contribs) > 0:
|
||||
if isinstance(daily_contribs[0], dict) and "count" in daily_contribs[0]:
|
||||
commits = sum(day.get("count", 0) for day in daily_contribs)
|
||||
else:
|
||||
commits = len(daily_contribs)
|
||||
else:
|
||||
commits = sum(
|
||||
len(ev.get("payload", {}).get("commits", []))
|
||||
for ev in events if ev.get("type") == "PushEvent"
|
||||
)
|
||||
|
||||
repo_count = min(len(repos), 50)
|
||||
stars = sum(r.get("stargazers_count", 0) for r in repos)
|
||||
forks = sum(r.get("forks_count", 0) for r in repos)
|
||||
followers = user.get("followers", 0)
|
||||
|
||||
# Use accurate PR count from search API
|
||||
prs = github_data.get("total_prs", 0)
|
||||
|
||||
# Fallback to events if not available
|
||||
if prs == 0:
|
||||
prs = sum(1 for ev in events if ev.get("type") == "PullRequestEvent")
|
||||
|
||||
scores = {
|
||||
"repos": min(repo_count / 30 * 100, 100),
|
||||
"stars": min(stars / 200 * 100, 100),
|
||||
"forks": min(forks / 50 * 100, 100),
|
||||
"followers": min(followers / 100 * 100, 100),
|
||||
"activity": min(len(events) / 80 * 100, 100),
|
||||
}
|
||||
|
||||
total = sum(scores.values()) / len(scores)
|
||||
|
||||
# Grade scale
|
||||
if total >= 97:
|
||||
grade = "S++"
|
||||
elif total >= 93:
|
||||
grade = "S+"
|
||||
elif total >= 89:
|
||||
grade = "S"
|
||||
elif total >= 86:
|
||||
grade = "A++"
|
||||
elif total >= 82:
|
||||
grade = "A+"
|
||||
elif total >= 78:
|
||||
grade = "A"
|
||||
elif total >= 72:
|
||||
grade = "A-"
|
||||
elif total >= 68:
|
||||
grade = "B++"
|
||||
elif total >= 64:
|
||||
grade = "B+"
|
||||
elif total >= 58:
|
||||
grade = "B"
|
||||
elif total >= 50:
|
||||
grade = "B-"
|
||||
elif total >= 42:
|
||||
grade = "C+"
|
||||
elif total >= 35:
|
||||
grade = "C"
|
||||
elif total >= 28:
|
||||
grade = "C-"
|
||||
elif total >= 20:
|
||||
grade = "D+"
|
||||
elif total >= 12:
|
||||
grade = "D"
|
||||
elif total >= 5:
|
||||
grade = "D-"
|
||||
else:
|
||||
grade = "F"
|
||||
|
||||
stats = {
|
||||
"commits": commits,
|
||||
"prs": prs,
|
||||
"stars": stars,
|
||||
"repos": repo_count,
|
||||
"followers": followers,
|
||||
}
|
||||
|
||||
tags = _compute_tags(github_data, custom_tags=custom_tags, hidden_languages=None)
|
||||
|
||||
return GradeData(
|
||||
grade=grade,
|
||||
score=round(total, 1),
|
||||
stats=stats,
|
||||
tags=tags,
|
||||
breakdown={k: round(v, 1) for k, v in scores.items()},
|
||||
)
|
||||
|
||||
|
||||
def _compute_tags(github_data: dict, max_tags: int = None, custom_tags: list[str] = None, hidden_languages: list[str] = None) -> list[TagData]:
|
||||
"""
|
||||
Infer developer tags from repo languages and topics using percentage thresholds.
|
||||
|
||||
Tags are awarded based on:
|
||||
- Frontend: >50% frontend languages
|
||||
- Backend: >50% backend languages
|
||||
- ML: >25% ML-related languages
|
||||
- Fullstack: >25% frontend AND >25% backend
|
||||
- Systems: >50% systems languages
|
||||
- DevOps: >25% DevOps-related languages
|
||||
- Mobile: >50% mobile languages
|
||||
|
||||
Args:
|
||||
github_data: GitHub data dictionary
|
||||
max_tags: Maximum number of tags to return (1-20). Defaults to TAG_MAX_COUNT from config.
|
||||
custom_tags: Optional list of custom tags to add (e.g., ["open-source", "hackathon-winner"])
|
||||
hidden_languages: Optional list of languages to exclude from tag calculation
|
||||
|
||||
Returns:
|
||||
List of TagData objects with inferred developer roles
|
||||
"""
|
||||
from ..config import TAG_MAX_COUNT, TAG_LANGUAGE_MAP, TAG_TOPIC_MAP, HIDDEN_LANGUAGES
|
||||
|
||||
if max_tags is None:
|
||||
max_tags = TAG_MAX_COUNT
|
||||
max_tags = min(max(max_tags, 1), 20) # Clamp between 1 and 20
|
||||
|
||||
if hidden_languages is None:
|
||||
hidden_languages = HIDDEN_LANGUAGES
|
||||
|
||||
repos = github_data["repos"]
|
||||
lang_counts = defaultdict(int)
|
||||
topic_set = set()
|
||||
|
||||
for r in repos:
|
||||
lang = r.get("language")
|
||||
if lang and lang not in hidden_languages:
|
||||
lang_counts[lang] += 1
|
||||
for topic in r.get("topics", []):
|
||||
topic_set.add(topic.lower())
|
||||
|
||||
tags = []
|
||||
total = sum(lang_counts.values()) or 1
|
||||
|
||||
# Calculate percentage for each category
|
||||
category_percentages = defaultdict(float)
|
||||
|
||||
for lang, count in lang_counts.items():
|
||||
pct = count / total
|
||||
for category in TAG_LANGUAGE_MAP.get(lang, []):
|
||||
category_percentages[category] += pct
|
||||
|
||||
# Infer tags from repository topics
|
||||
for topic in topic_set:
|
||||
if topic in TAG_TOPIC_MAP:
|
||||
category = TAG_TOPIC_MAP[topic]
|
||||
category_percentages[category] = max(category_percentages[category], 0.3)
|
||||
|
||||
# Apply threshold rules
|
||||
awarded_tags = []
|
||||
|
||||
# Fullstack: >25% frontend AND >25% backend
|
||||
if category_percentages.get("Frontend", 0) > 0.25 and category_percentages.get("Backend", 0) > 0.25:
|
||||
awarded_tags.append(("fullstack", max(category_percentages.get("Frontend", 0), category_percentages.get("Backend", 0))))
|
||||
|
||||
# ML: >25%
|
||||
if category_percentages.get("ML", 0) > 0.25:
|
||||
awarded_tags.append(("ml-engineer", category_percentages["ML"]))
|
||||
|
||||
# Backend: >50%
|
||||
if category_percentages.get("Backend", 0) > 0.50:
|
||||
awarded_tags.append(("backend", category_percentages["Backend"]))
|
||||
|
||||
# Frontend: >50%
|
||||
if category_percentages.get("Frontend", 0) > 0.50:
|
||||
awarded_tags.append(("frontend", category_percentages["Frontend"]))
|
||||
|
||||
# Systems: >50%
|
||||
if category_percentages.get("Systems", 0) > 0.50:
|
||||
awarded_tags.append(("systems", category_percentages["Systems"]))
|
||||
|
||||
# DevOps: >25%
|
||||
if category_percentages.get("DevOps", 0) > 0.25:
|
||||
awarded_tags.append(("devops", category_percentages["DevOps"]))
|
||||
|
||||
# Mobile: >50%
|
||||
if category_percentages.get("Mobile", 0) > 0.50:
|
||||
awarded_tags.append(("mobile", category_percentages["Mobile"]))
|
||||
|
||||
# Database: >25%
|
||||
if category_percentages.get("Database", 0) > 0.25:
|
||||
awarded_tags.append(("database", category_percentages["Database"]))
|
||||
|
||||
# Cloud: >25%
|
||||
if category_percentages.get("Cloud", 0) > 0.25:
|
||||
awarded_tags.append(("cloud", category_percentages["Cloud"]))
|
||||
|
||||
# Security: >25%
|
||||
if category_percentages.get("Security", 0) > 0.25:
|
||||
awarded_tags.append(("security", category_percentages["Security"]))
|
||||
|
||||
# Add custom tags with high confidence
|
||||
if custom_tags:
|
||||
for tag in custom_tags:
|
||||
awarded_tags.append((tag, 1.0))
|
||||
|
||||
# Sort by confidence and limit to max_tags
|
||||
for tag, conf in sorted(awarded_tags, key=lambda x: -x[1])[:max_tags]:
|
||||
tags.append(TagData(tag=tag, source="earned" if conf < 1.0 else "custom", confidence=round(conf, 2)))
|
||||
|
||||
return tags
|
||||
|
||||
|
||||
def compute_impact_timeline(github_data: dict) -> list[ImpactWeek]:
|
||||
"""Aggregate daily contributions into weekly impact data using GitHub's contribution calendar."""
|
||||
daily_contributions = github_data.get("commits", [])
|
||||
weekly = defaultdict(lambda: {"commits": 0})
|
||||
|
||||
# Calculate date boundaries
|
||||
now = datetime.now()
|
||||
current_week_start = (now - timedelta(days=now.weekday())).replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
six_months_ago = now - timedelta(days=180)
|
||||
|
||||
if daily_contributions and isinstance(daily_contributions, list) and len(daily_contributions) > 0:
|
||||
# Use GraphQL daily contribution data (format: [{"date": "YYYY-MM-DD", "count": N}])
|
||||
if isinstance(daily_contributions[0], dict) and "date" in daily_contributions[0] and "count" in daily_contributions[0]:
|
||||
for day_data in daily_contributions:
|
||||
date_str = day_data.get("date", "")
|
||||
count = day_data.get("count", 0)
|
||||
|
||||
if date_str:
|
||||
dt = datetime.fromisoformat(date_str)
|
||||
|
||||
# Calculate week start (Monday)
|
||||
week_start_dt = dt - timedelta(days=dt.weekday())
|
||||
week_start_str = week_start_dt.isoformat()[:10]
|
||||
|
||||
# Only include last 6 months, excluding current week
|
||||
if dt >= six_months_ago and week_start_dt < current_week_start:
|
||||
weekly[week_start_str]["commits"] += count
|
||||
else:
|
||||
# Old REST API format fallback
|
||||
for commit in daily_contributions:
|
||||
commit_date = commit.get("commit", {}).get("author", {}).get("date", "")
|
||||
if commit_date:
|
||||
created = commit_date[:10]
|
||||
dt = datetime.fromisoformat(created)
|
||||
|
||||
# Calculate week start (Monday)
|
||||
week_start_dt = dt - timedelta(days=dt.weekday())
|
||||
week_start_str = week_start_dt.isoformat()[:10]
|
||||
|
||||
# Only include last 6 months, excluding current week
|
||||
if dt >= six_months_ago and week_start_dt < current_week_start:
|
||||
weekly[week_start_str]["commits"] += 1
|
||||
else:
|
||||
# Fallback to events-based counting
|
||||
events = github_data.get("events", [])
|
||||
for ev in events:
|
||||
if ev.get("type") == "PushEvent":
|
||||
created = ev.get("created_at", "")[:10]
|
||||
if created:
|
||||
dt = datetime.fromisoformat(created)
|
||||
|
||||
# Calculate week start (Monday)
|
||||
week_start_dt = dt - timedelta(days=dt.weekday())
|
||||
week_start_str = week_start_dt.isoformat()[:10]
|
||||
|
||||
# Only include last 6 months, excluding current week
|
||||
if dt >= six_months_ago and week_start_dt < current_week_start:
|
||||
commits = len(ev.get("payload", {}).get("commits", []))
|
||||
weekly[week_start_str]["commits"] += commits
|
||||
|
||||
weeks = []
|
||||
for ws in sorted(weekly.keys()):
|
||||
d = weekly[ws]
|
||||
weeks.append(ImpactWeek(week_start=ws, commits=d["commits"]))
|
||||
|
||||
return weeks
|
||||
|
||||
|
||||
def compute_collaborators(github_data: dict) -> list[CollaboratorData]:
|
||||
"""
|
||||
Return top collaborators from pre-scored data produced by _fetch_collaborators_data.
|
||||
|
||||
The scoring (min(user_commits, their_commits) with owner boost and multi-repo
|
||||
weighting) happens in the fetcher so the widget just picks the top K.
|
||||
"""
|
||||
scored = github_data.get("collaborators_data", [])
|
||||
|
||||
# Fallback to events-based if collaborator scoring produced nothing
|
||||
if not scored:
|
||||
return _compute_collaborators_from_events(github_data)
|
||||
|
||||
collabs = []
|
||||
for s in scored[:5]:
|
||||
collabs.append(
|
||||
CollaboratorData(
|
||||
username=s["login"],
|
||||
shared_repos=s["shared_repos"],
|
||||
shared_commits=int(round(s["raw_score"])),
|
||||
avatar_b64="",
|
||||
)
|
||||
)
|
||||
return collabs
|
||||
|
||||
|
||||
def _compute_collaborators_from_events(github_data: dict) -> list[CollaboratorData]:
|
||||
"""Fallback: compute collaborators from events (less accurate)."""
|
||||
events = github_data["events"]
|
||||
me = github_data["user"].get("login", "").lower()
|
||||
collab_stats = defaultdict(lambda: {"repos": set(), "commits": 0})
|
||||
|
||||
for ev in events:
|
||||
actor = ev.get("actor", {}).get("login", "")
|
||||
if actor.lower() != me:
|
||||
repo = ev.get("repo", {}).get("name", "")
|
||||
collab_stats[actor]["repos"].add(repo)
|
||||
collab_stats[actor]["commits"] += 1
|
||||
|
||||
collabs = []
|
||||
for username, stats in sorted(
|
||||
collab_stats.items(), key=lambda x: -x[1]["commits"]
|
||||
)[:4]: # Match the main function: top 4
|
||||
collabs.append(
|
||||
CollaboratorData(
|
||||
username=username,
|
||||
shared_repos=len(stats["repos"]),
|
||||
shared_commits=stats["commits"],
|
||||
)
|
||||
)
|
||||
|
||||
return collabs
|
||||
|
||||
|
||||
def compute_focus(github_data: dict, hidden_languages: list[str] = None) -> list[FocusCategory]:
|
||||
"""
|
||||
Classify contributions into focus categories based on repo languages weighted by activity.
|
||||
|
||||
Args:
|
||||
github_data: GitHub profile data
|
||||
hidden_languages: Optional list of languages to exclude
|
||||
"""
|
||||
from ..config import HIDDEN_LANGUAGES
|
||||
|
||||
if hidden_languages is None:
|
||||
hidden_languages = HIDDEN_LANGUAGES
|
||||
|
||||
repos = github_data["repos"]
|
||||
total_contributions = github_data.get("recent_commits", 0) # Last 6 months
|
||||
|
||||
# Map languages to focus categories (languages can belong to multiple categories)
|
||||
lang_to_focus = {
|
||||
"Python": ["Backend", "ML"],
|
||||
"JavaScript": ["Frontend"],
|
||||
"TypeScript": ["Frontend"],
|
||||
"HTML": ["Frontend"],
|
||||
"CSS": ["Frontend"],
|
||||
"Vue": ["Frontend"],
|
||||
"React": ["Frontend"],
|
||||
"Go": ["Backend"],
|
||||
"Rust": ["Backend", "Systems"],
|
||||
"Java": ["Backend"],
|
||||
"C++": ["Systems"],
|
||||
"C": ["Systems"],
|
||||
"Ruby": ["Backend"],
|
||||
"PHP": ["Backend"],
|
||||
"Shell": ["DevOps"],
|
||||
"Dockerfile": ["DevOps"],
|
||||
"Makefile": ["DevOps"],
|
||||
"Jupyter Notebook": ["ML"],
|
||||
"R": ["ML"],
|
||||
"Scala": ["Backend", "ML"],
|
||||
"Kotlin": ["Backend", "Mobile"],
|
||||
"Swift": ["Mobile"],
|
||||
"Objective-C": ["Mobile"],
|
||||
}
|
||||
|
||||
focus_counts = defaultdict(float)
|
||||
|
||||
# Use top 30 most recently pushed repos
|
||||
sorted_repos = sorted(repos, key=lambda r: r.get("pushed_at", ""), reverse=True)
|
||||
active_repos = sorted_repos[:30]
|
||||
|
||||
# Count languages in active repos (excluding hidden languages)
|
||||
lang_weights = defaultdict(int)
|
||||
for r in active_repos:
|
||||
lang = r.get("language")
|
||||
if lang and lang not in hidden_languages:
|
||||
lang_weights[lang] += 1
|
||||
|
||||
total_weight = sum(lang_weights.values())
|
||||
|
||||
# Distribute contributions proportionally to language presence
|
||||
if total_weight > 0 and total_contributions > 0:
|
||||
for lang, weight in lang_weights.items():
|
||||
contribution_estimate = (weight / total_weight) * total_contributions
|
||||
|
||||
# Add to all applicable focus categories
|
||||
if lang in lang_to_focus:
|
||||
for focus in lang_to_focus[lang]:
|
||||
focus_counts[focus] += contribution_estimate
|
||||
else:
|
||||
focus_counts["Other"] += contribution_estimate
|
||||
else:
|
||||
# Fallback: use repo counts
|
||||
for r in active_repos:
|
||||
lang = r.get("language")
|
||||
if lang in lang_to_focus:
|
||||
for focus in lang_to_focus[lang]:
|
||||
focus_counts[focus] += 1
|
||||
elif lang:
|
||||
focus_counts["Other"] += 1
|
||||
|
||||
# Use total contributions as the base for percentages (allows overlap > 100%)
|
||||
total = total_contributions if total_contributions > 0 else sum(focus_counts.values())
|
||||
total = total or 1
|
||||
|
||||
return [
|
||||
FocusCategory(
|
||||
category=cat,
|
||||
percentage=round(count / total * 100, 1),
|
||||
commit_count=int(count),
|
||||
)
|
||||
for cat, count in sorted(focus_counts.items(), key=lambda x: -x[1])
|
||||
]
|
||||
|
||||
|
||||
def compute_languages(github_data: dict, hidden_languages: list[str] = None) -> list[LanguageData]:
|
||||
"""
|
||||
Compute language distribution from repos.
|
||||
|
||||
Args:
|
||||
github_data: GitHub profile data
|
||||
hidden_languages: Optional list of languages to exclude (e.g., ["HTML", "CSS"])
|
||||
"""
|
||||
from ..config import HIDDEN_LANGUAGES
|
||||
|
||||
if hidden_languages is None:
|
||||
hidden_languages = HIDDEN_LANGUAGES
|
||||
|
||||
repos = github_data["repos"]
|
||||
lang_counts = defaultdict(int)
|
||||
for r in repos:
|
||||
lang = r.get("language")
|
||||
if lang and lang not in hidden_languages:
|
||||
lang_counts[lang] += 1
|
||||
|
||||
total = sum(lang_counts.values()) or 1
|
||||
return [
|
||||
LanguageData(
|
||||
language=lang,
|
||||
percentage=round(count / total * 100, 1),
|
||||
loc=count,
|
||||
)
|
||||
for lang, count in sorted(lang_counts.items(), key=lambda x: -x[1])
|
||||
]
|
||||
|
||||
|
||||
def generate_widgets_from_github(
|
||||
github_data: dict,
|
||||
theme: str = "dark",
|
||||
custom_tags: list[str] = None,
|
||||
hidden_languages: list[str] = None,
|
||||
enabled: list[str] = None,
|
||||
widget_settings: dict[str, dict] | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""
|
||||
Takes raw GitHub API data and returns rendered SVG strings
|
||||
for each widget type.
|
||||
|
||||
Args:
|
||||
github_data: GitHub profile data
|
||||
theme: Color theme name
|
||||
custom_tags: Optional list of custom tags to add to the grade widget
|
||||
hidden_languages: Optional list of languages to exclude from stats
|
||||
enabled: Optional list of widget keys to generate; others are skipped.
|
||||
Defaults to ENABLED_WIDGETS from config.
|
||||
widget_settings: Optional per-widget settings dict, keyed by widget name.
|
||||
Each value is a dict of settings for that widget's renderer.
|
||||
"""
|
||||
from ..config import ENABLED_WIDGETS
|
||||
|
||||
if enabled is None:
|
||||
enabled = ENABLED_WIDGETS
|
||||
enabled_set = set(enabled)
|
||||
ws = widget_settings or {}
|
||||
|
||||
widgets: dict[str, str] = {}
|
||||
|
||||
if "grade" in enabled_set:
|
||||
grade = compute_grade(github_data, custom_tags=custom_tags)
|
||||
widgets["grade"] = render_grade_widget(grade, theme, settings=ws.get("grade"))
|
||||
|
||||
if "impact" in enabled_set:
|
||||
impact = compute_impact_timeline(github_data)
|
||||
widgets["impact"] = render_impact_widget(impact, theme, settings=ws.get("impact"))
|
||||
|
||||
if "collaborators" in enabled_set:
|
||||
collabs = compute_collaborators(github_data)
|
||||
widgets["collaborators"] = render_collaborators_widget(collabs, theme, settings=ws.get("collaborators"))
|
||||
|
||||
if "focus" in enabled_set:
|
||||
focus = compute_focus(github_data, hidden_languages=hidden_languages)
|
||||
widgets["focus"] = render_focus_widget(focus, theme, period="1y", settings=ws.get("focus"))
|
||||
|
||||
if "languages" in enabled_set:
|
||||
languages = compute_languages(github_data, hidden_languages=hidden_languages)
|
||||
widgets["languages"] = render_languages_widget(languages, theme, settings=ws.get("languages"))
|
||||
|
||||
return widgets
|
||||
Reference in New Issue
Block a user