feat(languages): add hidden languages picker and enrich language data

This commit is contained in:
shay
2026-04-18 13:39:44 -04:00
parent 5198eab86a
commit 3e70e4b4ef
6 changed files with 162 additions and 15 deletions
+45
View File
@@ -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,
+13 -4
View File
@@ -59,7 +59,7 @@ function iconSvg(kind: string, color: string): string {
const icons: Record<string, string> = {
commits: `<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: `<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: `<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"/>`,
stars: `<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="none" stroke="${color}" stroke-width="1.2" stroke-linejoin="round"/>`,
repos: `<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: `<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"/>`,
}
@@ -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: {
<rect width="${totalW}" height="${totalH}" rx="16" fill="${t.bg}"/>
<rect x="0.5" y="0.5" width="${totalW-1}" height="${totalH-1}" rx="16" fill="none" stroke="${t.card_border}" stroke-width="1"/>
${header}${embedded}
<text x="${totalW/2}" y="${totalH-8}" text-anchor="middle" font-family="${font}" font-size="9" fill="${t.text_secondary}" opacity="0.5">Generated with ♥</text>
<text x="${totalW/2}" y="${totalH-8}" text-anchor="middle" font-family="${font}" font-size="9" fill="${t.text_secondary}" opacity="0.5">Generated with gh-stats</text>
</svg>`
}
@@ -67,8 +67,7 @@ export function ResultScreen({ username, generating, generatedSvg, generateError
{!generating && !generateError && safeSvg && (
<>
<p className="text-xs text-gray-400 mb-6">Rendered from live GitHub data</p>
<div className="w-full rounded-2xl bg-white shadow-lg ring-1 ring-gray-200 p-6 flex justify-center">
<div className="w-full mt-6 rounded-2xl bg-white shadow-lg ring-1 ring-gray-200 p-6 flex justify-center">
{/*
Force the inline SVG to scale up to the card width. The
composite is authored at 380px wide — without this the
@@ -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<string>()
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 (
<div>
<div className="flex items-center justify-between mb-1.5">
<span className="text-[10px] text-gray-500">Hide languages</span>
{hidden.length > 0 && (
<button
onClick={() => onChange([])}
className="text-[10px] text-gray-400 hover:text-gray-600 transition-colors"
>
Clear
</button>
)}
</div>
<div className="flex flex-wrap gap-1">
{options.map(lang => {
const active = hidden.includes(lang)
return (
<button
key={lang}
onClick={() => toggle(lang)}
className={`px-2 py-0.5 rounded-md text-[10px] transition-colors ${
active
? 'bg-gray-800 text-white border border-gray-800'
: 'bg-white text-gray-500 border border-gray-200 hover:text-gray-800 hover:border-gray-300'
}`}
>
{lang}
</button>
)
})}
</div>
</div>
)
}
function ColorPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) {
return (
<div className="flex gap-1.5 flex-wrap">
@@ -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' && (
<div className="flex items-center justify-between">
<span className="text-[10px] text-gray-500">Max languages</span>
<NumberStepper
value={getWidgetSetting('languages', 'max_languages', 5)}
min={1} max={10}
onChange={v => updateWidgetSetting('languages', 'max_languages', v)}
<div className="flex flex-col gap-2.5">
<div className="flex items-center justify-between">
<span className="text-[10px] text-gray-500">Max languages</span>
<NumberStepper
value={getWidgetSetting('languages', 'max_languages', 5)}
min={1} max={10}
onChange={v => updateWidgetSetting('languages', 'max_languages', v)}
/>
</div>
<HiddenLanguagesPicker
detected={widgetData?.languages ?? []}
hidden={settings.hiddenLanguages}
onChange={next => updateSetting('hiddenLanguages', next)}
/>
</div>
)}
+31 -2
View File
@@ -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
+1 -1
View File
@@ -36,7 +36,7 @@ def icon_svg(kind: str, color: str) -> str:
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"/>',
"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="none" stroke="{color}" stroke-width="1.2" stroke-linejoin="round"/>',
"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"/>',
}