diff --git a/src/README.md b/src/README.md new file mode 100644 index 0000000..29ed4d2 --- /dev/null +++ b/src/README.md @@ -0,0 +1,87 @@ +# GitHub Profile Widget Generator + +A modular system for generating polished SVG widgets from GitHub profile data. + +## Project Structure + +``` +src/ +├── models/ # Data classes and types +│ ├── __init__.py +│ └── types.py # Widget data models +│ +├── themes/ # Color schemes and styling +│ ├── __init__.py +│ └── themes.py # Theme definitions +│ +├── widgets/ # Widget rendering modules +│ ├── __init__.py +│ ├── grade.py # Developer grade widget +│ ├── impact.py # Impact timeline chart +│ ├── collaborators.py # Top collaborators +│ ├── focus.py # Focus areas bars +│ ├── languages.py # Languages donut chart +│ ├── achievements.py # Achievements list +│ └── composite.py # Full widget composer +│ +├── data/ # Data fetching and processing +│ ├── __init__.py +│ ├── fetcher.py # GitHub API client +│ └── processor.py # Data transformation +│ +├── utils/ # Helper functions +│ ├── __init__.py +│ └── svg_helpers.py # SVG utilities +│ +└── generate.py # Main CLI entry point +``` + +## Usage + +Run from the project root directory: + +```bash +# Generate widgets for a user +python run.py [theme] + +# Or run as a module +python -m src.generate [theme] + +# With GitHub token for higher rate limits +GITHUB_TOKEN=your_token python run.py + +# Use light theme +python run.py light +``` + +## PyCharm Setup + +To fix import resolution in PyCharm: + +1. Right-click on the `src` folder +2. Select **Mark Directory as** → **Sources Root** +3. PyCharm will now resolve all imports correctly + +Alternatively, the project is set up with proper relative imports, so imports should work automatically once `src` is marked as a source root. + +## Extending + +### Adding a New Widget + +1. Create a new file in `widgets/` (e.g., `widgets/my_widget.py`) +2. Implement `render_my_widget(data, theme_name="dark") -> str` +3. Add to `widgets/__init__.py` exports +4. Update `data/processor.py` to include it in `generate_widgets_from_github()` + +### Adding a New Theme + +1. Add theme definition to `themes/themes.py` +2. Use the theme name when calling `generate_full_widget(theme="my_theme")` + +## Development + +All widgets follow the same pattern: +- Accept data models from `models/` +- Use themes from `themes/` +- Return SVG strings +- Use `utils.card_wrapper()` for consistent styling diff --git a/src/data/__init__.py b/src/data/__init__.py new file mode 100644 index 0000000..29d24b9 --- /dev/null +++ b/src/data/__init__.py @@ -0,0 +1,21 @@ +"""Data fetching and processing for GitHub profiles.""" + +from .fetcher import fetch_github_data +from .processor import ( + compute_grade, + compute_impact_timeline, + compute_collaborators, + compute_focus, + compute_languages, + generate_widgets_from_github, +) + +__all__ = [ + "fetch_github_data", + "compute_grade", + "compute_impact_timeline", + "compute_collaborators", + "compute_focus", + "compute_languages", + "generate_widgets_from_github", +] diff --git a/src/data/fetcher.py b/src/data/fetcher.py new file mode 100644 index 0000000..7f074e7 --- /dev/null +++ b/src/data/fetcher.py @@ -0,0 +1,51 @@ +"""GitHub data fetching functions.""" + +import requests +import base64 +from typing import Optional + + +def fetch_github_data(username: str, token: Optional[str] = None) -> dict: + """ + Fetches all relevant GitHub data for a user. + Returns a dict with user profile, repos, events, and avatar. + """ + headers = {"Accept": "application/vnd.github.v3+json"} + if token: + headers["Authorization"] = f"token {token}" + + base = "https://api.github.com" + + # User profile + user = requests.get(f"{base}/users/{username}", headers=headers).json() + + # Repos (up to 100) + repos = requests.get( + f"{base}/users/{username}/repos", + headers=headers, + params={"per_page": 100, "sort": "pushed", "type": "owner"}, + ).json() + + # Events (recent activity) + events = requests.get( + f"{base}/users/{username}/events", + headers=headers, + params={"per_page": 100}, + ).json() + + # Avatar as base64 + avatar_b64 = "" + if user.get("avatar_url"): + try: + resp = requests.get(user["avatar_url"] + "&s=64", timeout=5) + if resp.ok: + avatar_b64 = base64.b64encode(resp.content).decode("ascii") + except Exception: + pass + + return { + "user": user, + "repos": repos if isinstance(repos, list) else [], + "events": events if isinstance(events, list) else [], + "avatar_b64": avatar_b64, + } diff --git a/src/data/processor.py b/src/data/processor.py new file mode 100644 index 0000000..c3f668f --- /dev/null +++ b/src/data/processor.py @@ -0,0 +1,318 @@ +"""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) -> GradeData: + """Compute a developer grade from GitHub profile data.""" + user = github_data["user"] + repos = github_data["repos"] + events = github_data["events"] + + 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) + commits = sum( + len(ev.get("payload", {}).get("commits", [])) + for ev in events if ev.get("type") == "PushEvent" + ) + 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) + + 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) -> list[TagData]: + """Infer developer tags from repo languages and topics.""" + repos = github_data["repos"] + lang_counts = defaultdict(int) + topic_set = set() + + for r in repos: + lang = r.get("language") + if lang: + lang_counts[lang] += 1 + for topic in r.get("topics", []): + topic_set.add(topic.lower()) + + tags = [] + total = sum(lang_counts.values()) or 1 + + lang_map = { + "Python": ["ml-engineer", "backend"], + "JavaScript": ["frontend"], + "TypeScript": ["frontend"], + "Go": ["backend", "systems"], + "Rust": ["systems"], + "Java": ["backend"], + "C++": ["systems"], + "Swift": ["mobile"], + "Kotlin": ["mobile"], + "Dockerfile": ["devops"], + "HCL": ["devops", "cloud"], + } + + inferred = defaultdict(float) + for lang, count in lang_counts.items(): + pct = count / total + for tag in lang_map.get(lang, []): + inferred[tag] = max(inferred[tag], pct) + + topic_map = { + "machine-learning": "ml-engineer", + "deep-learning": "ml-engineer", + "frontend": "frontend", + "react": "frontend", + "vue": "frontend", + "backend": "backend", + "api": "backend", + "database": "database", + "devops": "devops", + "docker": "devops", + "kubernetes": "devops", + "security": "security", + "fullstack": "fullstack", + } + + for topic in topic_set: + if topic in topic_map: + inferred[topic_map[topic]] = max( + inferred.get(topic_map[topic], 0), 0.7 + ) + + # Fullstack heuristic + has_fe = any( + lang_counts.get(l, 0) > 0 for l in ["JavaScript", "TypeScript"] + ) + has_be = any( + lang_counts.get(l, 0) > 0 + for l in ["Python", "Go", "Java", "Rust", "C++"] + ) + if has_fe and has_be: + inferred["fullstack"] = max(inferred.get("fullstack", 0), 0.6) + + for tag, conf in sorted(inferred.items(), key=lambda x: -x[1])[:6]: + tags.append(TagData(tag=tag, source="earned", confidence=round(conf, 2))) + + return tags + + +def compute_impact_timeline(github_data: dict) -> list[ImpactWeek]: + """Aggregate events into weekly impact data.""" + events = github_data["events"] + weekly = defaultdict(lambda: {"commits": 0}) + + for ev in events: + if ev.get("type") == "PushEvent": + created = ev.get("created_at", "")[:10] + if created: + dt = datetime.fromisoformat(created) + week_start = (dt - timedelta(days=dt.weekday())).isoformat()[:10] + commits = len(ev.get("payload", {}).get("commits", [])) + weekly[week_start]["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]: + """Find top collaborators from events.""" + 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"] + )[:5]: + collabs.append( + CollaboratorData( + username=username, + shared_repos=len(stats["repos"]), + shared_commits=stats["commits"], + ) + ) + + return collabs + + +def compute_focus(github_data: dict) -> list[FocusCategory]: + """Classify commits into focus categories.""" + repos = github_data["repos"] + events = github_data["events"] + + lang_to_focus = { + "Python": "Python", + "JavaScript": "Frontend", + "TypeScript": "Frontend", + "HTML": "Frontend", + "CSS": "Frontend", + "Go": "Backend", + "Rust": "Systems", + "Java": "Backend", + "C++": "Systems", + "C": "Systems", + "Ruby": "Backend", + "PHP": "Backend", + "Shell": "DevOps", + "Dockerfile": "DevOps", + "Jupyter Notebook": "ML", + } + + focus_counts = defaultdict(int) + repo_langs = {} + for r in repos: + lang = r.get("language") + if lang: + repo_langs[r["full_name"]] = lang + + for ev in events: + if ev.get("type") == "PushEvent": + repo_name = ev.get("repo", {}).get("name", "") + lang = repo_langs.get(repo_name) + focus = lang_to_focus.get(lang, "Other") + commits = len(ev.get("payload", {}).get("commits", [])) + focus_counts[focus] += commits + + total = sum(focus_counts.values()) or 1 + return [ + FocusCategory( + category=cat, + percentage=round(count / total * 100, 1), + commit_count=count, + ) + for cat, count in sorted(focus_counts.items(), key=lambda x: -x[1]) + ] + + +def compute_languages(github_data: dict) -> list[LanguageData]: + """Compute language distribution from repos.""" + repos = github_data["repos"] + lang_counts = defaultdict(int) + for r in repos: + lang = r.get("language") + if lang: + 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" +) -> dict[str, str]: + """ + Takes raw GitHub API data and returns rendered SVG strings + for each widget type. + """ + grade = compute_grade(github_data) + impact = compute_impact_timeline(github_data) + collabs = compute_collaborators(github_data) + focus = compute_focus(github_data) + languages = compute_languages(github_data) + + return { + "grade": render_grade_widget(grade, theme), + "impact": render_impact_widget(impact, theme), + "collaborators": render_collaborators_widget(collabs, theme), + "focus": render_focus_widget(focus, theme, period="1y"), + "languages": render_languages_widget(languages, theme), + } diff --git a/src/models/__init__.py b/src/models/__init__.py new file mode 100644 index 0000000..bfd864b --- /dev/null +++ b/src/models/__init__.py @@ -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", +] diff --git a/src/models/types.py b/src/models/types.py new file mode 100644 index 0000000..8a542aa --- /dev/null +++ b/src/models/types.py @@ -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 diff --git a/src/themes/__init__.py b/src/themes/__init__.py new file mode 100644 index 0000000..a29ff0b --- /dev/null +++ b/src/themes/__init__.py @@ -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"] diff --git a/src/themes/themes.py b/src/themes/themes.py new file mode 100644 index 0000000..59d0d2f --- /dev/null +++ b/src/themes/themes.py @@ -0,0 +1,86 @@ +"""Theme definitions and color palettes.""" + +THEMES = { + "dark": { + "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", + }, + "light": { + "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", + }, +} + +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", +} diff --git a/src/utils/__init__.py b/src/utils/__init__.py new file mode 100644 index 0000000..732d9f8 --- /dev/null +++ b/src/utils/__init__.py @@ -0,0 +1,5 @@ +"""Utility functions for SVG generation.""" + +from .svg_helpers import escape, card_wrapper, icon_svg + +__all__ = ["escape", "card_wrapper", "icon_svg"] diff --git a/src/utils/svg_helpers.py b/src/utils/svg_helpers.py new file mode 100644 index 0000000..df67f1a --- /dev/null +++ b/src/utils/svg_helpers.py @@ -0,0 +1,36 @@ +"""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 = "") -> str: + """Wraps content in a styled card with rounded corners and border.""" + return f''' + + + + + + + + {f'{escape(title.upper())}' if title else ''} + + {inner_svg} + +''' + + +def icon_svg(kind: str, color: str) -> str: + """Returns SVG for stat icons (14x14).""" + icons = { + "commits": f'', + "prs": f'', + "stars": f'', + "repos": f'', + "followers": f'', + } + return f'{icons.get(kind, "")}' diff --git a/src/widgets/__init__.py b/src/widgets/__init__.py new file mode 100644 index 0000000..5489e47 --- /dev/null +++ b/src/widgets/__init__.py @@ -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", +] diff --git a/src/widgets/achievements.py b/src/widgets/achievements.py new file mode 100644 index 0000000..e68904f --- /dev/null +++ b/src/widgets/achievements.py @@ -0,0 +1,65 @@ +"""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''' + + ''', + "medal": f''' + + + + + ''', + "star": f''' + + ''', + "hackathon": f''' + + + + ''', + } + return icons.get(icon_type, icons["trophy"]) + + +def render_achievements_widget( + achievements: list[AchievementData], + theme_name: str = "dark", + max_items: int = 5 +) -> str: + """Renders the achievements widget with icons and descriptions.""" + t = THEMES[theme_name] + 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''' + + + + + {icon_svg} + + {escape(ach.title)} + {escape(ach.subtitle)}{(" · " + ach.event_date) if ach.event_date else ""} + ''' + + total_h = len(shown) * 56 + 50 + return card_wrapper(items, 380, total_h, t, "Achievements") diff --git a/src/widgets/collaborators.py b/src/widgets/collaborators.py new file mode 100644 index 0000000..e19836d --- /dev/null +++ b/src/widgets/collaborators.py @@ -0,0 +1,44 @@ +"""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") -> str: + """Renders the top collaborators widget with avatars and contribution bars.""" + t = THEMES[theme_name] + items = "" + + for i, c in enumerate(collabs[:5]): + y = i * 50 + avatar_el = "" + + if c.avatar_b64: + avatar_el = f'''''' + else: + hue = hash(c.username) % 360 + avatar_el = f''' + + {escape(c.username[0].upper())}''' + + bar_max = max((x.shared_commits for x in collabs[:5]), default=1) or 1 + bar_w = c.shared_commits / bar_max * 120 + + items += f''' + + {avatar_el} + {escape(c.username)} + {c.shared_repos} repos · {c.shared_commits} commits + + + + + ''' + + total_h = len(collabs[:5]) * 50 + 48 + return card_wrapper(items, 380, total_h, t, "Top Collaborators") diff --git a/src/widgets/composite.py b/src/widgets/composite.py new file mode 100644 index 0000000..27db1f5 --- /dev/null +++ b/src/widgets/composite.py @@ -0,0 +1,76 @@ +"""Composite widget builder for combining multiple widgets.""" + +import re +import base64 +from ..themes import THEMES +from ..utils import escape + + +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. + """ + t = THEMES[theme_name] + total_w = 420 + header_h = 60 + padding = 20 + gap = 16 + + # Parse each widget's height from its SVG + parts = [] + for key in enabled: + if key in widgets and widgets[key]: + svg = widgets[key] + hm = re.search(r'height="(\d+)"', svg) + h = int(hm.group(1)) if hm else 160 + parts.append((key, svg, 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''' + + ''' + else: + avatar_svg = f'' + + header = f''' + {avatar_svg} + {escape(username or "Developer")} + GitHub Profile Widget + ''' + + # Stack widgets via base64 data URI embedding + y_offset = header_h + padding + embedded = "" + for key, svg, h in parts: + svg_b64 = base64.b64encode(svg.encode("utf-8")).decode("ascii") + embedded += f''' + ''' + y_offset += h + gap + + return f''' + + + {header} + {embedded} + Generated with ♥ +''' diff --git a/src/widgets/focus.py b/src/widgets/focus.py new file mode 100644 index 0000000..6ca8559 --- /dev/null +++ b/src/widgets/focus.py @@ -0,0 +1,57 @@ +"""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") -> str: + """Renders the focus areas widget with horizontal bars.""" + t = THEMES[theme_name] + cats = sorted(categories, key=lambda c: -c.percentage)[:6] + 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''' + + {escape(cat.category)} + + + + + {cat.commit_count} commits + {cat.percentage:.0f}% + ''' + + # Add period subtitle + subtitle_y = len(cats) * 36 + 8 + items += f''' + Recent activity · {period_display}''' + + card_h = len(cats) * 36 + 54 + return card_wrapper(items, 380, card_h, t, "Recent Focus") diff --git a/src/widgets/grade.py b/src/widgets/grade.py new file mode 100644 index 0000000..35cdcd4 --- /dev/null +++ b/src/widgets/grade.py @@ -0,0 +1,111 @@ +"""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") -> str: + """Renders the developer grade widget with stats and tags.""" + t = THEMES[theme_name] + 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''' + + {icon_svg(key, t["text_secondary"])} + {val_str} + {stat_labels.get(key, key)} + ''' + + # 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''' + + + + {escape(label)} + ''' + 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''' + + + + + + {escape(data.grade)} + {score:.0f} / 100 + + + + Developer Profile + Grade {escape(data.grade)} · {score:.0f}/100 + + + + {stats_svg} + ''' + + if data.tags: + inner += f''' + + + {tags_svg} + ''' + + return card_wrapper(inner, 380, card_h, t, "") diff --git a/src/widgets/impact.py b/src/widgets/impact.py new file mode 100644 index 0000000..5f3e4df --- /dev/null +++ b/src/widgets/impact.py @@ -0,0 +1,77 @@ +"""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") -> str: + """Renders the impact timeline chart widget.""" + t = THEMES[theme_name] + if not weeks: + return "" + + w, h = 380, 200 + chart_x, chart_y = 40, 8 + chart_w, chart_h = 316, 82 + + 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'{val}' + y_labels += f'' + + # 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'{weeks[idx].week_start[:7]}' + + # Summary + total = sum(wk.commits for wk in weeks) + summary_y = chart_y + chart_h + 46 + + inner = f''' + + + + + + + {y_labels} + {x_labels} + + + + {total:,} + commits over {period} + ''' + + return card_wrapper(inner, w, h, t, "Impact Timeline") diff --git a/src/widgets/languages.py b/src/widgets/languages.py new file mode 100644 index 0000000..2d89052 --- /dev/null +++ b/src/widgets/languages.py @@ -0,0 +1,67 @@ +"""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") -> str: + """Renders the languages donut chart widget.""" + t = THEMES[theme_name] + langs = sorted(languages, key=lambda l: -l.percentage)[:6] + if not langs: + return "" + + # 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): + color = LANG_COLORS.get(lang.language, FOCUS_COLORS[i % len(FOCUS_COLORS)]) + dash = circumference * lang.percentage / 100 + gap = circumference - dash + + arcs += f''' + + + ''' + offset += dash + + ly = i * 22 + legend += f''' + + + {escape(lang.language)} + {lang.percentage:.0f}% + ''' + + # Center circle with top language + top_lang = langs[0].language if langs else "" + center = f''' + + {escape(top_lang)}''' + + inner = f''' + + {arcs} + {center} + {legend} + ''' + + rows_h = max(len(langs) * 22 + 40, 120) + return card_wrapper(inner, 380, rows_h + 36, t, "Languages")