diff --git a/fetcher/src/github.py b/fetcher/src/github.py index 4f8d87d..55842f2 100644 --- a/fetcher/src/github.py +++ b/fetcher/src/github.py @@ -2,6 +2,7 @@ import requests import base64 +from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Optional, Protocol from . import config @@ -46,6 +47,10 @@ class GitHubDataSource(Protocol): """Fetch and encode avatar as base64.""" ... + def fetch_repo_languages(self, full_name: str) -> dict: + """Return {language: bytes} for a single repo, or {} on failure.""" + ... + class DirectAPISource: """Direct GitHub API implementation - for immediate requests.""" @@ -502,6 +507,22 @@ class DirectAPISource: pass return "" + def fetch_repo_languages(self, full_name: str) -> dict: + """Return {language: bytes} for a repo. REST returns exactly this + shape — total is summed client-side.""" + try: + resp = requests.get( + f"{self.base}/repos/{full_name}/languages", + headers=self.headers, + timeout=config.API_TIMEOUT, + ) + if resp.ok: + data = resp.json() + return data if isinstance(data, dict) else {} + except Exception: + pass + return {} + # TODO: Future implementation for queue-based batching # class QueuedAPISource: @@ -542,6 +563,12 @@ def fetch_github_data( events = source.fetch_events(username) commits = source.fetch_commits(username) + # Attach per-repo language byte breakdown. Without this, the languages + # widget falls back to a primary-language repo-count tally, which + # heavily under-represents repos whose primary language has small files + # (e.g. HTML, Jupyter Notebook). + _enrich_repo_languages(repos, source) + # Fetch contribution counts (commits + PRs + issues + reviews) print(" Fetching all-time contribution count...") total_commits = source.fetch_commit_count(username, repos) @@ -578,6 +605,24 @@ def fetch_github_data( } +def _enrich_repo_languages(repos: list, source: GitHubDataSource) -> None: + """Mutates `repos` in-place, attaching `language_bytes: {lang: bytes}` to + each repo. Uses a small thread pool — one REST call per repo is cheap + individually, but sequentially N repos would block the fetch noticeably.""" + if not repos: + return + names = [(i, r["full_name"]) for i, r in enumerate(repos) if r.get("full_name")] + print(f" Fetching language byte breakdown for {len(names)} repos...") + with ThreadPoolExecutor(max_workers=10) as pool: + futures = {pool.submit(source.fetch_repo_languages, fn): i for i, fn in names} + for fut in as_completed(futures): + i = futures[fut] + try: + repos[i]["language_bytes"] = fut.result() or {} + except Exception: + repos[i]["language_bytes"] = {} + + def _fetch_collaborators_data( username: str, repos: list, diff --git a/generator/frontend/src/lib/renderWidgets.ts b/generator/frontend/src/lib/renderWidgets.ts index 5614493..d7211af 100644 --- a/generator/frontend/src/lib/renderWidgets.ts +++ b/generator/frontend/src/lib/renderWidgets.ts @@ -59,7 +59,7 @@ function iconSvg(kind: string, color: string): string { const icons: Record = { commits: ``, prs: ``, - stars: ``, + stars: ``, repos: ``, followers: ``, } @@ -305,6 +305,7 @@ export function renderAllWidgets(opts: { widgetOrder: string[] achievements: AchievementInput[] widgetSettings: PerWidgetSettings + hiddenLanguages?: string[] username: string }): string { const t = THEMES[opts.theme] ?? THEMES.dark @@ -319,8 +320,16 @@ export function renderAllWidgets(opts: { widgetSvgs.collaborators = renderCollaborators(opts.data.collaborators, t, opts.widgetSettings.collaborators) if (enabled.has('focus') && opts.data.focus) widgetSvgs.focus = renderFocus(opts.data.focus, t, opts.widgetSettings.focus) - if (enabled.has('languages') && opts.data.languages) - widgetSvgs.languages = renderLanguages(opts.data.languages, t, opts.widgetSettings.languages) + if (enabled.has('languages') && opts.data.languages) { + // Apply hidden_languages client-side too so the Workshop preview reflects + // the user's choice instantly — backend filtering only kicks in on the + // next prefetch or on POST /generate. + const hiddenSet = new Set(opts.hiddenLanguages ?? []) + const filtered = opts.data.languages.filter(l => !hiddenSet.has(l.language)) + const total = filtered.reduce((a, l) => a + l.percentage, 0) || 1 + const rescaled = filtered.map(l => ({ ...l, percentage: Math.round(l.percentage / total * 1000) / 10 })) + widgetSvgs.languages = renderLanguages(rescaled, t, opts.widgetSettings.languages) + } if (enabled.has('achievements')) widgetSvgs.achievements = renderAchievements(opts.achievements, t, opts.widgetSettings.achievements) @@ -350,6 +359,6 @@ export function renderAllWidgets(opts: { ${header}${embedded} - Generated with ♥ + Generated with gh-stats ` } diff --git a/generator/frontend/src/screens/ResultScreen.tsx b/generator/frontend/src/screens/ResultScreen.tsx index 63db692..a8868d8 100644 --- a/generator/frontend/src/screens/ResultScreen.tsx +++ b/generator/frontend/src/screens/ResultScreen.tsx @@ -67,8 +67,7 @@ export function ResultScreen({ username, generating, generatedSvg, generateError {!generating && !generateError && safeSvg && ( <> -

Rendered from live GitHub data

-
+
{/* Force the inline SVG to scale up to the card width. The composite is authored at 380px wide — without this the diff --git a/generator/frontend/src/screens/WorkshopScreen.tsx b/generator/frontend/src/screens/WorkshopScreen.tsx index 40d036b..5292caf 100644 --- a/generator/frontend/src/screens/WorkshopScreen.tsx +++ b/generator/frontend/src/screens/WorkshopScreen.tsx @@ -110,6 +110,63 @@ function NumberStepper({ value, min, max, onChange }: { ) } +// Common "noise" languages users typically want to hide — shown even when +// the account-level detection hasn't surfaced them yet (e.g., first load). +const COMMON_HIDE_LANGS = ['HTML', 'CSS', 'SCSS', 'Jupyter Notebook', 'TeX', 'Shell', 'Dockerfile', 'Makefile', 'Batchfile'] + +function HiddenLanguagesPicker({ + detected, hidden, onChange, +}: { + detected: { language: string }[] + hidden: string[] + onChange: (next: string[]) => void +}) { + const seen = new Set() + const options: string[] = [] + for (const d of detected) if (d.language && !seen.has(d.language)) { seen.add(d.language); options.push(d.language) } + for (const c of COMMON_HIDE_LANGS) if (!seen.has(c)) { seen.add(c); options.push(c) } + // Preserve any user-set hidden that we haven't otherwise seen. + for (const h of hidden) if (!seen.has(h)) { seen.add(h); options.push(h) } + + const toggle = (lang: string) => { + onChange(hidden.includes(lang) ? hidden.filter(h => h !== lang) : [...hidden, lang]) + } + + return ( +
+
+ Hide languages + {hidden.length > 0 && ( + + )} +
+
+ {options.map(lang => { + const active = hidden.includes(lang) + return ( + + ) + })} +
+
+ ) +} + function ColorPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) { return (
@@ -204,6 +261,7 @@ export function WorkshopScreen({ widgetOrder: ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'], achievements: settings.achievements, widgetSettings: settings.widgetSettings, + hiddenLanguages: settings.hiddenLanguages, username, }) }, [widgetData, settings, username]) @@ -346,12 +404,19 @@ export function WorkshopScreen({ )} {w.id === 'languages' && ( -
- Max languages - updateWidgetSetting('languages', 'max_languages', v)} +
+
+ Max languages + updateWidgetSetting('languages', 'max_languages', v)} + /> +
+
)} diff --git a/generator/src/processor.py b/generator/src/processor.py index 04f2abb..529432c 100644 --- a/generator/src/processor.py +++ b/generator/src/processor.py @@ -463,6 +463,11 @@ def compute_languages(github_data: dict, hidden_languages: list[str] = None) -> """ Compute language distribution from repos. + Prefers per-repo byte breakdowns (`repo["language_bytes"]`) when present — + that matches GitHub's own "Most Used Languages" widget. Falls back to a + primary-language repo-count tally for payloads fetched before the + enrichment step landed. + Args: github_data: GitHub profile data hidden_languages: Optional list of languages to exclude (e.g., ["HTML", "CSS"]) @@ -471,12 +476,36 @@ def compute_languages(github_data: dict, hidden_languages: list[str] = None) -> if hidden_languages is None: hidden_languages = HIDDEN_LANGUAGES + hidden_set = {h for h in hidden_languages} repos = github_data["repos"] - lang_counts = defaultdict(int) + byte_totals: dict[str, int] = defaultdict(int) + have_bytes = False + for r in repos: + lb = r.get("language_bytes") or {} + if not isinstance(lb, dict) or not lb: + continue + have_bytes = True + for lang, n in lb.items(): + if lang and lang not in hidden_set: + byte_totals[lang] += int(n or 0) + + if have_bytes and byte_totals: + total = sum(byte_totals.values()) or 1 + return [ + LanguageData( + language=lang, + percentage=round(size / total * 100, 1), + loc=size, + ) + for lang, size in sorted(byte_totals.items(), key=lambda x: -x[1]) + ] + + # Legacy fallback: repo-count by primary language. + lang_counts: dict[str, int] = defaultdict(int) for r in repos: lang = r.get("language") - if lang and lang not in hidden_languages: + if lang and lang not in hidden_set: lang_counts[lang] += 1 total = sum(lang_counts.values()) or 1 diff --git a/generator/src/utils/svg_helpers.py b/generator/src/utils/svg_helpers.py index 7d081b9..76d6d43 100644 --- a/generator/src/utils/svg_helpers.py +++ b/generator/src/utils/svg_helpers.py @@ -36,7 +36,7 @@ def icon_svg(kind: str, color: str) -> str: icons = { "commits": f'', "prs": f'', - "stars": f'', + "stars": f'', "repos": f'', "followers": f'', }