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,105 @@
|
||||
"""Configuration for GitHub widget generator."""
|
||||
|
||||
import os
|
||||
|
||||
# Collaborator settings
|
||||
COLLABORATOR_MAX_REPO_SIZE = int(os.getenv("COLLABORATOR_MAX_REPO_SIZE", "150"))
|
||||
"""Maximum contributors in a repo to be included (filters out huge OSS projects)."""
|
||||
|
||||
COLLABORATOR_TOP_REPOS = int(os.getenv("COLLABORATOR_TOP_REPOS", "30"))
|
||||
"""Safety cap on repos to scan for collaborators (ranked by user's own commit count)."""
|
||||
|
||||
SMALL_OWNED_REPO_SIZE = int(os.getenv("SMALL_OWNED_REPO_SIZE", "10"))
|
||||
"""User-owned repos with at most this many contributors are treated as 'tight' projects —
|
||||
single-repo collaborators in them bypass MIN_SHARED_REPOS (captures hackathon/side-project partners)."""
|
||||
|
||||
COLLABORATOR_LOOKBACK_DAYS = int(os.getenv("COLLABORATOR_LOOKBACK_DAYS", "365"))
|
||||
"""How far back to look for the user's commit activity (GraphQL contributionsCollection is capped at 1 year)."""
|
||||
|
||||
MEANINGFUL_MIN_COMMITS = int(os.getenv("MEANINGFUL_MIN_COMMITS", "3"))
|
||||
"""Minimum commits the user must have in a repo for it to count as 'meaningful' (kills drive-by commits)."""
|
||||
|
||||
FORK_MIN_COMMITS = int(os.getenv("FORK_MIN_COMMITS", "10"))
|
||||
"""For forks, require at least this many user commits — kills the 'forked a huge repo, made one commit' problem."""
|
||||
|
||||
OWNER_BOOST = float(os.getenv("OWNER_BOOST", "1.5"))
|
||||
"""Multiplier applied to collaborator scores in repos the user owns."""
|
||||
|
||||
MIN_SHARED_REPOS = int(os.getenv("MIN_SHARED_REPOS", "2"))
|
||||
"""A collaborator must share at least this many repos with the user — unless DEEP_COLLAB_THRESHOLD is hit."""
|
||||
|
||||
DEEP_COLLAB_THRESHOLD = int(os.getenv("DEEP_COLLAB_THRESHOLD", "25"))
|
||||
"""Single-repo escape hatch: a collaborator with raw_score above this qualifies even with only one shared repo."""
|
||||
|
||||
# Commit fetching settings
|
||||
COMMIT_MAX_REPOS = int(os.getenv("COMMIT_MAX_REPOS", "10"))
|
||||
"""Maximum number of repos to fetch commits from."""
|
||||
|
||||
COMMIT_PER_REPO = int(os.getenv("COMMIT_PER_REPO", "30"))
|
||||
"""Number of commits to fetch per repository."""
|
||||
|
||||
# API settings
|
||||
API_TIMEOUT = int(os.getenv("API_TIMEOUT", "5"))
|
||||
"""Timeout in seconds for API requests."""
|
||||
|
||||
# Data source
|
||||
DATA_SOURCE_TYPE = os.getenv("DATA_SOURCE", "direct")
|
||||
"""Data source type: 'direct' for immediate API calls, 'queued' for batch processing."""
|
||||
|
||||
# Widget settings
|
||||
WIDGET_ORDER = ["grade", "impact", "collaborators", "focus", "languages", "achievements"]
|
||||
"""Default order of widgets. Customize by reordering this list."""
|
||||
|
||||
ENABLED_WIDGETS = ["grade", "impact", "collaborators", "focus", "languages", "achievements"]
|
||||
"""Which widgets to display. Remove any you don't want to show."""
|
||||
|
||||
# Language filtering
|
||||
HIDDEN_LANGUAGES = []
|
||||
"""Languages to exclude from stats (e.g., ["HTML", "CSS", "Makefile"])."""
|
||||
|
||||
# Tag settings
|
||||
TAG_MAX_COUNT = int(os.getenv("TAG_MAX_COUNT", "6"))
|
||||
"""Maximum number of tags to display (1-20)."""
|
||||
|
||||
TAG_LANGUAGE_MAP = {
|
||||
"Python": ["ML", "Backend"],
|
||||
"JavaScript": ["Frontend"],
|
||||
"TypeScript": ["Frontend"],
|
||||
"HTML": ["Frontend"],
|
||||
"CSS": ["Frontend"],
|
||||
"Go": ["Backend"],
|
||||
"Rust": ["Systems", "Backend"],
|
||||
"Java": ["Backend"],
|
||||
"C++": ["Systems"],
|
||||
"C": ["Systems"],
|
||||
"Swift": ["Mobile"],
|
||||
"Kotlin": ["Mobile", "Backend"],
|
||||
"Ruby": ["Backend"],
|
||||
"PHP": ["Backend"],
|
||||
"Shell": ["DevOps"],
|
||||
"Dockerfile": ["DevOps"],
|
||||
"HCL": ["DevOps", "Cloud"],
|
||||
"Jupyter Notebook": ["ML"],
|
||||
}
|
||||
"""Map programming languages to developer role categories."""
|
||||
|
||||
TAG_TOPIC_MAP = {
|
||||
"machine-learning": "ML",
|
||||
"deep-learning": "ML",
|
||||
"ai": "ML",
|
||||
"frontend": "Frontend",
|
||||
"react": "Frontend",
|
||||
"vue": "Frontend",
|
||||
"backend": "Backend",
|
||||
"api": "Backend",
|
||||
"database": "Database",
|
||||
"devops": "DevOps",
|
||||
"docker": "DevOps",
|
||||
"kubernetes": "DevOps",
|
||||
"security": "Security",
|
||||
"cloud": "Cloud",
|
||||
"aws": "Cloud",
|
||||
"azure": "Cloud",
|
||||
"gcp": "Cloud",
|
||||
}
|
||||
"""Map repository topics to developer role categories."""
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Data models for GitHub profile widgets."""
|
||||
|
||||
from .types import (
|
||||
GradeData,
|
||||
TagData,
|
||||
ImpactWeek,
|
||||
CollaboratorData,
|
||||
FocusCategory,
|
||||
LanguageData,
|
||||
AchievementData,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"GradeData",
|
||||
"TagData",
|
||||
"ImpactWeek",
|
||||
"CollaboratorData",
|
||||
"FocusCategory",
|
||||
"LanguageData",
|
||||
"AchievementData",
|
||||
]
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Data class definitions for widget components."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
@dataclass
|
||||
class GradeData:
|
||||
grade: str # e.g. "A++", "S+", "B-"
|
||||
score: float # 0-100
|
||||
stats: dict # {"commits": 1423, "prs": 87, "stars": 342, "repos": 28, "followers": 156}
|
||||
tags: list # list of TagData
|
||||
breakdown: dict = field(default_factory=dict) # optional bar breakdown
|
||||
|
||||
|
||||
@dataclass
|
||||
class TagData:
|
||||
tag: str
|
||||
source: str = "earned" # "earned" | "chosen"
|
||||
confidence: float = 1.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class ImpactWeek:
|
||||
week_start: str # ISO date
|
||||
commits: int = 0
|
||||
additions: int = 0
|
||||
deletions: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class CollaboratorData:
|
||||
username: str
|
||||
avatar_b64: str = "" # base64 encoded avatar
|
||||
shared_repos: int = 0
|
||||
shared_commits: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class FocusCategory:
|
||||
category: str
|
||||
percentage: float
|
||||
commit_count: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class LanguageData:
|
||||
language: str
|
||||
percentage: float
|
||||
loc: int = 0 # lines of code or repo count
|
||||
|
||||
|
||||
@dataclass
|
||||
class AchievementData:
|
||||
title: str
|
||||
subtitle: str = ""
|
||||
event_date: str = ""
|
||||
icon: str = "trophy" # trophy, medal, star, hackathon
|
||||
@@ -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
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Theme configuration for widgets."""
|
||||
|
||||
from .themes import THEMES, TAG_COLORS, GRADE_COLORS, FOCUS_COLORS, LANG_COLORS
|
||||
|
||||
__all__ = ["THEMES", "TAG_COLORS", "GRADE_COLORS", "FOCUS_COLORS", "LANG_COLORS"]
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Theme definitions and color palettes."""
|
||||
|
||||
THEMES = {
|
||||
# --- Dark themes ---
|
||||
"dark": { # kept for backwards compat; "midnight" is the alias
|
||||
"bg": "#121820",
|
||||
"card_bg": "#1a2230",
|
||||
"card_border": "#2a3444",
|
||||
"text": "#d1d9e0",
|
||||
"text_secondary": "#7d8895",
|
||||
"accent": "#58a6ff",
|
||||
"green": "#3fb950",
|
||||
"orange": "#d29922",
|
||||
"red": "#f85149",
|
||||
"purple": "#bc8cff",
|
||||
"pink": "#f778ba",
|
||||
"grid": "#1e2836",
|
||||
},
|
||||
"onyx": { # high-contrast neon on pure black
|
||||
"bg": "#09090b",
|
||||
"card_bg": "#18181b",
|
||||
"card_border": "#27272a",
|
||||
"text": "#fafafa",
|
||||
"text_secondary": "#a1a1aa",
|
||||
"accent": "#a78bfa",
|
||||
"green": "#4ade80",
|
||||
"orange": "#fb923c",
|
||||
"red": "#f87171",
|
||||
"purple": "#c084fc",
|
||||
"pink": "#f472b6",
|
||||
"grid": "#27272a",
|
||||
},
|
||||
"nord": { # muted pastel on slate-blue — clearly cooler
|
||||
"bg": "#1e2433",
|
||||
"card_bg": "#2a3142",
|
||||
"card_border": "#3d4659",
|
||||
"text": "#e5e9f0",
|
||||
"text_secondary": "#8892a4",
|
||||
"accent": "#88c0d0",
|
||||
"green": "#a3be8c",
|
||||
"orange": "#ebcb8b",
|
||||
"red": "#bf616a",
|
||||
"purple": "#b48ead",
|
||||
"pink": "#d08770",
|
||||
"grid": "#333d50",
|
||||
},
|
||||
# --- Light themes ---
|
||||
"light": { # kept for backwards compat; "clean" is the alias
|
||||
"bg": "#ffffff",
|
||||
"card_bg": "#f6f8fa",
|
||||
"card_border": "#d8dee4",
|
||||
"text": "#24292f",
|
||||
"text_secondary": "#656d76",
|
||||
"accent": "#0969da",
|
||||
"green": "#1a7f37",
|
||||
"orange": "#9a6700",
|
||||
"red": "#cf222e",
|
||||
"purple": "#8250df",
|
||||
"pink": "#bf3989",
|
||||
"grid": "#eaeef2",
|
||||
},
|
||||
"paper": {
|
||||
"bg": "#faf8f5",
|
||||
"card_bg": "#f5f0eb",
|
||||
"card_border": "#e0d8cf",
|
||||
"text": "#3d3529",
|
||||
"text_secondary": "#7a7062",
|
||||
"accent": "#b45309",
|
||||
"green": "#4d7c0f",
|
||||
"orange": "#a16207",
|
||||
"red": "#b91c1c",
|
||||
"purple": "#7e22ce",
|
||||
"pink": "#be185d",
|
||||
"grid": "#ebe5dd",
|
||||
},
|
||||
}
|
||||
|
||||
# Aliases so the frontend can use friendly names
|
||||
THEMES["midnight"] = THEMES["dark"]
|
||||
THEMES["clean"] = THEMES["light"]
|
||||
|
||||
TAG_COLORS = {
|
||||
"ml-engineer": "#bc8cff",
|
||||
"frontend": "#58a6ff",
|
||||
"backend": "#3fb950",
|
||||
"fullstack": "#d29922",
|
||||
"devops": "#f0883e",
|
||||
"database": "#f778ba",
|
||||
"mobile": "#ff6b9d",
|
||||
"security": "#f85149",
|
||||
"data-science": "#79c0ff",
|
||||
"systems": "#7ee787",
|
||||
"cloud": "#58a6ff",
|
||||
"open-source": "#3fb950",
|
||||
}
|
||||
|
||||
GRADE_COLORS = {
|
||||
"S": "#ff6b9d",
|
||||
"A": "#3fb950",
|
||||
"B": "#58a6ff",
|
||||
"C": "#d29922",
|
||||
"D": "#f0883e",
|
||||
"F": "#f85149",
|
||||
}
|
||||
|
||||
FOCUS_COLORS = [
|
||||
"#58a6ff",
|
||||
"#3fb950",
|
||||
"#bc8cff",
|
||||
"#d29922",
|
||||
"#f0883e",
|
||||
"#f778ba",
|
||||
"#f85149",
|
||||
"#79c0ff",
|
||||
]
|
||||
|
||||
LANG_COLORS = {
|
||||
"Python": "#3572A5",
|
||||
"JavaScript": "#f1e05a",
|
||||
"TypeScript": "#3178c6",
|
||||
"Go": "#00ADD8",
|
||||
"Rust": "#dea584",
|
||||
"Java": "#b07219",
|
||||
"C++": "#f34b7d",
|
||||
"C": "#555555",
|
||||
"Ruby": "#701516",
|
||||
"Shell": "#89e051",
|
||||
"HTML": "#e34c26",
|
||||
"CSS": "#563d7c",
|
||||
"Kotlin": "#A97BFF",
|
||||
"Swift": "#F05138",
|
||||
"Jupyter Notebook": "#DA5B0B",
|
||||
"Dockerfile": "#384d54",
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Utility functions for SVG generation."""
|
||||
|
||||
from .svg_helpers import escape, card_wrapper, icon_svg
|
||||
|
||||
__all__ = ["escape", "card_wrapper", "icon_svg"]
|
||||
@@ -0,0 +1,43 @@
|
||||
"""SVG helper functions and utilities."""
|
||||
|
||||
|
||||
def escape(text: str) -> str:
|
||||
"""Escape special characters for SVG text."""
|
||||
return text.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
|
||||
|
||||
|
||||
def card_wrapper(inner_svg: str, width: int, height: int, theme: dict, title: str = "", id_prefix: str = "") -> str:
|
||||
"""Wraps content in a styled card with rounded corners and border.
|
||||
|
||||
Args:
|
||||
id_prefix: Optional prefix for SVG IDs to avoid conflicts when
|
||||
multiple widgets are inlined in the same document.
|
||||
"""
|
||||
shadow_id = f"{id_prefix}shadow" if id_prefix else "shadow"
|
||||
clip_id = f"{id_prefix}avatarClip" if id_prefix else "avatarClip"
|
||||
return f'''<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" fill="none">
|
||||
<defs>
|
||||
<filter id="{shadow_id}" x="-2%" y="-2%" width="104%" height="104%">
|
||||
<feDropShadow dx="0" dy="1" stdDeviation="2" flood-color="#000" flood-opacity="0.15"/>
|
||||
</filter>
|
||||
<clipPath id="{clip_id}"><circle cx="0" cy="0" r="18"/></clipPath>
|
||||
</defs>
|
||||
<rect x="1" y="1" width="{width-2}" height="{height-2}" rx="10" ry="10"
|
||||
fill="{theme["card_bg"]}" stroke="{theme["card_border"]}" stroke-width="1" filter="url(#{shadow_id})"/>
|
||||
{f'<text x="20" y="30" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Noto Sans,Helvetica,Arial,sans-serif" font-size="11" font-weight="600" fill="{theme["text_secondary"]}" letter-spacing="0.8" opacity="0.7">{escape(title.upper())}</text>' if title else ''}
|
||||
<g transform="translate(0, {36 if title else 0})">
|
||||
{inner_svg}
|
||||
</g>
|
||||
</svg>'''
|
||||
|
||||
|
||||
def icon_svg(kind: str, color: str) -> str:
|
||||
"""Returns SVG for stat icons (14x14)."""
|
||||
icons = {
|
||||
"commits": f'<circle cx="7" cy="7" r="3" fill="none" stroke="{color}" stroke-width="1.4"/><circle cx="7" cy="7" r="1" fill="{color}"/><line x1="7" y1="10" x2="7" y2="14" stroke="{color}" stroke-width="1.4"/><line x1="7" y1="0" x2="7" y2="4" stroke="{color}" stroke-width="1.4"/>',
|
||||
"prs": f'<circle cx="4" cy="4" r="2" fill="none" stroke="{color}" stroke-width="1.2"/><circle cx="10" cy="10" r="2" fill="none" stroke="{color}" stroke-width="1.2"/><path d="M4 6v4c0 1.1.9 2 2 2h2" fill="none" stroke="{color}" stroke-width="1.2"/>',
|
||||
"stars": f'<path d="M7 1l1.8 3.6 4 .6-2.9 2.8.7 4L7 10.2 3.4 12l.7-4L1.2 5.2l4-.6z" fill="{color}" opacity="0.85"/>',
|
||||
"repos": f'<rect x="2" y="1" width="10" height="12" rx="1.5" fill="none" stroke="{color}" stroke-width="1.2"/><line x1="5" y1="4" x2="9" y2="4" stroke="{color}" stroke-width="1"/><line x1="5" y1="6.5" x2="9" y2="6.5" stroke="{color}" stroke-width="1"/><line x1="5" y1="9" x2="7" y2="9" stroke="{color}" stroke-width="1"/>',
|
||||
"followers": f'<circle cx="5" cy="4" r="2.5" fill="none" stroke="{color}" stroke-width="1.2"/><path d="M0.5 12c0-2.5 2-4 4.5-4s4.5 1.5 4.5 4" fill="none" stroke="{color}" stroke-width="1.2"/><circle cx="11" cy="3.5" r="1.8" fill="none" stroke="{color}" stroke-width="1"/><path d="M10 7.5c1.5 0 3.5 1 3.5 3" fill="none" stroke="{color}" stroke-width="1"/>',
|
||||
}
|
||||
return f'<g>{icons.get(kind, "")}</g>'
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Widget rendering functions."""
|
||||
|
||||
from .grade import render_grade_widget
|
||||
from .impact import render_impact_widget
|
||||
from .collaborators import render_collaborators_widget
|
||||
from .focus import render_focus_widget
|
||||
from .languages import render_languages_widget
|
||||
from .achievements import render_achievements_widget
|
||||
from .composite import compose_widget
|
||||
|
||||
__all__ = [
|
||||
"render_grade_widget",
|
||||
"render_impact_widget",
|
||||
"render_collaborators_widget",
|
||||
"render_focus_widget",
|
||||
"render_languages_widget",
|
||||
"render_achievements_widget",
|
||||
"compose_widget",
|
||||
]
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Achievements widget rendering."""
|
||||
|
||||
from ..models import AchievementData
|
||||
from ..themes import THEMES
|
||||
from ..utils import escape, card_wrapper
|
||||
|
||||
|
||||
def _achievement_icon_svg(icon_type: str, color: str) -> str:
|
||||
"""Returns SVG for achievement icons (24x24)."""
|
||||
icons = {
|
||||
"trophy": f'''<svg viewBox="0 0 24 24" width="24" height="24">
|
||||
<path d="M7 2h10v2h2.5c.8 0 1.5.7 1.5 1.5V8c0 1.7-1.3 3-3 3h-.5c-.5 1.5-1.8 2.7-3.5 3v2.5h3c.6 0 1 .4 1 1s-.4 1-1 1H7c-.6 0-1-.4-1-1s.4-1 1-1h3V14c-1.7-.3-3-1.5-3.5-3H6c-1.7 0-3-1.3-3-3V5.5C3 4.7 3.7 4 4.5 4H7V2zm0 4H4.5v2c0 .8.7 1.5 1.5 1.5h1V6zm12.5 0H17v3.5h1c.8 0 1.5-.7 1.5-1.5V6z" fill="{color}" opacity="0.85"/>
|
||||
</svg>''',
|
||||
"medal": f'''<svg viewBox="0 0 24 24" width="24" height="24">
|
||||
<circle cx="12" cy="14" r="5" fill="{color}" opacity="0.2"/>
|
||||
<circle cx="12" cy="14" r="4" fill="none" stroke="{color}" stroke-width="1.5"/>
|
||||
<path d="M12 11.5l1 2 2.2.3-1.6 1.5.4 2.2-2-1-2 1 .4-2.2-1.6-1.5 2.2-.3z" fill="{color}"/>
|
||||
<path d="M9 3l3 8m0-8l3 8m-6-8h6" stroke="{color}" stroke-width="1.5" fill="none" stroke-linecap="round"/>
|
||||
</svg>''',
|
||||
"star": f'''<svg viewBox="0 0 24 24" width="24" height="24">
|
||||
<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" fill="{color}" opacity="0.85"/>
|
||||
</svg>''',
|
||||
"hackathon": f'''<svg viewBox="0 0 24 24" width="24" height="24">
|
||||
<rect x="4" y="5" width="16" height="11" rx="1" fill="none" stroke="{color}" stroke-width="1.5"/>
|
||||
<rect x="3" y="16" width="18" height="1.5" rx="0.5" fill="{color}" opacity="0.85"/>
|
||||
<path d="M9 9l-2 3 2 3m6-6l2 3-2 3" stroke="{color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
|
||||
</svg>''',
|
||||
}
|
||||
return icons.get(icon_type, icons["trophy"])
|
||||
|
||||
|
||||
def render_achievements_widget(
|
||||
achievements: list[AchievementData],
|
||||
theme_name: str = "dark",
|
||||
max_items: int = 5,
|
||||
settings: dict | None = None,
|
||||
) -> str:
|
||||
"""Renders the achievements widget with icons and descriptions.
|
||||
|
||||
Settings:
|
||||
max_items (int): Max achievements to show (default 5)
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
s = settings or {}
|
||||
max_items = min(max(int(s.get("max_items", max_items)), 1), 10)
|
||||
items = ""
|
||||
accent_colors = [t["orange"], t["green"], t["accent"], t["purple"], t["pink"]]
|
||||
|
||||
shown = achievements[:max_items]
|
||||
if not shown:
|
||||
return ""
|
||||
|
||||
for i, ach in enumerate(shown):
|
||||
y = i * 56
|
||||
color = accent_colors[i % len(accent_colors)]
|
||||
icon_svg = _achievement_icon_svg(ach.icon, color)
|
||||
|
||||
items += f'''
|
||||
<g transform="translate(16, {y + 8})">
|
||||
<rect width="348" height="48" rx="8" fill="{color}" opacity="0.06"/>
|
||||
<rect width="348" height="48" rx="8" fill="none" stroke="{color}" stroke-width="0.5" opacity="0.3"/>
|
||||
<g transform="translate(12, 12)">
|
||||
{icon_svg}
|
||||
</g>
|
||||
<text x="48" y="20" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="13" font-weight="600" fill="{t["text"]}">{escape(ach.title)}</text>
|
||||
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="10" fill="{t["text_secondary"]}">{escape(ach.subtitle)}{(" · " + ach.event_date) if ach.event_date else ""}</text>
|
||||
</g>'''
|
||||
|
||||
total_h = len(shown) * 56 + 50
|
||||
return card_wrapper(items, 380, total_h, t, "Achievements")
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Collaborators widget rendering."""
|
||||
|
||||
from ..models import CollaboratorData
|
||||
from ..themes import THEMES
|
||||
from ..utils import escape, card_wrapper
|
||||
|
||||
|
||||
def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str = "dark", settings: dict | None = None) -> str:
|
||||
"""Renders the top collaborators widget with avatars and contribution bars.
|
||||
|
||||
Settings:
|
||||
max_count (int): Number of collaborators to show (default 5)
|
||||
bar_color (str): Hex color for the contribution bars (default theme purple)
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
s = settings or {}
|
||||
max_count = min(max(int(s.get("max_count", 5)), 1), 10)
|
||||
bar_color = s.get("bar_color") or t["purple"]
|
||||
items = ""
|
||||
|
||||
for i, c in enumerate(collabs[:max_count]):
|
||||
y = i * 50
|
||||
avatar_el = ""
|
||||
|
||||
if c.avatar_b64:
|
||||
avatar_el = f'''<image x="-18" y="-18" width="36" height="36" href="data:image/png;base64,{c.avatar_b64}" clip-path="url(#avatarClip)"/>'''
|
||||
else:
|
||||
hue = hash(c.username) % 360
|
||||
avatar_el = f'''
|
||||
<circle cx="0" cy="0" r="18" fill="hsl({hue}, 50%, 40%)"/>
|
||||
<text x="0" y="1" text-anchor="middle" dominant-baseline="middle"
|
||||
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="14" font-weight="600" fill="white">{escape(c.username[0].upper())}</text>'''
|
||||
|
||||
bar_max = max((x.shared_commits for x in collabs[:max_count]), default=1) or 1
|
||||
bar_w = c.shared_commits / bar_max * 120
|
||||
|
||||
items += f'''
|
||||
<g transform="translate(36, {y + 20})">
|
||||
{avatar_el}
|
||||
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="13" font-weight="600" fill="{t["text"]}">{escape(c.username)}</text>
|
||||
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="10" fill="{t["text_secondary"]}">{c.shared_repos} repos · {c.shared_commits} commits</text>
|
||||
<rect x="200" y="-6" width="130" height="8" rx="4" fill="{t["grid"]}"/>
|
||||
<rect x="200" y="-6" width="{bar_w}" height="8" rx="4" fill="{bar_color}" opacity="0.8">
|
||||
<animate attributeName="width" from="0" to="{bar_w}" dur="0.6s" fill="freeze"/>
|
||||
</rect>
|
||||
</g>'''
|
||||
|
||||
total_h = len(collabs[:max_count]) * 50 + 48
|
||||
return card_wrapper(items, 380, total_h, t, "Top Collaborators")
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Composite widget builder for combining multiple widgets."""
|
||||
|
||||
import re
|
||||
from ..themes import THEMES
|
||||
from ..utils import escape
|
||||
|
||||
|
||||
def _extract_inner(svg: str, widget_key: str) -> tuple[str, int]:
|
||||
"""Extract the inner content from a widget SVG and rewrite IDs to be unique.
|
||||
|
||||
Returns (inner_svg_content, height).
|
||||
"""
|
||||
# Parse height
|
||||
hm = re.search(r'height="(\d+)"', svg)
|
||||
h = int(hm.group(1)) if hm else 160
|
||||
|
||||
# Rewrite IDs to avoid conflicts: shadow, avatarClip, areaGrad, etc.
|
||||
# Prefix all id="..." and url(#...) and href="#..." references
|
||||
prefix = f"{widget_key}_"
|
||||
|
||||
# Find all IDs in the SVG
|
||||
ids = re.findall(r'id="([^"]+)"', svg)
|
||||
inner = svg
|
||||
for old_id in ids:
|
||||
new_id = f"{prefix}{old_id}"
|
||||
inner = inner.replace(f'id="{old_id}"', f'id="{new_id}"')
|
||||
inner = inner.replace(f'url(#{old_id})', f'url(#{new_id})')
|
||||
inner = inner.replace(f'href="#{old_id}"', f'href="#{new_id}"')
|
||||
|
||||
# Strip the outer <svg> and </svg> tags to get just the content
|
||||
inner = re.sub(r'<svg[^>]*>', '', inner, count=1)
|
||||
inner = re.sub(r'</svg>\s*$', '', inner)
|
||||
|
||||
return inner, h
|
||||
|
||||
|
||||
def compose_widget(
|
||||
widgets: dict[str, str],
|
||||
enabled: list[str],
|
||||
theme_name: str = "dark",
|
||||
username: str = "",
|
||||
avatar_b64: str = "",
|
||||
) -> str:
|
||||
"""
|
||||
Takes rendered SVG strings for each widget type and composes them
|
||||
into a single unified profile widget by inlining widget SVGs directly.
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
total_w = 420
|
||||
header_h = 60
|
||||
padding = 20
|
||||
gap = 16
|
||||
|
||||
# Extract inner content from each widget SVG
|
||||
parts = []
|
||||
for key in enabled:
|
||||
if key in widgets and widgets[key]:
|
||||
inner, h = _extract_inner(widgets[key], key)
|
||||
parts.append((key, inner, h))
|
||||
|
||||
content_h = sum(h for _, _, h in parts) + gap * max(len(parts) - 1, 0)
|
||||
total_h = header_h + content_h + padding * 2 + 10
|
||||
|
||||
# Header
|
||||
avatar_svg = ""
|
||||
if avatar_b64:
|
||||
avatar_svg = f'''
|
||||
<defs><clipPath id="mainAvatarClip"><circle cx="30" cy="30" r="16"/></clipPath></defs>
|
||||
<image x="14" y="14" width="32" height="32" href="data:image/png;base64,{avatar_b64}" clip-path="url(#mainAvatarClip)"/>'''
|
||||
else:
|
||||
avatar_svg = f'<circle cx="30" cy="30" r="16" fill="{t["accent"]}" opacity="0.3"/>'
|
||||
|
||||
header = f'''
|
||||
{avatar_svg}
|
||||
<text x="54" y="38" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="16" font-weight="700" fill="{t["text"]}">{escape(username or "Developer")}</text>
|
||||
<line x1="{padding}" y1="{header_h}" x2="{total_w - padding}" y2="{header_h}"
|
||||
stroke="{t["card_border"]}" stroke-width="0.5"/>'''
|
||||
|
||||
# Inline widgets using <svg> sub-documents positioned with x/y
|
||||
y_offset = header_h + padding
|
||||
embedded = ""
|
||||
for key, inner, h in parts:
|
||||
embedded += f'''
|
||||
<svg x="{padding}" y="{y_offset}" width="380" height="{h}" viewBox="0 0 380 {h}">
|
||||
{inner}
|
||||
</svg>'''
|
||||
y_offset += h + gap
|
||||
|
||||
return f'''<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
width="{total_w}" height="{total_h}" viewBox="0 0 {total_w} {total_h}">
|
||||
<rect width="{total_w}" height="{total_h}" rx="16" fill="{t["bg"]}"/>
|
||||
<rect x="0.5" y="0.5" width="{total_w-1}" height="{total_h-1}" rx="16"
|
||||
fill="none" stroke="{t["card_border"]}" stroke-width="1"/>
|
||||
{header}
|
||||
{embedded}
|
||||
<text x="{total_w // 2}" y="{total_h - 8}" text-anchor="middle"
|
||||
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="9" fill="{t["text_secondary"]}" opacity="0.5">Generated with ♥</text>
|
||||
</svg>'''
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Focus areas widget rendering."""
|
||||
|
||||
from ..models import FocusCategory
|
||||
from ..themes import THEMES, FOCUS_COLORS
|
||||
from ..utils import escape, card_wrapper
|
||||
|
||||
|
||||
def render_focus_widget(categories: list[FocusCategory], theme_name: str = "dark", period: str = "1y", settings: dict | None = None) -> str:
|
||||
"""Renders the focus areas widget with horizontal bars.
|
||||
|
||||
Settings:
|
||||
max_categories (int): Max categories to show (default 6)
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
s = settings or {}
|
||||
max_cats = min(max(int(s.get("max_categories", 6)), 1), 10)
|
||||
cats = sorted(categories, key=lambda c: -c.percentage)[:max_cats]
|
||||
if not cats:
|
||||
return ""
|
||||
|
||||
# Format period for display
|
||||
period_map = {
|
||||
"1w": "last week",
|
||||
"1m": "last month",
|
||||
"3m": "last 3 months",
|
||||
"6m": "last 6 months",
|
||||
"1y": "last year",
|
||||
"all": "all time"
|
||||
}
|
||||
period_display = period_map.get(period, period)
|
||||
|
||||
max_pct = cats[0].percentage if cats else 100
|
||||
max_pct = max(max_pct, 1) # Avoid division by zero
|
||||
bar_max_w = 210
|
||||
items = ""
|
||||
|
||||
for i, cat in enumerate(cats):
|
||||
color = FOCUS_COLORS[i % len(FOCUS_COLORS)]
|
||||
y = i * 36
|
||||
bar_w = (cat.percentage / max_pct) * bar_max_w
|
||||
|
||||
items += f'''
|
||||
<g transform="translate(16, {y})">
|
||||
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="12" font-weight="600" fill="{t["text"]}">{escape(cat.category)}</text>
|
||||
<rect x="90" y="4" width="{bar_max_w}" height="14" rx="7" fill="{t["grid"]}"/>
|
||||
<rect x="90" y="4" width="{bar_w}" height="14" rx="7" fill="{color}" opacity="0.8">
|
||||
<animate attributeName="width" from="0" to="{bar_w}" dur="0.7s" fill="freeze"/>
|
||||
</rect>
|
||||
<text x="90" y="32" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="9" fill="{t["text_secondary"]}">{cat.commit_count} commits</text>
|
||||
<text x="{90 + bar_max_w + 8}" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="12" font-weight="700" fill="{color}">{cat.percentage:.0f}%</text>
|
||||
</g>'''
|
||||
|
||||
# Add period subtitle
|
||||
subtitle_y = len(cats) * 36 + 8
|
||||
items += f'''
|
||||
<text x="16" y="{subtitle_y}" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="9" fill="{t["text_secondary"]}" opacity="0.7">Recent activity · {period_display}</text>'''
|
||||
|
||||
card_h = len(cats) * 36 + 54
|
||||
return card_wrapper(items, 380, card_h, t, "Recent Focus")
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Grade widget rendering."""
|
||||
|
||||
import math
|
||||
from ..models import GradeData
|
||||
from ..themes import THEMES, TAG_COLORS, GRADE_COLORS
|
||||
from ..utils import escape, card_wrapper, icon_svg
|
||||
|
||||
|
||||
def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dict | None = None) -> str:
|
||||
"""Renders the developer grade widget with stats and tags.
|
||||
|
||||
Settings:
|
||||
max_tags (int): Max tags to display (default all)
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
s = settings or {}
|
||||
max_tags = s.get("max_tags")
|
||||
if max_tags is not None:
|
||||
max_tags = min(max(int(max_tags), 1), 20)
|
||||
data = GradeData(
|
||||
grade=data.grade, score=data.score, stats=data.stats,
|
||||
tags=data.tags[:max_tags] if data.tags else [],
|
||||
breakdown=data.breakdown,
|
||||
)
|
||||
base = data.grade[0]
|
||||
color = GRADE_COLORS.get(base, t["accent"])
|
||||
score = data.score
|
||||
|
||||
radius = 36
|
||||
circumference = 2 * math.pi * radius
|
||||
offset = circumference * (1 - score / 100)
|
||||
grade_font = 30 if len(data.grade) <= 2 else 22
|
||||
|
||||
# Stats row with icons
|
||||
stat_labels = {
|
||||
"commits": "Commits",
|
||||
"prs": "PRs",
|
||||
"stars": "Stars",
|
||||
"repos": "Repos",
|
||||
"followers": "Followers"
|
||||
}
|
||||
stat_keys = [k for k in ["commits", "prs", "stars", "repos", "followers"] if k in data.stats]
|
||||
stats_svg = ""
|
||||
stat_w = 340 / max(len(stat_keys), 1)
|
||||
|
||||
for i, key in enumerate(stat_keys):
|
||||
val = data.stats[key]
|
||||
sx = i * stat_w + stat_w / 2
|
||||
val_str = f"{val:,}" if val < 100000 else f"{val/1000:.0f}k"
|
||||
stats_svg += f'''
|
||||
<g transform="translate({sx}, 0)">
|
||||
<g transform="translate(-7, 0)">{icon_svg(key, t["text_secondary"])}</g>
|
||||
<text x="0" y="28" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="14" font-weight="700" fill="{t["text"]}">{val_str}</text>
|
||||
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="9" fill="{t["text_secondary"]}">{stat_labels.get(key, key)}</text>
|
||||
</g>'''
|
||||
|
||||
# Tag pills
|
||||
tags_svg = ""
|
||||
tx, ty = 0, 0
|
||||
max_tw = 340
|
||||
|
||||
for tag in (data.tags or []):
|
||||
tag_color = TAG_COLORS.get(tag.tag, t["accent"])
|
||||
label = tag.tag.replace("-", " ").title()
|
||||
tw = int(len(label) * 6.6 + 18)
|
||||
pill_opacity = 0.9 if tag.source == "earned" else 0.55
|
||||
|
||||
if tx + tw > max_tw:
|
||||
tx = 0
|
||||
ty += 30
|
||||
|
||||
tags_svg += f'''
|
||||
<g transform="translate({tx}, {ty})" opacity="{pill_opacity}">
|
||||
<rect width="{tw}" height="24" rx="12" fill="{tag_color}" opacity="0.12"/>
|
||||
<rect width="{tw}" height="24" rx="12" fill="none" stroke="{tag_color}" stroke-width="1" opacity="0.3"/>
|
||||
<text x="{tw // 2}" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="10" font-weight="500" fill="{tag_color}">{escape(label)}</text>
|
||||
</g>'''
|
||||
tx += tw + 6
|
||||
|
||||
tags_h = ty + 24 if data.tags else 0
|
||||
|
||||
# Layout
|
||||
stats_y = 100
|
||||
tags_y = stats_y + 54
|
||||
tag_padding = 18 if tags_h > 24 else 14
|
||||
card_h = (tags_y + tags_h + tag_padding) if data.tags else (stats_y + 54)
|
||||
|
||||
inner = f'''
|
||||
<g transform="translate(52, 48)">
|
||||
<circle cx="0" cy="0" r="{radius}" fill="none" stroke="{t["grid"]}" stroke-width="5"/>
|
||||
<circle cx="0" cy="0" r="{radius}" fill="none" stroke="{color}" stroke-width="5"
|
||||
stroke-dasharray="{circumference}" stroke-dashoffset="{offset}"
|
||||
stroke-linecap="round" transform="rotate(-90)">
|
||||
<animate attributeName="stroke-dashoffset" from="{circumference}" to="{offset}" dur="1s" fill="freeze"/>
|
||||
</circle>
|
||||
<text x="0" y="-4" text-anchor="middle" dominant-baseline="middle"
|
||||
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="{grade_font}" font-weight="800" fill="{color}">{escape(data.grade)}</text>
|
||||
<text x="0" y="18" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="11" fill="{t["text_secondary"]}">{score:.0f} / 100</text>
|
||||
</g>
|
||||
<line x1="100" y1="16" x2="100" y2="80" stroke="{t["grid"]}" stroke-width="1"/>
|
||||
<g transform="translate(114, 26)">
|
||||
<text x="0" y="10" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="16" font-weight="700" fill="{t["text"]}">Developer Profile</text>
|
||||
<text x="0" y="28" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="11" fill="{t["text_secondary"]}">Grade <tspan fill="{color}" font-weight="700">{escape(data.grade)}</tspan> · {score:.0f}/100</text>
|
||||
</g>
|
||||
<line x1="20" y1="{stats_y - 4}" x2="360" y2="{stats_y - 4}" stroke="{t["grid"]}" stroke-width="0.5"/>
|
||||
<g transform="translate(20, {stats_y})">
|
||||
{stats_svg}
|
||||
</g>'''
|
||||
|
||||
if data.tags:
|
||||
inner += f'''
|
||||
<line x1="20" y1="{tags_y - 6}" x2="360" y2="{tags_y - 6}" stroke="{t["grid"]}" stroke-width="0.5"/>
|
||||
<g transform="translate(20, {tags_y})">
|
||||
{tags_svg}
|
||||
</g>'''
|
||||
|
||||
return card_wrapper(inner, 380, card_h, t, "")
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Impact timeline widget rendering."""
|
||||
|
||||
from ..models import ImpactWeek
|
||||
from ..themes import THEMES
|
||||
from ..utils import card_wrapper
|
||||
|
||||
|
||||
def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", period: str = "6mo", settings: dict | None = None) -> str:
|
||||
"""Renders the impact timeline chart widget.
|
||||
|
||||
Settings:
|
||||
line_color (str): Hex color for the chart line/area (default theme accent)
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
s = settings or {}
|
||||
line_color = s.get("line_color") or t["accent"]
|
||||
w, h = 380, 200
|
||||
chart_x, chart_y = 40, 8
|
||||
chart_w, chart_h = 316, 82
|
||||
|
||||
if not weeks:
|
||||
# Render an empty chart so the widget still appears
|
||||
inner = f'''
|
||||
<line x1="{chart_x}" y1="{chart_y + chart_h}" x2="{chart_x + chart_w}" y2="{chart_y + chart_h}" stroke="{t["grid"]}" stroke-width="0.5"/>
|
||||
<text x="{chart_x + chart_w / 2}" y="{chart_y + chart_h / 2 + 4}" text-anchor="middle"
|
||||
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="11" fill="{t["text_secondary"]}">No contribution data yet</text>
|
||||
<g transform="translate(20, {chart_y + chart_h + 46})">
|
||||
<text x="0" y="0" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="13" font-weight="700" fill="{t["text"]}">0</text>
|
||||
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="9" fill="{t["text_secondary"]}">commits over {period}</text>
|
||||
</g>'''
|
||||
return card_wrapper(inner, w, h, t, "Impact Timeline")
|
||||
|
||||
max_commits = max((wk.commits for wk in weeks), default=1) or 1
|
||||
n = len(weeks)
|
||||
|
||||
# Build area path
|
||||
points = []
|
||||
for i, wk in enumerate(weeks):
|
||||
px = chart_x + (i / max(n - 1, 1)) * chart_w
|
||||
py = chart_y + chart_h - (wk.commits / max_commits) * chart_h
|
||||
points.append((px, py))
|
||||
|
||||
if not points:
|
||||
return ""
|
||||
|
||||
# Smooth curve using cardinal spline
|
||||
path_d = f"M {points[0][0]:.1f} {points[0][1]:.1f}"
|
||||
for i in range(1, len(points)):
|
||||
cx = (points[i-1][0] + points[i][0]) / 2
|
||||
path_d += f" C {cx:.1f} {points[i-1][1]:.1f}, {cx:.1f} {points[i][1]:.1f}, {points[i][0]:.1f} {points[i][1]:.1f}"
|
||||
|
||||
area_d = path_d + f" L {points[-1][0]:.1f} {chart_y + chart_h} L {points[0][0]:.1f} {chart_y + chart_h} Z"
|
||||
|
||||
# Y-axis labels
|
||||
y_labels = ""
|
||||
for i in range(3):
|
||||
val = int(max_commits * (1 - i / 2))
|
||||
yy = chart_y + (i / 2) * chart_h
|
||||
y_labels += f'<text x="{chart_x - 6}" y="{yy + 4}" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="{t["text_secondary"]}">{val}</text>'
|
||||
y_labels += f'<line x1="{chart_x}" y1="{yy}" x2="{chart_x + chart_w}" y2="{yy}" stroke="{t["grid"]}" stroke-width="0.5" stroke-dasharray="3,3"/>'
|
||||
|
||||
# X-axis labels
|
||||
x_labels = ""
|
||||
label_indices = [0, n // 2, n - 1] if n > 2 else list(range(n))
|
||||
for idx in label_indices:
|
||||
if idx < len(weeks):
|
||||
px = chart_x + (idx / max(n - 1, 1)) * chart_w
|
||||
x_labels += f'<text x="{px:.1f}" y="{chart_y + chart_h + 14}" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="{t["text_secondary"]}">{weeks[idx].week_start[:7]}</text>'
|
||||
|
||||
# Summary
|
||||
total = sum(wk.commits for wk in weeks)
|
||||
summary_y = chart_y + chart_h + 46
|
||||
|
||||
inner = f'''
|
||||
<defs>
|
||||
<linearGradient id="areaGrad" x1="0" y1="{chart_y}" x2="0" y2="{chart_y + chart_h}" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stop-color="{line_color}" stop-opacity="0.35"/>
|
||||
<stop offset="100%" stop-color="{line_color}" stop-opacity="0.02"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
{y_labels}
|
||||
{x_labels}
|
||||
<path d="{area_d}" fill="url(#areaGrad)"/>
|
||||
<path d="{path_d}" fill="none" stroke="{line_color}" stroke-width="2" stroke-linecap="round"/>
|
||||
<g transform="translate(20, {summary_y})">
|
||||
<text x="0" y="0" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="13" font-weight="700" fill="{t["text"]}">{total:,}</text>
|
||||
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="9" fill="{t["text_secondary"]}">commits over {period}</text>
|
||||
</g>'''
|
||||
|
||||
return card_wrapper(inner, w, h, t, "Impact Timeline")
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Languages widget rendering."""
|
||||
|
||||
import math
|
||||
from ..models import LanguageData
|
||||
from ..themes import THEMES, LANG_COLORS, FOCUS_COLORS
|
||||
from ..utils import escape, card_wrapper
|
||||
|
||||
|
||||
def render_languages_widget(languages: list[LanguageData], theme_name: str = "dark", settings: dict | None = None) -> str:
|
||||
"""Renders the languages donut chart widget.
|
||||
|
||||
Settings:
|
||||
max_languages (int): Max languages to show (default 5)
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
s = settings or {}
|
||||
max_langs = min(max(int(s.get("max_languages", 5)), 1), 10)
|
||||
top_langs = sorted(languages, key=lambda l: -l.percentage)[:max_langs]
|
||||
if not top_langs:
|
||||
return ""
|
||||
|
||||
# Ensure percentages always sum to exactly 100% for a complete circle
|
||||
total_percentage = sum(lang.percentage for lang in top_langs)
|
||||
langs = list(top_langs)
|
||||
|
||||
# Add "Other" category if there are remaining languages
|
||||
if total_percentage < 99.9 and len(languages) > max_langs:
|
||||
other_percentage = 100 - total_percentage
|
||||
from ..models import LanguageData
|
||||
langs.append(LanguageData(
|
||||
language="Other",
|
||||
percentage=round(other_percentage, 1),
|
||||
loc=0
|
||||
))
|
||||
elif total_percentage < 99.9:
|
||||
# If we have <= max_langs languages total but they don't sum to 100%,
|
||||
# adjust the percentages proportionally to sum to 100%
|
||||
if total_percentage > 0:
|
||||
factor = 100 / total_percentage
|
||||
for lang in langs:
|
||||
lang.percentage = round(lang.percentage * factor, 1)
|
||||
|
||||
# Calculate center position to align with legend
|
||||
legend_start = 20
|
||||
legend_height = len(langs) * 22
|
||||
cy = legend_start + legend_height / 2
|
||||
cx, r = 60, 44
|
||||
inner_r = 28
|
||||
circumference = 2 * math.pi * r
|
||||
|
||||
arcs = ""
|
||||
legend = ""
|
||||
offset = 0
|
||||
|
||||
for i, lang in enumerate(langs):
|
||||
# Use gray for "Other" category
|
||||
if lang.language == "Other":
|
||||
color = t["text_secondary"]
|
||||
else:
|
||||
color = LANG_COLORS.get(lang.language, FOCUS_COLORS[i % len(FOCUS_COLORS)])
|
||||
|
||||
dash = circumference * lang.percentage / 100
|
||||
gap = circumference - dash
|
||||
|
||||
arcs += f'''
|
||||
<circle cx="{cx}" cy="{cy}" r="{r}" fill="none" stroke="{color}" stroke-width="16"
|
||||
stroke-dasharray="{dash:.1f} {gap:.1f}" stroke-dashoffset="{-offset:.1f}"
|
||||
transform="rotate(-90 {cx} {cy})" opacity="0.85">
|
||||
<animate attributeName="stroke-dashoffset" from="{circumference - offset:.1f}" to="{-offset:.1f}" dur="0.8s" fill="freeze"/>
|
||||
</circle>'''
|
||||
offset += dash
|
||||
|
||||
ly = i * 22
|
||||
legend += f'''
|
||||
<g transform="translate(140, {ly + legend_start})">
|
||||
<rect width="10" height="10" rx="2" fill="{color}"/>
|
||||
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="12" fill="{t["text"]}">{escape(lang.language)}</text>
|
||||
<text x="210" y="9" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="11" font-weight="600" fill="{t["text_secondary"]}">{lang.percentage:.0f}%</text>
|
||||
</g>'''
|
||||
|
||||
# Center circle with top language
|
||||
top_lang = langs[0].language if langs else ""
|
||||
center = f'''
|
||||
<circle cx="{cx}" cy="{cy}" r="{inner_r}" fill="{t["card_bg"]}"/>
|
||||
<text x="{cx}" y="{cy + 1}" text-anchor="middle" dominant-baseline="middle"
|
||||
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="11" font-weight="700" fill="{t["text"]}">{escape(top_lang)}</text>'''
|
||||
|
||||
inner = f'''
|
||||
<g transform="translate(16, 0)">
|
||||
{arcs}
|
||||
{center}
|
||||
{legend}
|
||||
</g>'''
|
||||
|
||||
rows_h = max(len(langs) * 22 + 40, 120)
|
||||
return card_wrapper(inner, 380, rows_h + 36, t, "Languages")
|
||||
Reference in New Issue
Block a user