Author SHA1 Message Date
shayandClaude Opus 5.5 1d32dee489 fix(fetcher): back off on GitHub secondary limits in refresh cron
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:43:40 -05:00
shayandClaude Opus 5.5 0835c64a63 feat(seo): eight-theta rows on migration page; activity-graph heroku note
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:09:03 -08:00
shayandClaude Opus 5.5 60ff6ac7df feat(editor): Get embed code label; numbered create-repo and README steps
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:05:05 -08:00
shayandClaude Opus 5.5 01afeeda4e fix(fetcher): quota reserve and per-tick cap for refresh cron
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:15:57 -08:00
shayandClaude Opus 5.5 d4b4a8bc52 fix(launch): back off build retries on GitHub limits, dedupe fetcher misses, no ad hoc render before first build
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:11:03 -08:00
shayandClaude Opus 5.5 d907815f19 feat(launch): friendly GitHub-limit message on Generate; document the score formula
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 06:12:22 -08:00
shayandClaude Opus 5.5 b737a0171e chore(launch): score collaborators over top 15 repos
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 10:37:41 -08:00
shayandClaude Opus 5.5 53ae54fe98 feat(launch): cap per-user language fetch at 40 repos, raise enrollment caps, fix cap message
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 10:30:52 -08:00
shay e47a67d1a1 feat(seo): link the profile README template 2026-11-29 00:23:36 -08:00
shay f5fab0d6c3 feat(seo): add sigma-five mirror migration row 2026-11-28 10:36:02 -08:00
shay 98547a3f33 feat(seo): add IndexNow key file 2026-11-28 10:27:07 -08:00
shay c0eba0b5a4 feat(growth): themes and alternative pages, result-screen hints 2026-11-28 10:22:36 -08:00
shayandClaude Opus 5.5 3653ef66a5 feat(growth): link the card footer back, copy-on-open, two SEO pages
- composite footer links to gh-stats.com (?ref=card)
- result screen: 'Copy & open your README' copies the snippet
- new pages: github-top-languages-card, github-profile-readme (+ sitemap)
- README snippets wrap the card in a link

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 22:45:30 -08:00
shayandClaude Opus 5.5 74a8146779 feat(deploy): log one access line per request to stdout
Each gunicorn service (edge, fetcher, generator) now writes a request line
("GET /x HTTP/1.1" 200 12ms) to stdout, which Pantheos ingests for request
logs and rps / 5xx / p95. /metrics and /health are left out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:50:32 -04:00
shayandClaude Opus 5 02e7270440 feat(seo): add a migration landing page and list it in the sitemap
gh-stats.com had exactly one indexable URL. The app is a client-rendered
SPA with no content routes, so nothing ranked for anything but the brand
name, and acquisition stopped whenever a push channel stopped.

This adds a static page targeting the migration demand from
anuraghazra/github-readme-stats, which is marked no longer maintained.
Content is reused from the README's migration section. Vite copies
public/ into dist/, which the Dockerfile copies to src/static/, and the
Flask catch-all serves static paths before falling back to index.html,
so this needs no routing change.

It carries the same GA4 stream as index.html so the page is measurable
rather than another unattributed channel.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HPCsXoXrazZsFpxdLi8Pvn
2026-09-06 13:15:08 -07:00
shayandClaude Opus 5 9b5a13f26b fix(frontend): resolve the profile README link against HEAD, not main.
The link hardcoded /edit/main/README.md, so anyone whose profile repo
still defaults to master got a 404. GitHub resolves HEAD to the default
branch, verified against repos where /blob/main/ 404s and /blob/HEAD/
returns 200.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwMoSbmK77Ph7XaV5YnAdS
2026-08-25 08:28:41 -07:00
shayandClaude Opus 5 a25ae33f29 fix(frontend): give the embed snippet somewhere to paste.
The result screen ended at the snippet and a copy button. GitHub only
renders a profile README from the repo named exactly after the account,
and 15 of 23 arrivals did not have that repo, so the copy button was a
dead end for most people. Add two links under the snippet: open the
README, or create the repo.

Also serve a placeholder card instead of a JSON 400 when someone pastes
the README snippet without swapping YOUR_USERNAME for their own name,
and show a live example card in the README.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwMoSbmK77Ph7XaV5YnAdS
2026-08-25 08:10:32 -07:00
ShayManorandClaude Opus 5 27645048f1 feat(deploy): add self-host compose file and document self-hosting
The repo had three Dockerfiles but nothing that ran them together, and the
README never mentioned self-hosting. The only deploy path was deploy/compose.yml,
which is bound to the production box: it pulls private ghcr images and hard-fails
on seven env vars including OAuth credentials, so nobody else could run it.

Every one of those vars already has a default in the service config; the
:?missing guards are a production-deploy check, not an application requirement.
This adds a root compose file that builds the three services from source and
needs only GITHUB_PAT and FETCHER_INTERNAL_TOKEN.

deploy/compose.yml is unchanged, so production is unaffected.

Verified by running it: all three images build, all five containers start, the
generator serves the SPA and /api/health, and edge answers /<username> with
upstream_ok true.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwMoSbmK77Ph7XaV5YnAdS
2026-08-23 10:33:26 -07:00
shayandClaude Opus 5 107273a1c8 fix(auth): send an https redirect_uri so GitHub sign-in works
The OAuth app registers https://gh-stats.com/api/auth/github/callback, but
the app was sending the http:// form. GitHub compares redirect_uri to the
registered callback character for character, so it refused every attempt
with "The redirect_uri is not associated with this application" and showed
users a warning that the app might be redirecting them somewhere they were
not expecting. Sign-in has been failing for everyone, and it gates themes,
custom tags and achievements.

_derived_redirect_uri built the URL from X-Forwarded-Proto, falling back to
request.scheme. The cloudflared tunnel does not reliably forward that
header, so the scheme resolved to http. The comment above it claimed the
headers are set, which is what hid this.

Anything that is not localhost or 127.0.0.1 is https. Local dev keeps
working over plain http, pinned by a test.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwMoSbmK77Ph7XaV5YnAdS
2026-08-23 09:38:26 -07:00
shay 12f6890f57 feat(readme): add migration guide for transitioning from github-readme-stats. 2026-08-22 16:33:29 -07:00
shay 584306beb0 feat(api): add widget_name parameter to render_composite_adhoc function. 2026-08-22 16:33:24 -07:00
shayandClaude Opus 5 319f37761c chore: add MIT license
The repo had no license file, which means all rights reserved: nobody
could legally fork or reuse it. MIT is the category norm.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwMoSbmK77Ph7XaV5YnAdS
2026-08-22 16:10:44 -07:00
shayandClaude Opus 5 faf41ad952 feat(frontend): show the product, keep work across sign-in, add social preview
Of 27 people who typed a username in the last 14 days, 15 left before a
widget rendered. The landing page showed zero pixels of a product whose
entire value is visual, so it now leads with a live example card and says
concretely what you get.

Sign-in used to discard everything: with no router the OAuth `next` is
always "/", so users came back to an empty search box with their theme,
widget order and achievements gone. Persist work-in-progress to
sessionStorage and restore it on mount.

The Workshop preview seeds from demo data (grade A, 842 commits,
collaborators named alex/jordan/sam) with nothing saying so, so users saw
numbers they knew were wrong. Label it until real data arrives.

Add title, description, canonical, OG and Twitter tags, robots.txt and a
sitemap. The page was a 445-byte shell titled "GitHub Widgets", so every
link shared anywhere rendered with no image and no description.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwMoSbmK77Ph7XaV5YnAdS
2026-08-22 16:10:44 -07:00
shayandClaude Opus 5 0904c4bb9f feat(generator): raise enrollment ceiling, add burst guard, stop enqueue loop
ENROLLMENT_DAILY_CAP was 50, so any traffic spike past 50 new users in a
day was turned away with a rate_limited card. Raise the default to 500 and
add ENROLLMENT_HOURLY_CAP=60. The hourly guard is the one that actually
protects the shared PAT: a new user costs ~37 REST calls (p90 ~104)
against a 5000/hr budget, and a spike arrives inside an hour rather than
spread over a day. Counted off users.enrolled_at, so no schema change.

Also stop an unbounded enqueue loop. `name` is drawn inside the composite
and never persisted standalone, and `achievements` renders nothing until
the user authors one, so their SVG is permanently absent and every request
re-enqueued a build that could never produce it. Only self-heal when no
build has actually landed, keyed off widget_data for the current hash.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwMoSbmK77Ph7XaV5YnAdS
2026-08-22 16:10:44 -07:00
shayandClaude Opus 5 769cde552d feat(widgets): attribution on every widget, and make it legible
Five of the seven standalone widgets and all three placeholder cards
carried no attribution at all, and where it did render it was font-size 9
at opacity 0.5 (about 2.1:1 contrast) at the bottom of a 1500px card. Each
embedded widget sits on a public profile and is the only organic
acquisition surface we have.

Shared helper so the styling can't drift again. font-size 10, opacity
0.75 (about 3.1:1), still using the theme's text_secondary so it stays
roughly 4x fainter than the user's own content. Composite output is
byte-identical in size; four standalone cards grow 16px where the footer
would otherwise collide with existing content.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwMoSbmK77Ph7XaV5YnAdS
2026-08-22 16:10:26 -07:00
shayandClaude Opus 5 06ab1c878e fix(fetcher): guard REST calls so a rate limit can't poison user records
The five REST calls parsed `.json()` with no status check, so a 403
{"message": "API rate limit exceeded..."} body was returned as user data.
`_is_github_not_found` only matched "Not Found", so it was recorded as a
successful fetch and upsert_user overwrote the user's last-good row. Every
user touched during the exhaustion window then served a blank card for up
to 24h while /metrics reported ok.

Reuse the existing `_raise_if_transient` on all five so exhaustion raises
GitHubTransientError before the upsert, preserving last-good and letting
the caller retry. `_raise_if_transient` was GraphQL-shaped and crashed on
the JSON arrays the list endpoints return, so it now ignores non-dict
bodies. A rate limit inside the per-repo fan-out aborts the fetch; a 404
on a single repo stays non-fatal.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwMoSbmK77Ph7XaV5YnAdS
2026-08-22 16:10:26 -07:00
shay eea1734a04 fix(languages): center donut chart and legend based on card midline. 2026-07-25 16:23:28 -07:00
shay fe4bb4e87e fix(api): normalize GitHub usernames to lowercase and update tests. 2026-07-19 21:01:40 -07:00
shayandClaude Opus 4.8 0586f83a33 fix(fetcher): keep last-good counts on GitHub rate limits + expose fetch metrics
Rate-limited / 5xx / network failures were silently returning 0 from the
commit- and PR-count paths, then overwriting good values in fetcher.db —
turning a traffic spike into permanently-wrong "0 commits" cards. Raise
GitHubTransientError instead so the fetch aborts and the last-good row is
retained; genuine NOT_FOUND still yields 0.

Add a shared fetch-outcome counter (fetch_metrics table, spanning the web
workers and the cron container) surfaced at an unauthenticated GET /metrics
as ghstats_fetch_total{outcome="ok|not_found|rate_limited|error"}, so rate
limits are visible to the monitoring stack instead of dying silently.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 11:45:42 -07:00
shay d1e89fb1c3 fix(api): normalize GitHub usernames to lowercase and update tests. 2026-06-12 01:37:08 -07:00
shay e53d1cfbe0 fix(api): normalize GitHub usernames to lowercase and update tests. 2026-06-12 01:17:53 -07:00
shay c54b5ac6ff feat(ResultScreen): wraps embed image markdown in a link to origin 2026-06-11 21:33:39 -07:00
shay ceac269738 feat(ResultScreen): wraps embed image markdown in a link to origin 2026-06-11 16:12:06 -07:00
shay 78299fa2b9 feat(GrowthChart): refactor y-coordinate mapping and add 2026-05-29 10:27:45 -07:00
shay 410b503877 feat(Analytics): add daily stats rollup to persist data beyond pruning 2026-05-27 10:47:42 -07:00
shay 61b8090c64 feat(api): add endpoint for retrieving growth data for the dashboard 2026-05-27 10:28:51 -07:00
shay a1d1813a51 feat(api): add endpoint for retrieving growth data for the dashboard 2026-05-27 10:23:49 -07:00
shay f66088e5d6 feat(api): add endpoint for retrieving growth data for the dashboard 2026-05-27 10:21:32 -07:00
shay 99c40cb0ce feat(api): add endpoint for retrieving growth data for the dashboard 2026-05-27 10:16:11 -07:00
shay e7a0521ff6 feat(api): implement self-healing build enqueue for user widgets 2026-05-26 15:23:14 -07:00
shay 2be8dc1ca3 feat(firebase): add Firebase initialization script to index.html 2026-05-26 15:20:41 -07:00
shay 369d42bb5f feat(api): implement auto-enrollment for unknown users on first hit 2026-05-26 15:10:20 -07:00
shay 151f330d31 feat(analytics): add request tracking decorator for API endpoints 2026-05-12 01:47:13 -04:00
shay 01927b2173 feat(analytics): include render-only users in activity count query 2026-05-11 23:34:57 -04:00
shay d4cbbae82a feat(api): add basic auth protection to /dev dashboard route 2026-05-11 19:03:26 -04:00
shay ef48d2581b feat(admin dashboard): add admin dashboard 2026-05-11 18:26:43 -04:00
shay 00bf46968a feat(admin dashboard): add admin dashboard 2026-05-11 18:25:09 -04:00
shay ab7c9b32aa feat(README): update 2026-05-08 19:46:01 -04:00
shay 05efac8fd2 feat(README): update 2026-05-08 19:45:37 -04:00
shay 9d15dd6c94 feat(grade): add data attributes for footer attribution in widgets 2026-05-06 16:38:59 -04:00
shay 8f7b27f806 feat(grade): add footer attribution for visual consistency in widget 2026-05-06 10:32:00 -04:00
shay 99378e13cd feat(api): add compatibility route for top-langs to handle upstream URLs. 2026-05-06 10:26:53 -04:00
shay 9639051398 feat(ResultScreen): add widget status and manual refresh functionality. 2026-05-04 21:52:44 -04:00
shay 8dbbd16cf9 feat(api): auto-enroll users typing unknown usernames into workshop 2026-05-04 16:34:12 -04:00
shay 6edf98334c feat(api): add idempotency check for already queued builds in callback 2026-05-04 15:52:03 -04:00
shay 673eb5b39d feat(tests): implement dynamic GraphQL response handling for tests 2026-05-04 12:56:52 -04:00
shay 4a1d31ffdd feat(api): implement async fetch with callback to enqueue build job 2026-05-04 12:35:41 -04:00
shay 50dd73a0de feat(api): distinguish between not enrolled and not found user statuses 2026-05-03 20:38:21 -04:00
shay 954f259b8f feat(worker): update worker to render and persist SVGs with widget data 2026-04-25 12:28:38 -04:00
shay 7f1e53cfad feat(db): normalize usernames in enrollment_rank for case insensitivity 2026-04-22 12:50:14 -04:00
shay 5102a36238 feat(workshop): refine login banner to display only for signed-in users. 2026-04-21 15:40:46 -04:00
shay 9cc9de2147 feat(api): add shortcut for rendering grade widget with username query. 2026-04-21 15:09:17 -04:00
shay a4ca81eab9 feat(workshop): simplify button visibility and update user message. 2026-04-21 14:46:46 -04:00
shay 118c8b7cc4 feat(workshop): add drag-and-drop functionality for achievements list 2026-04-21 14:10:37 -04:00
shay 113e4747cf feat(readme): replace hero widget image with composite widget example 2026-04-21 14:09:13 -04:00
shay a06bd2a20c feat(readme): replace hero widget image with composite widget example 2026-04-21 14:07:26 -04:00
shay 8941ed2f15 feat(readme): replace hero widget image with composite widget example 2026-04-21 14:07:15 -04:00
shay 048756c787 feat(workshop-screen): add generate button for editable users 2026-04-21 11:43:00 -04:00
shay fc4e8e4da5 feat(readme): update instructions and add table of contents section 2026-04-20 16:13:28 -04:00
shay b5bba19d46 feat(readme): update instructions and add table of contents section 2026-04-20 16:05:42 -04:00
shay 795f49d0a8 feat(api): update ResultScreen to use fallback URL for embed snippet 2026-04-20 16:05:33 -04:00
shay 451cb45788 feat(api): add sanitize_settings_query function for URL params handling 2026-04-20 15:04:15 -04:00
shay 96dc98142f feat(composite): add show_name parameter to control header visibility. 2026-04-20 15:04:09 -04:00
shay b66f966adb feat(workshop): refactor achievements section for improved layout. 2026-04-20 14:38:29 -04:00
shay 599c1ed672 feat(processor): refactor byte tally logic for authored repositories only. 2026-04-20 14:19:26 -04:00
shay fdd6b61172 feat(rendering): adjust text position in SVG for better visibility. 2026-04-20 14:19:18 -04:00
shay 13cc2b4eed feat(build-system): introduce BUILD_VERSION for widget invalidation logic. 2026-04-20 14:09:04 -04:00
shay a88561073a feat(result-screen): add onRegenerate prop to ResultScreen component. 2026-04-20 13:56:43 -04:00
shay 58fd6fbe67 feat(streaks): replace show_dates with customizable color setting. 2026-04-20 13:49:21 -04:00
shay 39d07fb7e0 feat(processor): add consistency scoring based on active commit weeks. 2026-04-20 13:43:08 -04:00
shay bd59910e54 feat(workshop): fetch and set user-specific widget settings on load. 2026-04-20 13:33:10 -04:00
shay e60acaca74 feat(workshop): implement drag-and-drop reordering for widgets. 2026-04-20 13:28:33 -04:00
shay ca795f7e71 feat(api): add 'streaks' to allowed widgets and settings structure. 2026-04-20 13:05:40 -04:00
shay 4febce9fca feat(api): add 'streaks' to allowed widgets and settings structure. 2026-04-20 13:05:34 -04:00
shay f43beb2ef6 feat(workflows): add health check workflow for automated monitoring. 2026-04-20 12:57:58 -04:00
Shay ManorandGitHub b98b32f030 Merge pull request #3 from ShayManor/feat/streaks-widget
Feat/streaks widget
2026-04-20 12:45:38 -04:00
102 changed files with 12312 additions and 698 deletions
+14
View File
@@ -0,0 +1,14 @@
# Copy to .env and fill in. Only these two matter.
# A GitHub personal access token. Classic or fine-grained, no scopes needed
# for public data - it is only used to raise your GitHub API rate limit.
# Create one at https://github.com/settings/tokens
GITHUB_PAT=
# Shared secret the three services use to talk to each other. Any random
# string; it never leaves your machine. Generate one with:
# openssl rand -hex 32
FETCHER_INTERNAL_TOKEN=
# Port the card service listens on (http://localhost:PORT).
#GHSTATS_PORT=5003
+5
View File
@@ -25,6 +25,8 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: docker/setup-qemu-action@v3
- uses: docker/setup-buildx-action@v3 - uses: docker/setup-buildx-action@v3
- name: Log in to GHCR - name: Log in to GHCR
@@ -61,6 +63,7 @@ jobs:
uses: docker/build-push-action@v6 uses: docker/build-push-action@v6
with: with:
context: ./${{ matrix.service }} context: ./${{ matrix.service }}
platforms: linux/amd64,linux/arm64
push: ${{ github.event_name == 'push' }} push: ${{ github.event_name == 'push' }}
tags: ${{ steps.meta.outputs.tags }} tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }} labels: ${{ steps.meta.outputs.labels }}
@@ -84,4 +87,6 @@ jobs:
GH_OAUTH_CLIENT_SECRET: ${{ secrets.GH_OAUTH_CLIENT_SECRET }} GH_OAUTH_CLIENT_SECRET: ${{ secrets.GH_OAUTH_CLIENT_SECRET }}
GENERATOR_SECRET_KEY: ${{ secrets.GENERATOR_SECRET_KEY }} GENERATOR_SECRET_KEY: ${{ secrets.GENERATOR_SECRET_KEY }}
ALLOWED_ORIGINS: ${{ secrets.ALLOWED_ORIGINS }} ALLOWED_ORIGINS: ${{ secrets.ALLOWED_ORIGINS }}
DEV_DASHBOARD_USER: ${{ secrets.DEV_DASHBOARD_USER }}
DEV_DASHBOARD_PASSWORD: ${{ secrets.DEV_DASHBOARD_PASSWORD }}
run: ./deploy/deploy.sh run: ./deploy/deploy.sh
+258
View File
@@ -0,0 +1,258 @@
name: health check
on:
schedule:
# Every 15 minutes — matches the refresh cron cadence
- cron: '*/15 * * * *'
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
concurrency:
group: health-check-${{ github.ref }}
cancel-in-progress: false
jobs:
tests:
name: pytest-${{ matrix.service }}
runs-on: ubuntu-latest
# Scheduled runs are an uptime probe only — skip the test matrix.
if: github.event_name != 'schedule'
strategy:
fail-fast: false
matrix:
service: [fetcher, generator, edge]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
cache-dependency-path: ${{ matrix.service }}/requirements.txt
- name: Install dependencies
working-directory: ${{ matrix.service }}
run: pip install -r requirements.txt
- name: Run pytest
id: pytest
working-directory: ${{ matrix.service }}
run: |
set -o pipefail
pytest -v --tb=short --color=no 2>&1 | tee "/tmp/pytest-${SERVICE}.log"
env:
SERVICE: ${{ matrix.service }}
- name: Upload pytest log
if: always()
uses: actions/upload-artifact@v4
with:
name: pytest-${{ matrix.service }}
path: /tmp/pytest-${{ matrix.service }}.log
retention-days: 14
site-health:
name: site-health
runs-on: ubuntu-latest
# Only probe production on schedule / manual / push to main — not on
# PRs, where failures wouldn't indicate a prod incident.
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')
steps:
- name: Check edge homepage
id: check-edge
run: |
echo "GET https://gh-stats.com/"
HTTP_CODE=$(curl -sSL -o /tmp/edge-home.html -w "%{http_code}" --max-time 30 https://gh-stats.com/)
echo "HTTP $HTTP_CODE"
if [ "$HTTP_CODE" != "200" ]; then
echo "::error::Edge homepage returned HTTP $HTTP_CODE"
head -c 500 /tmp/edge-home.html || true
exit 1
fi
- name: Check widget SVG endpoint
id: check-widget
run: |
# Cloudflare routes /api/* to the generator directly. The bare
# /<user> and /<user>/<widget>.svg paths land on the SPA shell
# in prod, so we probe the canonical /api/<user>/<widget>.svg.
URL="https://gh-stats.com/api/ShayManor/grade.svg"
echo "GET $URL"
HTTP_CODE=$(curl -sS -D /tmp/widget-headers.txt -o /tmp/widget-body.svg \
-w "%{http_code}" --max-time 30 "$URL")
echo "HTTP $HTTP_CODE"
cat /tmp/widget-headers.txt
if [ "$HTTP_CODE" != "200" ]; then
echo "::error::Widget endpoint returned HTTP $HTTP_CODE"
exit 1
fi
CT=$(grep -i '^content-type:' /tmp/widget-headers.txt | tail -n1 | awk '{print $2}' | tr -d '\r' || true)
case "$CT" in
image/svg+xml*) : ;;
*) echo "::error::Unexpected Content-Type='$CT' (expected image/svg+xml)"; exit 1;;
esac
if ! head -c 200 /tmp/widget-body.svg | grep -q '<svg'; then
echo "::error::Response body does not look like SVG"
head -c 200 /tmp/widget-body.svg; echo
exit 1
fi
STATUS=$(grep -i '^x-widget-status:' /tmp/widget-headers.txt | tail -n1 | awk '{print $2}' | tr -d '\r' || true)
# ready / building / rate_limited are healthy; absent is fine
# on cache hits; not_found is a failure.
case "$STATUS" in
""|ready|building|rate_limited) echo "X-Widget-Status='${STATUS:-<absent>}' (ok)";;
*) echo "::error::Unhealthy X-Widget-Status='$STATUS'"; exit 1;;
esac
- name: Check generator health pipeline
id: check-api
run: |
# Generator's purpose-built liveness probe, routed through
# Cloudflare's /api/* rule.
URL="https://gh-stats.com/api/health"
echo "GET $URL"
BODY=$(curl -sS --max-time 30 -w "\n%{http_code}" "$URL")
HTTP_CODE=$(printf '%s\n' "$BODY" | tail -n1)
JSON=$(printf '%s\n' "$BODY" | sed '$d')
echo "HTTP $HTTP_CODE"
echo "$JSON"
if [ "$HTTP_CODE" != "200" ]; then
echo "::error::/api/health returned HTTP $HTTP_CODE"
exit 1
fi
STATUS=$(printf '%s' "$JSON" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("status",""))' 2>/dev/null || echo "")
if [ "$STATUS" != "ok" ]; then
echo "::error::/api/health reports status='$STATUS' (expected 'ok')"
exit 1
fi
echo "generator pipeline healthy"
notify:
name: notify-on-failure
runs-on: ubuntu-latest
needs: [tests, site-health]
if: always() && (needs.tests.result == 'failure' || needs.site-health.result == 'failure')
env:
TESTS_RESULT: ${{ needs.tests.result }}
HEALTH_RESULT: ${{ needs.site-health.result }}
EVENT_NAME: ${{ github.event_name }}
REF_NAME: ${{ github.ref_name }}
COMMIT_SHA: ${{ github.sha }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
SERVER_URL: ${{ github.server_url }}
RUN_ID: ${{ github.run_id }}
steps:
- name: Download pytest logs
if: needs.tests.result == 'failure'
uses: actions/download-artifact@v4
with:
path: logs
pattern: pytest-*
continue-on-error: true
- name: Assemble email body
run: |
NOW=$(date -u '+%Y-%m-%d %H:%M:%S UTC')
RUN_URL="${SERVER_URL}/${REPO}/actions/runs/${RUN_ID}"
{
echo "gh-stats.com — health check failed"
echo "===================================="
echo ""
case "$EVENT_NAME" in
schedule) echo "Trigger: scheduled uptime probe";;
push) echo "Trigger: push to ${REF_NAME} (${COMMIT_SHA})";;
pull_request) echo "Trigger: PR #${PR_NUMBER} → main";;
workflow_dispatch) echo "Trigger: manual run";;
*) echo "Trigger: ${EVENT_NAME}";;
esac
echo "Time: $NOW"
echo "Repo: ${REPO}"
echo ""
echo "Job results"
echo "-----------"
printf " %-14s %s\n" "pytest:" "${TESTS_RESULT}"
printf " %-14s %s\n" "site-health:" "${HEALTH_RESULT}"
echo ""
if [ "$HEALTH_RESULT" = "failure" ]; then
echo "Site health"
echo "-----------"
echo " One or more endpoints on https://gh-stats.com are not"
echo " responding as expected. See the run logs for the failing"
echo " step and its HTTP code."
echo ""
fi
if [ "$TESTS_RESULT" = "failure" ] && [ -d logs ]; then
echo "Failing tests"
echo "-------------"
for dir in logs/pytest-*; do
[ -d "$dir" ] || continue
service=${dir#logs/pytest-}
log="$dir/pytest-${service}.log"
[ -f "$log" ] || continue
# Did this service actually fail? pytest prints FAILED lines
# per failure and a summary like "=== 3 failed ...". If
# neither appears, skip it.
if ! grep -qE '^(FAILED |=+ .* failed)' "$log"; then
continue
fi
echo ""
echo "[$service]"
grep -E '^(FAILED |=+ .* (failed|error))' "$log" | head -n 20
echo "..."
tail -n 60 "$log"
done
echo ""
fi
echo "Full logs"
echo "---------"
echo " $RUN_URL"
echo ""
echo "--"
echo "github-readme-stats automated monitor"
} > /tmp/email-body.txt
echo "----- email body -----"
cat /tmp/email-body.txt
echo "----------------------"
- name: Send email via ntfy
env:
NTFY_TOKEN: ${{ secrets.NTFY_ACCESS_TOKEN }}
NTFY_TOPIC: ${{ secrets.NTFY_TOPIC }}
NOTIFY_EMAIL: ${{ secrets.NOTIFY_EMAIL }}
run: |
missing=()
[ -z "$NTFY_TOKEN" ] && missing+=("NTFY_ACCESS_TOKEN")
[ -z "$NTFY_TOPIC" ] && missing+=("NTFY_TOPIC")
[ -z "$NOTIFY_EMAIL" ] && missing+=("NOTIFY_EMAIL")
if [ ${#missing[@]} -gt 0 ]; then
echo "::error::Missing required secret(s): ${missing[*]}"
echo "::error::Configure at: Settings → Secrets and variables → Actions"
exit 1
fi
if [ "$HEALTH_RESULT" = "failure" ] && [ "$TESTS_RESULT" = "failure" ]; then
SUBJECT="gh-stats.com is DOWN and tests are failing"
elif [ "$HEALTH_RESULT" = "failure" ]; then
SUBJECT="gh-stats.com is DOWN"
else
SUBJECT="gh-stats.com tests failed on ${REF_NAME}"
fi
RUN_URL="${SERVER_URL}/${REPO}/actions/runs/${RUN_ID}"
curl -fsS \
-H "Title: $SUBJECT" \
-H "Priority: high" \
-H "Tags: warning,rotating_light,gh-stats" \
-H "Email: $NOTIFY_EMAIL" \
-H "Click: $RUN_URL" \
-H "Authorization: Bearer $NTFY_TOKEN" \
--data-binary @/tmp/email-body.txt \
"https://ntfy.sh/$NTFY_TOPIC"
+1
View File
@@ -241,3 +241,4 @@ screenshots/
**/*.md **/*.md
!README.md !README.md
!**/README.md !**/README.md
/data/
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Shay Manor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+364 -144
View File
@@ -5,215 +5,435 @@
A single SVG widget you drop into your GitHub profile README. It scores A single SVG widget you drop into your GitHub profile README. It scores
your account, charts your contribution timeline, highlights your top your account, charts your contribution timeline, highlights your top
collaborators, breaks down your languages, and earns you tags like collaborators, breaks down your languages, tracks your commit streaks,
`Backend`, `ML`, or `Founder #42`. and earns you tags like `Backend`, `ML`, or `Founder #42`.
![hero widget](https://gh-stats.com/ShayManor) [![example card](https://gh-stats.com/api/shaymanor)](https://gh-stats.com)
That card is live, not a screenshot. Swap in your own username:
```md
[![my stats](https://gh-stats.com/api/YOUR_USERNAME)](https://gh-stats.com)
```
<img src="./assets/examples/composite-midnight.svg" width="420" alt="composite widget, midnight theme" />
<details>
<summary>Table of contents (click to expand)</summary>
- [Quick start](#quick-start)
- [Themes](#themes)
- [Individual widgets](#individual-widgets)
- [Migrating from github-readme-stats](#migrating-from-github-readme-stats)
- [Query parameter reference](#query-parameter-reference)
- [Auto-awarded tags](#auto-awarded-tags)
- [Refreshing your data](#refreshing-your-data)
- [FAQ](#faq)
- [Gallery](#gallery)
</details>
--- ---
## Get your widget in 30 seconds ## Quick start
1. Open `https://gh-stats.com/` in a browser. 1. Open <https://gh-stats.com/api/>.
2. Type your GitHub username and hit **Continue**. 2. Sign in with GitHub. Signing in is how you prove ownership of the
3. Pick a theme, reorder widgets, add custom tags / achievements. username, and it unlocks the editor.
4. Click **Generate** — the SVG is built on the server and cached. 3. Pick a theme, reorder widgets, add any custom tags or achievements.
5. Copy the one-liner and paste it into your profile README: 4. Click **Get embed code**.
5. Paste this one line into your profile README:
```markdown ```md
![my stats](https://gh-stats.com/YOUR_USERNAME) [![my stats](https://gh-stats.com/api/YOUR_USERNAME)](https://gh-stats.com)
``` ```
That's it. Every push of GitHub activity is picked up by a 15-minute The image URL is stable. Once it's in your README you can change
refresh cron, so the image stays current without you doing anything. themes, tags, or widget order in the editor at any time without
touching the markdown.
--- > [!NOTE]
> Only public GitHub activity is counted. Private repos, private
## What's in the widget > commit counts, and contributions to org-restricted repos are never
> visible to the fetcher.
| Widget | What it shows |
|---|---|
| **Grade** | Overall score (0–100) + letter grade + top tags |
| **Impact Timeline** | Smooth contribution curve over the last 6 months |
| **Top Collaborators** | Avatars + shared-repo + commit bars |
| **Recent Focus** | What you've actually been working on lately |
| **Languages** | Your language mix, weighted by active code |
| **Achievements** | Hand-entered credentials — hackathons, talks, awards |
Widgets are composed into a single card, or you can embed any one of
them on its own — see [Individual widgets](#individual-widgets).
--- ---
## Themes ## Themes
Pass `?theme=<name>` or pick in the Workshop. Five built-ins: Pass `?theme=<name>` on the URL, or pick one in the editor.
| Theme | Tone | | Theme | Preview |
|---|---| |---|---|
| `midnight` *(default)* | dark, soft blue accents | | `midnight` (default) | <img src="./assets/examples/composite-midnight.svg" width="280" /> |
| `onyx` | deep black, neon violet | | `onyx` | <img src="./assets/examples/composite-onyx.svg" width="280" /> |
| `nord` | muted pastel on slate | | `nord` | <img src="./assets/examples/composite-nord.svg" width="280" /> |
| `clean` | white, understated | | `clean` | <img src="./assets/examples/composite-clean.svg" width="280" /> |
| `paper` | warm off-white | | `paper` | <img src="./assets/examples/composite-paper.svg" width="280" /> |
```markdown ```md
![my stats](https://gh-stats.com/YOUR_USERNAME?theme=onyx) ![stats](https://gh-stats.com/api/YOUR_USERNAME?theme=onyx)
```
### Auto-switching for dark and light mode
Add GitHub's theme suffix to serve a different image to dark vs. light
viewers:
```md
![dark](https://gh-stats.com/api/YOUR_USERNAME?theme=onyx#gh-dark-mode-only)
![light](https://gh-stats.com/api/YOUR_USERNAME?theme=clean#gh-light-mode-only)
```
Or use `<picture>` for precise `prefers-color-scheme` control:
```html
<picture>
<source srcset="https://gh-stats.com/api/YOUR_USERNAME?theme=onyx"
media="(prefers-color-scheme: dark)" />
<source srcset="https://gh-stats.com/api/YOUR_USERNAME?theme=clean"
media="(prefers-color-scheme: light)" />
<img src="https://gh-stats.com/api/YOUR_USERNAME" />
</picture>
``` ```
--- ---
## Individual widgets ## Individual widgets
Don't want the full composite? Embed exactly one: Every widget is independently addressable at
`https://gh-stats.com/api/<username>/<widget>.svg`. Embed one, two, or all
of them.
```markdown ### Grade
![grade](https://gh-stats.com/YOUR_USERNAME/grade.svg)
![impact](https://gh-stats.com/YOUR_USERNAME/impact.svg) Overall score (0 to 100), letter grade, and your top role tags.
![collaborators](https://gh-stats.com/YOUR_USERNAME/collaborators.svg)
![focus](https://gh-stats.com/YOUR_USERNAME/focus.svg) <img src="./assets/examples/grade.svg" width="380" alt="grade widget" />
![languages](https://gh-stats.com/YOUR_USERNAME/languages.svg)
![achievements](https://gh-stats.com/YOUR_USERNAME/achievements.svg) ```md
![grade](https://gh-stats.com/api/YOUR_USERNAME/grade.svg)
``` ```
Put two side-by-side with an HTML table: #### How the score works
The score is a weighted sum of seven public signals. Each signal earns
0 to 100 points, reaching 100 at the cap shown, and the weights add up to
100%.
| Signal | Weight | Cap |
| --- | --- | --- |
| Contributions, all time (commits, PRs, issues, reviews) | 33% | 3,000 |
| Active weeks in the last year | 22% | 40 |
| Repositories (owned and contributed to, at most 50 counted) | 15% | 40 |
| Stars across those repositories | 11% | 200 |
| Forks across those repositories | 8% | 20 |
| Recent public events | 8% | 80 |
| Followers | 3% | 100 |
Letters follow the total: S++ from 97, S+ 93, S 89, A++ 86, A+ 82, A 78,
A- 72, B++ 68, B+ 64, B 58, B- 50, C+ 42, and C below that. The score
measures the volume and regularity of public activity, not code quality.
Private work is invisible to it. To leave it off your card, turn off the
Grade widget in the editor.
### Impact
Your contribution volume over the last 6 months, drawn as a smooth area
chart.
<img src="./assets/examples/impact.svg" width="380" alt="impact widget" />
```md
![impact](https://gh-stats.com/api/YOUR_USERNAME/impact.svg)
```
### Streaks
Current and longest contribution streaks.
<img src="./assets/examples/streaks.svg" width="380" alt="streaks widget" />
```md
![streaks](https://gh-stats.com/api/YOUR_USERNAME/streaks.svg)
```
### Top collaborators
The people you actually work with, filtered down to repos of a
reasonable size so a drive-by PR to `react` does not put the React team
on your card.
<img src="./assets/examples/collaborators.svg" width="380" alt="collaborators widget" />
```md
![collaborators](https://gh-stats.com/api/YOUR_USERNAME/collaborators.svg)
```
### Recent focus
What you have actually been working on lately, grouped by topic.
<img src="./assets/examples/focus.svg" width="380" alt="focus widget" />
```md
![focus](https://gh-stats.com/api/YOUR_USERNAME/focus.svg)
```
### Languages
Your language mix, weighted by bytes in repos you authored. Forks with
no meaningful contribution are ignored.
<img src="./assets/examples/languages.svg" width="380" alt="languages widget" />
```md
![languages](https://gh-stats.com/api/YOUR_USERNAME/languages.svg)
```
### Achievements
Hand-entered lines for hackathons, talks, awards, and certifications.
<img src="./assets/examples/achievements.svg" width="380" alt="achievements widget" />
```md
![achievements](https://gh-stats.com/api/YOUR_USERNAME/achievements.svg)
```
### Side by side
GitHub strips inline CSS, so an HTML table is the simplest way to put
two widgets next to each other.
```html ```html
<table><tr> <table><tr>
<td><img src="https://gh-stats.com/YOUR_USERNAME/grade.svg"/></td> <td><img src="https://gh-stats.com/api/YOUR_USERNAME/grade.svg" /></td>
<td><img src="https://gh-stats.com/YOUR_USERNAME/languages.svg"/></td> <td><img src="https://gh-stats.com/api/YOUR_USERNAME/languages.svg" /></td>
</tr></table> </tr></table>
``` ```
--- ---
## Customization ## Migrating from github-readme-stats
Everything is editable from the Workshop UI — the settings are saved [`anuraghazra/github-readme-stats`](https://github.com/anuraghazra/github-readme-stats)
against your username, so re-embedding picks them up automatically. is the card most profile READMEs use, and it is a good project. Its README now
carries a deprecation notice pointing at a successor, so if you are looking to
move, the common URL shapes work here with only the domain changed.
- **Custom tags** — add role labels like `ML`, `Systems`, `Cloud`. The | Your current URL | Change it to |
grade widget will fit them into its tag cloud. |---|---|
- **Hidden languages** — exclude languages you don't want counted | `github-readme-stats.vercel.app/api?username=U` | `gh-stats.com/api?username=U` |
(e.g. `HTML`, `CSS`, `Makefile`). | `github-readme-stats.vercel.app/api/top-langs?username=U` | `gh-stats.com/api/top-langs?username=U` |
- **Widget colors** — per-widget accent overrides for the impact line | `github-readme-streak-stats.herokuapp.com/?user=U` | `gh-stats.com/api/streak/U` |
and collaborator bars (hex, `#RRGGBB`).
- **Widget limits** — cap the number of tags, collaborators, or
languages shown.
- **Achievements** — up to 10 hand-entered lines with icon
(`trophy`, `medal`, `star`, `hackathon`), title, subtitle, and date.
**Auto-awarded tags** fire from real activity — no way to fake them: Nothing else in your README changes.
- `Founder #N` — one of the first N enrolled users, with your number > [!NOTE]
- (plus anything your languages / topics map to: `Backend`, `Frontend`, > `theme=` is honoured on the composite card (`/api/<user>`). On the
`ML`, `Mobile`, `DevOps`, `Cloud`, …) > compatibility and single-widget URLs above it is currently ignored and the
> default theme is served.
--- If you would rather replace several badges with one image, use the composite
card instead and delete the rest:
## Refreshing ```md
![stats](https://gh-stats.com/api/YOUR_USERNAME)
```
Your data refreshes automatically every 15 minutes. If you just merged ## Query parameter reference
something big and want it to show up immediately, click **Refresh now**
in the Workshop (one-shot per account; requires the edit token that was
issued to your browser on first visit).
--- Every URL accepts query parameters. They override the owner's saved
settings on a per-embed basis, so viewers can tweak the look without
changing anything the owner has stored.
## Status states Values with special characters must be URL-encoded: `#a78bfa` becomes
`%23a78bfa`, a space becomes `%20`.
The SVG endpoint advertises its state via the `X-Widget-Status` header: ### Common parameters
| Status | Meaning | Your README shows | | Parameter | What it does | Example |
|---|---|---| |---|---|---|
| `ready` | Built and cached | the real widget | | `theme` | Built-in theme name. | `?theme=onyx` |
| `building` | Enrolled, first render in progress | a placeholder card | | `widgets` | Which widgets to show on the composite card. | `?widgets=grade,streaks,languages` |
| `rate_limited` | Daily enrollment cap hit | a placeholder card | | `order` | Render order on the composite card. | `?order=grade,streaks,languages` |
| `not_found` | GitHub username doesn't exist | a 404-style card | | `hide` | Languages to exclude from the languages widget. | `?hide=HTML,CSS,Makefile` |
| `tags` | Extra custom role tags on the grade widget. | `?tags=ML,Systems` |
GitHub caches the image aggressively; if a just-enrolled widget shows ### Per-widget parameters
the placeholder for a minute or two, that's expected.
Use dot notation: `<widget>.<key>=<value>`.
| Parameter | What it does | Type | Default |
|---|---|---|---|
| `grade.max_tags` | Max role tags shown (1 to 20). | int | all tags |
| `impact.line_color` | Accent color for the area curve. | hex color | theme accent |
| `streaks.color` | Accent color for the current-streak text. | hex color | theme accent |
| `collaborators.max_count` | Max collaborators shown (1 to 10). | int | 5 |
| `collaborators.bar_color` | Accent color for the commit bars. | hex color | theme accent |
| `focus.max_categories` | Max focus clusters shown (1 to 10). | int | 6 |
| `languages.max_languages` | Max languages shown (1 to 10). | int | 5 |
| `achievements.max_items` | Max achievement rows shown (1 to 10). | int | 5 |
---
## Auto-awarded tags
Some tags on the grade card are earned from real activity. No query
parameter will add them if you have not earned them:
- `Founder #N` is your enrollment number, fixed when you first sign in.
- Role tags like `Backend`, `Frontend`, `ML`, `Mobile`, `DevOps`,
`Cloud`, `Systems`, `Database`, `Security` are derived from your
language mix and repo topics.
---
## Refreshing your data
The refresh cron re-pulls GitHub data every 15 minutes, so new commits
usually appear in your widget within that window. GitHub's image CDN
may add another minute or two on top.
If you need an immediate update (for example right after merging
something big), click **Refresh now** in the editor. It is a one-shot
per account, so save it for when it matters.
--- ---
## Self-hosting ## Self-hosting
If you want your own instance, it runs as three Docker services plus a The public instance at `gh-stats.com` is free and you do not need to run your
Vite-built React SPA served by the generator. You'll need a GitHub own. Self-host if you want your own rate limit, private repository data staying
Personal Access Token (classic, `read:user` + `repo:public_repo` is on your hardware, or control over when cards rebuild.
enough).
You need Docker and a GitHub token. The token needs no scopes for public data;
it exists to raise your GitHub API rate limit.
```bash ```bash
# 1) fetcher — owns the PAT, talks to GitHub git clone https://github.com/ShayManor/github-readme-stats
(cd fetcher && pip install -r requirements.txt && cd github-readme-stats
FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=<your-pat> python -m src.api) & cp .env.example .env # put your token in GITHUB_PAT
docker compose up -d --build
# 2) generator — API + worker + refresh cron
cd generator && pip install -r requirements.txt
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.api &
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.worker &
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.cron &
# 3) edge — cache-first SVG proxy (this is what you put behind your domain)
(cd ../edge && pip install -r requirements.txt &&
GENERATOR_URL=http://localhost:5002 python -m src.api) &
# 4) frontend (dev only — production builds are baked into the generator image)
cd ../generator/frontend && npm install && npm run dev
``` ```
Per-service READMEs cover Docker, tests, and env vars: Then open `http://localhost:5002` and embed from your own host:
- [`fetcher/`](./fetcher/README.md) — port 5001 ```md
- [`generator/`](./generator/README.md) — port 5002 ![stats](http://localhost:5002/api/YOUR_USERNAME)
- [`edge/`](./edge/README.md) — port 5003
The generator image serves both the API and the pre-built frontend, so
after deploying edge + generator + fetcher you can point a domain at
the edge and you're done.
### Capacity knobs
Sensible defaults; all overridable via env:
| Env | Default | What it bounds |
|---|---|---|
| `GENERATE_CONCURRENCY` | `2` | Simultaneous SVG renders |
| `PREFETCH_MAX_WORKERS` | `2` | Background prefetch threads |
| `PENDING_JOB_QUEUE_CAP` | `200` | Build queue depth before new enrolls 429 |
| `ENROLLMENT_DAILY_CAP` | `50` | New users per day |
| `RATE_LIMIT_READ_MAX` | `3000` per 60s | Per-IP README embeds |
| `RATE_LIMIT_MUTATE_MAX` | `120` per 60s | Per-IP settings edits / generates |
| `RATE_LIMIT_ENROLL_MAX` | `60` per 300s | Per-IP new enrollments |
| `EDGE_RATE_LIMIT_MAX` | `3000` per 60s | Per-IP at the edge |
---
## Running tests
```bash
(cd fetcher && pytest) && (cd generator && pytest) && (cd edge && pytest)
``` ```
--- Three services come up behind `docker compose`: `fetcher` talks to GitHub and
owns the token, `generator` renders the SVGs and serves the web UI on 5002, and
`edge` is a caching proxy on 5003 that serves cards at `/<username>`. Data lives
in `./data`. Set `GHSTATS_PORT` to move the web UI off 5002.
## FAQ ## FAQ
**Can I use a private GitHub account?** **Can I use a private GitHub account?**
No — the fetcher only sees public activity. Private repos and private No. The service only reads public activity. Private repos, private
contribution counts aren't included. commit counts, and contributions to org-restricted repos are not
visible to GitHub's public API, so they are never part of the widget.
**How fresh is the data?** **How fresh is the data?**
The refresh cron ticks every 15 minutes. You can also click **Refresh Every 15 minutes, automatically. You can also click **Refresh now**
now** in the Workshop once per account. once per account for an immediate update.
**Someone else already enrolled my username — can I edit it?** **How do I edit my widget?**
The first browser to visit your username gets the edit token. If that Sign in with GitHub at <https://gh-stats.com/api/>. Only the account whose
was you but you've lost the token (cleared localStorage, switched login matches the username can edit that widget's settings.
browsers), there's no recovery path today — an OAuth-based reclaim
flow is on the roadmap.
**Can I change the widget without re-embedding?** **Can I change the widget without re-embedding?**
Yes. The image URL is stable. Edit settings in the Workshop, click Yes. The image URL is stable. Edit in the editor, click **Get embed code**,
Generate, and the next time the image is fetched it's the new version and the next fetch serves the new version. GitHub's image cache may
(GitHub's image cache may delay that by a few minutes). delay propagation by a few minutes.
**Can I embed someone else's widget with my own theme or filters?**
Yes, use the [query parameters](#query-parameter-reference). The
owner's saved settings are not affected.
**I am getting a placeholder card. What is wrong?**
`building` means the first render is still in progress, give it a
minute. `not_found` means GitHub does not know that username.
**Why does my languages card look wrong?**
It counts bytes in repos you authored. Forks with little commit
activity are dropped. Add `?hide=HTML,CSS,Makefile` if generated files
dominate the breakdown.
**Can I reorder widgets?**
Yes, either in the editor (drag and drop) or by passing
`?widgets=...&order=...` on the URL.
---
## Gallery
### Composite themes
<table>
<tr>
<td align="center"><b>midnight</b><br/><img src="./assets/examples/composite-midnight.svg" width="260" /></td>
<td align="center"><b>onyx</b><br/><img src="./assets/examples/composite-onyx.svg" width="260" /></td>
</tr>
<tr>
<td align="center"><b>nord</b><br/><img src="./assets/examples/composite-nord.svg" width="260" /></td>
<td align="center"><b>clean</b><br/><img src="./assets/examples/composite-clean.svg" width="260" /></td>
</tr>
<tr>
<td align="center"><b>paper</b><br/><img src="./assets/examples/composite-paper.svg" width="260" /></td>
<td align="center"><b>custom (onyx, 3 widgets)</b><br/><img src="./assets/examples/composite-custom.svg" width="260" /></td>
</tr>
</table>
### Single-widget examples
<table>
<tr>
<td align="center"><b>Grade</b><br/><img src="./assets/examples/grade.svg" width="320" /></td>
<td align="center"><b>Grade (max_tags=3)</b><br/><img src="./assets/examples/grade-compact.svg" width="320" /></td>
</tr>
<tr>
<td align="center"><b>Impact</b><br/><img src="./assets/examples/impact.svg" width="320" /></td>
<td align="center"><b>Impact (purple line)</b><br/><img src="./assets/examples/impact-purple.svg" width="320" /></td>
</tr>
<tr>
<td align="center"><b>Streaks</b><br/><img src="./assets/examples/streaks.svg" width="320" /></td>
<td align="center"><b>Streaks (green)</b><br/><img src="./assets/examples/streaks-green.svg" width="320" /></td>
</tr>
<tr>
<td align="center"><b>Languages</b><br/><img src="./assets/examples/languages.svg" width="320" /></td>
<td align="center"><b>Languages (hide Shell, Dockerfile)</b><br/><img src="./assets/examples/languages-hide.svg" width="320" /></td>
</tr>
<tr>
<td align="center"><b>Collaborators</b><br/><img src="./assets/examples/collaborators.svg" width="320" /></td>
<td align="center"><b>Focus</b><br/><img src="./assets/examples/focus.svg" width="320" /></td>
</tr>
<tr>
<td align="center"><b>Achievements</b><br/><img src="./assets/examples/achievements.svg" width="320" /></td>
<td></td>
</tr>
</table>
### Mix and match
Embed two widgets side by side with an HTML table:
```html
<table><tr>
<td><img src="https://gh-stats.com/api/YOUR_USERNAME/grade.svg" /></td>
<td><img src="https://gh-stats.com/api/YOUR_USERNAME/languages.svg" /></td>
</tr></table>
```
Stack a custom composite with only three widgets:
```md
![stats](https://gh-stats.com/api/YOUR_USERNAME?theme=onyx&widgets=grade,streaks,languages&order=grade,streaks,languages)
```
Recolor the impact line:
```md
![impact](https://gh-stats.com/api/YOUR_USERNAME/impact.svg?impact.line_color=%23a78bfa)
```
+72
View File
@@ -0,0 +1,72 @@
<svg xmlns="http://www.w3.org/2000/svg" width="380" height="274" viewBox="0 0 380 274" fill="none">
<defs>
<filter id="shadow" 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="avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="272" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">ACHIEVEMENTS</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 8)">
<rect width="348" height="48" rx="8" fill="#d29922" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#d29922" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<svg viewBox="0 0 24 24" width="24" height="24">
<rect x="4" y="5" width="16" height="11" rx="1" fill="none" stroke="#d29922" stroke-width="1.5"/>
<rect x="3" y="16" width="18" height="1.5" rx="0.5" fill="#d29922" opacity="0.85"/>
<path d="M9 9l-2 3 2 3m6-6l2 3-2 3" stroke="#d29922" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
</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="#d1d9e0">Hackathon winner</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">Y Combinator AI Hackathon · 2025-11</text>
</g>
<g transform="translate(16, 64)">
<rect width="348" height="48" rx="8" fill="#3fb950" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#3fb950" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<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="none" stroke="#3fb950" stroke-width="1.5" stroke-linejoin="round"/>
</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="#d1d9e0">Speaker at PyCon</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">Async at scale · 2024-05</text>
</g>
<g transform="translate(16, 120)">
<rect width="348" height="48" rx="8" fill="#58a6ff" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#58a6ff" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<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="#58a6ff" opacity="0.85"/>
</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="#d1d9e0">Open Source Award</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">GitHub Stars program · 2024-01</text>
</g>
<g transform="translate(16, 176)">
<rect width="348" height="48" rx="8" fill="#bc8cff" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#bc8cff" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<svg viewBox="0 0 24 24" width="24" height="24">
<circle cx="12" cy="14" r="5" fill="#bc8cff" opacity="0.2"/>
<circle cx="12" cy="14" r="4" fill="none" stroke="#bc8cff" 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="#bc8cff"/>
<path d="M9 3l3 8m0-8l3 8m-6-8h6" stroke="#bc8cff" stroke-width="1.5" fill="none" stroke-linecap="round"/>
</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="#d1d9e0">AWS Certified Solutions Architect</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">Professional · 2023-09</text>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+89
View File
@@ -0,0 +1,89 @@
<svg xmlns="http://www.w3.org/2000/svg" width="380" height="298" viewBox="0 0 380 298" fill="none">
<defs>
<filter id="shadow" 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="avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="296" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">TOP COLLABORATORS</text>
<g transform="translate(0, 36)">
<g transform="translate(36, 20)">
<circle cx="0" cy="0" r="18" fill="hsl(285, 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">T</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#d1d9e0">torvalds</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">4 repos · 142 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#1e2836"/>
<rect x="200" y="-6" width="120.0" height="8" rx="4" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="120.0" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 70)">
<circle cx="0" cy="0" r="18" fill="hsl(165, 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">G</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#d1d9e0">gaearon</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">3 repos · 98 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#1e2836"/>
<rect x="200" y="-6" width="82.8169014084507" height="8" rx="4" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="82.8169014084507" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 120)">
<circle cx="0" cy="0" r="18" fill="hsl(238, 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">S</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#d1d9e0">sindresorhus</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">2 repos · 64 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#1e2836"/>
<rect x="200" y="-6" width="54.08450704225352" height="8" rx="4" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="54.08450704225352" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 170)">
<circle cx="0" cy="0" r="18" fill="hsl(157, 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">T</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#d1d9e0">tj</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">2 repos · 47 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#1e2836"/>
<rect x="200" y="-6" width="39.71830985915493" height="8" rx="4" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="39.71830985915493" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 220)">
<circle cx="0" cy="0" r="18" fill="hsl(231, 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">Y</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#d1d9e0">yyx990803</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">1 repos · 31 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#1e2836"/>
<rect x="200" y="-6" width="26.197183098591548" height="8" rx="4" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="26.197183098591548" dur="0.6s" fill="freeze"/>
</rect>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 5.8 KiB

+543
View File
@@ -0,0 +1,543 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
width="420" height="1756" viewBox="0 0 420 1756">
<rect width="420" height="1756" rx="16" fill="#ffffff"/>
<rect x="0.5" y="0.5" width="419" height="1755" rx="16"
fill="none" stroke="#d8dee4" stroke-width="1"/>
<svg x="20" y="20" width="380" height="226" viewBox="0 0 380 226">
<defs>
<filter id="grade_shadow" 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="grade_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="224" rx="10" ry="10"
fill="#f6f8fa" stroke="#d8dee4" stroke-width="1" filter="url(#grade_shadow)"/>
<g transform="translate(0, 0)">
<g transform="translate(52, 48)">
<circle cx="0" cy="0" r="36" fill="none" stroke="#eaeef2" stroke-width="5"/>
<circle cx="0" cy="0" r="36" fill="none" stroke="#3fb950" stroke-width="5"
stroke-dasharray="226.1946710584651" stroke-dashoffset="26.23858184278195"
stroke-linecap="round" transform="rotate(-90)">
<animate attributeName="stroke-dashoffset" from="226.1946710584651" to="26.23858184278195" dur="1s" fill="freeze"/>
</circle>
<text x="0" y="10.50" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="30" font-weight="800" fill="#3fb950">A</text>
</g>
<line x1="100" y1="16" x2="100" y2="80" stroke="#eaeef2" 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="#24292f">Developer Profile</text>
<text x="0" y="32" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="#656d76"></text>
<text x="0" y="50" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#656d76" letter-spacing="0.4">Score <tspan fill="#24292f" font-weight="600">88</tspan> / 100</text>
</g>
<line x1="20" y1="96" x2="360" y2="96" stroke="#eaeef2" stroke-width="0.5"/>
<g transform="translate(20, 100)">
<g transform="translate(34.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="7" cy="7" r="3" fill="none" stroke="#656d76" stroke-width="1.4"/><circle cx="7" cy="7" r="1" fill="#656d76"/><line x1="7" y1="10" x2="7" y2="14" stroke="#656d76" stroke-width="1.4"/><line x1="7" y1="0" x2="7" y2="4" stroke="#656d76" stroke-width="1.4"/></g></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="#24292f">1,423</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#656d76">Commits</text>
</g>
<g transform="translate(102.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="4" cy="4" r="2" fill="none" stroke="#656d76" stroke-width="1.2"/><circle cx="10" cy="10" r="2" fill="none" stroke="#656d76" stroke-width="1.2"/><path d="M4 6v4c0 1.1.9 2 2 2h2" fill="none" stroke="#656d76" stroke-width="1.2"/></g></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="#24292f">87</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#656d76">PRs</text>
</g>
<g transform="translate(170.0, 0)">
<g transform="translate(-7, 0)"><g><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="#656d76" stroke-width="1.2" stroke-linejoin="round"/></g></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="#24292f">342</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#656d76">Stars</text>
</g>
<g transform="translate(238.0, 0)">
<g transform="translate(-7, 0)"><g><rect x="2" y="1" width="10" height="12" rx="1.5" fill="none" stroke="#656d76" stroke-width="1.2"/><line x1="5" y1="4" x2="9" y2="4" stroke="#656d76" stroke-width="1"/><line x1="5" y1="6.5" x2="9" y2="6.5" stroke="#656d76" stroke-width="1"/><line x1="5" y1="9" x2="7" y2="9" stroke="#656d76" stroke-width="1"/></g></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="#24292f">28</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#656d76">Repos</text>
</g>
<g transform="translate(306.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="5" cy="4" r="2.5" fill="none" stroke="#656d76" 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="#656d76" stroke-width="1.2"/><circle cx="11" cy="3.5" r="1.8" fill="none" stroke="#656d76" stroke-width="1"/><path d="M10 7.5c1.5 0 3.5 1 3.5 3" fill="none" stroke="#656d76" stroke-width="1"/></g></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="#24292f">156</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#656d76">Followers</text>
</g>
</g>
<line x1="20" y1="148" x2="360" y2="148" stroke="#eaeef2" stroke-width="0.5"/>
<g transform="translate(20, 154)">
<g transform="translate(0, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#0969da" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#0969da" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#0969da">Backend</text>
</g>
<g transform="translate(70, 0)" opacity="0.9">
<rect width="31" height="24" rx="12" fill="#0969da" opacity="0.12"/>
<rect width="31" height="24" rx="12" fill="none" stroke="#0969da" stroke-width="1" opacity="0.3"/>
<text x="15" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#0969da">ML</text>
</g>
<g transform="translate(107, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#0969da" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#0969da" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#0969da">Systems</text>
</g>
<g transform="translate(177, 0)" opacity="0.9">
<rect width="51" height="24" rx="12" fill="#0969da" opacity="0.12"/>
<rect width="51" height="24" rx="12" fill="none" stroke="#0969da" stroke-width="1" opacity="0.3"/>
<text x="25" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#0969da">Cloud</text>
</g>
<g transform="translate(234, 0)" opacity="0.9">
<rect width="90" height="24" rx="12" fill="#facc15" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#facc15" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#facc15">Founder #42</text>
</g>
<g transform="translate(0, 30)" opacity="0.55">
<rect width="90" height="24" rx="12" fill="#0969da" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#0969da" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#0969da">Open source</text>
</g>
</g>
</g>
</svg>
<svg x="20" y="262" width="380" height="200" viewBox="0 0 380 200">
<defs>
<filter id="impact_shadow" 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="impact_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="198" rx="10" ry="10"
fill="#f6f8fa" stroke="#d8dee4" stroke-width="1" filter="url(#impact_shadow)"/>
<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="#656d76" letter-spacing="0.8" opacity="0.7">IMPACT TIMELINE</text>
<g transform="translate(0, 36)">
<defs>
<linearGradient id="impact_areaGrad" x1="0" y1="8" x2="0" y2="90" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#0969da" stop-opacity="0.35"/>
<stop offset="100%" stop-color="#0969da" stop-opacity="0.02"/>
</linearGradient>
</defs>
<text x="34" y="12.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#656d76">41</text><line x1="40" y1="8.0" x2="356" y2="8.0" stroke="#eaeef2" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="53.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#656d76">20</text><line x1="40" y1="49.0" x2="356" y2="49.0" stroke="#eaeef2" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="94.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#656d76">0</text><line x1="40" y1="90.0" x2="356" y2="90.0" stroke="#eaeef2" stroke-width="0.5" stroke-dasharray="3,3"/>
<text x="40.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#656d76">2025-10</text><text x="204.3" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#656d76">2026-01</text><text x="356.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#656d76">2026-04</text>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0 L 356.0 90 L 40.0 90 Z" fill="url(#impact_areaGrad)"/>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0" fill="none" stroke="#0969da" stroke-width="2" stroke-linecap="round"/>
<g transform="translate(20, 136)">
<text x="0" y="0" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="700" fill="#24292f">577</text>
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#656d76">commits over 6mo</text>
</g>
</g>
</svg>
<svg x="20" y="478" width="380" height="170" viewBox="0 0 380 170">
<defs>
<filter id="streaks_shadow" 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="streaks_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="168" rx="10" ry="10"
fill="#f6f8fa" stroke="#d8dee4" stroke-width="1" filter="url(#streaks_shadow)"/>
<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="#656d76" letter-spacing="0.8" opacity="0.7">STREAKS</text>
<g transform="translate(0, 36)">
<text x="105" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#656d76">CURRENT</text>
<text x="105" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#0969da">23</text>
<text x="275" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#656d76">LONGEST</text>
<text x="275" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#24292f">61</text>
<line x1="190" y1="10" x2="190" y2="76"
stroke="#d8dee4" stroke-width="1"/>
<rect x="50" y="92" width="280" height="5" rx="2.5" fill="#eaeef2"/>
<rect x="50" y="92" width="105.57" height="5" rx="2.5" fill="#0969da"/>
<circle cx="155.57" cy="94.5" r="3.5" fill="#0969da"/>
<text x="50" y="116"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#656d76">Mar 30 – Today</text>
<text x="330" y="116" text-anchor="end"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#656d76">Sep 13 – Nov 12, 2025</text>
</g>
</svg>
<svg x="20" y="664" width="380" height="298" viewBox="0 0 380 298">
<defs>
<filter id="collaborators_shadow" 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="collaborators_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="296" rx="10" ry="10"
fill="#f6f8fa" stroke="#d8dee4" stroke-width="1" filter="url(#collaborators_shadow)"/>
<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="#656d76" letter-spacing="0.8" opacity="0.7">TOP COLLABORATORS</text>
<g transform="translate(0, 36)">
<g transform="translate(36, 20)">
<circle cx="0" cy="0" r="18" fill="hsl(285, 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">T</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#24292f">torvalds</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#656d76">4 repos · 142 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#eaeef2"/>
<rect x="200" y="-6" width="120.0" height="8" rx="4" fill="#8250df" opacity="0.8">
<animate attributeName="width" from="0" to="120.0" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 70)">
<circle cx="0" cy="0" r="18" fill="hsl(165, 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">G</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#24292f">gaearon</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#656d76">3 repos · 98 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#eaeef2"/>
<rect x="200" y="-6" width="82.8169014084507" height="8" rx="4" fill="#8250df" opacity="0.8">
<animate attributeName="width" from="0" to="82.8169014084507" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 120)">
<circle cx="0" cy="0" r="18" fill="hsl(238, 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">S</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#24292f">sindresorhus</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#656d76">2 repos · 64 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#eaeef2"/>
<rect x="200" y="-6" width="54.08450704225352" height="8" rx="4" fill="#8250df" opacity="0.8">
<animate attributeName="width" from="0" to="54.08450704225352" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 170)">
<circle cx="0" cy="0" r="18" fill="hsl(157, 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">T</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#24292f">tj</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#656d76">2 repos · 47 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#eaeef2"/>
<rect x="200" y="-6" width="39.71830985915493" height="8" rx="4" fill="#8250df" opacity="0.8">
<animate attributeName="width" from="0" to="39.71830985915493" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 220)">
<circle cx="0" cy="0" r="18" fill="hsl(231, 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">Y</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#24292f">yyx990803</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#656d76">1 repos · 31 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#eaeef2"/>
<rect x="200" y="-6" width="26.197183098591548" height="8" rx="4" fill="#8250df" opacity="0.8">
<animate attributeName="width" from="0" to="26.197183098591548" dur="0.6s" fill="freeze"/>
</rect>
</g>
</g>
</svg>
<svg x="20" y="978" width="380" height="234" viewBox="0 0 380 234">
<defs>
<filter id="focus_shadow" 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="focus_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="232" rx="10" ry="10"
fill="#f6f8fa" stroke="#d8dee4" stroke-width="1" filter="url(#focus_shadow)"/>
<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="#656d76" letter-spacing="0.8" opacity="0.7">RECENT FOCUS</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#24292f">Backend</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#eaeef2"/>
<rect x="90" y="4" width="210.0" height="14" rx="7" fill="#58a6ff" opacity="0.8">
<animate attributeName="width" from="0" to="210.0" 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="#656d76">412 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#58a6ff">38%</text>
</g>
<g transform="translate(16, 36)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#24292f">ML</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#eaeef2"/>
<rect x="90" y="4" width="132.6315789473684" height="14" rx="7" fill="#3fb950" opacity="0.8">
<animate attributeName="width" from="0" to="132.6315789473684" 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="#656d76">260 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#3fb950">24%</text>
</g>
<g transform="translate(16, 72)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#24292f">Frontend</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#eaeef2"/>
<rect x="90" y="4" width="99.47368421052632" height="14" rx="7" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="99.47368421052632" 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="#656d76">195 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#bc8cff">18%</text>
</g>
<g transform="translate(16, 108)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#24292f">DevOps</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#eaeef2"/>
<rect x="90" y="4" width="66.3157894736842" height="14" rx="7" fill="#d29922" opacity="0.8">
<animate attributeName="width" from="0" to="66.3157894736842" 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="#656d76">130 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#d29922">12%</text>
</g>
<g transform="translate(16, 144)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#24292f">Cloud</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#eaeef2"/>
<rect x="90" y="4" width="44.21052631578947" height="14" rx="7" fill="#f0883e" opacity="0.8">
<animate attributeName="width" from="0" to="44.21052631578947" 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="#656d76">87 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#f0883e">8%</text>
</g>
<text x="16" y="188" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#656d76" opacity="0.7">Recent activity · last year</text>
</g>
</svg>
<svg x="20" y="1228" width="380" height="208" viewBox="0 0 380 208">
<defs>
<filter id="languages_shadow" 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="languages_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="206" rx="10" ry="10"
fill="#f6f8fa" stroke="#d8dee4" stroke-width="1" filter="url(#languages_shadow)"/>
<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="#656d76" letter-spacing="0.8" opacity="0.7">LANGUAGES</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3572A5" stroke-width="16"
stroke-dasharray="113.3 163.1" stroke-dashoffset="0.0"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="276.5" to="0.0" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3178c6" stroke-width="16"
stroke-dasharray="63.6 212.9" stroke-dashoffset="-113.3"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="163.1" to="-113.3" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#00ADD8" stroke-width="16"
stroke-dasharray="41.5 235.0" stroke-dashoffset="-176.9"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="99.5" to="-176.9" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#dea584" stroke-width="16"
stroke-dasharray="30.4 246.0" stroke-dashoffset="-218.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="58.1" to="-218.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#89e051" stroke-width="16"
stroke-dasharray="16.6 259.9" stroke-dashoffset="-248.8"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="27.6" to="-248.8" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#656d76" stroke-width="16"
stroke-dasharray="11.1 265.4" stroke-dashoffset="-265.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="11.1" to="-265.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="28" fill="#f6f8fa"/>
<text x="60" y="87.0" text-anchor="middle" dominant-baseline="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" font-weight="700" fill="#24292f">Python</text>
<g transform="translate(140, 20)">
<rect width="10" height="10" rx="2" fill="#3572A5"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#24292f">Python</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="#656d76">41%</text>
</g>
<g transform="translate(140, 42)">
<rect width="10" height="10" rx="2" fill="#3178c6"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#24292f">TypeScript</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="#656d76">23%</text>
</g>
<g transform="translate(140, 64)">
<rect width="10" height="10" rx="2" fill="#00ADD8"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#24292f">Go</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="#656d76">15%</text>
</g>
<g transform="translate(140, 86)">
<rect width="10" height="10" rx="2" fill="#dea584"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#24292f">Rust</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="#656d76">11%</text>
</g>
<g transform="translate(140, 108)">
<rect width="10" height="10" rx="2" fill="#89e051"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#24292f">Shell</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="#656d76">6%</text>
</g>
<g transform="translate(140, 130)">
<rect width="10" height="10" rx="2" fill="#656d76"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#24292f">Other</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="#656d76">4%</text>
</g>
</g>
</g>
</svg>
<svg x="20" y="1452" width="380" height="274" viewBox="0 0 380 274">
<defs>
<filter id="achievements_shadow" 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="achievements_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="272" rx="10" ry="10"
fill="#f6f8fa" stroke="#d8dee4" stroke-width="1" filter="url(#achievements_shadow)"/>
<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="#656d76" letter-spacing="0.8" opacity="0.7">ACHIEVEMENTS</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 8)">
<rect width="348" height="48" rx="8" fill="#9a6700" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#9a6700" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<svg viewBox="0 0 24 24" width="24" height="24">
<rect x="4" y="5" width="16" height="11" rx="1" fill="none" stroke="#9a6700" stroke-width="1.5"/>
<rect x="3" y="16" width="18" height="1.5" rx="0.5" fill="#9a6700" opacity="0.85"/>
<path d="M9 9l-2 3 2 3m6-6l2 3-2 3" stroke="#9a6700" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
</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="#24292f">Hackathon winner</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#656d76">Y Combinator AI Hackathon · 2025-11</text>
</g>
<g transform="translate(16, 64)">
<rect width="348" height="48" rx="8" fill="#1a7f37" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#1a7f37" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<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="none" stroke="#1a7f37" stroke-width="1.5" stroke-linejoin="round"/>
</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="#24292f">Speaker at PyCon</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#656d76">Async at scale · 2024-05</text>
</g>
<g transform="translate(16, 120)">
<rect width="348" height="48" rx="8" fill="#0969da" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#0969da" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<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="#0969da" opacity="0.85"/>
</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="#24292f">Open Source Award</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#656d76">GitHub Stars program · 2024-01</text>
</g>
<g transform="translate(16, 176)">
<rect width="348" height="48" rx="8" fill="#8250df" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#8250df" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<svg viewBox="0 0 24 24" width="24" height="24">
<circle cx="12" cy="14" r="5" fill="#8250df" opacity="0.2"/>
<circle cx="12" cy="14" r="4" fill="none" stroke="#8250df" 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="#8250df"/>
<path d="M9 3l3 8m0-8l3 8m-6-8h6" stroke="#8250df" stroke-width="1.5" fill="none" stroke-linecap="round"/>
</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="#24292f">AWS Certified Solutions Architect</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#656d76">Professional · 2023-09</text>
</g>
</g>
</svg>
<text x="210" y="1748" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#656d76" opacity="0.5">Generated with gh-stats</text>
</svg>

After

Width:  |  Height:  |  Size: 38 KiB

+268
View File
@@ -0,0 +1,268 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
width="420" height="686" viewBox="0 0 420 686">
<rect width="420" height="686" rx="16" fill="#09090b"/>
<rect x="0.5" y="0.5" width="419" height="685" rx="16"
fill="none" stroke="#27272a" stroke-width="1"/>
<svg x="20" y="20" width="380" height="226" viewBox="0 0 380 226">
<defs>
<filter id="grade_shadow" 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="grade_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="224" rx="10" ry="10"
fill="#18181b" stroke="#27272a" stroke-width="1" filter="url(#grade_shadow)"/>
<g transform="translate(0, 0)">
<g transform="translate(52, 48)">
<circle cx="0" cy="0" r="36" fill="none" stroke="#27272a" stroke-width="5"/>
<circle cx="0" cy="0" r="36" fill="none" stroke="#3fb950" stroke-width="5"
stroke-dasharray="226.1946710584651" stroke-dashoffset="26.23858184278195"
stroke-linecap="round" transform="rotate(-90)">
<animate attributeName="stroke-dashoffset" from="226.1946710584651" to="26.23858184278195" dur="1s" fill="freeze"/>
</circle>
<text x="0" y="10.50" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="30" font-weight="800" fill="#3fb950">A</text>
</g>
<line x1="100" y1="16" x2="100" y2="80" stroke="#27272a" 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="#fafafa">Developer Profile</text>
<text x="0" y="32" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="#a1a1aa"></text>
<text x="0" y="50" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa" letter-spacing="0.4">Score <tspan fill="#fafafa" font-weight="600">88</tspan> / 100</text>
</g>
<line x1="20" y1="96" x2="360" y2="96" stroke="#27272a" stroke-width="0.5"/>
<g transform="translate(20, 100)">
<g transform="translate(34.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="7" cy="7" r="3" fill="none" stroke="#a1a1aa" stroke-width="1.4"/><circle cx="7" cy="7" r="1" fill="#a1a1aa"/><line x1="7" y1="10" x2="7" y2="14" stroke="#a1a1aa" stroke-width="1.4"/><line x1="7" y1="0" x2="7" y2="4" stroke="#a1a1aa" stroke-width="1.4"/></g></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="#fafafa">1,423</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa">Commits</text>
</g>
<g transform="translate(102.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="4" cy="4" r="2" fill="none" stroke="#a1a1aa" stroke-width="1.2"/><circle cx="10" cy="10" r="2" fill="none" stroke="#a1a1aa" stroke-width="1.2"/><path d="M4 6v4c0 1.1.9 2 2 2h2" fill="none" stroke="#a1a1aa" stroke-width="1.2"/></g></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="#fafafa">87</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa">PRs</text>
</g>
<g transform="translate(170.0, 0)">
<g transform="translate(-7, 0)"><g><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="#a1a1aa" stroke-width="1.2" stroke-linejoin="round"/></g></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="#fafafa">342</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa">Stars</text>
</g>
<g transform="translate(238.0, 0)">
<g transform="translate(-7, 0)"><g><rect x="2" y="1" width="10" height="12" rx="1.5" fill="none" stroke="#a1a1aa" stroke-width="1.2"/><line x1="5" y1="4" x2="9" y2="4" stroke="#a1a1aa" stroke-width="1"/><line x1="5" y1="6.5" x2="9" y2="6.5" stroke="#a1a1aa" stroke-width="1"/><line x1="5" y1="9" x2="7" y2="9" stroke="#a1a1aa" stroke-width="1"/></g></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="#fafafa">28</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa">Repos</text>
</g>
<g transform="translate(306.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="5" cy="4" r="2.5" fill="none" stroke="#a1a1aa" 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="#a1a1aa" stroke-width="1.2"/><circle cx="11" cy="3.5" r="1.8" fill="none" stroke="#a1a1aa" stroke-width="1"/><path d="M10 7.5c1.5 0 3.5 1 3.5 3" fill="none" stroke="#a1a1aa" stroke-width="1"/></g></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="#fafafa">156</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa">Followers</text>
</g>
</g>
<line x1="20" y1="148" x2="360" y2="148" stroke="#27272a" stroke-width="0.5"/>
<g transform="translate(20, 154)">
<g transform="translate(0, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#a78bfa" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#a78bfa" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#a78bfa">Backend</text>
</g>
<g transform="translate(70, 0)" opacity="0.9">
<rect width="31" height="24" rx="12" fill="#a78bfa" opacity="0.12"/>
<rect width="31" height="24" rx="12" fill="none" stroke="#a78bfa" stroke-width="1" opacity="0.3"/>
<text x="15" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#a78bfa">ML</text>
</g>
<g transform="translate(107, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#a78bfa" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#a78bfa" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#a78bfa">Systems</text>
</g>
<g transform="translate(177, 0)" opacity="0.9">
<rect width="51" height="24" rx="12" fill="#a78bfa" opacity="0.12"/>
<rect width="51" height="24" rx="12" fill="none" stroke="#a78bfa" stroke-width="1" opacity="0.3"/>
<text x="25" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#a78bfa">Cloud</text>
</g>
<g transform="translate(234, 0)" opacity="0.9">
<rect width="90" height="24" rx="12" fill="#facc15" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#facc15" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#facc15">Founder #42</text>
</g>
<g transform="translate(0, 30)" opacity="0.55">
<rect width="90" height="24" rx="12" fill="#a78bfa" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#a78bfa" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#a78bfa">Open source</text>
</g>
</g>
</g>
</svg>
<svg x="20" y="262" width="380" height="170" viewBox="0 0 380 170">
<defs>
<filter id="streaks_shadow" 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="streaks_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="168" rx="10" ry="10"
fill="#18181b" stroke="#27272a" stroke-width="1" filter="url(#streaks_shadow)"/>
<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="#a1a1aa" letter-spacing="0.8" opacity="0.7">STREAKS</text>
<g transform="translate(0, 36)">
<text x="105" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#a1a1aa">CURRENT</text>
<text x="105" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#a78bfa">23</text>
<text x="275" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#a1a1aa">LONGEST</text>
<text x="275" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#fafafa">61</text>
<line x1="190" y1="10" x2="190" y2="76"
stroke="#27272a" stroke-width="1"/>
<rect x="50" y="92" width="280" height="5" rx="2.5" fill="#27272a"/>
<rect x="50" y="92" width="105.57" height="5" rx="2.5" fill="#a78bfa"/>
<circle cx="155.57" cy="94.5" r="3.5" fill="#a78bfa"/>
<text x="50" y="116"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa">Mar 30 – Today</text>
<text x="330" y="116" text-anchor="end"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa">Sep 13 – Nov 12, 2025</text>
</g>
</svg>
<svg x="20" y="448" width="380" height="208" viewBox="0 0 380 208">
<defs>
<filter id="languages_shadow" 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="languages_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="206" rx="10" ry="10"
fill="#18181b" stroke="#27272a" stroke-width="1" filter="url(#languages_shadow)"/>
<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="#a1a1aa" letter-spacing="0.8" opacity="0.7">LANGUAGES</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3572A5" stroke-width="16"
stroke-dasharray="113.3 163.1" stroke-dashoffset="0.0"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="276.5" to="0.0" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3178c6" stroke-width="16"
stroke-dasharray="63.6 212.9" stroke-dashoffset="-113.3"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="163.1" to="-113.3" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#00ADD8" stroke-width="16"
stroke-dasharray="41.5 235.0" stroke-dashoffset="-176.9"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="99.5" to="-176.9" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#dea584" stroke-width="16"
stroke-dasharray="30.4 246.0" stroke-dashoffset="-218.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="58.1" to="-218.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#89e051" stroke-width="16"
stroke-dasharray="16.6 259.9" stroke-dashoffset="-248.8"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="27.6" to="-248.8" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#a1a1aa" stroke-width="16"
stroke-dasharray="11.1 265.4" stroke-dashoffset="-265.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="11.1" to="-265.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="28" fill="#18181b"/>
<text x="60" y="87.0" text-anchor="middle" dominant-baseline="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" font-weight="700" fill="#fafafa">Python</text>
<g transform="translate(140, 20)">
<rect width="10" height="10" rx="2" fill="#3572A5"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#fafafa">Python</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="#a1a1aa">41%</text>
</g>
<g transform="translate(140, 42)">
<rect width="10" height="10" rx="2" fill="#3178c6"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#fafafa">TypeScript</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="#a1a1aa">23%</text>
</g>
<g transform="translate(140, 64)">
<rect width="10" height="10" rx="2" fill="#00ADD8"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#fafafa">Go</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="#a1a1aa">15%</text>
</g>
<g transform="translate(140, 86)">
<rect width="10" height="10" rx="2" fill="#dea584"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#fafafa">Rust</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="#a1a1aa">11%</text>
</g>
<g transform="translate(140, 108)">
<rect width="10" height="10" rx="2" fill="#89e051"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#fafafa">Shell</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="#a1a1aa">6%</text>
</g>
<g transform="translate(140, 130)">
<rect width="10" height="10" rx="2" fill="#a1a1aa"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#fafafa">Other</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="#a1a1aa">4%</text>
</g>
</g>
</g>
</svg>
<text x="210" y="678" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa" opacity="0.5">Generated with gh-stats</text>
</svg>

After

Width:  |  Height:  |  Size: 17 KiB

+543
View File
@@ -0,0 +1,543 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
width="420" height="1756" viewBox="0 0 420 1756">
<rect width="420" height="1756" rx="16" fill="#121820"/>
<rect x="0.5" y="0.5" width="419" height="1755" rx="16"
fill="none" stroke="#2a3444" stroke-width="1"/>
<svg x="20" y="20" width="380" height="226" viewBox="0 0 380 226">
<defs>
<filter id="grade_shadow" 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="grade_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="224" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#grade_shadow)"/>
<g transform="translate(0, 0)">
<g transform="translate(52, 48)">
<circle cx="0" cy="0" r="36" fill="none" stroke="#1e2836" stroke-width="5"/>
<circle cx="0" cy="0" r="36" fill="none" stroke="#3fb950" stroke-width="5"
stroke-dasharray="226.1946710584651" stroke-dashoffset="26.23858184278195"
stroke-linecap="round" transform="rotate(-90)">
<animate attributeName="stroke-dashoffset" from="226.1946710584651" to="26.23858184278195" dur="1s" fill="freeze"/>
</circle>
<text x="0" y="10.50" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="30" font-weight="800" fill="#3fb950">A</text>
</g>
<line x1="100" y1="16" x2="100" y2="80" stroke="#1e2836" 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="#d1d9e0">Developer Profile</text>
<text x="0" y="32" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="#7d8895"></text>
<text x="0" y="50" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895" letter-spacing="0.4">Score <tspan fill="#d1d9e0" font-weight="600">88</tspan> / 100</text>
</g>
<line x1="20" y1="96" x2="360" y2="96" stroke="#1e2836" stroke-width="0.5"/>
<g transform="translate(20, 100)">
<g transform="translate(34.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="7" cy="7" r="3" fill="none" stroke="#7d8895" stroke-width="1.4"/><circle cx="7" cy="7" r="1" fill="#7d8895"/><line x1="7" y1="10" x2="7" y2="14" stroke="#7d8895" stroke-width="1.4"/><line x1="7" y1="0" x2="7" y2="4" stroke="#7d8895" stroke-width="1.4"/></g></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="#d1d9e0">1,423</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">Commits</text>
</g>
<g transform="translate(102.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="4" cy="4" r="2" fill="none" stroke="#7d8895" stroke-width="1.2"/><circle cx="10" cy="10" r="2" fill="none" stroke="#7d8895" stroke-width="1.2"/><path d="M4 6v4c0 1.1.9 2 2 2h2" fill="none" stroke="#7d8895" stroke-width="1.2"/></g></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="#d1d9e0">87</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">PRs</text>
</g>
<g transform="translate(170.0, 0)">
<g transform="translate(-7, 0)"><g><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="#7d8895" stroke-width="1.2" stroke-linejoin="round"/></g></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="#d1d9e0">342</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">Stars</text>
</g>
<g transform="translate(238.0, 0)">
<g transform="translate(-7, 0)"><g><rect x="2" y="1" width="10" height="12" rx="1.5" fill="none" stroke="#7d8895" stroke-width="1.2"/><line x1="5" y1="4" x2="9" y2="4" stroke="#7d8895" stroke-width="1"/><line x1="5" y1="6.5" x2="9" y2="6.5" stroke="#7d8895" stroke-width="1"/><line x1="5" y1="9" x2="7" y2="9" stroke="#7d8895" stroke-width="1"/></g></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="#d1d9e0">28</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">Repos</text>
</g>
<g transform="translate(306.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="5" cy="4" r="2.5" fill="none" stroke="#7d8895" 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="#7d8895" stroke-width="1.2"/><circle cx="11" cy="3.5" r="1.8" fill="none" stroke="#7d8895" stroke-width="1"/><path d="M10 7.5c1.5 0 3.5 1 3.5 3" fill="none" stroke="#7d8895" stroke-width="1"/></g></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="#d1d9e0">156</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">Followers</text>
</g>
</g>
<line x1="20" y1="148" x2="360" y2="148" stroke="#1e2836" stroke-width="0.5"/>
<g transform="translate(20, 154)">
<g transform="translate(0, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#58a6ff" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#58a6ff" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#58a6ff">Backend</text>
</g>
<g transform="translate(70, 0)" opacity="0.9">
<rect width="31" height="24" rx="12" fill="#58a6ff" opacity="0.12"/>
<rect width="31" height="24" rx="12" fill="none" stroke="#58a6ff" stroke-width="1" opacity="0.3"/>
<text x="15" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#58a6ff">ML</text>
</g>
<g transform="translate(107, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#58a6ff" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#58a6ff" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#58a6ff">Systems</text>
</g>
<g transform="translate(177, 0)" opacity="0.9">
<rect width="51" height="24" rx="12" fill="#58a6ff" opacity="0.12"/>
<rect width="51" height="24" rx="12" fill="none" stroke="#58a6ff" stroke-width="1" opacity="0.3"/>
<text x="25" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#58a6ff">Cloud</text>
</g>
<g transform="translate(234, 0)" opacity="0.9">
<rect width="90" height="24" rx="12" fill="#facc15" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#facc15" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#facc15">Founder #42</text>
</g>
<g transform="translate(0, 30)" opacity="0.55">
<rect width="90" height="24" rx="12" fill="#58a6ff" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#58a6ff" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#58a6ff">Open source</text>
</g>
</g>
</g>
</svg>
<svg x="20" y="262" width="380" height="200" viewBox="0 0 380 200">
<defs>
<filter id="impact_shadow" 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="impact_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="198" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#impact_shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">IMPACT TIMELINE</text>
<g transform="translate(0, 36)">
<defs>
<linearGradient id="impact_areaGrad" x1="0" y1="8" x2="0" y2="90" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#58a6ff" stop-opacity="0.35"/>
<stop offset="100%" stop-color="#58a6ff" stop-opacity="0.02"/>
</linearGradient>
</defs>
<text x="34" y="12.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">41</text><line x1="40" y1="8.0" x2="356" y2="8.0" stroke="#1e2836" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="53.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">20</text><line x1="40" y1="49.0" x2="356" y2="49.0" stroke="#1e2836" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="94.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">0</text><line x1="40" y1="90.0" x2="356" y2="90.0" stroke="#1e2836" stroke-width="0.5" stroke-dasharray="3,3"/>
<text x="40.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">2025-10</text><text x="204.3" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">2026-01</text><text x="356.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">2026-04</text>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0 L 356.0 90 L 40.0 90 Z" fill="url(#impact_areaGrad)"/>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0" fill="none" stroke="#58a6ff" stroke-width="2" stroke-linecap="round"/>
<g transform="translate(20, 136)">
<text x="0" y="0" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="700" fill="#d1d9e0">577</text>
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">commits over 6mo</text>
</g>
</g>
</svg>
<svg x="20" y="478" width="380" height="170" viewBox="0 0 380 170">
<defs>
<filter id="streaks_shadow" 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="streaks_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="168" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#streaks_shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">STREAKS</text>
<g transform="translate(0, 36)">
<text x="105" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#7d8895">CURRENT</text>
<text x="105" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#58a6ff">23</text>
<text x="275" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#7d8895">LONGEST</text>
<text x="275" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#d1d9e0">61</text>
<line x1="190" y1="10" x2="190" y2="76"
stroke="#2a3444" stroke-width="1"/>
<rect x="50" y="92" width="280" height="5" rx="2.5" fill="#1e2836"/>
<rect x="50" y="92" width="105.57" height="5" rx="2.5" fill="#58a6ff"/>
<circle cx="155.57" cy="94.5" r="3.5" fill="#58a6ff"/>
<text x="50" y="116"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">Mar 30 – Today</text>
<text x="330" y="116" text-anchor="end"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">Sep 13 – Nov 12, 2025</text>
</g>
</svg>
<svg x="20" y="664" width="380" height="298" viewBox="0 0 380 298">
<defs>
<filter id="collaborators_shadow" 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="collaborators_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="296" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#collaborators_shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">TOP COLLABORATORS</text>
<g transform="translate(0, 36)">
<g transform="translate(36, 20)">
<circle cx="0" cy="0" r="18" fill="hsl(285, 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">T</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#d1d9e0">torvalds</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">4 repos · 142 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#1e2836"/>
<rect x="200" y="-6" width="120.0" height="8" rx="4" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="120.0" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 70)">
<circle cx="0" cy="0" r="18" fill="hsl(165, 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">G</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#d1d9e0">gaearon</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">3 repos · 98 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#1e2836"/>
<rect x="200" y="-6" width="82.8169014084507" height="8" rx="4" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="82.8169014084507" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 120)">
<circle cx="0" cy="0" r="18" fill="hsl(238, 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">S</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#d1d9e0">sindresorhus</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">2 repos · 64 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#1e2836"/>
<rect x="200" y="-6" width="54.08450704225352" height="8" rx="4" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="54.08450704225352" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 170)">
<circle cx="0" cy="0" r="18" fill="hsl(157, 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">T</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#d1d9e0">tj</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">2 repos · 47 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#1e2836"/>
<rect x="200" y="-6" width="39.71830985915493" height="8" rx="4" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="39.71830985915493" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 220)">
<circle cx="0" cy="0" r="18" fill="hsl(231, 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">Y</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#d1d9e0">yyx990803</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">1 repos · 31 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#1e2836"/>
<rect x="200" y="-6" width="26.197183098591548" height="8" rx="4" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="26.197183098591548" dur="0.6s" fill="freeze"/>
</rect>
</g>
</g>
</svg>
<svg x="20" y="978" width="380" height="234" viewBox="0 0 380 234">
<defs>
<filter id="focus_shadow" 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="focus_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="232" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#focus_shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">RECENT FOCUS</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#d1d9e0">Backend</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#1e2836"/>
<rect x="90" y="4" width="210.0" height="14" rx="7" fill="#58a6ff" opacity="0.8">
<animate attributeName="width" from="0" to="210.0" 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="#7d8895">412 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#58a6ff">38%</text>
</g>
<g transform="translate(16, 36)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#d1d9e0">ML</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#1e2836"/>
<rect x="90" y="4" width="132.6315789473684" height="14" rx="7" fill="#3fb950" opacity="0.8">
<animate attributeName="width" from="0" to="132.6315789473684" 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="#7d8895">260 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#3fb950">24%</text>
</g>
<g transform="translate(16, 72)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#d1d9e0">Frontend</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#1e2836"/>
<rect x="90" y="4" width="99.47368421052632" height="14" rx="7" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="99.47368421052632" 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="#7d8895">195 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#bc8cff">18%</text>
</g>
<g transform="translate(16, 108)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#d1d9e0">DevOps</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#1e2836"/>
<rect x="90" y="4" width="66.3157894736842" height="14" rx="7" fill="#d29922" opacity="0.8">
<animate attributeName="width" from="0" to="66.3157894736842" 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="#7d8895">130 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#d29922">12%</text>
</g>
<g transform="translate(16, 144)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#d1d9e0">Cloud</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#1e2836"/>
<rect x="90" y="4" width="44.21052631578947" height="14" rx="7" fill="#f0883e" opacity="0.8">
<animate attributeName="width" from="0" to="44.21052631578947" 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="#7d8895">87 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#f0883e">8%</text>
</g>
<text x="16" y="188" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895" opacity="0.7">Recent activity · last year</text>
</g>
</svg>
<svg x="20" y="1228" width="380" height="208" viewBox="0 0 380 208">
<defs>
<filter id="languages_shadow" 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="languages_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="206" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#languages_shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">LANGUAGES</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3572A5" stroke-width="16"
stroke-dasharray="113.3 163.1" stroke-dashoffset="0.0"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="276.5" to="0.0" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3178c6" stroke-width="16"
stroke-dasharray="63.6 212.9" stroke-dashoffset="-113.3"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="163.1" to="-113.3" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#00ADD8" stroke-width="16"
stroke-dasharray="41.5 235.0" stroke-dashoffset="-176.9"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="99.5" to="-176.9" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#dea584" stroke-width="16"
stroke-dasharray="30.4 246.0" stroke-dashoffset="-218.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="58.1" to="-218.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#89e051" stroke-width="16"
stroke-dasharray="16.6 259.9" stroke-dashoffset="-248.8"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="27.6" to="-248.8" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#7d8895" stroke-width="16"
stroke-dasharray="11.1 265.4" stroke-dashoffset="-265.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="11.1" to="-265.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="28" fill="#1a2230"/>
<text x="60" y="87.0" text-anchor="middle" dominant-baseline="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" font-weight="700" fill="#d1d9e0">Python</text>
<g transform="translate(140, 20)">
<rect width="10" height="10" rx="2" fill="#3572A5"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">Python</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="#7d8895">41%</text>
</g>
<g transform="translate(140, 42)">
<rect width="10" height="10" rx="2" fill="#3178c6"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">TypeScript</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="#7d8895">23%</text>
</g>
<g transform="translate(140, 64)">
<rect width="10" height="10" rx="2" fill="#00ADD8"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">Go</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="#7d8895">15%</text>
</g>
<g transform="translate(140, 86)">
<rect width="10" height="10" rx="2" fill="#dea584"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">Rust</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="#7d8895">11%</text>
</g>
<g transform="translate(140, 108)">
<rect width="10" height="10" rx="2" fill="#89e051"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">Shell</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="#7d8895">6%</text>
</g>
<g transform="translate(140, 130)">
<rect width="10" height="10" rx="2" fill="#7d8895"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">Other</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="#7d8895">4%</text>
</g>
</g>
</g>
</svg>
<svg x="20" y="1452" width="380" height="274" viewBox="0 0 380 274">
<defs>
<filter id="achievements_shadow" 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="achievements_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="272" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#achievements_shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">ACHIEVEMENTS</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 8)">
<rect width="348" height="48" rx="8" fill="#d29922" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#d29922" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<svg viewBox="0 0 24 24" width="24" height="24">
<rect x="4" y="5" width="16" height="11" rx="1" fill="none" stroke="#d29922" stroke-width="1.5"/>
<rect x="3" y="16" width="18" height="1.5" rx="0.5" fill="#d29922" opacity="0.85"/>
<path d="M9 9l-2 3 2 3m6-6l2 3-2 3" stroke="#d29922" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
</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="#d1d9e0">Hackathon winner</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">Y Combinator AI Hackathon · 2025-11</text>
</g>
<g transform="translate(16, 64)">
<rect width="348" height="48" rx="8" fill="#3fb950" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#3fb950" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<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="none" stroke="#3fb950" stroke-width="1.5" stroke-linejoin="round"/>
</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="#d1d9e0">Speaker at PyCon</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">Async at scale · 2024-05</text>
</g>
<g transform="translate(16, 120)">
<rect width="348" height="48" rx="8" fill="#58a6ff" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#58a6ff" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<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="#58a6ff" opacity="0.85"/>
</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="#d1d9e0">Open Source Award</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">GitHub Stars program · 2024-01</text>
</g>
<g transform="translate(16, 176)">
<rect width="348" height="48" rx="8" fill="#bc8cff" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#bc8cff" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<svg viewBox="0 0 24 24" width="24" height="24">
<circle cx="12" cy="14" r="5" fill="#bc8cff" opacity="0.2"/>
<circle cx="12" cy="14" r="4" fill="none" stroke="#bc8cff" 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="#bc8cff"/>
<path d="M9 3l3 8m0-8l3 8m-6-8h6" stroke="#bc8cff" stroke-width="1.5" fill="none" stroke-linecap="round"/>
</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="#d1d9e0">AWS Certified Solutions Architect</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">Professional · 2023-09</text>
</g>
</g>
</svg>
<text x="210" y="1748" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895" opacity="0.5">Generated with gh-stats</text>
</svg>

After

Width:  |  Height:  |  Size: 38 KiB

+543
View File
@@ -0,0 +1,543 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
width="420" height="1756" viewBox="0 0 420 1756">
<rect width="420" height="1756" rx="16" fill="#1e2433"/>
<rect x="0.5" y="0.5" width="419" height="1755" rx="16"
fill="none" stroke="#3d4659" stroke-width="1"/>
<svg x="20" y="20" width="380" height="226" viewBox="0 0 380 226">
<defs>
<filter id="grade_shadow" 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="grade_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="224" rx="10" ry="10"
fill="#2a3142" stroke="#3d4659" stroke-width="1" filter="url(#grade_shadow)"/>
<g transform="translate(0, 0)">
<g transform="translate(52, 48)">
<circle cx="0" cy="0" r="36" fill="none" stroke="#333d50" stroke-width="5"/>
<circle cx="0" cy="0" r="36" fill="none" stroke="#3fb950" stroke-width="5"
stroke-dasharray="226.1946710584651" stroke-dashoffset="26.23858184278195"
stroke-linecap="round" transform="rotate(-90)">
<animate attributeName="stroke-dashoffset" from="226.1946710584651" to="26.23858184278195" dur="1s" fill="freeze"/>
</circle>
<text x="0" y="10.50" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="30" font-weight="800" fill="#3fb950">A</text>
</g>
<line x1="100" y1="16" x2="100" y2="80" stroke="#333d50" 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="#e5e9f0">Developer Profile</text>
<text x="0" y="32" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="#8892a4"></text>
<text x="0" y="50" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#8892a4" letter-spacing="0.4">Score <tspan fill="#e5e9f0" font-weight="600">88</tspan> / 100</text>
</g>
<line x1="20" y1="96" x2="360" y2="96" stroke="#333d50" stroke-width="0.5"/>
<g transform="translate(20, 100)">
<g transform="translate(34.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="7" cy="7" r="3" fill="none" stroke="#8892a4" stroke-width="1.4"/><circle cx="7" cy="7" r="1" fill="#8892a4"/><line x1="7" y1="10" x2="7" y2="14" stroke="#8892a4" stroke-width="1.4"/><line x1="7" y1="0" x2="7" y2="4" stroke="#8892a4" stroke-width="1.4"/></g></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="#e5e9f0">1,423</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#8892a4">Commits</text>
</g>
<g transform="translate(102.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="4" cy="4" r="2" fill="none" stroke="#8892a4" stroke-width="1.2"/><circle cx="10" cy="10" r="2" fill="none" stroke="#8892a4" stroke-width="1.2"/><path d="M4 6v4c0 1.1.9 2 2 2h2" fill="none" stroke="#8892a4" stroke-width="1.2"/></g></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="#e5e9f0">87</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#8892a4">PRs</text>
</g>
<g transform="translate(170.0, 0)">
<g transform="translate(-7, 0)"><g><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="#8892a4" stroke-width="1.2" stroke-linejoin="round"/></g></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="#e5e9f0">342</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#8892a4">Stars</text>
</g>
<g transform="translate(238.0, 0)">
<g transform="translate(-7, 0)"><g><rect x="2" y="1" width="10" height="12" rx="1.5" fill="none" stroke="#8892a4" stroke-width="1.2"/><line x1="5" y1="4" x2="9" y2="4" stroke="#8892a4" stroke-width="1"/><line x1="5" y1="6.5" x2="9" y2="6.5" stroke="#8892a4" stroke-width="1"/><line x1="5" y1="9" x2="7" y2="9" stroke="#8892a4" stroke-width="1"/></g></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="#e5e9f0">28</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#8892a4">Repos</text>
</g>
<g transform="translate(306.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="5" cy="4" r="2.5" fill="none" stroke="#8892a4" 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="#8892a4" stroke-width="1.2"/><circle cx="11" cy="3.5" r="1.8" fill="none" stroke="#8892a4" stroke-width="1"/><path d="M10 7.5c1.5 0 3.5 1 3.5 3" fill="none" stroke="#8892a4" stroke-width="1"/></g></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="#e5e9f0">156</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#8892a4">Followers</text>
</g>
</g>
<line x1="20" y1="148" x2="360" y2="148" stroke="#333d50" stroke-width="0.5"/>
<g transform="translate(20, 154)">
<g transform="translate(0, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#88c0d0" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#88c0d0" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#88c0d0">Backend</text>
</g>
<g transform="translate(70, 0)" opacity="0.9">
<rect width="31" height="24" rx="12" fill="#88c0d0" opacity="0.12"/>
<rect width="31" height="24" rx="12" fill="none" stroke="#88c0d0" stroke-width="1" opacity="0.3"/>
<text x="15" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#88c0d0">ML</text>
</g>
<g transform="translate(107, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#88c0d0" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#88c0d0" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#88c0d0">Systems</text>
</g>
<g transform="translate(177, 0)" opacity="0.9">
<rect width="51" height="24" rx="12" fill="#88c0d0" opacity="0.12"/>
<rect width="51" height="24" rx="12" fill="none" stroke="#88c0d0" stroke-width="1" opacity="0.3"/>
<text x="25" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#88c0d0">Cloud</text>
</g>
<g transform="translate(234, 0)" opacity="0.9">
<rect width="90" height="24" rx="12" fill="#facc15" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#facc15" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#facc15">Founder #42</text>
</g>
<g transform="translate(0, 30)" opacity="0.55">
<rect width="90" height="24" rx="12" fill="#88c0d0" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#88c0d0" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#88c0d0">Open source</text>
</g>
</g>
</g>
</svg>
<svg x="20" y="262" width="380" height="200" viewBox="0 0 380 200">
<defs>
<filter id="impact_shadow" 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="impact_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="198" rx="10" ry="10"
fill="#2a3142" stroke="#3d4659" stroke-width="1" filter="url(#impact_shadow)"/>
<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="#8892a4" letter-spacing="0.8" opacity="0.7">IMPACT TIMELINE</text>
<g transform="translate(0, 36)">
<defs>
<linearGradient id="impact_areaGrad" x1="0" y1="8" x2="0" y2="90" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#88c0d0" stop-opacity="0.35"/>
<stop offset="100%" stop-color="#88c0d0" stop-opacity="0.02"/>
</linearGradient>
</defs>
<text x="34" y="12.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#8892a4">41</text><line x1="40" y1="8.0" x2="356" y2="8.0" stroke="#333d50" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="53.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#8892a4">20</text><line x1="40" y1="49.0" x2="356" y2="49.0" stroke="#333d50" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="94.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#8892a4">0</text><line x1="40" y1="90.0" x2="356" y2="90.0" stroke="#333d50" stroke-width="0.5" stroke-dasharray="3,3"/>
<text x="40.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#8892a4">2025-10</text><text x="204.3" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#8892a4">2026-01</text><text x="356.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#8892a4">2026-04</text>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0 L 356.0 90 L 40.0 90 Z" fill="url(#impact_areaGrad)"/>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0" fill="none" stroke="#88c0d0" stroke-width="2" stroke-linecap="round"/>
<g transform="translate(20, 136)">
<text x="0" y="0" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="700" fill="#e5e9f0">577</text>
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#8892a4">commits over 6mo</text>
</g>
</g>
</svg>
<svg x="20" y="478" width="380" height="170" viewBox="0 0 380 170">
<defs>
<filter id="streaks_shadow" 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="streaks_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="168" rx="10" ry="10"
fill="#2a3142" stroke="#3d4659" stroke-width="1" filter="url(#streaks_shadow)"/>
<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="#8892a4" letter-spacing="0.8" opacity="0.7">STREAKS</text>
<g transform="translate(0, 36)">
<text x="105" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#8892a4">CURRENT</text>
<text x="105" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#88c0d0">23</text>
<text x="275" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#8892a4">LONGEST</text>
<text x="275" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#e5e9f0">61</text>
<line x1="190" y1="10" x2="190" y2="76"
stroke="#3d4659" stroke-width="1"/>
<rect x="50" y="92" width="280" height="5" rx="2.5" fill="#333d50"/>
<rect x="50" y="92" width="105.57" height="5" rx="2.5" fill="#88c0d0"/>
<circle cx="155.57" cy="94.5" r="3.5" fill="#88c0d0"/>
<text x="50" y="116"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#8892a4">Mar 30 – Today</text>
<text x="330" y="116" text-anchor="end"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#8892a4">Sep 13 – Nov 12, 2025</text>
</g>
</svg>
<svg x="20" y="664" width="380" height="298" viewBox="0 0 380 298">
<defs>
<filter id="collaborators_shadow" 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="collaborators_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="296" rx="10" ry="10"
fill="#2a3142" stroke="#3d4659" stroke-width="1" filter="url(#collaborators_shadow)"/>
<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="#8892a4" letter-spacing="0.8" opacity="0.7">TOP COLLABORATORS</text>
<g transform="translate(0, 36)">
<g transform="translate(36, 20)">
<circle cx="0" cy="0" r="18" fill="hsl(285, 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">T</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#e5e9f0">torvalds</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#8892a4">4 repos · 142 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#333d50"/>
<rect x="200" y="-6" width="120.0" height="8" rx="4" fill="#b48ead" opacity="0.8">
<animate attributeName="width" from="0" to="120.0" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 70)">
<circle cx="0" cy="0" r="18" fill="hsl(165, 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">G</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#e5e9f0">gaearon</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#8892a4">3 repos · 98 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#333d50"/>
<rect x="200" y="-6" width="82.8169014084507" height="8" rx="4" fill="#b48ead" opacity="0.8">
<animate attributeName="width" from="0" to="82.8169014084507" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 120)">
<circle cx="0" cy="0" r="18" fill="hsl(238, 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">S</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#e5e9f0">sindresorhus</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#8892a4">2 repos · 64 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#333d50"/>
<rect x="200" y="-6" width="54.08450704225352" height="8" rx="4" fill="#b48ead" opacity="0.8">
<animate attributeName="width" from="0" to="54.08450704225352" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 170)">
<circle cx="0" cy="0" r="18" fill="hsl(157, 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">T</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#e5e9f0">tj</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#8892a4">2 repos · 47 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#333d50"/>
<rect x="200" y="-6" width="39.71830985915493" height="8" rx="4" fill="#b48ead" opacity="0.8">
<animate attributeName="width" from="0" to="39.71830985915493" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 220)">
<circle cx="0" cy="0" r="18" fill="hsl(231, 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">Y</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#e5e9f0">yyx990803</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#8892a4">1 repos · 31 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#333d50"/>
<rect x="200" y="-6" width="26.197183098591548" height="8" rx="4" fill="#b48ead" opacity="0.8">
<animate attributeName="width" from="0" to="26.197183098591548" dur="0.6s" fill="freeze"/>
</rect>
</g>
</g>
</svg>
<svg x="20" y="978" width="380" height="234" viewBox="0 0 380 234">
<defs>
<filter id="focus_shadow" 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="focus_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="232" rx="10" ry="10"
fill="#2a3142" stroke="#3d4659" stroke-width="1" filter="url(#focus_shadow)"/>
<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="#8892a4" letter-spacing="0.8" opacity="0.7">RECENT FOCUS</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#e5e9f0">Backend</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#333d50"/>
<rect x="90" y="4" width="210.0" height="14" rx="7" fill="#58a6ff" opacity="0.8">
<animate attributeName="width" from="0" to="210.0" 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="#8892a4">412 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#58a6ff">38%</text>
</g>
<g transform="translate(16, 36)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#e5e9f0">ML</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#333d50"/>
<rect x="90" y="4" width="132.6315789473684" height="14" rx="7" fill="#3fb950" opacity="0.8">
<animate attributeName="width" from="0" to="132.6315789473684" 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="#8892a4">260 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#3fb950">24%</text>
</g>
<g transform="translate(16, 72)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#e5e9f0">Frontend</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#333d50"/>
<rect x="90" y="4" width="99.47368421052632" height="14" rx="7" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="99.47368421052632" 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="#8892a4">195 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#bc8cff">18%</text>
</g>
<g transform="translate(16, 108)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#e5e9f0">DevOps</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#333d50"/>
<rect x="90" y="4" width="66.3157894736842" height="14" rx="7" fill="#d29922" opacity="0.8">
<animate attributeName="width" from="0" to="66.3157894736842" 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="#8892a4">130 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#d29922">12%</text>
</g>
<g transform="translate(16, 144)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#e5e9f0">Cloud</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#333d50"/>
<rect x="90" y="4" width="44.21052631578947" height="14" rx="7" fill="#f0883e" opacity="0.8">
<animate attributeName="width" from="0" to="44.21052631578947" 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="#8892a4">87 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#f0883e">8%</text>
</g>
<text x="16" y="188" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#8892a4" opacity="0.7">Recent activity · last year</text>
</g>
</svg>
<svg x="20" y="1228" width="380" height="208" viewBox="0 0 380 208">
<defs>
<filter id="languages_shadow" 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="languages_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="206" rx="10" ry="10"
fill="#2a3142" stroke="#3d4659" stroke-width="1" filter="url(#languages_shadow)"/>
<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="#8892a4" letter-spacing="0.8" opacity="0.7">LANGUAGES</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3572A5" stroke-width="16"
stroke-dasharray="113.3 163.1" stroke-dashoffset="0.0"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="276.5" to="0.0" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3178c6" stroke-width="16"
stroke-dasharray="63.6 212.9" stroke-dashoffset="-113.3"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="163.1" to="-113.3" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#00ADD8" stroke-width="16"
stroke-dasharray="41.5 235.0" stroke-dashoffset="-176.9"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="99.5" to="-176.9" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#dea584" stroke-width="16"
stroke-dasharray="30.4 246.0" stroke-dashoffset="-218.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="58.1" to="-218.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#89e051" stroke-width="16"
stroke-dasharray="16.6 259.9" stroke-dashoffset="-248.8"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="27.6" to="-248.8" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#8892a4" stroke-width="16"
stroke-dasharray="11.1 265.4" stroke-dashoffset="-265.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="11.1" to="-265.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="28" fill="#2a3142"/>
<text x="60" y="87.0" text-anchor="middle" dominant-baseline="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" font-weight="700" fill="#e5e9f0">Python</text>
<g transform="translate(140, 20)">
<rect width="10" height="10" rx="2" fill="#3572A5"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#e5e9f0">Python</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="#8892a4">41%</text>
</g>
<g transform="translate(140, 42)">
<rect width="10" height="10" rx="2" fill="#3178c6"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#e5e9f0">TypeScript</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="#8892a4">23%</text>
</g>
<g transform="translate(140, 64)">
<rect width="10" height="10" rx="2" fill="#00ADD8"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#e5e9f0">Go</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="#8892a4">15%</text>
</g>
<g transform="translate(140, 86)">
<rect width="10" height="10" rx="2" fill="#dea584"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#e5e9f0">Rust</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="#8892a4">11%</text>
</g>
<g transform="translate(140, 108)">
<rect width="10" height="10" rx="2" fill="#89e051"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#e5e9f0">Shell</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="#8892a4">6%</text>
</g>
<g transform="translate(140, 130)">
<rect width="10" height="10" rx="2" fill="#8892a4"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#e5e9f0">Other</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="#8892a4">4%</text>
</g>
</g>
</g>
</svg>
<svg x="20" y="1452" width="380" height="274" viewBox="0 0 380 274">
<defs>
<filter id="achievements_shadow" 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="achievements_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="272" rx="10" ry="10"
fill="#2a3142" stroke="#3d4659" stroke-width="1" filter="url(#achievements_shadow)"/>
<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="#8892a4" letter-spacing="0.8" opacity="0.7">ACHIEVEMENTS</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 8)">
<rect width="348" height="48" rx="8" fill="#ebcb8b" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#ebcb8b" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<svg viewBox="0 0 24 24" width="24" height="24">
<rect x="4" y="5" width="16" height="11" rx="1" fill="none" stroke="#ebcb8b" stroke-width="1.5"/>
<rect x="3" y="16" width="18" height="1.5" rx="0.5" fill="#ebcb8b" opacity="0.85"/>
<path d="M9 9l-2 3 2 3m6-6l2 3-2 3" stroke="#ebcb8b" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
</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="#e5e9f0">Hackathon winner</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#8892a4">Y Combinator AI Hackathon · 2025-11</text>
</g>
<g transform="translate(16, 64)">
<rect width="348" height="48" rx="8" fill="#a3be8c" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#a3be8c" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<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="none" stroke="#a3be8c" stroke-width="1.5" stroke-linejoin="round"/>
</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="#e5e9f0">Speaker at PyCon</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#8892a4">Async at scale · 2024-05</text>
</g>
<g transform="translate(16, 120)">
<rect width="348" height="48" rx="8" fill="#88c0d0" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#88c0d0" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<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="#88c0d0" opacity="0.85"/>
</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="#e5e9f0">Open Source Award</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#8892a4">GitHub Stars program · 2024-01</text>
</g>
<g transform="translate(16, 176)">
<rect width="348" height="48" rx="8" fill="#b48ead" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#b48ead" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<svg viewBox="0 0 24 24" width="24" height="24">
<circle cx="12" cy="14" r="5" fill="#b48ead" opacity="0.2"/>
<circle cx="12" cy="14" r="4" fill="none" stroke="#b48ead" 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="#b48ead"/>
<path d="M9 3l3 8m0-8l3 8m-6-8h6" stroke="#b48ead" stroke-width="1.5" fill="none" stroke-linecap="round"/>
</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="#e5e9f0">AWS Certified Solutions Architect</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#8892a4">Professional · 2023-09</text>
</g>
</g>
</svg>
<text x="210" y="1748" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#8892a4" opacity="0.5">Generated with gh-stats</text>
</svg>

After

Width:  |  Height:  |  Size: 38 KiB

+543
View File
@@ -0,0 +1,543 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
width="420" height="1756" viewBox="0 0 420 1756">
<rect width="420" height="1756" rx="16" fill="#09090b"/>
<rect x="0.5" y="0.5" width="419" height="1755" rx="16"
fill="none" stroke="#27272a" stroke-width="1"/>
<svg x="20" y="20" width="380" height="226" viewBox="0 0 380 226">
<defs>
<filter id="grade_shadow" 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="grade_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="224" rx="10" ry="10"
fill="#18181b" stroke="#27272a" stroke-width="1" filter="url(#grade_shadow)"/>
<g transform="translate(0, 0)">
<g transform="translate(52, 48)">
<circle cx="0" cy="0" r="36" fill="none" stroke="#27272a" stroke-width="5"/>
<circle cx="0" cy="0" r="36" fill="none" stroke="#3fb950" stroke-width="5"
stroke-dasharray="226.1946710584651" stroke-dashoffset="26.23858184278195"
stroke-linecap="round" transform="rotate(-90)">
<animate attributeName="stroke-dashoffset" from="226.1946710584651" to="26.23858184278195" dur="1s" fill="freeze"/>
</circle>
<text x="0" y="10.50" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="30" font-weight="800" fill="#3fb950">A</text>
</g>
<line x1="100" y1="16" x2="100" y2="80" stroke="#27272a" 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="#fafafa">Developer Profile</text>
<text x="0" y="32" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="#a1a1aa"></text>
<text x="0" y="50" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa" letter-spacing="0.4">Score <tspan fill="#fafafa" font-weight="600">88</tspan> / 100</text>
</g>
<line x1="20" y1="96" x2="360" y2="96" stroke="#27272a" stroke-width="0.5"/>
<g transform="translate(20, 100)">
<g transform="translate(34.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="7" cy="7" r="3" fill="none" stroke="#a1a1aa" stroke-width="1.4"/><circle cx="7" cy="7" r="1" fill="#a1a1aa"/><line x1="7" y1="10" x2="7" y2="14" stroke="#a1a1aa" stroke-width="1.4"/><line x1="7" y1="0" x2="7" y2="4" stroke="#a1a1aa" stroke-width="1.4"/></g></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="#fafafa">1,423</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa">Commits</text>
</g>
<g transform="translate(102.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="4" cy="4" r="2" fill="none" stroke="#a1a1aa" stroke-width="1.2"/><circle cx="10" cy="10" r="2" fill="none" stroke="#a1a1aa" stroke-width="1.2"/><path d="M4 6v4c0 1.1.9 2 2 2h2" fill="none" stroke="#a1a1aa" stroke-width="1.2"/></g></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="#fafafa">87</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa">PRs</text>
</g>
<g transform="translate(170.0, 0)">
<g transform="translate(-7, 0)"><g><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="#a1a1aa" stroke-width="1.2" stroke-linejoin="round"/></g></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="#fafafa">342</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa">Stars</text>
</g>
<g transform="translate(238.0, 0)">
<g transform="translate(-7, 0)"><g><rect x="2" y="1" width="10" height="12" rx="1.5" fill="none" stroke="#a1a1aa" stroke-width="1.2"/><line x1="5" y1="4" x2="9" y2="4" stroke="#a1a1aa" stroke-width="1"/><line x1="5" y1="6.5" x2="9" y2="6.5" stroke="#a1a1aa" stroke-width="1"/><line x1="5" y1="9" x2="7" y2="9" stroke="#a1a1aa" stroke-width="1"/></g></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="#fafafa">28</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa">Repos</text>
</g>
<g transform="translate(306.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="5" cy="4" r="2.5" fill="none" stroke="#a1a1aa" 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="#a1a1aa" stroke-width="1.2"/><circle cx="11" cy="3.5" r="1.8" fill="none" stroke="#a1a1aa" stroke-width="1"/><path d="M10 7.5c1.5 0 3.5 1 3.5 3" fill="none" stroke="#a1a1aa" stroke-width="1"/></g></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="#fafafa">156</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa">Followers</text>
</g>
</g>
<line x1="20" y1="148" x2="360" y2="148" stroke="#27272a" stroke-width="0.5"/>
<g transform="translate(20, 154)">
<g transform="translate(0, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#a78bfa" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#a78bfa" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#a78bfa">Backend</text>
</g>
<g transform="translate(70, 0)" opacity="0.9">
<rect width="31" height="24" rx="12" fill="#a78bfa" opacity="0.12"/>
<rect width="31" height="24" rx="12" fill="none" stroke="#a78bfa" stroke-width="1" opacity="0.3"/>
<text x="15" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#a78bfa">ML</text>
</g>
<g transform="translate(107, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#a78bfa" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#a78bfa" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#a78bfa">Systems</text>
</g>
<g transform="translate(177, 0)" opacity="0.9">
<rect width="51" height="24" rx="12" fill="#a78bfa" opacity="0.12"/>
<rect width="51" height="24" rx="12" fill="none" stroke="#a78bfa" stroke-width="1" opacity="0.3"/>
<text x="25" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#a78bfa">Cloud</text>
</g>
<g transform="translate(234, 0)" opacity="0.9">
<rect width="90" height="24" rx="12" fill="#facc15" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#facc15" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#facc15">Founder #42</text>
</g>
<g transform="translate(0, 30)" opacity="0.55">
<rect width="90" height="24" rx="12" fill="#a78bfa" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#a78bfa" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#a78bfa">Open source</text>
</g>
</g>
</g>
</svg>
<svg x="20" y="262" width="380" height="200" viewBox="0 0 380 200">
<defs>
<filter id="impact_shadow" 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="impact_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="198" rx="10" ry="10"
fill="#18181b" stroke="#27272a" stroke-width="1" filter="url(#impact_shadow)"/>
<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="#a1a1aa" letter-spacing="0.8" opacity="0.7">IMPACT TIMELINE</text>
<g transform="translate(0, 36)">
<defs>
<linearGradient id="impact_areaGrad" x1="0" y1="8" x2="0" y2="90" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#a78bfa" stop-opacity="0.35"/>
<stop offset="100%" stop-color="#a78bfa" stop-opacity="0.02"/>
</linearGradient>
</defs>
<text x="34" y="12.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#a1a1aa">41</text><line x1="40" y1="8.0" x2="356" y2="8.0" stroke="#27272a" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="53.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#a1a1aa">20</text><line x1="40" y1="49.0" x2="356" y2="49.0" stroke="#27272a" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="94.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#a1a1aa">0</text><line x1="40" y1="90.0" x2="356" y2="90.0" stroke="#27272a" stroke-width="0.5" stroke-dasharray="3,3"/>
<text x="40.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#a1a1aa">2025-10</text><text x="204.3" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#a1a1aa">2026-01</text><text x="356.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#a1a1aa">2026-04</text>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0 L 356.0 90 L 40.0 90 Z" fill="url(#impact_areaGrad)"/>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0" fill="none" stroke="#a78bfa" stroke-width="2" stroke-linecap="round"/>
<g transform="translate(20, 136)">
<text x="0" y="0" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="700" fill="#fafafa">577</text>
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa">commits over 6mo</text>
</g>
</g>
</svg>
<svg x="20" y="478" width="380" height="170" viewBox="0 0 380 170">
<defs>
<filter id="streaks_shadow" 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="streaks_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="168" rx="10" ry="10"
fill="#18181b" stroke="#27272a" stroke-width="1" filter="url(#streaks_shadow)"/>
<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="#a1a1aa" letter-spacing="0.8" opacity="0.7">STREAKS</text>
<g transform="translate(0, 36)">
<text x="105" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#a1a1aa">CURRENT</text>
<text x="105" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#a78bfa">23</text>
<text x="275" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#a1a1aa">LONGEST</text>
<text x="275" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#fafafa">61</text>
<line x1="190" y1="10" x2="190" y2="76"
stroke="#27272a" stroke-width="1"/>
<rect x="50" y="92" width="280" height="5" rx="2.5" fill="#27272a"/>
<rect x="50" y="92" width="105.57" height="5" rx="2.5" fill="#a78bfa"/>
<circle cx="155.57" cy="94.5" r="3.5" fill="#a78bfa"/>
<text x="50" y="116"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa">Mar 30 – Today</text>
<text x="330" y="116" text-anchor="end"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa">Sep 13 – Nov 12, 2025</text>
</g>
</svg>
<svg x="20" y="664" width="380" height="298" viewBox="0 0 380 298">
<defs>
<filter id="collaborators_shadow" 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="collaborators_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="296" rx="10" ry="10"
fill="#18181b" stroke="#27272a" stroke-width="1" filter="url(#collaborators_shadow)"/>
<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="#a1a1aa" letter-spacing="0.8" opacity="0.7">TOP COLLABORATORS</text>
<g transform="translate(0, 36)">
<g transform="translate(36, 20)">
<circle cx="0" cy="0" r="18" fill="hsl(285, 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">T</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#fafafa">torvalds</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa">4 repos · 142 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#27272a"/>
<rect x="200" y="-6" width="120.0" height="8" rx="4" fill="#c084fc" opacity="0.8">
<animate attributeName="width" from="0" to="120.0" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 70)">
<circle cx="0" cy="0" r="18" fill="hsl(165, 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">G</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#fafafa">gaearon</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa">3 repos · 98 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#27272a"/>
<rect x="200" y="-6" width="82.8169014084507" height="8" rx="4" fill="#c084fc" opacity="0.8">
<animate attributeName="width" from="0" to="82.8169014084507" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 120)">
<circle cx="0" cy="0" r="18" fill="hsl(238, 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">S</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#fafafa">sindresorhus</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa">2 repos · 64 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#27272a"/>
<rect x="200" y="-6" width="54.08450704225352" height="8" rx="4" fill="#c084fc" opacity="0.8">
<animate attributeName="width" from="0" to="54.08450704225352" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 170)">
<circle cx="0" cy="0" r="18" fill="hsl(157, 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">T</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#fafafa">tj</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa">2 repos · 47 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#27272a"/>
<rect x="200" y="-6" width="39.71830985915493" height="8" rx="4" fill="#c084fc" opacity="0.8">
<animate attributeName="width" from="0" to="39.71830985915493" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 220)">
<circle cx="0" cy="0" r="18" fill="hsl(231, 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">Y</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#fafafa">yyx990803</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa">1 repos · 31 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#27272a"/>
<rect x="200" y="-6" width="26.197183098591548" height="8" rx="4" fill="#c084fc" opacity="0.8">
<animate attributeName="width" from="0" to="26.197183098591548" dur="0.6s" fill="freeze"/>
</rect>
</g>
</g>
</svg>
<svg x="20" y="978" width="380" height="234" viewBox="0 0 380 234">
<defs>
<filter id="focus_shadow" 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="focus_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="232" rx="10" ry="10"
fill="#18181b" stroke="#27272a" stroke-width="1" filter="url(#focus_shadow)"/>
<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="#a1a1aa" letter-spacing="0.8" opacity="0.7">RECENT FOCUS</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#fafafa">Backend</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#27272a"/>
<rect x="90" y="4" width="210.0" height="14" rx="7" fill="#58a6ff" opacity="0.8">
<animate attributeName="width" from="0" to="210.0" 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="#a1a1aa">412 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#58a6ff">38%</text>
</g>
<g transform="translate(16, 36)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#fafafa">ML</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#27272a"/>
<rect x="90" y="4" width="132.6315789473684" height="14" rx="7" fill="#3fb950" opacity="0.8">
<animate attributeName="width" from="0" to="132.6315789473684" 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="#a1a1aa">260 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#3fb950">24%</text>
</g>
<g transform="translate(16, 72)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#fafafa">Frontend</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#27272a"/>
<rect x="90" y="4" width="99.47368421052632" height="14" rx="7" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="99.47368421052632" 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="#a1a1aa">195 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#bc8cff">18%</text>
</g>
<g transform="translate(16, 108)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#fafafa">DevOps</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#27272a"/>
<rect x="90" y="4" width="66.3157894736842" height="14" rx="7" fill="#d29922" opacity="0.8">
<animate attributeName="width" from="0" to="66.3157894736842" 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="#a1a1aa">130 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#d29922">12%</text>
</g>
<g transform="translate(16, 144)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#fafafa">Cloud</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#27272a"/>
<rect x="90" y="4" width="44.21052631578947" height="14" rx="7" fill="#f0883e" opacity="0.8">
<animate attributeName="width" from="0" to="44.21052631578947" 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="#a1a1aa">87 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#f0883e">8%</text>
</g>
<text x="16" y="188" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa" opacity="0.7">Recent activity · last year</text>
</g>
</svg>
<svg x="20" y="1228" width="380" height="208" viewBox="0 0 380 208">
<defs>
<filter id="languages_shadow" 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="languages_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="206" rx="10" ry="10"
fill="#18181b" stroke="#27272a" stroke-width="1" filter="url(#languages_shadow)"/>
<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="#a1a1aa" letter-spacing="0.8" opacity="0.7">LANGUAGES</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3572A5" stroke-width="16"
stroke-dasharray="113.3 163.1" stroke-dashoffset="0.0"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="276.5" to="0.0" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3178c6" stroke-width="16"
stroke-dasharray="63.6 212.9" stroke-dashoffset="-113.3"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="163.1" to="-113.3" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#00ADD8" stroke-width="16"
stroke-dasharray="41.5 235.0" stroke-dashoffset="-176.9"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="99.5" to="-176.9" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#dea584" stroke-width="16"
stroke-dasharray="30.4 246.0" stroke-dashoffset="-218.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="58.1" to="-218.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#89e051" stroke-width="16"
stroke-dasharray="16.6 259.9" stroke-dashoffset="-248.8"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="27.6" to="-248.8" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#a1a1aa" stroke-width="16"
stroke-dasharray="11.1 265.4" stroke-dashoffset="-265.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="11.1" to="-265.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="28" fill="#18181b"/>
<text x="60" y="87.0" text-anchor="middle" dominant-baseline="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" font-weight="700" fill="#fafafa">Python</text>
<g transform="translate(140, 20)">
<rect width="10" height="10" rx="2" fill="#3572A5"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#fafafa">Python</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="#a1a1aa">41%</text>
</g>
<g transform="translate(140, 42)">
<rect width="10" height="10" rx="2" fill="#3178c6"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#fafafa">TypeScript</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="#a1a1aa">23%</text>
</g>
<g transform="translate(140, 64)">
<rect width="10" height="10" rx="2" fill="#00ADD8"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#fafafa">Go</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="#a1a1aa">15%</text>
</g>
<g transform="translate(140, 86)">
<rect width="10" height="10" rx="2" fill="#dea584"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#fafafa">Rust</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="#a1a1aa">11%</text>
</g>
<g transform="translate(140, 108)">
<rect width="10" height="10" rx="2" fill="#89e051"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#fafafa">Shell</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="#a1a1aa">6%</text>
</g>
<g transform="translate(140, 130)">
<rect width="10" height="10" rx="2" fill="#a1a1aa"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#fafafa">Other</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="#a1a1aa">4%</text>
</g>
</g>
</g>
</svg>
<svg x="20" y="1452" width="380" height="274" viewBox="0 0 380 274">
<defs>
<filter id="achievements_shadow" 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="achievements_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="272" rx="10" ry="10"
fill="#18181b" stroke="#27272a" stroke-width="1" filter="url(#achievements_shadow)"/>
<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="#a1a1aa" letter-spacing="0.8" opacity="0.7">ACHIEVEMENTS</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 8)">
<rect width="348" height="48" rx="8" fill="#fb923c" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#fb923c" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<svg viewBox="0 0 24 24" width="24" height="24">
<rect x="4" y="5" width="16" height="11" rx="1" fill="none" stroke="#fb923c" stroke-width="1.5"/>
<rect x="3" y="16" width="18" height="1.5" rx="0.5" fill="#fb923c" opacity="0.85"/>
<path d="M9 9l-2 3 2 3m6-6l2 3-2 3" stroke="#fb923c" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
</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="#fafafa">Hackathon winner</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa">Y Combinator AI Hackathon · 2025-11</text>
</g>
<g transform="translate(16, 64)">
<rect width="348" height="48" rx="8" fill="#4ade80" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#4ade80" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<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="none" stroke="#4ade80" stroke-width="1.5" stroke-linejoin="round"/>
</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="#fafafa">Speaker at PyCon</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa">Async at scale · 2024-05</text>
</g>
<g transform="translate(16, 120)">
<rect width="348" height="48" rx="8" fill="#a78bfa" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#a78bfa" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<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="#a78bfa" opacity="0.85"/>
</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="#fafafa">Open Source Award</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa">GitHub Stars program · 2024-01</text>
</g>
<g transform="translate(16, 176)">
<rect width="348" height="48" rx="8" fill="#c084fc" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#c084fc" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<svg viewBox="0 0 24 24" width="24" height="24">
<circle cx="12" cy="14" r="5" fill="#c084fc" opacity="0.2"/>
<circle cx="12" cy="14" r="4" fill="none" stroke="#c084fc" 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="#c084fc"/>
<path d="M9 3l3 8m0-8l3 8m-6-8h6" stroke="#c084fc" stroke-width="1.5" fill="none" stroke-linecap="round"/>
</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="#fafafa">AWS Certified Solutions Architect</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#a1a1aa">Professional · 2023-09</text>
</g>
</g>
</svg>
<text x="210" y="1748" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#a1a1aa" opacity="0.5">Generated with gh-stats</text>
</svg>

After

Width:  |  Height:  |  Size: 38 KiB

+543
View File
@@ -0,0 +1,543 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
width="420" height="1756" viewBox="0 0 420 1756">
<rect width="420" height="1756" rx="16" fill="#faf8f5"/>
<rect x="0.5" y="0.5" width="419" height="1755" rx="16"
fill="none" stroke="#e0d8cf" stroke-width="1"/>
<svg x="20" y="20" width="380" height="226" viewBox="0 0 380 226">
<defs>
<filter id="grade_shadow" 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="grade_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="224" rx="10" ry="10"
fill="#f5f0eb" stroke="#e0d8cf" stroke-width="1" filter="url(#grade_shadow)"/>
<g transform="translate(0, 0)">
<g transform="translate(52, 48)">
<circle cx="0" cy="0" r="36" fill="none" stroke="#ebe5dd" stroke-width="5"/>
<circle cx="0" cy="0" r="36" fill="none" stroke="#3fb950" stroke-width="5"
stroke-dasharray="226.1946710584651" stroke-dashoffset="26.23858184278195"
stroke-linecap="round" transform="rotate(-90)">
<animate attributeName="stroke-dashoffset" from="226.1946710584651" to="26.23858184278195" dur="1s" fill="freeze"/>
</circle>
<text x="0" y="10.50" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="30" font-weight="800" fill="#3fb950">A</text>
</g>
<line x1="100" y1="16" x2="100" y2="80" stroke="#ebe5dd" 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="#3d3529">Developer Profile</text>
<text x="0" y="32" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="#7a7062"></text>
<text x="0" y="50" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7a7062" letter-spacing="0.4">Score <tspan fill="#3d3529" font-weight="600">88</tspan> / 100</text>
</g>
<line x1="20" y1="96" x2="360" y2="96" stroke="#ebe5dd" stroke-width="0.5"/>
<g transform="translate(20, 100)">
<g transform="translate(34.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="7" cy="7" r="3" fill="none" stroke="#7a7062" stroke-width="1.4"/><circle cx="7" cy="7" r="1" fill="#7a7062"/><line x1="7" y1="10" x2="7" y2="14" stroke="#7a7062" stroke-width="1.4"/><line x1="7" y1="0" x2="7" y2="4" stroke="#7a7062" stroke-width="1.4"/></g></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="#3d3529">1,423</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7a7062">Commits</text>
</g>
<g transform="translate(102.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="4" cy="4" r="2" fill="none" stroke="#7a7062" stroke-width="1.2"/><circle cx="10" cy="10" r="2" fill="none" stroke="#7a7062" stroke-width="1.2"/><path d="M4 6v4c0 1.1.9 2 2 2h2" fill="none" stroke="#7a7062" stroke-width="1.2"/></g></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="#3d3529">87</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7a7062">PRs</text>
</g>
<g transform="translate(170.0, 0)">
<g transform="translate(-7, 0)"><g><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="#7a7062" stroke-width="1.2" stroke-linejoin="round"/></g></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="#3d3529">342</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7a7062">Stars</text>
</g>
<g transform="translate(238.0, 0)">
<g transform="translate(-7, 0)"><g><rect x="2" y="1" width="10" height="12" rx="1.5" fill="none" stroke="#7a7062" stroke-width="1.2"/><line x1="5" y1="4" x2="9" y2="4" stroke="#7a7062" stroke-width="1"/><line x1="5" y1="6.5" x2="9" y2="6.5" stroke="#7a7062" stroke-width="1"/><line x1="5" y1="9" x2="7" y2="9" stroke="#7a7062" stroke-width="1"/></g></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="#3d3529">28</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7a7062">Repos</text>
</g>
<g transform="translate(306.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="5" cy="4" r="2.5" fill="none" stroke="#7a7062" 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="#7a7062" stroke-width="1.2"/><circle cx="11" cy="3.5" r="1.8" fill="none" stroke="#7a7062" stroke-width="1"/><path d="M10 7.5c1.5 0 3.5 1 3.5 3" fill="none" stroke="#7a7062" stroke-width="1"/></g></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="#3d3529">156</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7a7062">Followers</text>
</g>
</g>
<line x1="20" y1="148" x2="360" y2="148" stroke="#ebe5dd" stroke-width="0.5"/>
<g transform="translate(20, 154)">
<g transform="translate(0, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#b45309" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#b45309" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#b45309">Backend</text>
</g>
<g transform="translate(70, 0)" opacity="0.9">
<rect width="31" height="24" rx="12" fill="#b45309" opacity="0.12"/>
<rect width="31" height="24" rx="12" fill="none" stroke="#b45309" stroke-width="1" opacity="0.3"/>
<text x="15" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#b45309">ML</text>
</g>
<g transform="translate(107, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#b45309" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#b45309" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#b45309">Systems</text>
</g>
<g transform="translate(177, 0)" opacity="0.9">
<rect width="51" height="24" rx="12" fill="#b45309" opacity="0.12"/>
<rect width="51" height="24" rx="12" fill="none" stroke="#b45309" stroke-width="1" opacity="0.3"/>
<text x="25" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#b45309">Cloud</text>
</g>
<g transform="translate(234, 0)" opacity="0.9">
<rect width="90" height="24" rx="12" fill="#facc15" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#facc15" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#facc15">Founder #42</text>
</g>
<g transform="translate(0, 30)" opacity="0.55">
<rect width="90" height="24" rx="12" fill="#b45309" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#b45309" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#b45309">Open source</text>
</g>
</g>
</g>
</svg>
<svg x="20" y="262" width="380" height="200" viewBox="0 0 380 200">
<defs>
<filter id="impact_shadow" 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="impact_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="198" rx="10" ry="10"
fill="#f5f0eb" stroke="#e0d8cf" stroke-width="1" filter="url(#impact_shadow)"/>
<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="#7a7062" letter-spacing="0.8" opacity="0.7">IMPACT TIMELINE</text>
<g transform="translate(0, 36)">
<defs>
<linearGradient id="impact_areaGrad" x1="0" y1="8" x2="0" y2="90" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#b45309" stop-opacity="0.35"/>
<stop offset="100%" stop-color="#b45309" stop-opacity="0.02"/>
</linearGradient>
</defs>
<text x="34" y="12.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7a7062">41</text><line x1="40" y1="8.0" x2="356" y2="8.0" stroke="#ebe5dd" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="53.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7a7062">20</text><line x1="40" y1="49.0" x2="356" y2="49.0" stroke="#ebe5dd" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="94.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7a7062">0</text><line x1="40" y1="90.0" x2="356" y2="90.0" stroke="#ebe5dd" stroke-width="0.5" stroke-dasharray="3,3"/>
<text x="40.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7a7062">2025-10</text><text x="204.3" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7a7062">2026-01</text><text x="356.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7a7062">2026-04</text>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0 L 356.0 90 L 40.0 90 Z" fill="url(#impact_areaGrad)"/>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0" fill="none" stroke="#b45309" stroke-width="2" stroke-linecap="round"/>
<g transform="translate(20, 136)">
<text x="0" y="0" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="700" fill="#3d3529">577</text>
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7a7062">commits over 6mo</text>
</g>
</g>
</svg>
<svg x="20" y="478" width="380" height="170" viewBox="0 0 380 170">
<defs>
<filter id="streaks_shadow" 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="streaks_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="168" rx="10" ry="10"
fill="#f5f0eb" stroke="#e0d8cf" stroke-width="1" filter="url(#streaks_shadow)"/>
<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="#7a7062" letter-spacing="0.8" opacity="0.7">STREAKS</text>
<g transform="translate(0, 36)">
<text x="105" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#7a7062">CURRENT</text>
<text x="105" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#b45309">23</text>
<text x="275" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#7a7062">LONGEST</text>
<text x="275" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#3d3529">61</text>
<line x1="190" y1="10" x2="190" y2="76"
stroke="#e0d8cf" stroke-width="1"/>
<rect x="50" y="92" width="280" height="5" rx="2.5" fill="#ebe5dd"/>
<rect x="50" y="92" width="105.57" height="5" rx="2.5" fill="#b45309"/>
<circle cx="155.57" cy="94.5" r="3.5" fill="#b45309"/>
<text x="50" y="116"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7a7062">Mar 30 – Today</text>
<text x="330" y="116" text-anchor="end"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7a7062">Sep 13 – Nov 12, 2025</text>
</g>
</svg>
<svg x="20" y="664" width="380" height="298" viewBox="0 0 380 298">
<defs>
<filter id="collaborators_shadow" 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="collaborators_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="296" rx="10" ry="10"
fill="#f5f0eb" stroke="#e0d8cf" stroke-width="1" filter="url(#collaborators_shadow)"/>
<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="#7a7062" letter-spacing="0.8" opacity="0.7">TOP COLLABORATORS</text>
<g transform="translate(0, 36)">
<g transform="translate(36, 20)">
<circle cx="0" cy="0" r="18" fill="hsl(285, 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">T</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#3d3529">torvalds</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7a7062">4 repos · 142 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#ebe5dd"/>
<rect x="200" y="-6" width="120.0" height="8" rx="4" fill="#7e22ce" opacity="0.8">
<animate attributeName="width" from="0" to="120.0" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 70)">
<circle cx="0" cy="0" r="18" fill="hsl(165, 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">G</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#3d3529">gaearon</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7a7062">3 repos · 98 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#ebe5dd"/>
<rect x="200" y="-6" width="82.8169014084507" height="8" rx="4" fill="#7e22ce" opacity="0.8">
<animate attributeName="width" from="0" to="82.8169014084507" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 120)">
<circle cx="0" cy="0" r="18" fill="hsl(238, 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">S</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#3d3529">sindresorhus</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7a7062">2 repos · 64 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#ebe5dd"/>
<rect x="200" y="-6" width="54.08450704225352" height="8" rx="4" fill="#7e22ce" opacity="0.8">
<animate attributeName="width" from="0" to="54.08450704225352" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 170)">
<circle cx="0" cy="0" r="18" fill="hsl(157, 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">T</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#3d3529">tj</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7a7062">2 repos · 47 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#ebe5dd"/>
<rect x="200" y="-6" width="39.71830985915493" height="8" rx="4" fill="#7e22ce" opacity="0.8">
<animate attributeName="width" from="0" to="39.71830985915493" dur="0.6s" fill="freeze"/>
</rect>
</g>
<g transform="translate(36, 220)">
<circle cx="0" cy="0" r="18" fill="hsl(231, 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">Y</text>
<text x="28" y="-2" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="#3d3529">yyx990803</text>
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7a7062">1 repos · 31 commits</text>
<rect x="200" y="-6" width="130" height="8" rx="4" fill="#ebe5dd"/>
<rect x="200" y="-6" width="26.197183098591548" height="8" rx="4" fill="#7e22ce" opacity="0.8">
<animate attributeName="width" from="0" to="26.197183098591548" dur="0.6s" fill="freeze"/>
</rect>
</g>
</g>
</svg>
<svg x="20" y="978" width="380" height="234" viewBox="0 0 380 234">
<defs>
<filter id="focus_shadow" 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="focus_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="232" rx="10" ry="10"
fill="#f5f0eb" stroke="#e0d8cf" stroke-width="1" filter="url(#focus_shadow)"/>
<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="#7a7062" letter-spacing="0.8" opacity="0.7">RECENT FOCUS</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#3d3529">Backend</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#ebe5dd"/>
<rect x="90" y="4" width="210.0" height="14" rx="7" fill="#58a6ff" opacity="0.8">
<animate attributeName="width" from="0" to="210.0" 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="#7a7062">412 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#58a6ff">38%</text>
</g>
<g transform="translate(16, 36)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#3d3529">ML</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#ebe5dd"/>
<rect x="90" y="4" width="132.6315789473684" height="14" rx="7" fill="#3fb950" opacity="0.8">
<animate attributeName="width" from="0" to="132.6315789473684" 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="#7a7062">260 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#3fb950">24%</text>
</g>
<g transform="translate(16, 72)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#3d3529">Frontend</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#ebe5dd"/>
<rect x="90" y="4" width="99.47368421052632" height="14" rx="7" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="99.47368421052632" 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="#7a7062">195 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#bc8cff">18%</text>
</g>
<g transform="translate(16, 108)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#3d3529">DevOps</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#ebe5dd"/>
<rect x="90" y="4" width="66.3157894736842" height="14" rx="7" fill="#d29922" opacity="0.8">
<animate attributeName="width" from="0" to="66.3157894736842" 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="#7a7062">130 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#d29922">12%</text>
</g>
<g transform="translate(16, 144)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#3d3529">Cloud</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#ebe5dd"/>
<rect x="90" y="4" width="44.21052631578947" height="14" rx="7" fill="#f0883e" opacity="0.8">
<animate attributeName="width" from="0" to="44.21052631578947" 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="#7a7062">87 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#f0883e">8%</text>
</g>
<text x="16" y="188" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7a7062" opacity="0.7">Recent activity · last year</text>
</g>
</svg>
<svg x="20" y="1228" width="380" height="208" viewBox="0 0 380 208">
<defs>
<filter id="languages_shadow" 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="languages_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="206" rx="10" ry="10"
fill="#f5f0eb" stroke="#e0d8cf" stroke-width="1" filter="url(#languages_shadow)"/>
<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="#7a7062" letter-spacing="0.8" opacity="0.7">LANGUAGES</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3572A5" stroke-width="16"
stroke-dasharray="113.3 163.1" stroke-dashoffset="0.0"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="276.5" to="0.0" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3178c6" stroke-width="16"
stroke-dasharray="63.6 212.9" stroke-dashoffset="-113.3"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="163.1" to="-113.3" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#00ADD8" stroke-width="16"
stroke-dasharray="41.5 235.0" stroke-dashoffset="-176.9"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="99.5" to="-176.9" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#dea584" stroke-width="16"
stroke-dasharray="30.4 246.0" stroke-dashoffset="-218.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="58.1" to="-218.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#89e051" stroke-width="16"
stroke-dasharray="16.6 259.9" stroke-dashoffset="-248.8"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="27.6" to="-248.8" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#7a7062" stroke-width="16"
stroke-dasharray="11.1 265.4" stroke-dashoffset="-265.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="11.1" to="-265.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="28" fill="#f5f0eb"/>
<text x="60" y="87.0" text-anchor="middle" dominant-baseline="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" font-weight="700" fill="#3d3529">Python</text>
<g transform="translate(140, 20)">
<rect width="10" height="10" rx="2" fill="#3572A5"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#3d3529">Python</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="#7a7062">41%</text>
</g>
<g transform="translate(140, 42)">
<rect width="10" height="10" rx="2" fill="#3178c6"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#3d3529">TypeScript</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="#7a7062">23%</text>
</g>
<g transform="translate(140, 64)">
<rect width="10" height="10" rx="2" fill="#00ADD8"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#3d3529">Go</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="#7a7062">15%</text>
</g>
<g transform="translate(140, 86)">
<rect width="10" height="10" rx="2" fill="#dea584"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#3d3529">Rust</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="#7a7062">11%</text>
</g>
<g transform="translate(140, 108)">
<rect width="10" height="10" rx="2" fill="#89e051"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#3d3529">Shell</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="#7a7062">6%</text>
</g>
<g transform="translate(140, 130)">
<rect width="10" height="10" rx="2" fill="#7a7062"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#3d3529">Other</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="#7a7062">4%</text>
</g>
</g>
</g>
</svg>
<svg x="20" y="1452" width="380" height="274" viewBox="0 0 380 274">
<defs>
<filter id="achievements_shadow" 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="achievements_avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="272" rx="10" ry="10"
fill="#f5f0eb" stroke="#e0d8cf" stroke-width="1" filter="url(#achievements_shadow)"/>
<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="#7a7062" letter-spacing="0.8" opacity="0.7">ACHIEVEMENTS</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 8)">
<rect width="348" height="48" rx="8" fill="#a16207" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#a16207" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<svg viewBox="0 0 24 24" width="24" height="24">
<rect x="4" y="5" width="16" height="11" rx="1" fill="none" stroke="#a16207" stroke-width="1.5"/>
<rect x="3" y="16" width="18" height="1.5" rx="0.5" fill="#a16207" opacity="0.85"/>
<path d="M9 9l-2 3 2 3m6-6l2 3-2 3" stroke="#a16207" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
</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="#3d3529">Hackathon winner</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7a7062">Y Combinator AI Hackathon · 2025-11</text>
</g>
<g transform="translate(16, 64)">
<rect width="348" height="48" rx="8" fill="#4d7c0f" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#4d7c0f" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<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="none" stroke="#4d7c0f" stroke-width="1.5" stroke-linejoin="round"/>
</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="#3d3529">Speaker at PyCon</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7a7062">Async at scale · 2024-05</text>
</g>
<g transform="translate(16, 120)">
<rect width="348" height="48" rx="8" fill="#b45309" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#b45309" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<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="#b45309" opacity="0.85"/>
</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="#3d3529">Open Source Award</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7a7062">GitHub Stars program · 2024-01</text>
</g>
<g transform="translate(16, 176)">
<rect width="348" height="48" rx="8" fill="#7e22ce" opacity="0.06"/>
<rect width="348" height="48" rx="8" fill="none" stroke="#7e22ce" stroke-width="0.5" opacity="0.3"/>
<g transform="translate(12, 12)">
<svg viewBox="0 0 24 24" width="24" height="24">
<circle cx="12" cy="14" r="5" fill="#7e22ce" opacity="0.2"/>
<circle cx="12" cy="14" r="4" fill="none" stroke="#7e22ce" 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="#7e22ce"/>
<path d="M9 3l3 8m0-8l3 8m-6-8h6" stroke="#7e22ce" stroke-width="1.5" fill="none" stroke-linecap="round"/>
</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="#3d3529">AWS Certified Solutions Architect</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7a7062">Professional · 2023-09</text>
</g>
</g>
</svg>
<text x="210" y="1748" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7a7062" opacity="0.5">Generated with gh-stats</text>
</svg>

After

Width:  |  Height:  |  Size: 38 KiB

+76
View File
@@ -0,0 +1,76 @@
<svg xmlns="http://www.w3.org/2000/svg" width="380" height="234" viewBox="0 0 380 234" fill="none">
<defs>
<filter id="shadow" 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="avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="232" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">RECENT FOCUS</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#d1d9e0">Backend</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#1e2836"/>
<rect x="90" y="4" width="210.0" height="14" rx="7" fill="#58a6ff" opacity="0.8">
<animate attributeName="width" from="0" to="210.0" 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="#7d8895">412 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#58a6ff">38%</text>
</g>
<g transform="translate(16, 36)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#d1d9e0">ML</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#1e2836"/>
<rect x="90" y="4" width="132.6315789473684" height="14" rx="7" fill="#3fb950" opacity="0.8">
<animate attributeName="width" from="0" to="132.6315789473684" 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="#7d8895">260 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#3fb950">24%</text>
</g>
<g transform="translate(16, 72)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#d1d9e0">Frontend</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#1e2836"/>
<rect x="90" y="4" width="99.47368421052632" height="14" rx="7" fill="#bc8cff" opacity="0.8">
<animate attributeName="width" from="0" to="99.47368421052632" 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="#7d8895">195 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#bc8cff">18%</text>
</g>
<g transform="translate(16, 108)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#d1d9e0">DevOps</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#1e2836"/>
<rect x="90" y="4" width="66.3157894736842" height="14" rx="7" fill="#d29922" opacity="0.8">
<animate attributeName="width" from="0" to="66.3157894736842" 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="#7d8895">130 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#d29922">12%</text>
</g>
<g transform="translate(16, 144)">
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="600" fill="#d1d9e0">Cloud</text>
<rect x="90" y="4" width="210" height="14" rx="7" fill="#1e2836"/>
<rect x="90" y="4" width="44.21052631578947" height="14" rx="7" fill="#f0883e" opacity="0.8">
<animate attributeName="width" from="0" to="44.21052631578947" 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="#7d8895">87 commits</text>
<text x="308" y="15" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" font-weight="700" fill="#f0883e">8%</text>
</g>
<text x="16" y="188" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895" opacity="0.7">Recent activity · last year</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 5.1 KiB

+95
View File
@@ -0,0 +1,95 @@
<svg xmlns="http://www.w3.org/2000/svg" width="380" height="192" viewBox="0 0 380 192" fill="none">
<defs>
<filter id="shadow" 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="avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="190" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#shadow)"/>
<g transform="translate(0, 0)">
<g transform="translate(52, 48)">
<circle cx="0" cy="0" r="36" fill="none" stroke="#1e2836" stroke-width="5"/>
<circle cx="0" cy="0" r="36" fill="none" stroke="#3fb950" stroke-width="5"
stroke-dasharray="226.1946710584651" stroke-dashoffset="26.23858184278195"
stroke-linecap="round" transform="rotate(-90)">
<animate attributeName="stroke-dashoffset" from="226.1946710584651" to="26.23858184278195" dur="1s" fill="freeze"/>
</circle>
<text x="0" y="10.50" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="30" font-weight="800" fill="#3fb950">A</text>
</g>
<line x1="100" y1="16" x2="100" y2="80" stroke="#1e2836" 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="#d1d9e0">Developer Profile</text>
<text x="0" y="32" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="#7d8895"></text>
<text x="0" y="50" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895" letter-spacing="0.4">Score <tspan fill="#d1d9e0" font-weight="600">88</tspan> / 100</text>
</g>
<line x1="20" y1="96" x2="360" y2="96" stroke="#1e2836" stroke-width="0.5"/>
<g transform="translate(20, 100)">
<g transform="translate(34.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="7" cy="7" r="3" fill="none" stroke="#7d8895" stroke-width="1.4"/><circle cx="7" cy="7" r="1" fill="#7d8895"/><line x1="7" y1="10" x2="7" y2="14" stroke="#7d8895" stroke-width="1.4"/><line x1="7" y1="0" x2="7" y2="4" stroke="#7d8895" stroke-width="1.4"/></g></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="#d1d9e0">1,423</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">Commits</text>
</g>
<g transform="translate(102.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="4" cy="4" r="2" fill="none" stroke="#7d8895" stroke-width="1.2"/><circle cx="10" cy="10" r="2" fill="none" stroke="#7d8895" stroke-width="1.2"/><path d="M4 6v4c0 1.1.9 2 2 2h2" fill="none" stroke="#7d8895" stroke-width="1.2"/></g></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="#d1d9e0">87</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">PRs</text>
</g>
<g transform="translate(170.0, 0)">
<g transform="translate(-7, 0)"><g><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="#7d8895" stroke-width="1.2" stroke-linejoin="round"/></g></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="#d1d9e0">342</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">Stars</text>
</g>
<g transform="translate(238.0, 0)">
<g transform="translate(-7, 0)"><g><rect x="2" y="1" width="10" height="12" rx="1.5" fill="none" stroke="#7d8895" stroke-width="1.2"/><line x1="5" y1="4" x2="9" y2="4" stroke="#7d8895" stroke-width="1"/><line x1="5" y1="6.5" x2="9" y2="6.5" stroke="#7d8895" stroke-width="1"/><line x1="5" y1="9" x2="7" y2="9" stroke="#7d8895" stroke-width="1"/></g></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="#d1d9e0">28</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">Repos</text>
</g>
<g transform="translate(306.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="5" cy="4" r="2.5" fill="none" stroke="#7d8895" 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="#7d8895" stroke-width="1.2"/><circle cx="11" cy="3.5" r="1.8" fill="none" stroke="#7d8895" stroke-width="1"/><path d="M10 7.5c1.5 0 3.5 1 3.5 3" fill="none" stroke="#7d8895" stroke-width="1"/></g></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="#d1d9e0">156</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">Followers</text>
</g>
</g>
<line x1="20" y1="148" x2="360" y2="148" stroke="#1e2836" stroke-width="0.5"/>
<g transform="translate(20, 154)">
<g transform="translate(0, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#58a6ff" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#58a6ff" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#58a6ff">Backend</text>
</g>
<g transform="translate(70, 0)" opacity="0.9">
<rect width="31" height="24" rx="12" fill="#58a6ff" opacity="0.12"/>
<rect width="31" height="24" rx="12" fill="none" stroke="#58a6ff" stroke-width="1" opacity="0.3"/>
<text x="15" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#58a6ff">ML</text>
</g>
<g transform="translate(107, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#58a6ff" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#58a6ff" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#58a6ff">Systems</text>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 7.2 KiB

+113
View File
@@ -0,0 +1,113 @@
<svg xmlns="http://www.w3.org/2000/svg" width="380" height="226" viewBox="0 0 380 226" fill="none">
<defs>
<filter id="shadow" 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="avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="224" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#shadow)"/>
<g transform="translate(0, 0)">
<g transform="translate(52, 48)">
<circle cx="0" cy="0" r="36" fill="none" stroke="#1e2836" stroke-width="5"/>
<circle cx="0" cy="0" r="36" fill="none" stroke="#3fb950" stroke-width="5"
stroke-dasharray="226.1946710584651" stroke-dashoffset="26.23858184278195"
stroke-linecap="round" transform="rotate(-90)">
<animate attributeName="stroke-dashoffset" from="226.1946710584651" to="26.23858184278195" dur="1s" fill="freeze"/>
</circle>
<text x="0" y="10.50" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="30" font-weight="800" fill="#3fb950">A</text>
</g>
<line x1="100" y1="16" x2="100" y2="80" stroke="#1e2836" 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="#d1d9e0">Developer Profile</text>
<text x="0" y="32" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="#7d8895"></text>
<text x="0" y="50" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895" letter-spacing="0.4">Score <tspan fill="#d1d9e0" font-weight="600">88</tspan> / 100</text>
</g>
<line x1="20" y1="96" x2="360" y2="96" stroke="#1e2836" stroke-width="0.5"/>
<g transform="translate(20, 100)">
<g transform="translate(34.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="7" cy="7" r="3" fill="none" stroke="#7d8895" stroke-width="1.4"/><circle cx="7" cy="7" r="1" fill="#7d8895"/><line x1="7" y1="10" x2="7" y2="14" stroke="#7d8895" stroke-width="1.4"/><line x1="7" y1="0" x2="7" y2="4" stroke="#7d8895" stroke-width="1.4"/></g></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="#d1d9e0">1,423</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">Commits</text>
</g>
<g transform="translate(102.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="4" cy="4" r="2" fill="none" stroke="#7d8895" stroke-width="1.2"/><circle cx="10" cy="10" r="2" fill="none" stroke="#7d8895" stroke-width="1.2"/><path d="M4 6v4c0 1.1.9 2 2 2h2" fill="none" stroke="#7d8895" stroke-width="1.2"/></g></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="#d1d9e0">87</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">PRs</text>
</g>
<g transform="translate(170.0, 0)">
<g transform="translate(-7, 0)"><g><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="#7d8895" stroke-width="1.2" stroke-linejoin="round"/></g></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="#d1d9e0">342</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">Stars</text>
</g>
<g transform="translate(238.0, 0)">
<g transform="translate(-7, 0)"><g><rect x="2" y="1" width="10" height="12" rx="1.5" fill="none" stroke="#7d8895" stroke-width="1.2"/><line x1="5" y1="4" x2="9" y2="4" stroke="#7d8895" stroke-width="1"/><line x1="5" y1="6.5" x2="9" y2="6.5" stroke="#7d8895" stroke-width="1"/><line x1="5" y1="9" x2="7" y2="9" stroke="#7d8895" stroke-width="1"/></g></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="#d1d9e0">28</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">Repos</text>
</g>
<g transform="translate(306.0, 0)">
<g transform="translate(-7, 0)"><g><circle cx="5" cy="4" r="2.5" fill="none" stroke="#7d8895" 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="#7d8895" stroke-width="1.2"/><circle cx="11" cy="3.5" r="1.8" fill="none" stroke="#7d8895" stroke-width="1"/><path d="M10 7.5c1.5 0 3.5 1 3.5 3" fill="none" stroke="#7d8895" stroke-width="1"/></g></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="#d1d9e0">156</text>
<text x="0" y="41" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">Followers</text>
</g>
</g>
<line x1="20" y1="148" x2="360" y2="148" stroke="#1e2836" stroke-width="0.5"/>
<g transform="translate(20, 154)">
<g transform="translate(0, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#58a6ff" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#58a6ff" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#58a6ff">Backend</text>
</g>
<g transform="translate(70, 0)" opacity="0.9">
<rect width="31" height="24" rx="12" fill="#58a6ff" opacity="0.12"/>
<rect width="31" height="24" rx="12" fill="none" stroke="#58a6ff" stroke-width="1" opacity="0.3"/>
<text x="15" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#58a6ff">ML</text>
</g>
<g transform="translate(107, 0)" opacity="0.9">
<rect width="64" height="24" rx="12" fill="#58a6ff" opacity="0.12"/>
<rect width="64" height="24" rx="12" fill="none" stroke="#58a6ff" stroke-width="1" opacity="0.3"/>
<text x="32" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#58a6ff">Systems</text>
</g>
<g transform="translate(177, 0)" opacity="0.9">
<rect width="51" height="24" rx="12" fill="#58a6ff" opacity="0.12"/>
<rect width="51" height="24" rx="12" fill="none" stroke="#58a6ff" stroke-width="1" opacity="0.3"/>
<text x="25" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#58a6ff">Cloud</text>
</g>
<g transform="translate(234, 0)" opacity="0.9">
<rect width="90" height="24" rx="12" fill="#facc15" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#facc15" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#facc15">Founder #42</text>
</g>
<g transform="translate(0, 30)" opacity="0.55">
<rect width="90" height="24" rx="12" fill="#58a6ff" opacity="0.12"/>
<rect width="90" height="24" rx="12" fill="none" stroke="#58a6ff" stroke-width="1" opacity="0.3"/>
<text x="45" y="16" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="500" fill="#58a6ff">Open source</text>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 8.6 KiB

+30
View File
@@ -0,0 +1,30 @@
<svg xmlns="http://www.w3.org/2000/svg" width="380" height="200" viewBox="0 0 380 200" fill="none">
<defs>
<filter id="shadow" 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="avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="198" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">IMPACT TIMELINE</text>
<g transform="translate(0, 36)">
<defs>
<linearGradient id="areaGrad" x1="0" y1="8" x2="0" y2="90" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#a78bfa" stop-opacity="0.35"/>
<stop offset="100%" stop-color="#a78bfa" stop-opacity="0.02"/>
</linearGradient>
</defs>
<text x="34" y="12.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">41</text><line x1="40" y1="8.0" x2="356" y2="8.0" stroke="#1e2836" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="53.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">20</text><line x1="40" y1="49.0" x2="356" y2="49.0" stroke="#1e2836" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="94.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">0</text><line x1="40" y1="90.0" x2="356" y2="90.0" stroke="#1e2836" stroke-width="0.5" stroke-dasharray="3,3"/>
<text x="40.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">2025-10</text><text x="204.3" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">2026-01</text><text x="356.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">2026-04</text>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0 L 356.0 90 L 40.0 90 Z" fill="url(#areaGrad)"/>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0" fill="none" stroke="#a78bfa" stroke-width="2" stroke-linecap="round"/>
<g transform="translate(20, 136)">
<text x="0" y="0" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="700" fill="#d1d9e0">577</text>
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">commits over 6mo</text>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.7 KiB

+30
View File
@@ -0,0 +1,30 @@
<svg xmlns="http://www.w3.org/2000/svg" width="380" height="200" viewBox="0 0 380 200" fill="none">
<defs>
<filter id="shadow" 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="avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="198" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">IMPACT TIMELINE</text>
<g transform="translate(0, 36)">
<defs>
<linearGradient id="areaGrad" x1="0" y1="8" x2="0" y2="90" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#58a6ff" stop-opacity="0.35"/>
<stop offset="100%" stop-color="#58a6ff" stop-opacity="0.02"/>
</linearGradient>
</defs>
<text x="34" y="12.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">41</text><line x1="40" y1="8.0" x2="356" y2="8.0" stroke="#1e2836" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="53.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">20</text><line x1="40" y1="49.0" x2="356" y2="49.0" stroke="#1e2836" stroke-width="0.5" stroke-dasharray="3,3"/><text x="34" y="94.0" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">0</text><line x1="40" y1="90.0" x2="356" y2="90.0" stroke="#1e2836" stroke-width="0.5" stroke-dasharray="3,3"/>
<text x="40.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">2025-10</text><text x="204.3" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">2026-01</text><text x="356.0" y="104" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="9" fill="#7d8895">2026-04</text>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0 L 356.0 90 L 40.0 90 Z" fill="url(#areaGrad)"/>
<path d="M 40.0 84.0 C 46.3 84.0, 46.3 80.0, 52.6 80.0 C 59.0 80.0, 59.0 74.0, 65.3 74.0 C 71.6 74.0, 71.6 78.0, 77.9 78.0 C 84.2 78.0, 84.2 68.0, 90.6 68.0 C 96.9 68.0, 96.9 62.0, 103.2 62.0 C 109.5 62.0, 109.5 72.0, 115.8 72.0 C 122.2 72.0, 122.2 66.0, 128.5 66.0 C 134.8 66.0, 134.8 54.0, 141.1 54.0 C 147.4 54.0, 147.4 46.0, 153.8 46.0 C 160.1 46.0, 160.1 56.0, 166.4 56.0 C 172.7 56.0, 172.7 52.0, 179.0 52.0 C 185.4 52.0, 185.4 40.0, 191.7 40.0 C 198.0 40.0, 198.0 48.0, 204.3 48.0 C 210.6 48.0, 210.6 34.0, 217.0 34.0 C 223.3 34.0, 223.3 26.0, 229.6 26.0 C 235.9 26.0, 235.9 38.0, 242.2 38.0 C 248.6 38.0, 248.6 42.0, 254.9 42.0 C 261.2 42.0, 261.2 30.0, 267.5 30.0 C 273.8 30.0, 273.8 20.0, 280.2 20.0 C 286.5 20.0, 286.5 32.0, 292.8 32.0 C 299.1 32.0, 299.1 24.0, 305.4 24.0 C 311.8 24.0, 311.8 8.0, 318.1 8.0 C 324.4 8.0, 324.4 14.0, 330.7 14.0 C 337.0 14.0, 337.0 22.0, 343.4 22.0 C 349.7 22.0, 349.7 16.0, 356.0 16.0" fill="none" stroke="#58a6ff" stroke-width="2" stroke-linecap="round"/>
<g transform="translate(20, 136)">
<text x="0" y="0" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="700" fill="#d1d9e0">577</text>
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="#7d8895">commits over 6mo</text>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.7 KiB

+71
View File
@@ -0,0 +1,71 @@
<svg xmlns="http://www.w3.org/2000/svg" width="380" height="164" viewBox="0 0 380 164" fill="none">
<defs>
<filter id="shadow" 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="avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="162" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">LANGUAGES</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<circle cx="60" cy="64.0" r="44" fill="none" stroke="#3572A5" stroke-width="16"
stroke-dasharray="126.1 150.4" stroke-dashoffset="0.0"
transform="rotate(-90 60 64.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="276.5" to="0.0" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="64.0" r="44" fill="none" stroke="#3178c6" stroke-width="16"
stroke-dasharray="70.8 205.7" stroke-dashoffset="-126.1"
transform="rotate(-90 60 64.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="150.4" to="-126.1" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="64.0" r="44" fill="none" stroke="#00ADD8" stroke-width="16"
stroke-dasharray="46.2 230.3" stroke-dashoffset="-196.8"
transform="rotate(-90 60 64.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="79.6" to="-196.8" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="64.0" r="44" fill="none" stroke="#dea584" stroke-width="16"
stroke-dasharray="33.7 242.7" stroke-dashoffset="-243.0"
transform="rotate(-90 60 64.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="33.5" to="-243.0" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="64.0" r="28" fill="#1a2230"/>
<text x="60" y="65.0" text-anchor="middle" dominant-baseline="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" font-weight="700" fill="#d1d9e0">Python</text>
<g transform="translate(140, 20)">
<rect width="10" height="10" rx="2" fill="#3572A5"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">Python</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="#7d8895">46%</text>
</g>
<g transform="translate(140, 42)">
<rect width="10" height="10" rx="2" fill="#3178c6"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">TypeScript</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="#7d8895">26%</text>
</g>
<g transform="translate(140, 64)">
<rect width="10" height="10" rx="2" fill="#00ADD8"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">Go</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="#7d8895">17%</text>
</g>
<g transform="translate(140, 86)">
<rect width="10" height="10" rx="2" fill="#dea584"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">Rust</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="#7d8895">12%</text>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.2 KiB

+95
View File
@@ -0,0 +1,95 @@
<svg xmlns="http://www.w3.org/2000/svg" width="380" height="208" viewBox="0 0 380 208" fill="none">
<defs>
<filter id="shadow" 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="avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="206" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">LANGUAGES</text>
<g transform="translate(0, 36)">
<g transform="translate(16, 0)">
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3572A5" stroke-width="16"
stroke-dasharray="113.3 163.1" stroke-dashoffset="0.0"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="276.5" to="0.0" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#3178c6" stroke-width="16"
stroke-dasharray="63.6 212.9" stroke-dashoffset="-113.3"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="163.1" to="-113.3" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#00ADD8" stroke-width="16"
stroke-dasharray="41.5 235.0" stroke-dashoffset="-176.9"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="99.5" to="-176.9" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#dea584" stroke-width="16"
stroke-dasharray="30.4 246.0" stroke-dashoffset="-218.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="58.1" to="-218.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#89e051" stroke-width="16"
stroke-dasharray="16.6 259.9" stroke-dashoffset="-248.8"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="27.6" to="-248.8" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="44" fill="none" stroke="#7d8895" stroke-width="16"
stroke-dasharray="11.1 265.4" stroke-dashoffset="-265.4"
transform="rotate(-90 60 86.0)" opacity="0.85">
<animate attributeName="stroke-dashoffset" from="11.1" to="-265.4" dur="0.8s" fill="freeze"/>
</circle>
<circle cx="60" cy="86.0" r="28" fill="#1a2230"/>
<text x="60" y="87.0" text-anchor="middle" dominant-baseline="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" font-weight="700" fill="#d1d9e0">Python</text>
<g transform="translate(140, 20)">
<rect width="10" height="10" rx="2" fill="#3572A5"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">Python</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="#7d8895">41%</text>
</g>
<g transform="translate(140, 42)">
<rect width="10" height="10" rx="2" fill="#3178c6"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">TypeScript</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="#7d8895">23%</text>
</g>
<g transform="translate(140, 64)">
<rect width="10" height="10" rx="2" fill="#00ADD8"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">Go</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="#7d8895">15%</text>
</g>
<g transform="translate(140, 86)">
<rect width="10" height="10" rx="2" fill="#dea584"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">Rust</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="#7d8895">11%</text>
</g>
<g transform="translate(140, 108)">
<rect width="10" height="10" rx="2" fill="#89e051"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">Shell</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="#7d8895">6%</text>
</g>
<g transform="translate(140, 130)">
<rect width="10" height="10" rx="2" fill="#7d8895"/>
<text x="16" y="9" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="12" fill="#d1d9e0">Other</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="#7d8895">4%</text>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 5.8 KiB

+43
View File
@@ -0,0 +1,43 @@
<svg xmlns="http://www.w3.org/2000/svg" width="380" height="170" viewBox="0 0 380 170" fill="none">
<defs>
<filter id="shadow" 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="avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="168" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">STREAKS</text>
<g transform="translate(0, 36)">
<text x="105" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#7d8895">CURRENT</text>
<text x="105" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#3fb950">23</text>
<text x="275" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#7d8895">LONGEST</text>
<text x="275" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#d1d9e0">61</text>
<line x1="190" y1="10" x2="190" y2="76"
stroke="#2a3444" stroke-width="1"/>
<rect x="50" y="92" width="280" height="5" rx="2.5" fill="#1e2836"/>
<rect x="50" y="92" width="105.57" height="5" rx="2.5" fill="#3fb950"/>
<circle cx="155.57" cy="94.5" r="3.5" fill="#3fb950"/>
<text x="50" y="116"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">Mar 30 – Today</text>
<text x="330" y="116" text-anchor="end"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">Sep 13 – Nov 12, 2025</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

+43
View File
@@ -0,0 +1,43 @@
<svg xmlns="http://www.w3.org/2000/svg" width="380" height="170" viewBox="0 0 380 170" fill="none">
<defs>
<filter id="shadow" 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="avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
</defs>
<rect x="1" y="1" width="378" height="168" rx="10" ry="10"
fill="#1a2230" stroke="#2a3444" stroke-width="1" filter="url(#shadow)"/>
<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="#7d8895" letter-spacing="0.8" opacity="0.7">STREAKS</text>
<g transform="translate(0, 36)">
<text x="105" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#7d8895">CURRENT</text>
<text x="105" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#58a6ff">23</text>
<text x="275" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="#7d8895">LONGEST</text>
<text x="275" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="#d1d9e0">61</text>
<line x1="190" y1="10" x2="190" y2="76"
stroke="#2a3444" stroke-width="1"/>
<rect x="50" y="92" width="280" height="5" rx="2.5" fill="#1e2836"/>
<rect x="50" y="92" width="105.57" height="5" rx="2.5" fill="#58a6ff"/>
<circle cx="155.57" cy="94.5" r="3.5" fill="#58a6ff"/>
<text x="50" y="116"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">Mar 30 – Today</text>
<text x="330" y="116" text-anchor="end"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="#7d8895">Sep 13 – Nov 12, 2025</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

+16 -2
View File
@@ -8,6 +8,8 @@ services:
environment: environment:
GITHUB_PAT: ${GITHUB_PAT:?missing GITHUB_PAT} GITHUB_PAT: ${GITHUB_PAT:?missing GITHUB_PAT}
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN} FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
GENERATOR_URL: http://generator:5002
COLLABORATOR_TOP_REPOS: "15"
volumes: volumes:
- ${HOME}/ghstats/data/fetcher:/app/data - ${HOME}/ghstats/data/fetcher:/app/data
ports: ports:
@@ -21,6 +23,7 @@ services:
environment: environment:
GITHUB_PAT: ${GITHUB_PAT:?missing GITHUB_PAT} GITHUB_PAT: ${GITHUB_PAT:?missing GITHUB_PAT}
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN} FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
COLLABORATOR_TOP_REPOS: "15"
volumes: volumes:
- ${HOME}/ghstats/data/fetcher:/app/data - ${HOME}/ghstats/data/fetcher:/app/data
depends_on: depends_on:
@@ -37,10 +40,18 @@ services:
GH_OAUTH_CLIENT_SECRET: ${GH_OAUTH_CLIENT_SECRET:?missing GH_OAUTH_CLIENT_SECRET} GH_OAUTH_CLIENT_SECRET: ${GH_OAUTH_CLIENT_SECRET:?missing GH_OAUTH_CLIENT_SECRET}
GENERATOR_SECRET_KEY: ${GENERATOR_SECRET_KEY:?missing GENERATOR_SECRET_KEY} GENERATOR_SECRET_KEY: ${GENERATOR_SECRET_KEY:?missing GENERATOR_SECRET_KEY}
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://gh-stats.com} ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://gh-stats.com}
BUILD_VERSION: ${IMAGE_TAG:-}
DEV_DASHBOARD_USER: ${DEV_DASHBOARD_USER:?missing DEV_DASHBOARD_USER}
DEV_DASHBOARD_PASSWORD: ${DEV_DASHBOARD_PASSWORD:?missing DEV_DASHBOARD_PASSWORD}
ENROLLMENT_HOURLY_CAP: "120"
ENROLLMENT_DAILY_CAP: "1500"
# Fallback while Caddy sends every visitor as 127.0.0.1 (one shared
# bucket). Remove once Caddy forwards Cf-Connecting-Ip as X-Forwarded-For.
RATE_LIMIT_READ_MAX: "30000"
volumes: volumes:
- ${HOME}/ghstats/data/generator:/app/data - ${HOME}/ghstats/data/generator:/app/data
ports: ports:
- "5002:5002" - "127.0.0.1:5002:5002"
depends_on: depends_on:
- fetcher - fetcher
@@ -52,6 +63,7 @@ services:
environment: environment:
FETCHER_URL: http://fetcher:5001 FETCHER_URL: http://fetcher:5001
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN} FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
BUILD_VERSION: ${IMAGE_TAG:-}
volumes: volumes:
- ${HOME}/ghstats/data/generator:/app/data - ${HOME}/ghstats/data/generator:/app/data
depends_on: depends_on:
@@ -65,6 +77,7 @@ services:
environment: environment:
FETCHER_URL: http://fetcher:5001 FETCHER_URL: http://fetcher:5001
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN} FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
BUILD_VERSION: ${IMAGE_TAG:-}
volumes: volumes:
- ${HOME}/ghstats/data/generator:/app/data - ${HOME}/ghstats/data/generator:/app/data
depends_on: depends_on:
@@ -76,7 +89,8 @@ services:
restart: unless-stopped restart: unless-stopped
environment: environment:
GENERATOR_URL: http://generator:5002 GENERATOR_URL: http://generator:5002
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
ports: ports:
- "5003:5003" - "127.0.0.1:5003:5003"
depends_on: depends_on:
- generator - generator
+4
View File
@@ -9,5 +9,9 @@ cd "$(dirname "$0")"
mkdir -p "$HOME/ghstats/data/fetcher" "$HOME/ghstats/data/generator" mkdir -p "$HOME/ghstats/data/fetcher" "$HOME/ghstats/data/generator"
docker compose pull docker compose pull
# Keep fetcher-cron stopped across a deploy if an operator stopped it (e.g.
# during a sign-up spike); otherwise the recreated container runs at once.
cron_was_stopped=$(docker inspect -f '{{.State.Status}}' ghstats-fetcher-cron 2>/dev/null | grep -qx exited && echo 1 || true)
docker compose up -d --remove-orphans docker compose up -d --remove-orphans
if [ -n "$cron_was_stopped" ]; then docker stop ghstats-fetcher-cron; fi
docker compose ps docker compose ps
+72
View File
@@ -0,0 +1,72 @@
# Self-hosting gh-stats.
#
# Runs the same three services and the same published images that gh-stats.com
# runs. Everything is optional except GITHUB_PAT and FETCHER_INTERNAL_TOKEN.
#
# cp .env.example .env # then put your PAT in it
# docker compose up -d --build
# open http://localhost:5002
#
# The production deploy uses deploy/compose.yml instead; this file is the
# stripped-down version for running it on your own box.
name: ghstats
x-fetcher-env: &fetcher-env
GITHUB_PAT: ${GITHUB_PAT:?set GITHUB_PAT in .env - see .env.example}
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?set FETCHER_INTERNAL_TOKEN in .env - any random string}
services:
fetcher:
build: ./fetcher
image: ghstats-fetcher:local
restart: unless-stopped
environment:
<<: *fetcher-env
GENERATOR_URL: http://generator:5002
volumes:
- ./data/fetcher:/app/data
fetcher-cron:
build: ./fetcher
image: ghstats-fetcher:local
restart: unless-stopped
command: ["python", "-m", "src.cron"]
environment: *fetcher-env
volumes:
- ./data/fetcher:/app/data
depends_on: [fetcher]
generator:
build: ./generator
image: ghstats-generator:local
restart: unless-stopped
environment: &generator-env
FETCHER_URL: http://fetcher:5001
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?set FETCHER_INTERNAL_TOKEN in .env - any random string}
volumes:
- ./data/generator:/app/data
ports:
- "${GHSTATS_PORT:-5002}:5002"
depends_on: [fetcher]
generator-worker:
build: ./generator
image: ghstats-generator:local
restart: unless-stopped
command: ["python", "-m", "src.worker"]
environment: *generator-env
volumes:
- ./data/generator:/app/data
depends_on: [generator]
edge:
build: ./edge
image: ghstats-edge:local
restart: unless-stopped
environment:
GENERATOR_URL: http://generator:5002
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?set FETCHER_INTERNAL_TOKEN in .env - any random string}
ports:
- "${GHSTATS_EDGE_PORT:-5003}:5003"
depends_on: [generator]
+1
View File
@@ -4,6 +4,7 @@ WORKDIR /app
COPY requirements.txt ./ COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt RUN pip install --no-cache-dir -r requirements.txt
COPY src ./src COPY src ./src
COPY gunicorn.conf.py ./
EXPOSE 5003 EXPOSE 5003
# Bind to $PORT when set (e.g. Cloud Run injects PORT=8080); default to 5003. # Bind to $PORT when set (e.g. Cloud Run injects PORT=8080); default to 5003.
+22
View File
@@ -0,0 +1,22 @@
"""Gunicorn settings: one access line per request on stdout, for Pantheos.
Docker's json-file driver captures stdout and Pantheos ingests it, so each line
becomes a request log and feeds the container's rps / 5xx / p95. Monitoring
traffic (/metrics scrapes, /health checks) is left out so it doesn't drown the
real requests.
"""
from gunicorn import glogging
accesslog = "-"
access_log_format = '"%(r)s" %(s)s %(M)sms'
_QUIET_PATHS = ("/metrics", "/health")
class _Logger(glogging.Logger):
def access(self, resp, req, environ, request_time):
if req.path not in _QUIET_PATHS:
super().access(resp, req, environ, request_time)
logger_class = _Logger
+93
View File
@@ -0,0 +1,93 @@
"""Edge analytics — record + flush + push to generator.
The hot path enqueues; the background thread does the network I/O. If the
generator is unreachable we drop the batch (logging a warning) and let the
queue catch the next tick.
"""
import logging
import threading
import time
from collections import deque
import requests
from . import config
log = logging.getLogger("edge.analytics")
_QUEUE: deque = deque(maxlen=config.ANALYTICS_QUEUE_MAX)
_QUEUE_LOCK = threading.Lock()
_THREAD_LOCK = threading.Lock()
_FLUSH_THREAD: threading.Thread | None = None
_events_dropped: int = 0
_drop_lock = threading.Lock()
def _reset_for_tests() -> None:
global _events_dropped, _FLUSH_THREAD, _QUEUE
with _QUEUE_LOCK:
_QUEUE = deque(maxlen=config.ANALYTICS_QUEUE_MAX)
with _drop_lock:
_events_dropped = 0
_FLUSH_THREAD = None
def record_request(endpoint: str, username: str | None, widget: str | None,
status: int, latency_ms: int, cache_hit: int | None = None) -> None:
ev = {
"ts": int(time.time()),
"service": "edge",
"kind": "request",
"username": username,
"endpoint": endpoint,
"widget": widget,
"status": int(status),
"latency_ms": int(latency_ms),
"cache_hit": cache_hit,
}
global _events_dropped
with _QUEUE_LOCK:
if len(_QUEUE) >= _QUEUE.maxlen:
with _drop_lock:
_events_dropped += 1
return
_QUEUE.append(ev)
def flush_now() -> int:
with _QUEUE_LOCK:
batch = list(_QUEUE)
_QUEUE.clear()
if not batch:
return 0
if not config.ANALYTICS_GENERATOR_URL or not config.ANALYTICS_INTERNAL_TOKEN:
return 0
try:
requests.post(
f"{config.ANALYTICS_GENERATOR_URL}/internal/analytics/events",
headers={"X-Internal-Token": config.ANALYTICS_INTERNAL_TOKEN},
json={"events": batch},
timeout=2,
)
except Exception:
log.warning("analytics flush failed (events lost)", exc_info=True)
return 0
return len(batch)
def _flush_loop():
while True:
time.sleep(config.ANALYTICS_FLUSH_SECONDS)
try:
flush_now()
except Exception:
log.exception("flush loop error")
def start_flush_thread():
global _FLUSH_THREAD
with _THREAD_LOCK:
if _FLUSH_THREAD is not None and _FLUSH_THREAD.is_alive():
return
t = threading.Thread(target=_flush_loop, name="edge-analytics-flush", daemon=True)
t.start()
_FLUSH_THREAD = t
+34 -2
View File
@@ -8,12 +8,17 @@ import requests
from flask import Flask, Response, jsonify, request from flask import Flask, Response, jsonify, request
from flask_compress import Compress from flask_compress import Compress
from . import cache as cache_mod, config from . import analytics, cache as cache_mod, config
app = Flask(__name__) app = Flask(__name__)
# Tolerate stray trailing slashes on every route, matching the generator. A
# hand-copied embed URL like `/alice/` should resolve like `/alice` instead of
# Flask's default strict_slashes 404. Set before the route decorators run.
app.url_map.strict_slashes = False
Compress(app) Compress(app)
cache_ext = cache_mod.build_cache(app) cache_ext = cache_mod.build_cache(app)
log = logging.getLogger("edge") log = logging.getLogger("edge")
analytics.start_flush_thread()
# GitHub usernames: 1-39 chars, alnum, single hyphens. Keep the regex in # GitHub usernames: 1-39 chars, alnum, single hyphens. Keep the regex in
# sync with generator/src/utils/validate.py so invalid paths get rejected # sync with generator/src/utils/validate.py so invalid paths get rejected
@@ -85,6 +90,9 @@ def health():
def serve(username: str): def serve(username: str):
if not _valid_username(username): if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400 return jsonify({"error": "invalid_username"}), 400
# GitHub usernames are case-insensitive; canonicalize to lowercase so the
# cache key and the upstream path don't fragment by case.
username = username.lower()
return _serve(username, path=username) return _serve(username, path=username)
@@ -94,10 +102,12 @@ def serve_widget(username: str, widget: str):
return jsonify({"error": "invalid_username"}), 400 return jsonify({"error": "invalid_username"}), 400
if widget not in _ALLOWED_WIDGETS: if widget not in _ALLOWED_WIDGETS:
return jsonify({"error": "unknown_widget"}), 400 return jsonify({"error": "unknown_widget"}), 400
username = username.lower()
return _serve(f"{username}/{widget}", path=f"{username}/{widget}.svg") return _serve(f"{username}/{widget}", path=f"{username}/{widget}.svg")
def _serve(key_suffix: str, path: str) -> Response: def _serve(key_suffix: str, path: str) -> Response:
t0 = time.monotonic()
ip = _client_ip() ip = _client_ip()
if not _allow(ip): if not _allow(ip):
return jsonify({"error": "rate_limited"}), 429 return jsonify({"error": "rate_limited"}), 429
@@ -106,19 +116,23 @@ def _serve(key_suffix: str, path: str) -> Response:
cached = cache_ext.get(ck) cached = cache_ext.get(ck)
if cached is not None: if cached is not None:
body, content_type = cached body, content_type = cached
return Response(body, mimetype=content_type, headers={ resp = Response(body, mimetype=content_type, headers={
"X-Widget-Status": "ready", "X-Widget-Status": "ready",
"X-Cache": "HIT", "X-Cache": "HIT",
"Cache-Control": "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400", "Cache-Control": "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400",
}) })
_record(path, key_suffix, 200, t0, cache_hit=1)
return resp
try: try:
r = _fetch_origin(path, ip) r = _fetch_origin(path, ip)
except Exception as e: except Exception as e:
log.warning("origin unreachable for %s: %s", path, e) log.warning("origin unreachable for %s: %s", path, e)
_record(path, key_suffix, 503, t0, cache_hit=0)
return jsonify({"error": "origin unreachable"}), 503 return jsonify({"error": "origin unreachable"}), 503
if r.status_code >= 500: if r.status_code >= 500:
_record(path, key_suffix, 503, t0, cache_hit=0)
return jsonify({"error": "origin error"}), 503 return jsonify({"error": "origin error"}), 503
status = r.headers.get("X-Widget-Status", "ready") status = r.headers.get("X-Widget-Status", "ready")
@@ -129,6 +143,7 @@ def _serve(key_suffix: str, path: str) -> Response:
else: else:
cc = "no-store" cc = "no-store"
_record(path, key_suffix, r.status_code, t0, cache_hit=0)
return Response(r.content, status=r.status_code, mimetype=content_type, headers={ return Response(r.content, status=r.status_code, mimetype=content_type, headers={
"X-Widget-Status": status, "X-Widget-Status": status,
"X-Cache": "MISS", "X-Cache": "MISS",
@@ -136,6 +151,23 @@ def _serve(key_suffix: str, path: str) -> Response:
}) })
def _record(path: str, key_suffix: str, status: int, t0: float, cache_hit: int) -> None:
"""Normalize the edge URL into (endpoint_template, username, widget)
so the dashboard can group across users without exploding cardinality."""
if "/" in key_suffix:
username, widget = key_suffix.split("/", 1)
endpoint = "/<u>/<widget>.svg"
else:
username = key_suffix
widget = "composite"
endpoint = "/<u>"
analytics.record_request(
endpoint=endpoint, username=username, widget=widget,
status=status, latency_ms=int((time.monotonic() - t0) * 1000),
cache_hit=cache_hit,
)
def main(): def main():
app.run(host="0.0.0.0", port=config.PORT) app.run(host="0.0.0.0", port=config.PORT)
+5
View File
@@ -14,3 +14,8 @@ UPSTREAM_TIMEOUT = int(os.getenv("EDGE_UPSTREAM_TIMEOUT", "10"))
# default; tighten via env if a specific IP misbehaves. # default; tighten via env if a specific IP misbehaves.
RATE_LIMIT_MAX = int(os.getenv("EDGE_RATE_LIMIT_MAX", "3000")) RATE_LIMIT_MAX = int(os.getenv("EDGE_RATE_LIMIT_MAX", "3000"))
RATE_LIMIT_WINDOW = int(os.getenv("EDGE_RATE_LIMIT_WINDOW", "60")) RATE_LIMIT_WINDOW = int(os.getenv("EDGE_RATE_LIMIT_WINDOW", "60"))
ANALYTICS_GENERATOR_URL = os.getenv("ANALYTICS_GENERATOR_URL", os.getenv("GENERATOR_URL", "http://localhost:5002"))
ANALYTICS_INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
ANALYTICS_FLUSH_SECONDS = int(os.getenv("ANALYTICS_FLUSH_SECONDS", "5"))
ANALYTICS_QUEUE_MAX = int(os.getenv("ANALYTICS_QUEUE_MAX", "2000"))
+46
View File
@@ -0,0 +1,46 @@
import responses
from src import analytics as a
from src import config as cfg
def test_record_request_enqueues():
a._reset_for_tests()
a.record_request("/<u>", "alice", "composite", 200, 12, cache_hit=1)
assert len(a._QUEUE) == 1
e = a._QUEUE[0]
assert e["service"] == "edge"
assert e["username"] == "alice"
assert e["latency_ms"] == 12
@responses.activate
def test_flush_posts_batch(monkeypatch):
monkeypatch.setattr(cfg, "ANALYTICS_GENERATOR_URL", "http://gen:5002")
monkeypatch.setattr(cfg, "ANALYTICS_INTERNAL_TOKEN", "secret")
a._reset_for_tests()
responses.add(responses.POST, "http://gen:5002/internal/analytics/events",
json={"ingested": 2}, status=200)
a.record_request("/<u>", "alice", "composite", 200, 12, cache_hit=1)
a.record_request("/<u>", "bob", "composite", 200, 8, cache_hit=0)
a.flush_now()
assert len(responses.calls) == 1
import json
body = json.loads(responses.calls[0].request.body)
assert len(body["events"]) == 2
def test_instrument_wraps_serve_and_records(monkeypatch):
monkeypatch.setattr(cfg, "ANALYTICS_INTERNAL_TOKEN", "secret")
a._reset_for_tests()
from src import api as apimod
with apimod.app.test_client() as c:
class FakeResp:
status_code = 200
content = b"<svg/>"
headers = {"X-Widget-Status": "ready", "Content-Type": "image/svg+xml"}
monkeypatch.setattr(apimod, "_fetch_origin", lambda *a, **k: FakeResp())
apimod.cache_ext.clear()
c.get("/alice")
assert len(a._QUEUE) == 1
assert a._QUEUE[0]["username"] == "alice"
assert a._QUEUE[0]["endpoint"] == "/<u>"
+11
View File
@@ -44,6 +44,17 @@ def test_origin_error_returns_503(client):
assert r.status_code == 503 assert r.status_code == 503
@responses.activate
def test_trailing_slash_tolerated(client):
"""A hand-copied `/alice/` must resolve like `/alice`, not 404."""
responses.add(responses.GET, "http://gen:5002/api/alice",
body=b"<svg>ready</svg>", status=200,
headers={"X-Widget-Status": "ready", "Content-Type": "image/svg+xml"})
r = client.get("/alice/")
assert r.status_code == 200
assert r.data == b"<svg>ready</svg>"
def test_health(client): def test_health(client):
r = client.get("/health") r = client.get("/health")
assert r.status_code == 200 assert r.status_code == 200
+1
View File
@@ -5,6 +5,7 @@ COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt RUN pip install --no-cache-dir -r requirements.txt
COPY src ./src COPY src ./src
COPY gunicorn.conf.py ./
RUN mkdir -p /app/data RUN mkdir -p /app/data
EXPOSE 5001 EXPOSE 5001
+22
View File
@@ -0,0 +1,22 @@
"""Gunicorn settings: one access line per request on stdout, for Pantheos.
Docker's json-file driver captures stdout and Pantheos ingests it, so each line
becomes a request log and feeds the container's rps / 5xx / p95. Monitoring
traffic (/metrics scrapes, /health checks) is left out so it doesn't drown the
real requests.
"""
from gunicorn import glogging
accesslog = "-"
access_log_format = '"%(r)s" %(s)s %(M)sms'
_QUIET_PATHS = ("/metrics", "/health")
class _Logger(glogging.Logger):
def access(self, resp, req, environ, request_time):
if req.path not in _QUIET_PATHS:
super().access(resp, req, environ, request_time)
logger_class = _Logger
+91
View File
@@ -0,0 +1,91 @@
"""Fetcher analytics — record fetch latency + push batches to the generator.
The hot path enqueues; a daemon thread flushes batches over the internal
Docker network. On push failure we drop the batch and keep going.
"""
import logging
import threading
import time
from collections import deque
import requests
from . import config
log = logging.getLogger("fetcher.analytics")
_QUEUE: deque = deque(maxlen=config.ANALYTICS_QUEUE_MAX)
_QUEUE_LOCK = threading.Lock()
_THREAD_LOCK = threading.Lock()
_FLUSH_THREAD: threading.Thread | None = None
_events_dropped: int = 0
_drop_lock = threading.Lock()
def _reset_for_tests() -> None:
global _events_dropped, _FLUSH_THREAD, _QUEUE
with _QUEUE_LOCK:
_QUEUE = deque(maxlen=config.ANALYTICS_QUEUE_MAX)
with _drop_lock:
_events_dropped = 0
_FLUSH_THREAD = None
def record_fetch(username: str, status: int, latency_ms: int) -> None:
ev = {
"ts": int(time.time()),
"service": "fetcher",
"kind": "fetch",
"username": username,
"endpoint": "github/users/<u>",
"widget": None,
"status": int(status),
"latency_ms": int(latency_ms),
"cache_hit": None,
}
global _events_dropped
with _QUEUE_LOCK:
if len(_QUEUE) >= _QUEUE.maxlen:
with _drop_lock:
_events_dropped += 1
return
_QUEUE.append(ev)
def flush_now() -> int:
with _QUEUE_LOCK:
batch = list(_QUEUE)
_QUEUE.clear()
if not batch:
return 0
if not config.GENERATOR_URL or not config.INTERNAL_TOKEN:
return 0
try:
requests.post(
f"{config.GENERATOR_URL}/internal/analytics/events",
headers={"X-Internal-Token": config.INTERNAL_TOKEN},
json={"events": batch},
timeout=2,
)
except Exception:
log.warning("analytics flush failed (events lost)", exc_info=True)
return 0
return len(batch)
def _flush_loop():
while True:
time.sleep(config.ANALYTICS_FLUSH_SECONDS)
try:
flush_now()
except Exception:
log.exception("flush loop error")
def start_flush_thread():
global _FLUSH_THREAD
with _THREAD_LOCK:
if _FLUSH_THREAD is not None and _FLUSH_THREAD.is_alive():
return
t = threading.Thread(target=_flush_loop, name="fetcher-analytics-flush", daemon=True)
t.start()
_FLUSH_THREAD = t
+170 -3
View File
@@ -1,16 +1,44 @@
"""Flask app for the fetcher service. All endpoints require X-Internal-Token.""" """Flask app for the fetcher service. All endpoints require X-Internal-Token."""
import fcntl
import hmac import hmac
import logging import logging
import os
import re import re
import threading
import time
import requests import requests
import tempfile
from concurrent.futures import ThreadPoolExecutor
from flask import Flask, jsonify, request, Response from flask import Flask, jsonify, request, Response
from functools import wraps from functools import wraps
from . import config, db, github from . import analytics, config, db, github
app = Flask(__name__) app = Flask(__name__)
log = logging.getLogger("fetcher.api") log = logging.getLogger("fetcher.api")
analytics.start_flush_thread()
# Background pool for /fetch-async. The fetch routinely takes 10-20s of
# wall clock even after parallelization, which is too long to hold an HTTP
# request open from the generator (it would block the worker on its hot
# path). Submitting to this pool lets us return 202 immediately and call
# the generator back when the fetch finishes.
_BG_POOL = ThreadPoolExecutor(
max_workers=max(1, config.ASYNC_FETCH_WORKERS),
thread_name_prefix="fetch-bg",
)
# Per-process in-flight set. If two callers ask us to fetch the same user
# while the first fetch is still running, we ack the second one without
# starting a duplicate GitHub call. Per-process only — fine for v1's single
# fetcher container; a multi-replica deploy would need a distributed lock.
_INFLIGHT: set[str] = set()
_INFLIGHT_LOCK = threading.Lock()
# /data misses for the same user (worker build, ad hoc renders, cron) used to
# each run a full GitHub fetch. gunicorn runs sync worker processes, so the
# lock is a per-username file lock that all workers in the container share.
_MISS_LOCK_DIR = tempfile.gettempdir()
# Must stay in sync with github.py's _USERNAME_RE. Trust boundary: the # Must stay in sync with github.py's _USERNAME_RE. Trust boundary: the
# fetcher is called only by the generator over the internal network, but # fetcher is called only by the generator over the internal network, but
# a compromised/bugged generator must not be able to turn us into an # a compromised/bugged generator must not be able to turn us into an
@@ -37,21 +65,57 @@ def health():
return jsonify({"status": "ok", "service": "fetcher", "users": len(db.list_usernames())}) return jsonify({"status": "ok", "service": "fetcher", "users": len(db.list_usernames())})
@app.route("/metrics", methods=["GET"])
def metrics():
"""Prometheus-format fetch-outcome counters for the monitoring stack.
Deliberately unauthenticated (the rest of the API requires the internal
token): it exposes only aggregate counts — no usernames, no payloads — and
the scraper (vmagent) can't send our internal header. The counts are read
from fetcher.db, so they include the cron container's fetches too."""
counts = db.read_fetch_metrics()
lines = [
"# HELP ghstats_fetch_total GitHub fetch outcomes by result.",
"# TYPE ghstats_fetch_total counter",
]
for outcome, n in counts.items():
lines.append(f'ghstats_fetch_total{{outcome="{outcome}"}} {n}')
return Response("\n".join(lines) + "\n", mimetype="text/plain; version=0.0.4")
@app.route("/data/<username>", methods=["GET"]) @app.route("/data/<username>", methods=["GET"])
@require_internal_token @require_internal_token
def get_data(username: str): def get_data(username: str):
if not _valid_username(username): if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400 return jsonify({"error": "invalid_username"}), 400
if db.get_user(username) is None:
path = os.path.join(_MISS_LOCK_DIR, f"ghstats-miss-{username.lower()}.lock")
with open(path, "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
return _get_data(username)
return _get_data(username)
def _get_data(username: str):
row = db.get_user(username) row = db.get_user(username)
if row is None: if row is None:
# Auto-fetch path # Auto-fetch path
t0 = time.monotonic()
try: try:
data = github.fetch_github_data(username, token=config.GITHUB_PAT) data = github.fetch_github_data(username, token=config.GITHUB_PAT)
except github.GitHubTransientError as e:
analytics.record_fetch(username, 503, int((time.monotonic() - t0) * 1000))
log.warning("github fetch rate-limited for %s: %s", username, e)
return jsonify({"error": "github_rate_limited"}), 503
except Exception: except Exception:
analytics.record_fetch(username, 502, int((time.monotonic() - t0) * 1000))
log.exception("github fetch failed for %s", username) log.exception("github fetch failed for %s", username)
return jsonify({"error": "fetch_failed"}), 502 return jsonify({"error": "fetch_failed"}), 502
if _is_github_not_found(data): if _is_github_not_found(data):
data = {"error": "not_found"} data = {"error": "not_found"}
analytics.record_fetch(username, 404, int((time.monotonic() - t0) * 1000))
else:
analytics.record_fetch(username, 200, int((time.monotonic() - t0) * 1000))
h = db.upsert_user(username, data) h = db.upsert_user(username, data)
return jsonify({"data": data, "payload_hash": h, "fetched": True}) return jsonify({"data": data, "payload_hash": h, "fetched": True})
return jsonify({ return jsonify({
@@ -69,21 +133,106 @@ def force_fetch():
username = body.get("username") username = body.get("username")
if not _valid_username(username): if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400 return jsonify({"error": "invalid_username"}), 400
t0 = time.monotonic()
try: try:
data = github.fetch_github_data(username, token=config.GITHUB_PAT) data = github.fetch_github_data(username, token=config.GITHUB_PAT)
except Exception: except Exception as e:
# Previously returned f"fetch failed: {e}" which leaks internal # Previously returned f"fetch failed: {e}" which leaks internal
# exception text (URLs, stack fragments) across the trust boundary. # exception text (URLs, stack fragments) across the trust boundary.
log.exception("github fetch failed for %s", username) analytics.record_fetch(username, 502, int((time.monotonic() - t0) * 1000))
_record_fetch_failure(username, e)
return jsonify({"error": "fetch_failed"}), 502 return jsonify({"error": "fetch_failed"}), 502
if _is_github_not_found(data): if _is_github_not_found(data):
data = {"error": "not_found"} data = {"error": "not_found"}
analytics.record_fetch(username, 404, int((time.monotonic() - t0) * 1000))
db.bump_fetch_metric("not_found")
else:
analytics.record_fetch(username, 200, int((time.monotonic() - t0) * 1000))
db.bump_fetch_metric("ok")
old = db.get_user(username) old = db.get_user(username)
old_hash = old["payload_hash"] if old else None old_hash = old["payload_hash"] if old else None
new_hash = db.upsert_user(username, data) new_hash = db.upsert_user(username, data)
return jsonify({"stored": True, "payload_hash": new_hash, "changed": old_hash != new_hash}) return jsonify({"stored": True, "payload_hash": new_hash, "changed": old_hash != new_hash})
def _bg_fetch(username: str) -> None:
"""Background fetch + generator callback. Runs on _BG_POOL.
Always notifies the generator on completion (including not_found and
failure cases) so the generator can decide whether to enqueue a build,
persist a not_found marker, or do nothing. Without the callback the
generator would have to poll, which is exactly the design we're
removing — the worker used to block on the synchronous /data call and
time out on long fetches.
"""
try:
t0 = time.monotonic()
try:
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
if _is_github_not_found(data):
data = {"error": "not_found"}
analytics.record_fetch(username, 404, int((time.monotonic() - t0) * 1000))
db.bump_fetch_metric("not_found")
else:
analytics.record_fetch(username, 200, int((time.monotonic() - t0) * 1000))
db.bump_fetch_metric("ok")
payload_hash = db.upsert_user(username, data)
ok = True
except Exception as e:
analytics.record_fetch(username, 502, int((time.monotonic() - t0) * 1000))
_record_fetch_failure(username, e)
payload_hash = ""
ok = False
_notify_generator_data_ready(username, payload_hash, ok)
finally:
with _INFLIGHT_LOCK:
_INFLIGHT.discard(username)
def _notify_generator_data_ready(username: str, payload_hash: str, ok: bool) -> None:
if not config.GENERATOR_URL or not config.INTERNAL_TOKEN:
return
try:
requests.post(
f"{config.GENERATOR_URL}/internal/data-ready",
headers={"X-Internal-Token": config.INTERNAL_TOKEN},
json={"username": username, "payload_hash": payload_hash, "ok": ok},
timeout=5,
)
except Exception:
log.warning("data-ready callback to generator failed for %s", username, exc_info=True)
@app.route("/fetch-async", methods=["POST"])
@require_internal_token
def fetch_async():
"""Kick off a background GitHub fetch and return immediately.
The generator calls this on enrollment so the user-perceived latency
isn't bounded by GitHub's response time + the generator's HTTP
timeout. When the fetch completes the fetcher posts back to
/internal/data-ready on the generator, which is what enqueues the
build job.
"""
body = request.get_json(silent=True) or {}
username = body.get("username")
if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400
with _INFLIGHT_LOCK:
if username in _INFLIGHT:
return jsonify({"queued": True, "already_inflight": True}), 202
_INFLIGHT.add(username)
try:
_BG_POOL.submit(_bg_fetch, username)
except RuntimeError:
# Pool was shut down (process exiting). Drop the in-flight marker
# so a retry after restart isn't blocked by a stale entry.
with _INFLIGHT_LOCK:
_INFLIGHT.discard(username)
return jsonify({"error": "shutting_down"}), 503
return jsonify({"queued": True}), 202
@app.route("/avatar/<username>", methods=["GET"]) @app.route("/avatar/<username>", methods=["GET"])
@require_internal_token @require_internal_token
def avatar(username: str): def avatar(username: str):
@@ -113,9 +262,27 @@ def _is_github_not_found(data: dict) -> bool:
return True return True
if isinstance(user, dict) and user.get("message") == "Not Found": if isinstance(user, dict) and user.get("message") == "Not Found":
return True return True
# An error body (rate limit, abuse detection, anything else GitHub answers
# with a bare {"message": ...}) carries no login. It is not user data and
# must never be recorded as a successful fetch. github.py raises
# GitHubTransientError before we get here in practice; this is the backstop.
if isinstance(user, dict) and "login" not in user:
return True
return False return False
def _record_fetch_failure(username: str, exc: Exception) -> None:
"""Classify a failed fetch for metrics + logs. A transient failure (rate
limit / 5xx / network) is the signal worth surfacing: it means we aborted
and kept the last-good record instead of persisting zeros."""
if isinstance(exc, github.GitHubTransientError):
db.bump_fetch_metric("rate_limited")
log.warning("github fetch transient failure for %s (kept last-good): %s", username, exc)
else:
db.bump_fetch_metric("error")
log.exception("github fetch failed for %s", username)
def main(): def main():
db.init_db() db.init_db()
app.run(host="0.0.0.0", port=config.PORT) app.run(host="0.0.0.0", port=config.PORT)
+26
View File
@@ -7,8 +7,27 @@ GITHUB_PAT = os.getenv("GITHUB_PAT", "")
INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "") INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
REFRESH_INTERVAL_HOURS = int(os.getenv("FETCHER_REFRESH_INTERVAL_HOURS", "24")) REFRESH_INTERVAL_HOURS = int(os.getenv("FETCHER_REFRESH_INTERVAL_HOURS", "24"))
TRIAL_GC_DAYS = int(os.getenv("FETCHER_TRIAL_GC_DAYS", "7")) TRIAL_GC_DAYS = int(os.getenv("FETCHER_TRIAL_GC_DAYS", "7"))
# The hourly refresh tick stops once the PAT's core budget falls under this
# reserve, so new sign-ups still get fetched, and refreshes at most this many
# users per tick, so a day's worth of sign-ups going stale together is spread
# over several hours. Oldest-fetched users go first; the rest wait a tick.
REFRESH_CORE_RESERVE = int(os.getenv("FETCHER_REFRESH_CORE_RESERVE", "1500"))
REFRESH_MAX_PER_TICK = int(os.getenv("FETCHER_REFRESH_MAX_PER_TICK", "60"))
# GitHub's secondary (burst) limits trip when refreshes run back to back. The
# tick pauses between users; on a rate limit it waits Retry-After (else the
# default, capped) and retries that user once, then stops and defers the rest.
REFRESH_USER_PAUSE = float(os.getenv("FETCHER_REFRESH_USER_PAUSE", "1.5"))
REFRESH_RETRY_SLEEP = int(os.getenv("FETCHER_REFRESH_RETRY_SLEEP", "60"))
REFRESH_RETRY_SLEEP_MAX = int(os.getenv("FETCHER_REFRESH_RETRY_SLEEP_MAX", "120"))
API_TIMEOUT = int(os.getenv("API_TIMEOUT", "15")) API_TIMEOUT = int(os.getenv("API_TIMEOUT", "15"))
# Generator URL is used as a callback target when a /fetch-async background
# task completes. Token-protected via the same FETCHER_INTERNAL_TOKEN that
# secures generator -> fetcher calls. Empty string disables the callback,
# which is fine for tests and one-shot scripts.
GENERATOR_URL = os.getenv("GENERATOR_URL", "http://localhost:5002")
ASYNC_FETCH_WORKERS = int(os.getenv("FETCHER_ASYNC_WORKERS", "2"))
# Collaborator-detection tuning # Collaborator-detection tuning
COLLABORATOR_MAX_REPO_SIZE = int(os.getenv("COLLABORATOR_MAX_REPO_SIZE", "150")) COLLABORATOR_MAX_REPO_SIZE = int(os.getenv("COLLABORATOR_MAX_REPO_SIZE", "150"))
COLLABORATOR_TOP_REPOS = int(os.getenv("COLLABORATOR_TOP_REPOS", "30")) COLLABORATOR_TOP_REPOS = int(os.getenv("COLLABORATOR_TOP_REPOS", "30"))
@@ -23,3 +42,10 @@ DEEP_COLLAB_THRESHOLD = int(os.getenv("DEEP_COLLAB_THRESHOLD", "25"))
# Commit-fetching caps # Commit-fetching caps
COMMIT_MAX_REPOS = int(os.getenv("COMMIT_MAX_REPOS", "10")) COMMIT_MAX_REPOS = int(os.getenv("COMMIT_MAX_REPOS", "10"))
COMMIT_PER_REPO = int(os.getenv("COMMIT_PER_REPO", "30")) COMMIT_PER_REPO = int(os.getenv("COMMIT_PER_REPO", "30"))
# Per-repo language-bytes fetches: one REST call each, so cap them to the
# most recently pushed repos the user owns (forks excluded).
LANGUAGE_MAX_REPOS = int(os.getenv("LANGUAGE_MAX_REPOS", "40"))
ANALYTICS_FLUSH_SECONDS = int(os.getenv("ANALYTICS_FLUSH_SECONDS", "5"))
ANALYTICS_QUEUE_MAX = int(os.getenv("ANALYTICS_QUEUE_MAX", "2000"))
+52 -3
View File
@@ -2,29 +2,78 @@
import logging import logging
import time import time
import requests
from . import config, db, github from . import config, db, github
log = logging.getLogger("fetcher.cron") log = logging.getLogger("fetcher.cron")
def _core_remaining() -> int | None:
"""Core REST calls left on the PAT, or None if unknown. GitHub does not
count /rate_limit calls against the quota."""
if not config.GITHUB_PAT:
return None
try:
r = requests.get("https://api.github.com/rate_limit",
headers={"Authorization": f"Bearer {config.GITHUB_PAT}"},
timeout=config.API_TIMEOUT)
return int(r.json()["resources"]["core"]["remaining"])
except Exception:
return None
def _fetch_retrying_once(username: str) -> dict:
"""Fetch a user; on a transient GitHub error wait Retry-After (else the
default, capped) and try once more. A second failure propagates."""
try:
return github.fetch_github_data(username, token=config.GITHUB_PAT)
except github.GitHubTransientError as e:
wait = min(e.retry_after or config.REFRESH_RETRY_SLEEP, config.REFRESH_RETRY_SLEEP_MAX)
log.warning("refresh rate-limited for %s: %s; retrying once in %ss", username, e, wait)
time.sleep(wait)
return github.fetch_github_data(username, token=config.GITHUB_PAT)
def tick(hours: int, active_within_days: int, gc_days: int) -> dict: def tick(hours: int, active_within_days: int, gc_days: int) -> dict:
"""Refresh due users, then GC abandoned ones. Returns counts.""" """Refresh due users, then GC abandoned ones. Returns counts."""
refreshed = 0 refreshed = 0
failed = 0 failed = 0
due = db.users_due_for_refresh(hours=hours, active_within_days=active_within_days) due = db.users_due_for_refresh(hours=hours, active_within_days=active_within_days)
for username in due: deferred = max(len(due) - config.REFRESH_MAX_PER_TICK, 0)
due = due[:config.REFRESH_MAX_PER_TICK]
for i, username in enumerate(due):
if i:
time.sleep(config.REFRESH_USER_PAUSE)
left = _core_remaining()
if left is not None and left < config.REFRESH_CORE_RESERVE:
log.info("core budget %s under reserve %s; deferring %s refreshes",
left, config.REFRESH_CORE_RESERVE, len(due) - i)
deferred += len(due) - i
break
try: try:
data = github.fetch_github_data(username, token=config.GITHUB_PAT) data = _fetch_retrying_once(username)
user = data.get("user") user = data.get("user")
if user is None or (isinstance(user, dict) and user.get("message") == "Not Found"): if user is None or (isinstance(user, dict) and user.get("message") == "Not Found"):
data = {"error": "not_found"} data = {"error": "not_found"}
db.bump_fetch_metric("not_found")
else:
db.bump_fetch_metric("ok")
db.upsert_user(username, data) db.upsert_user(username, data)
refreshed += 1 refreshed += 1
except github.GitHubTransientError as e:
db.bump_fetch_metric("rate_limited")
log.warning("refresh rate-limited for %s (kept last-good): %s; deferring %s refreshes",
username, e, len(due) - i - 1)
failed += 1
deferred += len(due) - i - 1
break
except Exception as e: except Exception as e:
db.bump_fetch_metric("error")
log.warning("refresh failed for %s: %s", username, e) log.warning("refresh failed for %s: %s", username, e)
failed += 1 failed += 1
gc_removed = db.delete_stale(days=gc_days) gc_removed = db.delete_stale(days=gc_days)
return {"refreshed": refreshed, "failed": failed, "gc_removed": gc_removed} return {"refreshed": refreshed, "failed": failed, "deferred": deferred, "gc_removed": gc_removed}
def main(): def main():
+45 -1
View File
@@ -25,8 +25,20 @@ CREATE TABLE IF NOT EXISTS users (
); );
CREATE INDEX IF NOT EXISTS idx_users_fetched_at ON users(fetched_at); CREATE INDEX IF NOT EXISTS idx_users_fetched_at ON users(fetched_at);
CREATE INDEX IF NOT EXISTS idx_users_last_requested_at ON users(last_requested_at); CREATE INDEX IF NOT EXISTS idx_users_last_requested_at ON users(last_requested_at);
-- Monotonic fetch-outcome counters, shared across the web workers and the
-- cron container (both mount the same fetcher.db). Scraped via /metrics so
-- rate limits surface in the monitoring stack instead of dying silently.
CREATE TABLE IF NOT EXISTS fetch_metrics (
outcome TEXT PRIMARY KEY,
count INTEGER NOT NULL DEFAULT 0
);
""" """
# The full label set is emitted even at zero so the counter exists in the
# scrape target from the first request (rate() needs a prior sample to work).
FETCH_OUTCOMES = ("ok", "not_found", "rate_limited", "error")
def _now() -> str: def _now() -> str:
return datetime.utcnow().isoformat(timespec="seconds") + "Z" return datetime.utcnow().isoformat(timespec="seconds") + "Z"
@@ -110,7 +122,7 @@ def users_due_for_refresh(hours: int, active_within_days: int) -> list[str]:
active_after = (datetime.utcnow() - timedelta(days=active_within_days)).isoformat(timespec="seconds") + "Z" active_after = (datetime.utcnow() - timedelta(days=active_within_days)).isoformat(timespec="seconds") + "Z"
with _connect() as c: with _connect() as c:
rows = c.execute( rows = c.execute(
"SELECT username FROM users WHERE fetched_at < ? AND last_requested_at > ?", "SELECT username FROM users WHERE fetched_at < ? AND last_requested_at > ? ORDER BY fetched_at",
(stale_before, active_after), (stale_before, active_after),
).fetchall() ).fetchall()
return [r["username"] for r in rows] return [r["username"] for r in rows]
@@ -119,3 +131,35 @@ def users_due_for_refresh(hours: int, active_within_days: int) -> list[str]:
def list_usernames() -> list[str]: def list_usernames() -> list[str]:
with _connect() as c: with _connect() as c:
return [r["username"] for r in c.execute("SELECT username FROM users ORDER BY username").fetchall()] return [r["username"] for r in c.execute("SELECT username FROM users ORDER BY username").fetchall()]
def bump_fetch_metric(outcome: str, n: int = 1) -> None:
"""Increment the counter for a fetch outcome (one of FETCH_OUTCOMES).
Best-effort telemetry: a metrics write must never break a fetch, so
failures are swallowed."""
if outcome not in FETCH_OUTCOMES:
outcome = "error"
try:
with _connect() as c:
c.execute(
"""INSERT INTO fetch_metrics(outcome, count) VALUES (?, ?)
ON CONFLICT(outcome) DO UPDATE SET count = count + excluded.count""",
(outcome, n),
)
c.commit()
except sqlite3.Error:
pass
def read_fetch_metrics() -> dict:
"""Return {outcome: count} for every outcome in FETCH_OUTCOMES (zero-filled)."""
counts = {o: 0 for o in FETCH_OUTCOMES}
try:
with _connect() as c:
for row in c.execute("SELECT outcome, count FROM fetch_metrics"):
if row["outcome"] in counts:
counts[row["outcome"]] = row["count"]
except sqlite3.Error:
pass
return counts
+177 -63
View File
@@ -36,6 +36,52 @@ def _assert_repo_full_name(name: str) -> str:
return name return name
class GitHubTransientError(Exception):
"""A GitHub call failed transiently (rate limit, 5xx, or a network error)
rather than returning real data.
This MUST NOT be swallowed into a zero/empty count. A contribution count
computed from a rate-limited response is 0, and persisting that 0 silently
overwrites the last good value in fetcher.db — which is exactly how a
traffic spike turns into permanently-wrong "0 commits" cards until the
next successful fetch. Propagate it instead so the caller aborts the fetch
and keeps the previously-cached record."""
def __init__(self, msg="", retry_after=None):
super().__init__(msg)
# Seconds from GitHub's Retry-After header, when it sent one.
self.retry_after = retry_after
def _raise_if_transient(resp) -> None:
"""Raise GitHubTransientError if `resp` looks like a rate limit or server
error. A genuine NOT_FOUND (unknown user) is left alone — that is a real,
persistable "this user has no data" answer, not a transient failure."""
retry_after = resp.headers.get("Retry-After")
retry_after = int(retry_after) if retry_after and retry_after.isdigit() else None
if resp.status_code in (429, 500, 502, 503, 504):
raise GitHubTransientError(f"HTTP {resp.status_code}", retry_after)
# Primary/secondary REST rate limits come back as 403 with the remaining
# budget at 0 (or a "secondary rate limit" message).
if resp.status_code == 403 and resp.headers.get("X-RateLimit-Remaining") == "0":
raise GitHubTransientError("REST rate limit exhausted", retry_after)
if resp.status_code == 403 and "rate limit" in (resp.text or "").lower():
raise GitHubTransientError("REST rate limit exhausted", retry_after)
# GraphQL reports rate limits as HTTP 200 with an `errors` array — the same
# 200 that a valid response uses — so the body has to be inspected.
try:
body = resp.json()
except ValueError:
return
# REST list endpoints (events, repos, contributors) answer with a JSON
# array — only a GraphQL-shaped object can carry an `errors` block.
if not isinstance(body, dict):
return
for err in (body.get("errors") or []):
if err.get("type") in ("RATE_LIMITED", "SERVICE_UNAVAILABLE"):
raise GitHubTransientError(err.get("message") or err.get("type"))
class GitHubDataSource(Protocol): class GitHubDataSource(Protocol):
"""Protocol for GitHub data sources - allows swapping implementations.""" """Protocol for GitHub data sources - allows swapping implementations."""
@@ -130,30 +176,35 @@ class DirectAPISource:
def fetch_user_data(self, username: str) -> dict: def fetch_user_data(self, username: str) -> dict:
"""Fetch user profile data.""" """Fetch user profile data."""
_assert_username(username) _assert_username(username)
return requests.get( resp = requests.get(
f"{self.base}/users/{username}", f"{self.base}/users/{username}",
headers=self.headers, headers=self.headers,
timeout=config.API_TIMEOUT, timeout=config.API_TIMEOUT,
).json() )
_raise_if_transient(resp)
return resp.json()
def fetch_repos(self, username: str) -> list: def fetch_repos(self, username: str) -> list:
"""Fetch user repositories (owned + contributed to).""" """Fetch user repositories (owned + contributed to)."""
_assert_username(username) _assert_username(username)
# Fetch owned repos
owned = requests.get(
f"{self.base}/users/{username}/repos",
headers=self.headers,
params={"per_page": 100, "sort": "pushed", "type": "owner"},
timeout=config.API_TIMEOUT,
).json()
# Fetch all repos (includes collabs, orgs) def _get(repo_type: str):
all_repos = requests.get( resp = requests.get(
f"{self.base}/users/{username}/repos", f"{self.base}/users/{username}/repos",
headers=self.headers, headers=self.headers,
params={"per_page": 100, "sort": "pushed", "type": "all"}, params={"per_page": 100, "sort": "pushed", "type": repo_type},
timeout=config.API_TIMEOUT, timeout=config.API_TIMEOUT,
).json() )
_raise_if_transient(resp)
return resp.json()
# The two REST calls are independent — fire them in parallel so the
# second isn't waiting on the first to come back.
with ThreadPoolExecutor(max_workers=2, thread_name_prefix="fetch-repos") as pool:
fut_owned = pool.submit(_get, "owner")
fut_all = pool.submit(_get, "all")
owned = fut_owned.result()
all_repos = fut_all.result()
# Combine and deduplicate # Combine and deduplicate
repos = owned if isinstance(owned, list) else [] repos = owned if isinstance(owned, list) else []
@@ -175,8 +226,10 @@ class DirectAPISource:
headers=self.headers, headers=self.headers,
params={"per_page": 100}, params={"per_page": 100},
timeout=config.API_TIMEOUT, timeout=config.API_TIMEOUT,
).json() )
return resp if isinstance(resp, list) else [] _raise_if_transient(resp)
events = resp.json()
return events if isinstance(events, list) else []
def fetch_commits(self, username: str, repos: list = None) -> list: def fetch_commits(self, username: str, repos: list = None) -> list:
""" """
@@ -293,6 +346,13 @@ class DirectAPISource:
return self._fetch_commit_count_graphql_range(username, since_date) return self._fetch_commit_count_graphql_range(username, since_date)
else: else:
return self._fetch_commit_count_graphql_alltime(username) return self._fetch_commit_count_graphql_alltime(username)
except GitHubTransientError:
# Rate limit / 5xx: abort the fetch so the caller keeps the last
# good count instead of persisting a spurious 0.
raise
except requests.RequestException as e:
# A network-level failure is transient too.
raise GitHubTransientError(str(e))
except Exception as e: except Exception as e:
print(f" Error fetching contribution count: {e}") print(f" Error fetching contribution count: {e}")
return 0 return 0
@@ -326,6 +386,7 @@ class DirectAPISource:
timeout=config.API_TIMEOUT timeout=config.API_TIMEOUT
) )
_raise_if_transient(resp)
if not resp.ok or 'data' not in resp.json(): if not resp.ok or 'data' not in resp.json():
print(f" GraphQL error: {resp.status_code}") print(f" GraphQL error: {resp.status_code}")
return 0 return 0
@@ -338,8 +399,9 @@ class DirectAPISource:
created_year = int(created_at[:4]) created_year = int(created_at[:4])
current_year = datetime.now().year current_year = datetime.now().year
# Fetch year by year # Fetch year by year, in parallel. Sequentially this was 1 request
total_contributions = 0 # per year of account age (~7-10 calls for typical accounts), each
# ~1s — easily a 10s wall-clock contributor on its own.
print(f" Fetching contributions from {created_year} to {current_year}...") print(f" Fetching contributions from {created_year} to {current_year}...")
year_query = """ year_query = """
query($login: String!, $from: DateTime!, $to: DateTime!) { query($login: String!, $from: DateTime!, $to: DateTime!) {
@@ -350,7 +412,8 @@ class DirectAPISource:
} }
} }
""" """
for year in range(created_year, current_year + 1):
def _fetch_year(year: int) -> tuple[int, int]:
year_resp = requests.post( year_resp = requests.post(
'https://api.github.com/graphql', 'https://api.github.com/graphql',
json={ json={
@@ -364,17 +427,23 @@ class DirectAPISource:
headers=headers, headers=headers,
timeout=config.API_TIMEOUT, timeout=config.API_TIMEOUT,
) )
_raise_if_transient(year_resp)
if year_resp.ok: if not year_resp.ok:
year_data = year_resp.json()
if 'data' in year_data and year_data['data'].get('user'):
year_contributions = year_data['data']['user']['contributionsCollection']['contributionCalendar']['totalContributions']
total_contributions += year_contributions
print(f" {year}: {year_contributions:,} contributions")
else:
print(f" {year}: Error - {year_data}")
else:
print(f" {year}: HTTP {year_resp.status_code}") print(f" {year}: HTTP {year_resp.status_code}")
return year, 0
year_data = year_resp.json()
if 'data' in year_data and year_data['data'].get('user'):
n = year_data['data']['user']['contributionsCollection']['contributionCalendar']['totalContributions']
return year, n
print(f" {year}: Error - {year_data}")
return year, 0
years = list(range(created_year, current_year + 1))
total_contributions = 0
with ThreadPoolExecutor(max_workers=min(10, len(years) or 1)) as pool:
for year, n in sorted(pool.map(_fetch_year, years)):
total_contributions += n
print(f" {year}: {n:,} contributions")
print(f" GraphQL API found {total_contributions:,} contributions (all-time)") print(f" GraphQL API found {total_contributions:,} contributions (all-time)")
return total_contributions return total_contributions
@@ -416,6 +485,7 @@ class DirectAPISource:
timeout=config.API_TIMEOUT, timeout=config.API_TIMEOUT,
) )
_raise_if_transient(resp)
if resp.ok: if resp.ok:
data = resp.json() data = resp.json()
if 'data' in data and data['data'].get('user'): if 'data' in data and data['data'].get('user'):
@@ -446,9 +516,14 @@ class DirectAPISource:
timeout=config.API_TIMEOUT timeout=config.API_TIMEOUT
) )
_raise_if_transient(resp)
if resp.ok: if resp.ok:
data = resp.json() data = resp.json()
return data.get("total_count", 0) return data.get("total_count", 0)
except GitHubTransientError:
raise
except requests.RequestException as e:
raise GitHubTransientError(str(e))
except Exception as e: except Exception as e:
print(f"Warning: Failed to fetch PR count via search API: {e}") print(f"Warning: Failed to fetch PR count via search API: {e}")
@@ -473,6 +548,7 @@ class DirectAPISource:
timeout=config.API_TIMEOUT timeout=config.API_TIMEOUT
) )
_raise_if_transient(resp)
if resp.ok: if resp.ok:
contributors = resp.json() contributors = resp.json()
# Filter by minimum commits # Filter by minimum commits
@@ -480,6 +556,8 @@ class DirectAPISource:
c for c in contributors c for c in contributors
if c.get("contributions", 0) >= min_commits if c.get("contributions", 0) >= min_commits
] ]
except GitHubTransientError:
raise
except Exception as e: except Exception as e:
print(f"Warning: Failed to fetch contributors from {repo_name}: {e}") print(f"Warning: Failed to fetch contributors from {repo_name}: {e}")
@@ -566,9 +644,12 @@ class DirectAPISource:
headers=self.headers, headers=self.headers,
timeout=config.API_TIMEOUT, timeout=config.API_TIMEOUT,
) )
_raise_if_transient(resp)
if resp.ok: if resp.ok:
data = resp.json() data = resp.json()
return data if isinstance(data, dict) else {} return data if isinstance(data, dict) else {}
except GitHubTransientError:
raise
except Exception: except Exception:
pass pass
return {} return {}
@@ -607,40 +688,44 @@ def fetch_github_data(
# Use provided data source or default to direct API # Use provided data source or default to direct API
source = data_source or DirectAPISource(token) source = data_source or DirectAPISource(token)
# Fetch all data through the data source abstraction
user = source.fetch_user_data(username)
repos = source.fetch_repos(username)
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)
# Recent contributions (last 6 months)
six_months_ago = (datetime.now() - timedelta(days=180)).strftime("%Y-%m-%d") six_months_ago = (datetime.now() - timedelta(days=180)).strftime("%Y-%m-%d")
print(" Fetching recent contribution count (last 6 months)...")
recent_commits = source.fetch_commit_count(username, repos, since_date=six_months_ago)
# Fetch PR count # Stage 1: every fetch with no dependencies on another fetch's result
print(" Fetching PR count...") # runs in parallel. Previously these 8 calls ran one at a time, so the
total_prs = source.fetch_pr_count(username) # whole pipeline was wait-time × 8. Each is I/O-bound (a single HTTPS
# request to GitHub or a small GraphQL query), so threading is the
# right primitive. _fetch_collaborators_data internally calls
# fetch_user_commit_repos and ignores the `repos` arg, so it has no
# ordering dependency on fetch_repos — start them together.
with ThreadPoolExecutor(max_workers=10, thread_name_prefix="fetch-stage1") as pool:
fut_user = pool.submit(source.fetch_user_data, username)
fut_repos = pool.submit(source.fetch_repos, username)
fut_events = pool.submit(source.fetch_events, username)
fut_commits = pool.submit(source.fetch_commits, username)
fut_total = pool.submit(source.fetch_commit_count, username, [])
fut_recent = pool.submit(source.fetch_commit_count, username, [], six_months_ago)
fut_prs = pool.submit(source.fetch_pr_count, username)
fut_collab = pool.submit(_fetch_collaborators_data, username, [], source)
# Fetch collaborators from user's active repos user = fut_user.result()
collaborators_data = _fetch_collaborators_data( repos = fut_repos.result()
username, repos, source events = fut_events.result()
) commits = fut_commits.result()
total_commits = fut_total.result()
recent_commits = fut_recent.result()
total_prs = fut_prs.result()
collaborators_data = fut_collab.result()
# Fetch avatar # Stage 2: avatar needs user.avatar_url, languages need the repos list.
# Both run in parallel against each other.
avatar_b64 = "" avatar_b64 = ""
if user.get("avatar_url"): avatar_url = user.get("avatar_url") if isinstance(user, dict) else None
avatar_b64 = source.fetch_avatar(user["avatar_url"]) with ThreadPoolExecutor(max_workers=2, thread_name_prefix="fetch-stage2") as pool:
fut_lang = pool.submit(_enrich_repo_languages, repos, source, username)
fut_avatar = pool.submit(source.fetch_avatar, avatar_url) if avatar_url else None
fut_lang.result()
if fut_avatar is not None:
avatar_b64 = fut_avatar.result()
return { return {
"user": user, "user": user,
@@ -655,13 +740,19 @@ def fetch_github_data(
} }
def _enrich_repo_languages(repos: list, source: GitHubDataSource) -> None: def _enrich_repo_languages(repos: list, source: GitHubDataSource, username: str = "") -> None:
"""Mutates `repos` in-place, attaching `language_bytes: {lang: bytes}` to """Mutates `repos` in-place, attaching `language_bytes: {lang: bytes}` to
each repo. Uses a small thread pool — one REST call per repo is cheap each repo. Uses a small thread pool — one REST call per repo is cheap
individually, but sequentially N repos would block the fetch noticeably.""" individually, but sequentially N repos would block the fetch noticeably."""
if not repos: if not repos:
return return
names = [(i, r["full_name"]) for i, r in enumerate(repos) if r.get("full_name")] names = [(i, r["full_name"]) for i, r in enumerate(repos) if r.get("full_name")]
if username:
owner = username.lower()
names = [(i, fn) for i, fn in names
if not repos[i].get("fork") and fn.split("/")[0].lower() == owner]
names.sort(key=lambda p: repos[p[0]].get("pushed_at") or "", reverse=True)
names = names[:config.LANGUAGE_MAX_REPOS]
print(f" Fetching language byte breakdown for {len(names)} repos...") print(f" Fetching language byte breakdown for {len(names)} repos...")
with ThreadPoolExecutor(max_workers=10) as pool: with ThreadPoolExecutor(max_workers=10) as pool:
futures = {pool.submit(source.fetch_repo_languages, fn): i for i, fn in names} futures = {pool.submit(source.fetch_repo_languages, fn): i for i, fn in names}
@@ -669,6 +760,8 @@ def _enrich_repo_languages(repos: list, source: GitHubDataSource) -> None:
i = futures[fut] i = futures[fut]
try: try:
repos[i]["language_bytes"] = fut.result() or {} repos[i]["language_bytes"] = fut.result() or {}
except GitHubTransientError:
raise
except Exception: except Exception:
repos[i]["language_bytes"] = {} repos[i]["language_bytes"] = {}
@@ -729,14 +822,35 @@ def _fetch_collaborators_data(
qualifying = qualifying[:config.COLLABORATOR_TOP_REPOS] qualifying = qualifying[:config.COLLABORATOR_TOP_REPOS]
print(f" Scoring collaborators across {len(qualifying)} qualifying repos") print(f" Scoring collaborators across {len(qualifying)} qualifying repos")
# Step 3+4: fetch contributors and score # Step 3: fetch contributors for all qualifying repos in parallel.
# The per-repo REST call is ~300-500ms; sequentially this dominated the
# whole fetch (30 repos × ~0.5s ≈ 15s). Fan out with the same pool size
# used for languages — GitHub's secondary rate limit tolerates this fine.
contributors_by_repo: dict[str, list] = {}
with ThreadPoolExecutor(max_workers=10) as pool:
futures = {
pool.submit(source.fetch_repo_contributors, r["full_name"], 1): r["full_name"]
for r in qualifying
}
for fut in as_completed(futures):
full_name = futures[fut]
try:
contributors_by_repo[full_name] = fut.result() or []
except GitHubTransientError:
raise
except Exception as e:
print(f" failed to fetch contributors for {full_name}: {e}")
contributors_by_repo[full_name] = []
# Step 4: score sequentially (cheap, in-memory) preserving the original
# `qualifying` order so deterministic-output tests still pass.
collab_stats: dict = {} collab_stats: dict = {}
for r in qualifying: for r in qualifying:
full_name = r["full_name"] full_name = r["full_name"]
user_commits = r["user_commits"] user_commits = r["user_commits"]
boost = config.OWNER_BOOST if r["is_owner"] else 1.0 boost = config.OWNER_BOOST if r["is_owner"] else 1.0
contributors = source.fetch_repo_contributors(full_name, min_commits=1) contributors = contributors_by_repo.get(full_name, [])
# Drop huge OSS projects # Drop huge OSS projects
if len(contributors) >= config.COLLABORATOR_MAX_REPO_SIZE: if len(contributors) >= config.COLLABORATOR_MAX_REPO_SIZE:
print(f" skipping {full_name}: too many contributors ({len(contributors)})") print(f" skipping {full_name}: too many contributors ({len(contributors)})")
+57
View File
@@ -0,0 +1,57 @@
import os
import tempfile
import pytest
import responses
from src import analytics as a
from src import config as cfg
from src import db as dbmod
from src import api as apimod
@pytest.fixture
def client(monkeypatch):
with tempfile.TemporaryDirectory() as d:
monkeypatch.setattr(dbmod, "DB_PATH", os.path.join(d, "t.db"))
monkeypatch.setattr(apimod.config, "INTERNAL_TOKEN", "secret")
monkeypatch.setattr(apimod.config, "GITHUB_PAT", "ghp_test")
dbmod.init_db()
app = apimod.app
app.config["TESTING"] = True
with app.test_client() as c:
yield c
def test_record_fetch():
a._reset_for_tests()
a.record_fetch("alice", 200, 312)
assert len(a._QUEUE) == 1
e = a._QUEUE[0]
assert e["service"] == "fetcher"
assert e["kind"] == "fetch"
assert e["status"] == 200
assert e["latency_ms"] == 312
assert e["endpoint"] == "github/users/<u>"
@responses.activate
def test_flush_posts(monkeypatch):
monkeypatch.setattr(cfg, "GENERATOR_URL", "http://gen:5002")
monkeypatch.setattr(cfg, "INTERNAL_TOKEN", "secret")
a._reset_for_tests()
responses.add(responses.POST, "http://gen:5002/internal/analytics/events",
json={"ingested": 1}, status=200)
a.record_fetch("alice", 200, 100)
a.flush_now()
assert len(responses.calls) == 1
def test_force_fetch_records_event(monkeypatch, client):
a._reset_for_tests()
monkeypatch.setattr("src.api.github.fetch_github_data",
lambda u, token: {"user": {"login": u}})
r = client.post("/fetch",
headers={"X-Internal-Token": "secret"},
json={"username": "alice"})
assert r.status_code == 200
assert any(e["kind"] == "fetch" and e["username"] == "alice"
for e in a._QUEUE)
+193 -22
View File
@@ -30,33 +30,57 @@ def test_endpoints_require_internal_token(client):
assert r.status_code == 401 assert r.status_code == 401
def test_metrics_endpoint_no_auth_and_prometheus_format(client):
from src import db as dbmod
dbmod.bump_fetch_metric("ok")
dbmod.bump_fetch_metric("rate_limited")
r = client.get("/metrics")
assert r.status_code == 200
body = r.get_data(as_text=True)
assert "# TYPE ghstats_fetch_total counter" in body
assert 'ghstats_fetch_total{outcome="ok"} 1' in body
assert 'ghstats_fetch_total{outcome="rate_limited"} 1' in body
# Every outcome is emitted even at zero so rate() has a baseline sample.
assert 'ghstats_fetch_total{outcome="not_found"} 0' in body
@resp_lib.activate @resp_lib.activate
def test_data_auto_fetches_on_miss(client, monkeypatch): def test_data_auto_fetches_on_miss(client, monkeypatch):
# fetch_commits: contributionCalendar/weeks # The fetcher fires the independent GitHub calls in parallel, so we
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", # can't rely on a fixed FIFO order of `resp_lib.add` calls. Match each
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}}, status=200) # GraphQL call by inspecting the request body and returning the right
# fetch_commit_count (alltime) — first call: get createdAt # response for that query — this mirrors how the real GitHub API
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", # routes by query content rather than insertion order.
json={"data": {"user": {"createdAt": "2020-01-01T00:00:00Z"}}}, status=200) import json as _json
# fetch_commit_count (alltime) — per-year contribution totals (2020–2026, 7 years)
for _ in range(7): def _graphql_callback(request):
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", body = _json.loads(request.body)
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}}, q = body.get("query", "")
status=200) variables = body.get("variables", {})
# fetch_commit_count (recent, last 6 months) if "weeks" in q:
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", data = {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}}, elif "createdAt" in q:
status=200) data = {"user": {"createdAt": "2020-01-01T00:00:00Z"}}
# fetch_user_commit_repos (for collaborators) elif "commitContributionsByRepository" in q:
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", data = {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}
json={"data": {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}}, elif "contributionCalendar" in q and "totalContributions" in q:
status=200) # Both alltime per-year and 6-month range queries land here. Tests
# PR count search # don't care about the exact totals — just that a number comes back.
data = {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}
else:
data = {"user": None}
return (200, {}, _json.dumps({"data": data}))
resp_lib.add_callback(resp_lib.POST, "https://api.github.com/graphql",
callback=_graphql_callback)
resp_lib.add(resp_lib.GET, "https://api.github.com/search/issues", resp_lib.add(resp_lib.GET, "https://api.github.com/search/issues",
json={"total_count": 0, "items": []}, status=200) json={"total_count": 0, "items": []}, status=200)
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice", resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice",
json={"login": "alice", "public_repos": 1, "followers": 0, "avatar_url": "https://avatars.example/a"}, status=200) json={"login": "alice", "public_repos": 1, "followers": 0,
# fetch_repos: two calls (owner + all) "avatar_url": "https://avatars.example/a"},
status=200)
# fetch_repos fires the owner+all calls in parallel; both hit the same URL.
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200) resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200)
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200) resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200)
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/events", json=[], status=200) resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/events", json=[], status=200)
@@ -71,3 +95,150 @@ def test_data_auto_fetches_on_miss(client, monkeypatch):
def test_force_fetch_requires_auth(client): def test_force_fetch_requires_auth(client):
r = client.post("/fetch", json={"username": "alice"}) r = client.post("/fetch", json={"username": "alice"})
assert r.status_code == 401 assert r.status_code == 401
def test_fetch_async_requires_auth(client):
r = client.post("/fetch-async", json={"username": "alice"})
assert r.status_code == 401
def test_fetch_async_rejects_invalid_username(client):
r = client.post("/fetch-async", headers={"X-Internal-Token": "secret"},
json={"username": "../etc/passwd"})
assert r.status_code == 400
def test_fetch_async_runs_in_background_and_calls_back(client, monkeypatch):
"""The async path must (a) return 202 immediately without waiting for
GitHub, and (b) POST back to the generator's /internal/data-ready when
the background fetch completes. Without (a) we'd be back to the old
synchronous-blocking design that timed out the worker; without (b)
nothing would ever enqueue the build job."""
import threading
from src import api as apimod
fetch_done = threading.Event()
callback_calls: list = []
def fake_fetch(username, token=None):
# Block briefly so the test can prove /fetch-async returned before
# this finished.
fetch_done.wait(timeout=2)
return {"user": {"login": username, "avatar_url": "x"}, "repos": []}
def fake_post(url, headers=None, json=None, timeout=None):
callback_calls.append({"url": url, "json": json, "headers": headers})
class _R: status_code = 200
return _R()
monkeypatch.setattr(apimod.github, "fetch_github_data", fake_fetch)
monkeypatch.setattr(apimod.requests, "post", fake_post)
monkeypatch.setattr(apimod.config, "GENERATOR_URL", "http://gen:5002")
r = client.post("/fetch-async", headers={"X-Internal-Token": "secret"},
json={"username": "alice"})
assert r.status_code == 202
assert r.get_json()["queued"] is True
# Let the background fetch finish; wait for the callback.
fetch_done.set()
for _ in range(50):
if callback_calls:
break
threading.Event().wait(0.05)
assert len(callback_calls) == 1
cb = callback_calls[0]
assert cb["url"] == "http://gen:5002/internal/data-ready"
assert cb["json"]["username"] == "alice"
assert cb["json"]["ok"] is True
assert cb["json"]["payload_hash"]
def test_fetch_async_dedupes_inflight(client, monkeypatch):
"""A second /fetch-async call for the same user while the first is
still in flight must not start a second GitHub fetch."""
import threading
from src import api as apimod
started = threading.Event()
release = threading.Event()
fetch_calls = {"n": 0}
def fake_fetch(username, token=None):
fetch_calls["n"] += 1
started.set()
release.wait(timeout=2)
return {"user": {"login": username, "avatar_url": "x"}, "repos": []}
monkeypatch.setattr(apimod.github, "fetch_github_data", fake_fetch)
monkeypatch.setattr(apimod.requests, "post", lambda *a, **kw: type("R", (), {"status_code": 200})())
monkeypatch.setattr(apimod.config, "GENERATOR_URL", "")
r1 = client.post("/fetch-async", headers={"X-Internal-Token": "secret"},
json={"username": "alice"})
assert r1.status_code == 202
assert started.wait(timeout=2)
r2 = client.post("/fetch-async", headers={"X-Internal-Token": "secret"},
json={"username": "alice"})
assert r2.status_code == 202
assert r2.get_json().get("already_inflight") is True
release.set()
# Drain
for _ in range(50):
if fetch_calls["n"] >= 1 and "alice" not in apimod._INFLIGHT:
break
threading.Event().wait(0.05)
assert fetch_calls["n"] == 1
def test_rate_limit_body_is_not_classified_as_valid_user_data():
# A rate-limit body reaching the classifier must never take the success
# branch — that is what overwrote a good record with a blank card.
data = {"user": {"message": "API rate limit exceeded for user ID 123.",
"documentation_url": "https://docs.github.com/"}}
assert apimod._is_github_not_found(data) is True
assert apimod._is_github_not_found({"user": {"login": "alice"}}) is False
assert apimod._is_github_not_found({"user": {"message": "Not Found"}}) is True
assert apimod._is_github_not_found({"user": None}) is True
def test_data_miss_rate_limited_returns_503(client, monkeypatch):
# A spent GitHub quota is transient: the fetcher says so (503), so the
# generator can tell the user the card will build after the reset.
def fake_fetch(*_a, **_kw):
raise apimod.github.GitHubTransientError("REST rate limit exhausted")
monkeypatch.setattr(apimod.github, "fetch_github_data", fake_fetch)
r = client.get("/data/alice", headers={"X-Internal-Token": "secret"})
assert r.status_code == 503
assert r.get_json() == {"error": "github_rate_limited"}
assert dbmod.get_user("alice") is None
def test_concurrent_data_misses_fetch_once(client, monkeypatch):
# Concurrent misses for one user used to each run a full GitHub fetch;
# the per-user lock makes later callers read what the first stored.
import threading, time as _time
calls = []
def fake_fetch(username, **_kw):
calls.append(username)
_time.sleep(0.3)
return {"user": {"login": username}, "repos": [], "events": []}
monkeypatch.setattr(apimod.github, "fetch_github_data", fake_fetch)
monkeypatch.setattr(apimod, "_is_github_not_found", lambda _d: False)
app = apimod.app
codes = []
def hit():
with app.test_client() as c:
codes.append(c.get("/data/alice", headers={"X-Internal-Token": "secret"}).status_code)
threads = [threading.Thread(target=hit) for _ in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
assert codes == [200, 200, 200]
assert calls == ["alice"]
+90
View File
@@ -4,6 +4,7 @@ import pytest
from unittest.mock import patch from unittest.mock import patch
from src import db as dbmod from src import db as dbmod
from src import cron as cronmod from src import cron as cronmod
from src import github as ghmod
@pytest.fixture @pytest.fixture
@@ -14,6 +15,14 @@ def tmp_db(monkeypatch):
yield yield
@pytest.fixture(autouse=True)
def sleeps(monkeypatch):
# The tick pauses between users and before a retry; record, don't wait.
calls = []
monkeypatch.setattr(cronmod.time, "sleep", calls.append)
return calls
def test_refresh_tick_calls_github_for_due_users(tmp_db): def test_refresh_tick_calls_github_for_due_users(tmp_db):
dbmod.upsert_user("alice", {"user": {"login": "alice"}}) dbmod.upsert_user("alice", {"user": {"login": "alice"}})
# Backdate # Backdate
@@ -26,6 +35,22 @@ def test_refresh_tick_calls_github_for_due_users(tmp_db):
assert stats["refreshed"] == 1 assert stats["refreshed"] == 1
def test_refresh_rate_limit_keeps_last_good_and_counts_metric(tmp_db):
# A rate-limited refresh must NOT overwrite the cached row, and must be
# counted as rate_limited so the monitoring stack can see it.
dbmod.upsert_user("alice", {"user": {"login": "alice"}, "total_commits": 1841})
with dbmod._connect() as c:
c.execute("UPDATE users SET fetched_at='2020-01-01T00:00:00Z', last_requested_at=? WHERE username='alice'",
(dbmod._now(),))
with patch("src.cron.github.fetch_github_data",
side_effect=ghmod.GitHubTransientError("rate limited")):
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
assert stats["failed"] == 1 and stats["refreshed"] == 0
# Last-good data retained.
assert dbmod.get_user("alice")["data"]["total_commits"] == 1841
assert dbmod.read_fetch_metrics()["rate_limited"] == 1
def test_tick_runs_gc_for_abandoned_trial_users(tmp_db): def test_tick_runs_gc_for_abandoned_trial_users(tmp_db):
dbmod.upsert_user("ghost", {"user": {"login": "ghost"}}) dbmod.upsert_user("ghost", {"user": {"login": "ghost"}})
with dbmod._connect() as c: with dbmod._connect() as c:
@@ -33,3 +58,68 @@ def test_tick_runs_gc_for_abandoned_trial_users(tmp_db):
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7) stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
assert stats["gc_removed"] == 1 assert stats["gc_removed"] == 1
assert dbmod.get_user("ghost") is None assert dbmod.get_user("ghost") is None
def _due(*names):
# Backdate each user so they're due; later names are fetched more recently.
for i, n in enumerate(names):
dbmod.upsert_user(n, {"user": {"login": n}})
with dbmod._connect() as c:
c.execute("UPDATE users SET fetched_at=?, last_requested_at=? WHERE username=?",
(f"2020-01-0{i + 1}T00:00:00Z", dbmod._now(), n))
def test_tick_caps_refreshes_oldest_first(tmp_db, monkeypatch):
_due("old", "mid", "new")
monkeypatch.setattr(cronmod.config, "REFRESH_MAX_PER_TICK", 2)
monkeypatch.setattr(cronmod, "_core_remaining", lambda: None)
with patch("src.cron.github.fetch_github_data", side_effect=lambda u, **_k: {"user": {"login": u}}) as gh:
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
assert [c.args[0] for c in gh.call_args_list] == ["old", "mid"]
assert stats["refreshed"] == 2 and stats["deferred"] == 1
def test_tick_stops_under_core_reserve(tmp_db, monkeypatch):
# New sign-ups need the quota more than a day-old card does: once the
# PAT's core budget drops under the reserve, the tick stops refreshing.
_due("a", "b", "c")
monkeypatch.setattr(cronmod.config, "REFRESH_CORE_RESERVE", 1500)
left = iter([4000, 1400, 1400])
monkeypatch.setattr(cronmod, "_core_remaining", lambda: next(left))
with patch("src.cron.github.fetch_github_data", side_effect=lambda u, **_k: {"user": {"login": u}}) as gh:
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
assert [c.args[0] for c in gh.call_args_list] == ["a"]
assert stats["refreshed"] == 1 and stats["deferred"] == 2
def test_tick_retries_once_after_capped_retry_after(tmp_db, monkeypatch, sleeps):
# A secondary rate limit clears after a wait: honour Retry-After (capped)
# and retry the same user once; pause between users.
_due("a", "b")
monkeypatch.setattr(cronmod, "_core_remaining", lambda: None)
results = iter([ghmod.GitHubTransientError("rate limited", retry_after=500),
{"user": {"login": "a"}}, {"user": {"login": "b"}}])
def fake(u, **_k):
r = next(results)
if isinstance(r, Exception):
raise r
return r
with patch("src.cron.github.fetch_github_data", side_effect=fake) as gh:
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
assert [c.args[0] for c in gh.call_args_list] == ["a", "a", "b"]
assert sleeps == [120, 1.5]
assert stats["refreshed"] == 2 and stats["failed"] == 0
def test_tick_stops_and_defers_after_second_rate_limit(tmp_db, monkeypatch, sleeps):
# Hammering on after a repeat rate limit only fails every remaining user;
# stop the tick and leave them due for the next one.
_due("a", "b", "c")
monkeypatch.setattr(cronmod, "_core_remaining", lambda: None)
with patch("src.cron.github.fetch_github_data",
side_effect=ghmod.GitHubTransientError("rate limited")) as gh:
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
assert [c.args[0] for c in gh.call_args_list] == ["a", "a"]
assert sleeps == [60]
assert stats["failed"] == 1 and stats["refreshed"] == 0 and stats["deferred"] == 2
+17
View File
@@ -30,6 +30,23 @@ def test_upsert_and_get_round_trip(tmp_db):
assert row["fetched_at"] assert row["fetched_at"]
def test_fetch_metrics_round_trip(tmp_db):
# Zero-filled for every known outcome before anything is recorded.
assert dbmod.read_fetch_metrics() == {o: 0 for o in dbmod.FETCH_OUTCOMES}
dbmod.bump_fetch_metric("ok")
dbmod.bump_fetch_metric("ok")
dbmod.bump_fetch_metric("rate_limited")
counts = dbmod.read_fetch_metrics()
assert counts["ok"] == 2
assert counts["rate_limited"] == 1
assert counts["not_found"] == 0
def test_fetch_metric_unknown_outcome_buckets_to_error(tmp_db):
dbmod.bump_fetch_metric("bogus")
assert dbmod.read_fetch_metrics()["error"] == 1
def test_payload_hash_is_deterministic_and_changes_on_diff(): def test_payload_hash_is_deterministic_and_changes_on_diff():
h1 = dbmod.payload_hash({"a": 1, "b": 2}) h1 = dbmod.payload_hash({"a": 1, "b": 2})
h2 = dbmod.payload_hash({"b": 2, "a": 1}) h2 = dbmod.payload_hash({"b": 2, "a": 1})
+255 -51
View File
@@ -5,61 +5,38 @@ from src import github
@responses.activate @responses.activate
def test_fetch_user_data_returns_user_payload(): def test_fetch_user_data_returns_user_payload():
# fetch_commits: contributionCalendar/weeks # The fetcher fires the independent GitHub calls in parallel, so the
responses.add( # mock registry can't depend on FIFO ordering. Route GraphQL requests
responses.POST, "https://api.github.com/graphql", # by query content instead.
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}}, import json as _json
status=200,
) def _graphql_callback(request):
# fetch_commit_count (alltime) — first call: get createdAt q = _json.loads(request.body).get("query", "")
responses.add( if "weeks" in q:
responses.POST, "https://api.github.com/graphql", data = {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}
json={"data": {"user": {"createdAt": "2020-01-01T00:00:00Z"}}}, elif "createdAt" in q:
status=200, data = {"user": {"createdAt": "2020-01-01T00:00:00Z"}}
) elif "commitContributionsByRepository" in q:
# fetch_commit_count (alltime) — per-year contribution totals (2020–2026) data = {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}
for _ in range(7): elif "totalContributions" in q:
responses.add( data = {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}
responses.POST, "https://api.github.com/graphql", else:
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}}, data = {"user": None}
status=200, return (200, {}, _json.dumps({"data": data}))
)
# fetch_commit_count (recent, last 6 months) responses.add_callback(responses.POST, "https://api.github.com/graphql",
responses.add( callback=_graphql_callback)
responses.POST, "https://api.github.com/graphql", responses.add(responses.GET, "https://api.github.com/search/issues",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}}, json={"total_count": 0, "items": []}, status=200)
status=200,
)
# fetch_user_commit_repos (for collaborators)
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}},
status=200,
)
# PR count search
responses.add(
responses.GET, "https://api.github.com/search/issues",
json={"total_count": 0, "items": []},
status=200,
)
responses.add( responses.add(
responses.GET, "https://api.github.com/users/alice", responses.GET, "https://api.github.com/users/alice",
json={"login": "alice", "public_repos": 3, "followers": 5, "avatar_url": "https://avatars.example/1"}, json={"login": "alice", "public_repos": 3, "followers": 5,
"avatar_url": "https://avatars.example/1"},
status=200, status=200,
) )
# fetch_repos: two calls (owner + all) responses.add(responses.GET, "https://api.github.com/users/alice/repos", json=[], status=200)
responses.add( responses.add(responses.GET, "https://api.github.com/users/alice/repos", json=[], status=200)
responses.GET, "https://api.github.com/users/alice/repos", responses.add(responses.GET, "https://api.github.com/users/alice/events", json=[], status=200)
json=[], status=200,
)
responses.add(
responses.GET, "https://api.github.com/users/alice/repos",
json=[], status=200,
)
responses.add(
responses.GET, "https://api.github.com/users/alice/events",
json=[], status=200,
)
data = github.fetch_github_data("alice", token="t") data = github.fetch_github_data("alice", token="t")
assert data["user"]["login"] == "alice" assert data["user"]["login"] == "alice"
assert "repos" in data assert "repos" in data
@@ -76,6 +53,12 @@ def test_fetch_handles_404():
responses.POST, "https://api.github.com/graphql", responses.POST, "https://api.github.com/graphql",
json={"data": {"user": None}}, status=200, json={"data": {"user": None}}, status=200,
) )
# Both fetch_repos calls (owner + all) hit the same URL — register
# twice so the parallel firing gets a response either way round.
responses.add(
responses.GET, "https://api.github.com/users/nope/repos",
json={"message": "Not Found"}, status=404,
)
responses.add( responses.add(
responses.GET, "https://api.github.com/users/nope/repos", responses.GET, "https://api.github.com/users/nope/repos",
json={"message": "Not Found"}, status=404, json={"message": "Not Found"}, status=404,
@@ -84,5 +67,226 @@ def test_fetch_handles_404():
responses.GET, "https://api.github.com/users/nope/events", responses.GET, "https://api.github.com/users/nope/events",
json={"message": "Not Found"}, status=404, json={"message": "Not Found"}, status=404,
) )
responses.add(
responses.GET, "https://api.github.com/search/issues",
json={"total_count": 0, "items": []}, status=200,
)
data = github.fetch_github_data("nope", token="t") data = github.fetch_github_data("nope", token="t")
assert data["user"].get("message") == "Not Found" or data["user"] is None assert data["user"].get("message") == "Not Found" or data["user"] is None
@responses.activate
def test_commit_count_raises_on_graphql_rate_limit():
# GraphQL reports a rate limit as HTTP 200 with an `errors` array — the
# exact shape a valid response uses. It must NOT be swallowed into a 0
# that would overwrite the last good count in fetcher.db.
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": None},
"errors": [{"type": "RATE_LIMITED", "message": "API rate limit exceeded"}]},
status=200,
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_commit_count("alice", [])
@responses.activate
def test_commit_count_raises_on_rest_rate_limit():
# A 403 with the remaining budget at 0 is a rate limit, not a real answer.
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"message": "rate limited"}, status=403,
headers={"X-RateLimit-Remaining": "0"},
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_commit_count("alice", [])
@responses.activate
def test_commit_count_zero_on_not_found_is_not_transient():
# A genuinely unknown user (NOT_FOUND, no rate-limit error) is a real,
# persistable "no data" answer — return 0, don't raise.
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": None}}, status=200,
)
src = github.DirectAPISource(token="t")
assert src.fetch_commit_count("ghost", []) == 0
# --- REST rate-limit guards -------------------------------------------------
# The REST calls used to hand `.json()` straight back, so a 403 rate-limit body
# ({"message": "API rate limit exceeded for user ID ..."}) was persisted as if
# it were real data, wiping the user's last-good record for up to 24h.
RATE_LIMIT_BODY = {
"message": "API rate limit exceeded for user ID 123.",
"documentation_url": "https://docs.github.com/rest/overview/rate-limits",
}
RATE_LIMIT_HEADERS = {"X-RateLimit-Remaining": "0"}
@responses.activate
def test_fetch_user_data_raises_on_rest_rate_limit():
responses.add(
responses.GET, "https://api.github.com/users/alice",
json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS,
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_user_data("alice")
@responses.activate
def test_fetch_user_data_raises_on_rate_limit_without_header():
# Secondary rate limits come back as 403 without the remaining-budget
# header — the message is the only signal.
responses.add(
responses.GET, "https://api.github.com/users/alice",
json={"message": "You have exceeded a secondary rate limit."}, status=403,
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_user_data("alice")
@responses.activate
def test_fetch_repos_raises_on_rest_rate_limit():
responses.add(
responses.GET, "https://api.github.com/users/alice/repos",
json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS,
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_repos("alice")
@responses.activate
def test_fetch_events_raises_on_rest_rate_limit():
responses.add(
responses.GET, "https://api.github.com/users/alice/events",
json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS,
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_events("alice")
@responses.activate
def test_fetch_repo_contributors_raises_on_rest_rate_limit():
responses.add(
responses.GET, "https://api.github.com/repos/alice/proj/contributors",
json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS,
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_repo_contributors("alice/proj")
@responses.activate
def test_fetch_repo_languages_raises_on_rest_rate_limit():
responses.add(
responses.GET, "https://api.github.com/repos/alice/proj/languages",
json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS,
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_repo_languages("alice/proj")
@responses.activate
def test_single_repo_404_stays_non_fatal():
# A deleted/renamed repo is a real per-repo answer, not a budget problem:
# it must keep degrading gracefully instead of aborting the whole fetch.
responses.add(
responses.GET, "https://api.github.com/repos/alice/gone/languages",
json={"message": "Not Found"}, status=404,
)
responses.add(
responses.GET, "https://api.github.com/repos/alice/gone/contributors",
json={"message": "Not Found"}, status=404,
)
src = github.DirectAPISource(token="t")
assert src.fetch_repo_languages("alice/gone") == {}
assert src.fetch_repo_contributors("alice/gone") == []
@responses.activate
def test_rest_success_path_unchanged():
responses.add(
responses.GET, "https://api.github.com/users/alice",
json={"login": "alice", "followers": 5}, status=200,
)
responses.add(
responses.GET, "https://api.github.com/users/alice/events",
json=[{"type": "PushEvent"}], status=200,
)
responses.add(
responses.GET, "https://api.github.com/repos/alice/proj/languages",
json={"Python": 100}, status=200,
)
responses.add(
responses.GET, "https://api.github.com/repos/alice/proj/contributors",
json=[{"login": "bob", "contributions": 4}], status=200,
)
src = github.DirectAPISource(token="t")
assert src.fetch_user_data("alice")["login"] == "alice"
assert src.fetch_events("alice") == [{"type": "PushEvent"}]
assert src.fetch_repo_languages("alice/proj") == {"Python": 100}
assert src.fetch_repo_contributors("alice/proj") == [{"login": "bob", "contributions": 4}]
@responses.activate
def test_rate_limited_repo_languages_aborts_whole_fetch():
# A rate limit inside the per-repo fan-out means the budget is gone, so it
# must propagate rather than being swallowed into an empty breakdown.
responses.add(
responses.GET, "https://api.github.com/repos/alice/proj/languages",
json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS,
)
src = github.DirectAPISource(token="t")
repos = [{"full_name": "alice/proj"}]
with pytest.raises(github.GitHubTransientError):
github._enrich_repo_languages(repos, src)
def test_repo_languages_capped_to_recent_owned_repos(monkeypatch):
# One REST call per repo, so only the most recently pushed non-fork repos
# the user owns get a byte breakdown.
monkeypatch.setattr(github.config, "LANGUAGE_MAX_REPOS", 2)
class _Src:
def __init__(self):
self.calls = []
def fetch_repo_languages(self, full_name):
self.calls.append(full_name)
return {"Python": 1}
repos = [
{"full_name": "Alice/old", "pushed_at": "2024-01-01T00:00:00Z"},
{"full_name": "alice/new", "pushed_at": "2026-01-01T00:00:00Z"},
{"full_name": "alice/mid", "pushed_at": "2025-01-01T00:00:00Z"},
{"full_name": "alice/fork", "pushed_at": "2026-06-01T00:00:00Z", "fork": True},
{"full_name": "org/other", "pushed_at": "2026-06-01T00:00:00Z"},
]
src = _Src()
github._enrich_repo_languages(repos, src, "alice")
assert sorted(src.calls) == ["alice/mid", "alice/new"]
assert repos[1]["language_bytes"] == {"Python": 1}
assert "language_bytes" not in repos[0]
@responses.activate
def test_rate_limit_error_carries_retry_after():
responses.add(
responses.GET, "https://api.github.com/users/alice",
json={"message": "You have exceeded a secondary rate limit."}, status=403,
headers={"Retry-After": "42"},
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError) as exc:
src.fetch_user_data("alice")
assert exc.value.retry_after == 42
+1
View File
@@ -17,6 +17,7 @@ COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt RUN pip install --no-cache-dir -r requirements.txt
COPY src ./src COPY src ./src
COPY gunicorn.conf.py ./
RUN mkdir -p /app/src/static /app/data RUN mkdir -p /app/src/static /app/data
COPY --from=frontend-build /app/frontend/dist/ /app/src/static/ COPY --from=frontend-build /app/frontend/dist/ /app/src/static/
+51 -10
View File
@@ -1,13 +1,54 @@
<!doctype html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8"/>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>GitHub Widgets</title> <title>gh-stats - one stats card for your GitHub profile README</title>
</head> <meta name="description"
<body> content="Drop one line into your GitHub profile README and get a single SVG card: your score, contribution timeline, top collaborators, language breakdown, commit streaks and auto-awarded tags. Free, no signup needed."/>
<div id="root"></div> <link rel="canonical" href="https://gh-stats.com/"/>
<script type="module" src="/src/main.tsx"></script> <meta property="og:type" content="website"/>
</body> <meta property="og:site_name" content="gh-stats"/>
<meta property="og:url" content="https://gh-stats.com/"/>
<meta property="og:title" content="One stats card for your GitHub profile README"/>
<meta property="og:description"
content="Score, contribution timeline, top collaborators, languages, streaks and tags. One line of markdown, five themes, no signup."/>
<meta property="og:image" content="https://gh-stats.com/og.png"/>
<meta property="og:image:width" content="1200"/>
<meta property="og:image:height" content="630"/>
<meta property="og:image:alt" content="A gh-stats card on a GitHub profile README."/>
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:title" content="One stats card for your GitHub profile README"/>
<meta name="twitter:description"
content="Score, contribution timeline, top collaborators, languages, streaks and tags. One line of markdown, five themes, no signup."/>
<meta name="twitter:image" content="https://gh-stats.com/og.png"/>
<script type="module">
// Import the functions you need from the SDKs you need
import {initializeApp} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-app.js";
import {getAnalytics} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-analytics.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyCy2pUW8Geo0Aagq9mTYKlfCpa9GUIXpy8",
authDomain: "gh-stats-284de.firebaseapp.com",
projectId: "gh-stats-284de",
storageBucket: "gh-stats-284de.firebasestorage.app",
messagingSenderId: "723662839762",
appId: "1:723662839762:web:4ba5337f6489ea67dc320b",
measurementId: "G-228GR89RYX"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html> </html>
@@ -0,0 +1 @@
45e91fcd547e2331201dd125dd388d94
@@ -0,0 +1,197 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>How to create a GitHub profile README (and add a stats card)</title>
<meta name="description"
content="Create the special repository that GitHub shows on your profile, then add a live stats card with one line of markdown. Five steps, about two minutes, no signup."/>
<link rel="canonical" href="https://gh-stats.com/github-profile-readme.html"/>
<link rel="icon" type="image/svg+xml" href="/favicon.svg"/>
<meta property="og:type" content="article"/>
<meta property="og:site_name" content="gh-stats"/>
<meta property="og:url" content="https://gh-stats.com/github-profile-readme.html"/>
<meta property="og:title" content="How to create a GitHub profile README"/>
<meta property="og:description"
content="The special repository, the one setting that trips people up, and a stats card in one line."/>
<meta property="og:image" content="https://gh-stats.com/og.png"/>
<meta name="twitter:card" content="summary_large_image"/>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,wght@9..40,400..700&family=Instrument+Serif&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"/>
<script type="module">
// Same GA4 stream as the SPA (index.html), so this page's traffic and its
// referrers land in the existing property instead of going unmeasured.
import {initializeApp} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-app.js";
import {getAnalytics} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-analytics.js";
getAnalytics(initializeApp({
apiKey: "AIzaSyCy2pUW8Geo0Aagq9mTYKlfCpa9GUIXpy8",
authDomain: "gh-stats-284de.firebaseapp.com",
projectId: "gh-stats-284de",
storageBucket: "gh-stats-284de.firebasestorage.app",
messagingSenderId: "723662839762",
appId: "1:723662839762:web:4ba5337f6489ea67dc320b",
measurementId: "G-228GR89RYX"
}));
</script>
<style>
:root{
--bg:#f9fafb; --card:#ffffff; --line:#e5e7eb;
--ink:#1f2937; --muted:#6b7280; --faint:#9ca3af; --accent:#0969da;
}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--ink);
font-family:'DM Sans',system-ui,sans-serif;-webkit-font-smoothing:antialiased;
line-height:1.65}
main{max-width:760px;margin:0 auto;padding:56px 24px 96px}
h1{font-family:'Instrument Serif',Georgia,serif;font-weight:400;
font-size:2.6rem;line-height:1.15;letter-spacing:-.01em;margin:0 0 16px}
h2{font-family:'Instrument Serif',Georgia,serif;font-weight:400;
font-size:1.65rem;margin:48px 0 12px;letter-spacing:-.01em}
p{margin:0 0 16px}
.lede{font-size:1.08rem;color:var(--muted);margin-bottom:32px}
a{color:var(--accent);text-decoration:none}
a:hover{text-decoration:underline}
code,pre{font-family:'JetBrains Mono',ui-monospace,monospace;font-size:.86rem}
pre{background:var(--card);border:1px solid var(--line);border-radius:10px;
padding:14px 16px;overflow-x:auto;margin:0 0 16px}
code:not(pre code){background:#f3f4f6;border-radius:5px;padding:.12em .38em;font-size:.85em}
.tablewrap{overflow-x:auto;margin:0 0 16px}
table{border-collapse:collapse;width:100%;font-size:.86rem;background:var(--card);
border:1px solid var(--line);border-radius:10px}
th,td{text-align:left;padding:10px 14px;border-bottom:1px solid var(--line);
vertical-align:top}
th{font-weight:600;color:var(--muted);font-size:.78rem;text-transform:uppercase;
letter-spacing:.04em}
tr:last-child td{border-bottom:none}
td code{white-space:nowrap}
figure{margin:0 0 28px}
figure img{width:100%;max-width:400px;display:block;border-radius:12px}
figcaption{color:var(--faint);font-size:.8rem;margin-top:8px}
.clip{position:relative;max-width:340px;max-height:400px;overflow:hidden;
border-radius:12px}
.clip img{width:100%;display:block;border-radius:12px}
.clip::after{content:"";position:absolute;left:0;right:0;bottom:0;height:72px;
background:linear-gradient(to top,var(--bg),transparent)}
.cta{display:inline-block;background:var(--ink);color:#fff;border-radius:9px;
padding:11px 20px;font-weight:600;font-size:.92rem;margin:8px 0 0}
.cta:hover{text-decoration:none;opacity:.9}
.note{border-left:3px solid var(--line);padding:2px 0 2px 16px;color:var(--muted);
font-size:.92rem;margin:0 0 16px}
footer{border-top:1px solid var(--line);margin-top:64px;padding-top:20px;
color:var(--faint);font-size:.82rem}
@media (max-width:640px){h1{font-size:2.05rem}main{padding:36px 20px 72px}}
</style>
</head>
<body>
<main>
<h1>How to create a GitHub profile README</h1>
<p class="lede">
A profile README is the block of text and images at the top of your GitHub profile
page. GitHub builds it from one specific repository, so setting it up is a matter of
creating that repository and writing a README in it.
</p>
<h2>What GitHub needs</h2>
<p>GitHub shows a README on your profile when all four of these hold:</p>
<div class="tablewrap">
<table>
<tr><th>Requirement</th><th>Example for the username <code>octocat</code></th></tr>
<tr><td>A repository named exactly like your username</td><td><code>octocat/octocat</code></td></tr>
<tr><td>The repository is public</td><td>Visibility: Public</td></tr>
<tr><td>A file named <code>README.md</code> in its root</td><td><code>octocat/octocat/README.md</code></td></tr>
<tr><td>The file is not empty</td><td>Any text at all</td></tr>
</table>
</div>
<h2>Create it in five steps</h2>
<p>
1. Open <a href="https://github.com/new">github.com/new</a>.<br/>
2. Under Repository name, type your username exactly. GitHub confirms with a
note that this is a special repository.<br/>
3. Select <strong>Public</strong>.<br/>
4. Turn on <strong>Add a README file</strong>.<br/>
5. Click <strong>Create repository</strong>, then <strong>Edit README</strong>.
</p>
<p>
Save any text and your profile page shows it. The pre-filled template is fine to
keep, replace, or delete.
</p>
<p>
To start from a finished layout instead, open the
<a href="https://github.com/ShayManor/profile-readme-template">profile README template</a>,
click <strong>Use this template</strong>, name the new repository after your username,
and replace <code>YOUR_USERNAME</code> in its README.
</p>
<p class="note">
If you made a public repository with your username before July 2020, GitHub does
not show it automatically. Open the repository and click <strong>Share to
profile</strong>.
</p>
<h2>Add a stats card</h2>
<p>
Paste this line into the README, replace the username in both places, and commit:
</p>
<pre><code>[![GitHub stats](https://gh-stats.com/api/YOUR_USERNAME)](https://gh-stats.com)</code></pre>
<p>
It renders one card with a score out of 100, your contribution timeline, top
collaborators, language breakdown and commit streaks, and it updates on its own.
The first request for a new username queues a build, so give it a minute.
</p>
<figure>
<div class="clip">
<img src="https://gh-stats.com/api/ShayManor" alt="A gh-stats card: profile score, impact timeline, collaborators, languages, streaks and achievements."/>
</div>
<figcaption>A stats card in a profile README, cropped.</figcaption>
</figure>
<a class="cta" href="https://gh-stats.com/">Preview the card for your username</a>
<p style="margin-top:24px">
Want only one part? The
<a href="https://gh-stats.com/github-top-languages-card.html">top languages card</a>
works the same way, and there are <a href="https://gh-stats.com/github-readme-themes.html">five
themes</a> to pick from. Already using github-readme-stats? See the
<a href="https://gh-stats.com/github-readme-stats-alternative.html">migration guide</a>.
</p>
<h2>Common questions</h2>
<p>
<strong>I created the repository but my profile shows nothing.</strong> Check the
four requirements above. The usual cause is a private repository or a name that does
not match the username exactly.
</p>
<p>
<strong>Can I edit it later?</strong> Yes. Every commit to that <code>README.md</code>
updates your profile page.
</p>
<p>
<strong>Does the card need a token or an account?</strong> No. It reads public
GitHub activity only, and there is nothing to sign up for.
</p>
<footer>
<a href="https://gh-stats.com/">gh-stats.com</a> &middot;
<a href="https://github.com/ShayManor/github-readme-stats">source on GitHub</a> &middot;
MIT licensed
</footer>
</main>
</body>
</html>
@@ -0,0 +1,177 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>github-profile-trophy not loading (402)? Two fixes</title>
<meta name="description"
content="github-profile-trophy.vercel.app returns HTTP 402, so trophy images in GitHub profile READMEs are broken. Self-host it, or swap in a rank card with one line."/>
<link rel="canonical" href="https://gh-stats.com/github-profile-trophy-alternative.html"/>
<link rel="icon" type="image/svg+xml" href="/favicon.svg"/>
<meta property="og:type" content="article"/>
<meta property="og:site_name" content="gh-stats"/>
<meta property="og:url" content="https://gh-stats.com/github-profile-trophy-alternative.html"/>
<meta property="og:title" content="github-profile-trophy not loading? Two fixes"/>
<meta property="og:description"
content="The public trophy instance returns 402. Self-host it, or use a rank card instead."/>
<meta property="og:image" content="https://gh-stats.com/og.png"/>
<meta name="twitter:card" content="summary_large_image"/>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,wght@9..40,400..700&family=Instrument+Serif&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"/>
<script type="module">
// Same GA4 stream as the SPA (index.html), so this page's traffic and its
// referrers land in the existing property instead of going unmeasured.
import {initializeApp} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-app.js";
import {getAnalytics} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-analytics.js";
getAnalytics(initializeApp({
apiKey: "AIzaSyCy2pUW8Geo0Aagq9mTYKlfCpa9GUIXpy8",
authDomain: "gh-stats-284de.firebaseapp.com",
projectId: "gh-stats-284de",
storageBucket: "gh-stats-284de.firebasestorage.app",
messagingSenderId: "723662839762",
appId: "1:723662839762:web:4ba5337f6489ea67dc320b",
measurementId: "G-228GR89RYX"
}));
</script>
<style>
:root{
--bg:#f9fafb; --card:#ffffff; --line:#e5e7eb;
--ink:#1f2937; --muted:#6b7280; --faint:#9ca3af; --accent:#0969da;
}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--ink);
font-family:'DM Sans',system-ui,sans-serif;-webkit-font-smoothing:antialiased;
line-height:1.65}
main{max-width:760px;margin:0 auto;padding:56px 24px 96px}
h1{font-family:'Instrument Serif',Georgia,serif;font-weight:400;
font-size:2.6rem;line-height:1.15;letter-spacing:-.01em;margin:0 0 16px}
h2{font-family:'Instrument Serif',Georgia,serif;font-weight:400;
font-size:1.65rem;margin:48px 0 12px;letter-spacing:-.01em}
p{margin:0 0 16px}
.lede{font-size:1.08rem;color:var(--muted);margin-bottom:32px}
a{color:var(--accent);text-decoration:none}
a:hover{text-decoration:underline}
code,pre{font-family:'JetBrains Mono',ui-monospace,monospace;font-size:.86rem}
pre{background:var(--card);border:1px solid var(--line);border-radius:10px;
padding:14px 16px;overflow-x:auto;margin:0 0 16px}
code:not(pre code){background:#f3f4f6;border-radius:5px;padding:.12em .38em;font-size:.85em}
.tablewrap{overflow-x:auto;margin:0 0 16px}
table{border-collapse:collapse;width:100%;font-size:.86rem;background:var(--card);
border:1px solid var(--line);border-radius:10px}
th,td{text-align:left;padding:10px 14px;border-bottom:1px solid var(--line);
vertical-align:top}
th{font-weight:600;color:var(--muted);font-size:.78rem;text-transform:uppercase;
letter-spacing:.04em}
tr:last-child td{border-bottom:none}
td code{white-space:nowrap}
figure{margin:0 0 28px}
figure img{width:100%;max-width:400px;display:block;border-radius:12px}
figcaption{color:var(--faint);font-size:.8rem;margin-top:8px}
.clip{position:relative;max-width:340px;max-height:400px;overflow:hidden;
border-radius:12px}
.clip img{width:100%;display:block;border-radius:12px}
.clip::after{content:"";position:absolute;left:0;right:0;bottom:0;height:72px;
background:linear-gradient(to top,var(--bg),transparent)}
.cta{display:inline-block;background:var(--ink);color:#fff;border-radius:9px;
padding:11px 20px;font-weight:600;font-size:.92rem;margin:8px 0 0}
.cta:hover{text-decoration:none;opacity:.9}
.note{border-left:3px solid var(--line);padding:2px 0 2px 16px;color:var(--muted);
font-size:.92rem;margin:0 0 16px}
footer{border-top:1px solid var(--line);margin-top:64px;padding-top:20px;
color:var(--faint);font-size:.82rem}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:20px;margin:0 0 16px}
.grid .clip{max-height:300px}
.grid h3{font-size:1rem;margin:0 0 8px}
.grid pre{font-size:.72rem;margin-top:10px}
@media (max-width:640px){h1{font-size:2.05rem}main{padding:36px 20px 72px}}
</style>
</head>
<body>
<main>
<h1>github-profile-trophy not loading?</h1>
<p class="lede">
The public instance at <code>github-profile-trophy.vercel.app</code> returns
<code>402 Payment required</code> (Vercel's <code>DEPLOYMENT_DISABLED</code>), so every
README that embeds it shows a broken image. There are two ways to fix it: run your own
copy, or switch to a different card.
</p>
<h2>Is yours broken?</h2>
<p>Open your profile. If the trophies are a broken-image icon or alt text, your README
points at the disabled instance. The line looks like this:</p>
<pre><code>[![trophy](https://github-profile-trophy.vercel.app/?username=YOUR_USERNAME)](https://github.com/ryo-ma/github-profile-trophy)</code></pre>
<h2>Fix 1: host your own copy</h2>
<p>
The project is open source and its README asks users to fork it and deploy the fork to
Vercel, then point the image at the new address. Its README also lists volunteer
mirrors, but most of them returned errors when this page was written (November 2026),
so a mirror may break again.
</p>
<h2>Fix 2: a rank card, in one line</h2>
<p>To switch to gh-stats instead, replace the line with this one, change the username, and commit:</p>
<pre><code>[![GitHub rank](https://gh-stats.com/api/YOUR_USERNAME/grade.svg)](https://gh-stats.com)</code></pre>
<figure>
<img src="https://gh-stats.com/api/torvalds/grade.svg" alt="gh-stats grade card: a letter rank, a score out of 100, and commit, PR, star, repo and follower counts." style="max-width:380px"/>
<figcaption>The grade card for torvalds, rendered live.</figcaption>
</figure>
<p>
There is no token to create, no signup and nothing to deploy. The first request for a
new username queues a build, so the image can take a minute to appear.
</p>
<h2>How it differs</h2>
<div class="tablewrap">
<table>
<tr><th></th><th>github-profile-trophy</th><th>gh-stats grade card</th></tr>
<tr><td>Shows</td><td>A row of trophies, each with its own rank</td><td>One overall rank and score, plus commits, PRs, stars, repos and followers</td></tr>
<tr><td>Extras</td><td>Many themes, row and column layout</td><td>Role tags worked out from your repos; five themes</td></tr>
<tr><td>Hosting</td><td>Public instance returns 402; self-host on Vercel</td><td>gh-stats.com, or self-host (MIT)</td></tr>
</table>
</div>
<h2>Want the whole profile?</h2>
<p>
Drop the <code>/grade.svg</code> and the same URL renders one card with the rank, a
contribution timeline, top collaborators, languages and streaks:
</p>
<pre><code>[![GitHub stats](https://gh-stats.com/api/YOUR_USERNAME)](https://gh-stats.com)</code></pre>
<a class="cta" href="https://gh-stats.com/">Preview it for your username</a>
<p style="margin-top:24px">
See the <a href="https://gh-stats.com/github-readme-themes.html">five themes</a>, or
<a href="https://gh-stats.com/github-profile-readme.html">how to create a profile README</a>
if you do not have one yet.
</p>
<h2>Common questions</h2>
<p>
<strong>Does gh-stats need access to my account?</strong> No. It reads public GitHub
activity only.
</p>
<footer>
<a href="https://gh-stats.com/">gh-stats.com</a> &middot;
<a href="https://github.com/ShayManor/github-readme-stats">source on GitHub</a> &middot;
MIT licensed
</footer>
</main>
</body>
</html>
@@ -0,0 +1,187 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>github-readme-activity-graph not loading (402)? Two fixes</title>
<meta name="description"
content="The vercel.app address of github-readme-activity-graph returns HTTP 402. Point at the project's new address, or swap in a different contribution graph with one line."/>
<link rel="canonical" href="https://gh-stats.com/github-readme-activity-graph-alternative.html"/>
<link rel="icon" type="image/svg+xml" href="/favicon.svg"/>
<meta property="og:type" content="article"/>
<meta property="og:site_name" content="gh-stats"/>
<meta property="og:url" content="https://gh-stats.com/github-readme-activity-graph-alternative.html"/>
<meta property="og:title" content="github-readme-activity-graph not loading? Two fixes"/>
<meta property="og:description"
content="The old vercel.app address returns 402. Here is the new one, and an alternative."/>
<meta property="og:image" content="https://gh-stats.com/og.png"/>
<meta name="twitter:card" content="summary_large_image"/>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,wght@9..40,400..700&family=Instrument+Serif&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"/>
<script type="module">
// Same GA4 stream as the SPA (index.html), so this page's traffic and its
// referrers land in the existing property instead of going unmeasured.
import {initializeApp} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-app.js";
import {getAnalytics} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-analytics.js";
getAnalytics(initializeApp({
apiKey: "AIzaSyCy2pUW8Geo0Aagq9mTYKlfCpa9GUIXpy8",
authDomain: "gh-stats-284de.firebaseapp.com",
projectId: "gh-stats-284de",
storageBucket: "gh-stats-284de.firebasestorage.app",
messagingSenderId: "723662839762",
appId: "1:723662839762:web:4ba5337f6489ea67dc320b",
measurementId: "G-228GR89RYX"
}));
</script>
<style>
:root{
--bg:#f9fafb; --card:#ffffff; --line:#e5e7eb;
--ink:#1f2937; --muted:#6b7280; --faint:#9ca3af; --accent:#0969da;
}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--ink);
font-family:'DM Sans',system-ui,sans-serif;-webkit-font-smoothing:antialiased;
line-height:1.65}
main{max-width:760px;margin:0 auto;padding:56px 24px 96px}
h1{font-family:'Instrument Serif',Georgia,serif;font-weight:400;
font-size:2.6rem;line-height:1.15;letter-spacing:-.01em;margin:0 0 16px}
h2{font-family:'Instrument Serif',Georgia,serif;font-weight:400;
font-size:1.65rem;margin:48px 0 12px;letter-spacing:-.01em}
p{margin:0 0 16px}
.lede{font-size:1.08rem;color:var(--muted);margin-bottom:32px}
a{color:var(--accent);text-decoration:none}
a:hover{text-decoration:underline}
code,pre{font-family:'JetBrains Mono',ui-monospace,monospace;font-size:.86rem}
pre{background:var(--card);border:1px solid var(--line);border-radius:10px;
padding:14px 16px;overflow-x:auto;margin:0 0 16px}
code:not(pre code){background:#f3f4f6;border-radius:5px;padding:.12em .38em;font-size:.85em}
.tablewrap{overflow-x:auto;margin:0 0 16px}
table{border-collapse:collapse;width:100%;font-size:.86rem;background:var(--card);
border:1px solid var(--line);border-radius:10px}
th,td{text-align:left;padding:10px 14px;border-bottom:1px solid var(--line);
vertical-align:top}
th{font-weight:600;color:var(--muted);font-size:.78rem;text-transform:uppercase;
letter-spacing:.04em}
tr:last-child td{border-bottom:none}
td code{white-space:nowrap}
figure{margin:0 0 28px}
figure img{width:100%;max-width:400px;display:block;border-radius:12px}
figcaption{color:var(--faint);font-size:.8rem;margin-top:8px}
.clip{position:relative;max-width:340px;max-height:400px;overflow:hidden;
border-radius:12px}
.clip img{width:100%;display:block;border-radius:12px}
.clip::after{content:"";position:absolute;left:0;right:0;bottom:0;height:72px;
background:linear-gradient(to top,var(--bg),transparent)}
.cta{display:inline-block;background:var(--ink);color:#fff;border-radius:9px;
padding:11px 20px;font-weight:600;font-size:.92rem;margin:8px 0 0}
.cta:hover{text-decoration:none;opacity:.9}
.note{border-left:3px solid var(--line);padding:2px 0 2px 16px;color:var(--muted);
font-size:.92rem;margin:0 0 16px}
footer{border-top:1px solid var(--line);margin-top:64px;padding-top:20px;
color:var(--faint);font-size:.82rem}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:20px;margin:0 0 16px}
.grid .clip{max-height:300px}
.grid h3{font-size:1rem;margin:0 0 8px}
.grid pre{font-size:.72rem;margin-top:10px}
@media (max-width:640px){h1{font-size:2.05rem}main{padding:36px 20px 72px}}
</style>
</head>
<body>
<main>
<h1>github-readme-activity-graph not loading?</h1>
<p class="lede">
The old github-readme-activity-graph address on vercel.app has returned
<code>402 Payment required</code> (Vercel's <code>DEPLOYMENT_DISABLED</code>) since
September 2026, so READMEs that still use it show a broken image. There are two ways
to fix it: point at the project's new address, or switch to a different graph.
</p>
<h2>Is yours broken?</h2>
<p>Open your profile. If the graph is a broken-image icon or alt text, your README points at
the disabled instance. The line looks like this:</p>
<pre><code>![Activity graph](https://github-readme-activity-graph.vercel.app/graph?username=YOUR_USERNAME)</code></pre>
<p>The older address <code>activity-graph.herokuapp.com</code> returns 404 too, and both fixes below work for it.</p>
<h2>Fix 1: the project's new address</h2>
<p>The project now runs on Cloudflare Workers. Change the domain and keep everything else:</p>
<pre><code>https://github-readme-activity-graph.ashutosh-dwivedi0710.workers.dev/graph?username=YOUR_USERNAME</code></pre>
<h2>Fix 2: a different graph, in one line</h2>
<p>To switch to gh-stats instead, replace the line with this one, change the username, and commit:</p>
<pre><code>[![Contribution graph](https://gh-stats.com/api/YOUR_USERNAME/impact.svg)](https://gh-stats.com)</code></pre>
<figure>
<img src="https://gh-stats.com/api/torvalds/impact.svg" alt="gh-stats impact timeline: weekly contributions over the last six months." style="max-width:380px"/>
<figcaption>The impact timeline for torvalds, rendered live.</figcaption>
</figure>
<p>
There is no token to create and no signup. The first request for a new username queues
a build, so the image can take a minute to appear.
</p>
<h2>How it differs</h2>
<div class="tablewrap">
<table>
<tr><th></th><th>github-readme-activity-graph</th><th>gh-stats impact timeline</th></tr>
<tr><td>Window</td><td>Last 31 days by default (up to 90), one point per day</td><td>Last six months, one point per week</td></tr>
<tr><td>Counts</td><td>Daily contributions</td><td>Weekly totals from your contribution calendar</td></tr>
<tr><td>Themes</td><td>Many, plus custom colours and title</td><td>Five: <code>?theme=midnight</code>, <code>onyx</code>, <code>nord</code>, <code>clean</code>, <code>paper</code></td></tr>
<tr><td>Address</td><td>Moved from vercel.app to workers.dev</td><td>gh-stats.com</td></tr>
</table>
</div>
<p>
A weekly line over six months is smoother than a daily one. It shows the shape of your
year, and a quiet weekend does not read as a gap.
</p>
<h2>Want the whole profile?</h2>
<p>
Drop the <code>/impact.svg</code> and the same URL renders one card with a score out of
100, the timeline, top collaborators, languages and streaks:
</p>
<pre><code>[![GitHub stats](https://gh-stats.com/api/YOUR_USERNAME)](https://gh-stats.com)</code></pre>
<a class="cta" href="https://gh-stats.com/">Preview it for your username</a>
<p style="margin-top:24px">
See the <a href="https://gh-stats.com/github-readme-themes.html">five themes</a>, or
<a href="https://gh-stats.com/github-profile-readme.html">how to create a profile README</a>
if you do not have one yet.
</p>
<h2>Common questions</h2>
<p>
<strong>Can I keep using github-readme-activity-graph?</strong> Yes. Use Fix 1; the
project is maintained and only its old vercel.app address is disabled.
</p>
<p>
<strong>Does gh-stats need access to my account?</strong> No. It reads public GitHub
activity only.
</p>
<footer>
<a href="https://gh-stats.com/">gh-stats.com</a> &middot;
<a href="https://github.com/ShayManor/github-readme-stats">source on GitHub</a> &middot;
MIT licensed
</footer>
</main>
</body>
</html>
@@ -0,0 +1,214 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>github-readme-stats alternative: a maintained stats card for your profile README</title>
<meta name="description"
content="anuraghazra/github-readme-stats is marked no longer maintained. gh-stats is a maintained, MIT-licensed stats card you can drop into your GitHub profile README by changing the domain in your existing URL, or self-host on your own API quota."/>
<link rel="canonical" href="https://gh-stats.com/github-readme-stats-alternative.html"/>
<link rel="icon" type="image/svg+xml" href="/favicon.svg"/>
<meta property="og:type" content="article"/>
<meta property="og:site_name" content="gh-stats"/>
<meta property="og:url" content="https://gh-stats.com/github-readme-stats-alternative.html"/>
<meta property="og:title" content="github-readme-stats alternative: a maintained stats card"/>
<meta property="og:description"
content="The card most profile READMEs use is marked no longer maintained. Here is how to move, with the URL shapes you already have."/>
<meta property="og:image" content="https://gh-stats.com/og.png"/>
<meta name="twitter:card" content="summary_large_image"/>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,wght@9..40,400..700&family=Instrument+Serif&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"/>
<script type="module">
// Same GA4 stream as the SPA (index.html), so this page's traffic and its
// referrers land in the existing property instead of going unmeasured.
import {initializeApp} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-app.js";
import {getAnalytics} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-analytics.js";
getAnalytics(initializeApp({
apiKey: "AIzaSyCy2pUW8Geo0Aagq9mTYKlfCpa9GUIXpy8",
authDomain: "gh-stats-284de.firebaseapp.com",
projectId: "gh-stats-284de",
storageBucket: "gh-stats-284de.firebasestorage.app",
messagingSenderId: "723662839762",
appId: "1:723662839762:web:4ba5337f6489ea67dc320b",
measurementId: "G-228GR89RYX"
}));
</script>
<style>
:root{
--bg:#f9fafb; --card:#ffffff; --line:#e5e7eb;
--ink:#1f2937; --muted:#6b7280; --faint:#9ca3af; --accent:#0969da;
}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--ink);
font-family:'DM Sans',system-ui,sans-serif;-webkit-font-smoothing:antialiased;
line-height:1.65}
main{max-width:760px;margin:0 auto;padding:56px 24px 96px}
h1{font-family:'Instrument Serif',Georgia,serif;font-weight:400;
font-size:2.6rem;line-height:1.15;letter-spacing:-.01em;margin:0 0 16px}
h2{font-family:'Instrument Serif',Georgia,serif;font-weight:400;
font-size:1.65rem;margin:48px 0 12px;letter-spacing:-.01em}
p{margin:0 0 16px}
.lede{font-size:1.08rem;color:var(--muted);margin-bottom:32px}
a{color:var(--accent);text-decoration:none}
a:hover{text-decoration:underline}
code,pre{font-family:'JetBrains Mono',ui-monospace,monospace;font-size:.86rem}
pre{background:var(--card);border:1px solid var(--line);border-radius:10px;
padding:14px 16px;overflow-x:auto;margin:0 0 16px}
code:not(pre code){background:#f3f4f6;border-radius:5px;padding:.12em .38em;font-size:.85em}
.tablewrap{overflow-x:auto;margin:0 0 16px}
table{border-collapse:collapse;width:100%;font-size:.86rem;background:var(--card);
border:1px solid var(--line);border-radius:10px}
th,td{text-align:left;padding:10px 14px;border-bottom:1px solid var(--line);
vertical-align:top}
th{font-weight:600;color:var(--muted);font-size:.78rem;text-transform:uppercase;
letter-spacing:.04em}
tr:last-child td{border-bottom:none}
td code{white-space:nowrap}
figure{margin:0 0 28px}
figure img{width:100%;max-width:400px;display:block;border-radius:12px}
figcaption{color:var(--faint);font-size:.8rem;margin-top:8px}
.clip{position:relative;max-width:340px;max-height:400px;overflow:hidden;
border-radius:12px}
.clip img{width:100%;display:block;border-radius:12px}
.clip::after{content:"";position:absolute;left:0;right:0;bottom:0;height:72px;
background:linear-gradient(to top,var(--bg),transparent)}
.cta{display:inline-block;background:var(--ink);color:#fff;border-radius:9px;
padding:11px 20px;font-weight:600;font-size:.92rem;margin:8px 0 0}
.cta:hover{text-decoration:none;opacity:.9}
.note{border-left:3px solid var(--line);padding:2px 0 2px 16px;color:var(--muted);
font-size:.92rem;margin:0 0 16px}
footer{border-top:1px solid var(--line);margin-top:64px;padding-top:20px;
color:var(--faint);font-size:.82rem}
@media (max-width:640px){h1{font-size:2.05rem}main{padding:36px 20px 72px}}
</style>
</head>
<body>
<main>
<h1>A maintained alternative to github-readme-stats</h1>
<p class="lede">
<a href="https://github.com/anuraghazra/github-readme-stats">anuraghazra/github-readme-stats</a>
is the stats card most GitHub profile READMEs use, and it earned that place.
Its README now opens with a caution notice saying the repository is no longer
maintained. If you are looking for somewhere to move, this page shows the swap.
</p>
<figure>
<img src="https://gh-stats.com/?username=ShayManor" alt="A gh-stats developer profile card showing score, commits, pull requests, stars and role tags."/>
<figcaption>The profile card: score out of 100, headline counts, and role tags earned from your repositories.</figcaption>
</figure>
<h2>Change the domain, keep the URL</h2>
<p>
The common URL shapes work here with only the domain changed, so migrating is
an edit to one line of markdown.
</p>
<div class="tablewrap">
<table>
<tr><th>Your current URL</th><th>Change it to</th></tr>
<tr><td><code>github-readme-stats.vercel.app/api?username=U</code></td>
<td><code>gh-stats.com/api?username=U</code></td></tr>
<tr><td><code>github-readme-stats.vercel.app/api/top-langs?username=U</code></td>
<td><code>gh-stats.com/api/top-langs?username=U</code></td></tr>
<tr><td><code>github-readme-stats-sigma-five.vercel.app/api?username=U</code> (returns 402)</td>
<td><code>gh-stats.com/api?username=U</code></td></tr>
<tr><td><code>github-readme-stats-eight-theta.vercel.app/api?username=U</code> (returns 402)</td>
<td><code>gh-stats.com/api?username=U</code></td></tr>
<tr><td><code>github-readme-stats-eight-theta.vercel.app/api/top-langs?username=U</code> (returns 402)</td>
<td><code>gh-stats.com/api/top-langs?username=U</code></td></tr>
<tr><td><code>github-readme-streak-stats.herokuapp.com/?user=U</code></td>
<td><code>gh-stats.com/api/streak/U</code></td></tr>
</table>
</div>
<p>Nothing else in your README changes.</p>
<p class="note">
<code>theme=</code> is honoured on the composite card (<code>/api/&lt;user&gt;</code>).
On the compatibility and single-widget URLs above it is currently ignored and the
default theme is served.
</p>
<h2>Or replace several badges with one card</h2>
<p>
Most profile READMEs stack a stats badge, a streak badge, a languages badge and a
trophy row, each one a separate request. The composite card covers all of it in a
single image:
</p>
<pre><code>![stats](https://gh-stats.com/api/YOUR_USERNAME)</code></pre>
<figure>
<div class="clip">
<img src="https://gh-stats.com/api/ShayManor" alt="The full gh-stats composite card: profile score, impact timeline, collaborators, languages, streaks and achievements."/>
</div>
<figcaption>The composite card, cropped. It stacks profile, timeline, collaborators, languages, streaks and achievements.</figcaption>
</figure>
<p>
No signup is required to try it. Type a username on the
<a href="https://gh-stats.com/">home page</a> and the real card renders immediately.
Signing in with GitHub proves you own the username and unlocks the editor for
themes, widget order and custom tags.
</p>
<a class="cta" href="https://gh-stats.com/">Try it on your username</a>
<h2>What you should know before switching</h2>
<p>
The project's own successor is
<a href="https://github.com/stats-organization/github-stats-extended">GitHub Stats Extended</a>,
named in that caution notice. It is a fork that keeps the original's shape, so pick
it if what you want is the same card with the same options.
</p>
<p>
gh-stats is a different design: one card that summarises the whole profile, rather
than a set of separate badges. It is MIT licensed, and you can
<a href="https://github.com/ShayManor/github-readme-stats">self-host it</a> with
<code>docker compose up</code> on your own GitHub API quota if you would rather not
depend on someone else's instance.
</p>
<p>
Only public GitHub activity is counted. Private repositories, private commit counts
and contributions to org-restricted repositories are never visible to the fetcher.
</p>
<h2>Common questions</h2>
<p>
<strong>Is github-readme-stats actually dead?</strong> The repository is not archived
and the hosted instance still serves cards. The maintainer marked it no longer
maintained in the README, which is a statement about future work rather than an
outage.
</p>
<p>
<strong>Why do stats cards return an error or a blank image?</strong> A shared
instance runs on one GitHub API quota, so a popular deployment hits rate limits and
serves errors to everyone behind it. Self-hosting puts you on your own quota and
removes that failure mode.
</p>
<p>
<strong>Do I have to change my README again later?</strong> No. The image URL is
stable, so themes, tags and widget order can change in the editor without touching
the markdown.
</p>
<footer>
<a href="https://gh-stats.com/">gh-stats.com</a> &middot;
<a href="https://github.com/ShayManor/github-readme-stats">source on GitHub</a> &middot;
MIT licensed
</footer>
</main>
</body>
</html>
@@ -0,0 +1,193 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>GitHub README stats card themes: dark, light and auto-switching</title>
<meta name="description"
content="Five themes for a GitHub profile stats card, with a live preview and a copy-paste line for each, plus the snippet that switches between dark and light with the viewer's GitHub theme."/>
<link rel="canonical" href="https://gh-stats.com/github-readme-themes.html"/>
<link rel="icon" type="image/svg+xml" href="/favicon.svg"/>
<meta property="og:type" content="article"/>
<meta property="og:site_name" content="gh-stats"/>
<meta property="og:url" content="https://gh-stats.com/github-readme-themes.html"/>
<meta property="og:title" content="GitHub README stats card themes"/>
<meta property="og:description"
content="Five themes, a live preview of each, and dark/light auto-switching in one snippet."/>
<meta property="og:image" content="https://gh-stats.com/og.png"/>
<meta name="twitter:card" content="summary_large_image"/>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,wght@9..40,400..700&family=Instrument+Serif&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"/>
<script type="module">
// Same GA4 stream as the SPA (index.html), so this page's traffic and its
// referrers land in the existing property instead of going unmeasured.
import {initializeApp} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-app.js";
import {getAnalytics} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-analytics.js";
getAnalytics(initializeApp({
apiKey: "AIzaSyCy2pUW8Geo0Aagq9mTYKlfCpa9GUIXpy8",
authDomain: "gh-stats-284de.firebaseapp.com",
projectId: "gh-stats-284de",
storageBucket: "gh-stats-284de.firebasestorage.app",
messagingSenderId: "723662839762",
appId: "1:723662839762:web:4ba5337f6489ea67dc320b",
measurementId: "G-228GR89RYX"
}));
</script>
<style>
:root{
--bg:#f9fafb; --card:#ffffff; --line:#e5e7eb;
--ink:#1f2937; --muted:#6b7280; --faint:#9ca3af; --accent:#0969da;
}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--ink);
font-family:'DM Sans',system-ui,sans-serif;-webkit-font-smoothing:antialiased;
line-height:1.65}
main{max-width:760px;margin:0 auto;padding:56px 24px 96px}
h1{font-family:'Instrument Serif',Georgia,serif;font-weight:400;
font-size:2.6rem;line-height:1.15;letter-spacing:-.01em;margin:0 0 16px}
h2{font-family:'Instrument Serif',Georgia,serif;font-weight:400;
font-size:1.65rem;margin:48px 0 12px;letter-spacing:-.01em}
p{margin:0 0 16px}
.lede{font-size:1.08rem;color:var(--muted);margin-bottom:32px}
a{color:var(--accent);text-decoration:none}
a:hover{text-decoration:underline}
code,pre{font-family:'JetBrains Mono',ui-monospace,monospace;font-size:.86rem}
pre{background:var(--card);border:1px solid var(--line);border-radius:10px;
padding:14px 16px;overflow-x:auto;margin:0 0 16px}
code:not(pre code){background:#f3f4f6;border-radius:5px;padding:.12em .38em;font-size:.85em}
.tablewrap{overflow-x:auto;margin:0 0 16px}
table{border-collapse:collapse;width:100%;font-size:.86rem;background:var(--card);
border:1px solid var(--line);border-radius:10px}
th,td{text-align:left;padding:10px 14px;border-bottom:1px solid var(--line);
vertical-align:top}
th{font-weight:600;color:var(--muted);font-size:.78rem;text-transform:uppercase;
letter-spacing:.04em}
tr:last-child td{border-bottom:none}
td code{white-space:nowrap}
figure{margin:0 0 28px}
figure img{width:100%;max-width:400px;display:block;border-radius:12px}
figcaption{color:var(--faint);font-size:.8rem;margin-top:8px}
.clip{position:relative;max-width:340px;max-height:400px;overflow:hidden;
border-radius:12px}
.clip img{width:100%;display:block;border-radius:12px}
.clip::after{content:"";position:absolute;left:0;right:0;bottom:0;height:72px;
background:linear-gradient(to top,var(--bg),transparent)}
.cta{display:inline-block;background:var(--ink);color:#fff;border-radius:9px;
padding:11px 20px;font-weight:600;font-size:.92rem;margin:8px 0 0}
.cta:hover{text-decoration:none;opacity:.9}
.note{border-left:3px solid var(--line);padding:2px 0 2px 16px;color:var(--muted);
font-size:.92rem;margin:0 0 16px}
footer{border-top:1px solid var(--line);margin-top:64px;padding-top:20px;
color:var(--faint);font-size:.82rem}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:20px;margin:0 0 16px}
.grid .clip{max-height:300px}
.grid h3{font-size:1rem;margin:0 0 8px}
.grid pre{font-size:.72rem;margin-top:10px}
@media (max-width:640px){h1{font-size:2.05rem}main{padding:36px 20px 72px}}
</style>
</head>
<body>
<main>
<h1>Stats card themes for your GitHub profile README</h1>
<p class="lede">
A gh-stats card takes one <code>theme</code> parameter. Pick one of five, or serve a dark
card to dark-mode visitors and a light one to everyone else.
</p>
<h2>The five themes</h2>
<div class="grid">
<div>
<h3>midnight</h3>
<div class="clip"><img loading="lazy" src="https://gh-stats.com/api/ShayManor?theme=midnight" alt="gh-stats card in the midnight theme"/></div>
<p style="margin:8px 0 0;color:var(--muted);font-size:.86rem">Dark slate. The default look.</p>
<pre><code>?theme=midnight</code></pre>
</div>
<div>
<h3>onyx</h3>
<div class="clip"><img loading="lazy" src="https://gh-stats.com/api/ShayManor?theme=onyx" alt="gh-stats card in the onyx theme"/></div>
<p style="margin:8px 0 0;color:var(--muted);font-size:.86rem">High-contrast neon on pure black.</p>
<pre><code>?theme=onyx</code></pre>
</div>
<div>
<h3>nord</h3>
<div class="clip"><img loading="lazy" src="https://gh-stats.com/api/ShayManor?theme=nord" alt="gh-stats card in the nord theme"/></div>
<p style="margin:8px 0 0;color:var(--muted);font-size:.86rem">Muted pastels on slate blue.</p>
<pre><code>?theme=nord</code></pre>
</div>
<div>
<h3>clean</h3>
<div class="clip"><img loading="lazy" src="https://gh-stats.com/api/ShayManor?theme=clean" alt="gh-stats card in the clean theme"/></div>
<p style="margin:8px 0 0;color:var(--muted);font-size:.86rem">White, for light-mode profiles.</p>
<pre><code>?theme=clean</code></pre>
</div>
<div>
<h3>paper</h3>
<div class="clip"><img loading="lazy" src="https://gh-stats.com/api/ShayManor?theme=paper" alt="gh-stats card in the paper theme"/></div>
<p style="margin:8px 0 0;color:var(--muted);font-size:.86rem">Warm off-white.</p>
<pre><code>?theme=paper</code></pre>
</div>
</div>
<h2>Use a theme</h2>
<p>Add <code>?theme=</code> to the card URL in your README, replace the username, and commit:</p>
<pre><code>[![GitHub stats](https://gh-stats.com/api/YOUR_USERNAME?theme=nord)](https://gh-stats.com)</code></pre>
<p>Leave the parameter out and the card uses midnight.</p>
<h2>Switch with the viewer's GitHub theme</h2>
<p>
GitHub renders <code>&lt;picture&gt;</code> in READMEs and honours
<code>prefers-color-scheme</code>, so each visitor sees the card that matches their
GitHub appearance setting:
</p>
<pre><code>&lt;a href="https://gh-stats.com"&gt;
&lt;picture&gt;
&lt;source media="(prefers-color-scheme: dark)"
srcset="https://gh-stats.com/api/YOUR_USERNAME?theme=onyx"/&gt;
&lt;source media="(prefers-color-scheme: light)"
srcset="https://gh-stats.com/api/YOUR_USERNAME?theme=clean"/&gt;
&lt;img alt="GitHub stats" src="https://gh-stats.com/api/YOUR_USERNAME?theme=clean"/&gt;
&lt;/picture&gt;
&lt;/a&gt;</code></pre>
<p>Any dark theme works in the first line and any light one in the second.</p>
<a class="cta" href="https://gh-stats.com/">Preview every theme with your username</a>
<p style="margin-top:24px">
New to profile READMEs? Start with
<a href="https://gh-stats.com/github-profile-readme.html">how to create one</a>.
Coming from github-readme-stats? See the
<a href="https://gh-stats.com/github-readme-stats-alternative.html">migration guide</a>.
</p>
<h2>Common questions</h2>
<p>
<strong>Can I make a theme the default without the parameter?</strong> Yes. Sign in on
<a href="https://gh-stats.com/">gh-stats.com</a> with the GitHub account the card belongs
to, pick the theme, and save. <code>/api/YOUR_USERNAME</code> then uses it.
</p>
<p>
<strong>Does changing the theme reset my card?</strong> No. The theme changes colours
only; the data is the same.
</p>
<footer>
<a href="https://gh-stats.com/">gh-stats.com</a> &middot;
<a href="https://github.com/ShayManor/github-readme-stats">source on GitHub</a> &middot;
MIT licensed
</footer>
</main>
</body>
</html>
@@ -0,0 +1,188 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>GitHub top languages card for your profile README</title>
<meta name="description"
content="Add a most-used-languages card to your GitHub profile README with one line of markdown. Hide languages you do not want counted, pick a theme, no signup. Drop-in for github-readme-stats top-langs URLs."/>
<link rel="canonical" href="https://gh-stats.com/github-top-languages-card.html"/>
<link rel="icon" type="image/svg+xml" href="/favicon.svg"/>
<meta property="og:type" content="article"/>
<meta property="og:site_name" content="gh-stats"/>
<meta property="og:url" content="https://gh-stats.com/github-top-languages-card.html"/>
<meta property="og:title" content="GitHub top languages card for your profile README"/>
<meta property="og:description"
content="One line of markdown, a theme, and a list of languages to hide."/>
<meta property="og:image" content="https://gh-stats.com/og.png"/>
<meta name="twitter:card" content="summary_large_image"/>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,wght@9..40,400..700&family=Instrument+Serif&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"/>
<script type="module">
// Same GA4 stream as the SPA (index.html), so this page's traffic and its
// referrers land in the existing property instead of going unmeasured.
import {initializeApp} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-app.js";
import {getAnalytics} from "https://www.gstatic.com/firebasejs/12.13.0/firebase-analytics.js";
getAnalytics(initializeApp({
apiKey: "AIzaSyCy2pUW8Geo0Aagq9mTYKlfCpa9GUIXpy8",
authDomain: "gh-stats-284de.firebaseapp.com",
projectId: "gh-stats-284de",
storageBucket: "gh-stats-284de.firebasestorage.app",
messagingSenderId: "723662839762",
appId: "1:723662839762:web:4ba5337f6489ea67dc320b",
measurementId: "G-228GR89RYX"
}));
</script>
<style>
:root{
--bg:#f9fafb; --card:#ffffff; --line:#e5e7eb;
--ink:#1f2937; --muted:#6b7280; --faint:#9ca3af; --accent:#0969da;
}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--ink);
font-family:'DM Sans',system-ui,sans-serif;-webkit-font-smoothing:antialiased;
line-height:1.65}
main{max-width:760px;margin:0 auto;padding:56px 24px 96px}
h1{font-family:'Instrument Serif',Georgia,serif;font-weight:400;
font-size:2.6rem;line-height:1.15;letter-spacing:-.01em;margin:0 0 16px}
h2{font-family:'Instrument Serif',Georgia,serif;font-weight:400;
font-size:1.65rem;margin:48px 0 12px;letter-spacing:-.01em}
p{margin:0 0 16px}
.lede{font-size:1.08rem;color:var(--muted);margin-bottom:32px}
a{color:var(--accent);text-decoration:none}
a:hover{text-decoration:underline}
code,pre{font-family:'JetBrains Mono',ui-monospace,monospace;font-size:.86rem}
pre{background:var(--card);border:1px solid var(--line);border-radius:10px;
padding:14px 16px;overflow-x:auto;margin:0 0 16px}
code:not(pre code){background:#f3f4f6;border-radius:5px;padding:.12em .38em;font-size:.85em}
.tablewrap{overflow-x:auto;margin:0 0 16px}
table{border-collapse:collapse;width:100%;font-size:.86rem;background:var(--card);
border:1px solid var(--line);border-radius:10px}
th,td{text-align:left;padding:10px 14px;border-bottom:1px solid var(--line);
vertical-align:top}
th{font-weight:600;color:var(--muted);font-size:.78rem;text-transform:uppercase;
letter-spacing:.04em}
tr:last-child td{border-bottom:none}
td code{white-space:nowrap}
figure{margin:0 0 28px}
figure img{width:100%;max-width:400px;display:block;border-radius:12px}
figcaption{color:var(--faint);font-size:.8rem;margin-top:8px}
.clip{position:relative;max-width:340px;max-height:400px;overflow:hidden;
border-radius:12px}
.clip img{width:100%;display:block;border-radius:12px}
.clip::after{content:"";position:absolute;left:0;right:0;bottom:0;height:72px;
background:linear-gradient(to top,var(--bg),transparent)}
.cta{display:inline-block;background:var(--ink);color:#fff;border-radius:9px;
padding:11px 20px;font-weight:600;font-size:.92rem;margin:8px 0 0}
.cta:hover{text-decoration:none;opacity:.9}
.note{border-left:3px solid var(--line);padding:2px 0 2px 16px;color:var(--muted);
font-size:.92rem;margin:0 0 16px}
footer{border-top:1px solid var(--line);margin-top:64px;padding-top:20px;
color:var(--faint);font-size:.82rem}
@media (max-width:640px){h1{font-size:2.05rem}main{padding:36px 20px 72px}}
</style>
</head>
<body>
<main>
<h1>A top languages card for your GitHub profile README</h1>
<p class="lede">
The languages card shows which languages your public repositories are written in,
as a donut and a ranked legend. It is one image, served from one URL, and it stays
current without a GitHub Action or a token.
</p>
<figure>
<img src="https://gh-stats.com/api/ShayManor?widgets=languages" alt="A gh-stats top languages card: a donut chart with Python, Go, Jupyter Notebook, JavaScript and TypeScript, each with a percentage."/>
<figcaption>The languages card for one profile.</figcaption>
</figure>
<h2>Add it to your README</h2>
<p>Paste this into your profile README and replace the username:</p>
<pre><code>![Top languages](https://gh-stats.com/api/YOUR_USERNAME?widgets=languages)</code></pre>
<p>
The first request for a new username queues a build, so the card can take a minute
to fill in. After that it is served from cache and refreshed in the background.
</p>
<a class="cta" href="https://gh-stats.com/">Preview it on your username</a>
<h2>Hide languages and pick a theme</h2>
<p>
Notebooks, generated HTML and vendored code often dominate a languages chart.
List what to leave out in <code>hide</code>, comma-separated, and choose a look
with <code>theme</code>:
</p>
<pre><code>![Top languages](https://gh-stats.com/api/YOUR_USERNAME?widgets=languages&amp;hide=Jupyter%20Notebook,HTML&amp;theme=nord)</code></pre>
<div class="tablewrap">
<table>
<tr><th>Parameter</th><th>What it does</th></tr>
<tr><td><code>hide</code></td>
<td>Languages to exclude, comma-separated. Use <code>%20</code> for spaces.</td></tr>
<tr><td><code>theme</code></td>
<td><code>clean</code>, <code>midnight</code>, <code>nord</code>, <code>onyx</code> or <code>paper</code>.</td></tr>
</table>
</div>
<h2>Coming from github-readme-stats</h2>
<p>
If your README already has a <code>top-langs</code> card from
<code>github-readme-stats.vercel.app</code>, change only the domain:
</p>
<div class="tablewrap">
<table>
<tr><th>Your current URL</th><th>Change it to</th></tr>
<tr><td><code>github-readme-stats.vercel.app/api/top-langs?username=U</code></td>
<td><code>gh-stats.com/api/top-langs?username=U</code></td></tr>
</table>
</div>
<p class="note">
The compatibility URL ignores the original styling parameters (<code>layout</code>,
<code>langs_count</code>, colours) and serves the default card. Use the
<code>?widgets=languages</code> form above for <code>hide</code> and <code>theme</code>.
</p>
<p>
The full migration guide covers the stats and streak cards too:
<a href="https://gh-stats.com/github-readme-stats-alternative.html">github-readme-stats alternative</a>.
</p>
<h2>Common questions</h2>
<p>
<strong>How are percentages worked out?</strong> From the byte counts GitHub reports
for each public repository you authored, summed across those repositories. Forks are
left out. A large repository in one language weighs more than several small ones.
</p>
<p>
<strong>Are private repositories counted?</strong> No. Only public activity is
visible to the fetcher.
</p>
<p>
<strong>Can I show it alongside other stats?</strong> Yes. Drop the
<code>?widgets=languages</code> part and the same URL serves the full profile card:
score, contribution timeline, collaborators, languages and streaks in one image.
</p>
<footer>
<a href="https://gh-stats.com/">gh-stats.com</a> &middot;
<a href="https://github.com/ShayManor/github-readme-stats">source on GitHub</a> &middot;
MIT licensed
</footer>
</main>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

+3
View File
@@ -0,0 +1,3 @@
User-agent: *
Allow: /
Sitemap: https://gh-stats.com/sitemap.xml
+38
View File
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://gh-stats.com/</loc>
<changefreq>weekly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>https://gh-stats.com/github-readme-stats-alternative.html</loc>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://gh-stats.com/github-top-languages-card.html</loc>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://gh-stats.com/github-profile-readme.html</loc>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://gh-stats.com/github-readme-themes.html</loc>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://gh-stats.com/github-readme-activity-graph-alternative.html</loc>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://gh-stats.com/github-profile-trophy-alternative.html</loc>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
</urlset>
+265 -50
View File
@@ -3,10 +3,12 @@ import './index.css'
import { SearchScreen } from './screens/SearchScreen' import { SearchScreen } from './screens/SearchScreen'
import { WorkshopScreen } from './screens/WorkshopScreen' import { WorkshopScreen } from './screens/WorkshopScreen'
import { ResultScreen } from './screens/ResultScreen' import { ResultScreen } from './screens/ResultScreen'
import { DevScreen } from './screens/DevScreen'
import { AuthButton } from './components/AuthButton' import { AuthButton } from './components/AuthButton'
import type { WidgetData } from './lib/renderWidgets' import type { WidgetData } from './lib/renderWidgets'
import { DEMO_WIDGET_DATA } from './lib/demoData' import { DEMO_WIDGET_DATA } from './lib/demoData'
import { fetchMe, type Me } from './lib/auth' import { fetchMe, type Me } from './lib/auth'
import { buildEmbedUrl } from './lib/settingsQuery'
export type Achievement = { export type Achievement = {
title: string title: string
@@ -18,6 +20,7 @@ export type Achievement = {
export type PerWidgetSettings = { export type PerWidgetSettings = {
grade?: { max_tags?: number } grade?: { max_tags?: number }
impact?: { line_color?: string } impact?: { line_color?: string }
streaks?: { color?: string }
collaborators?: { max_count?: number; bar_color?: string } collaborators?: { max_count?: number; bar_color?: string }
focus?: { max_categories?: number } focus?: { max_categories?: number }
languages?: { max_languages?: number } languages?: { max_languages?: number }
@@ -27,6 +30,7 @@ export type PerWidgetSettings = {
export type WidgetSettings = { export type WidgetSettings = {
theme: string theme: string
widgets: string[] widgets: string[]
widgetOrder: string[]
impactPeriod: string impactPeriod: string
customTags: string[] customTags: string[]
hiddenLanguages: string[] hiddenLanguages: string[]
@@ -36,7 +40,8 @@ export type WidgetSettings = {
const DEFAULT_SETTINGS: WidgetSettings = { const DEFAULT_SETTINGS: WidgetSettings = {
theme: 'midnight', theme: 'midnight',
widgets: ['grade', 'impact', 'collaborators', 'focus', 'languages'], widgets: ['name', 'grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages'],
widgetOrder: ['name', 'grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages', 'achievements'],
impactPeriod: '6mo', impactPeriod: '6mo',
customTags: [], customTags: [],
hiddenLanguages: [], hiddenLanguages: [],
@@ -46,14 +51,55 @@ const DEFAULT_SETTINGS: WidgetSettings = {
type Step = 'search' | 'workshop' | 'result' type Step = 'search' | 'workshop' | 'result'
// Signing in navigates the whole tab through GitHub's OAuth flow, and the
// SPA keeps username + settings only in React state, so without this the
// user comes back to an empty search box with their edits gone.
// sessionStorage survives the round trip within the tab.
const RESUME_KEY = 'gh-stats:in-progress'
type Resume = { username: string; settings: WidgetSettings }
function loadResume(): Resume | null {
try {
const raw = sessionStorage.getItem(RESUME_KEY)
if (!raw) return null
const parsed = JSON.parse(raw) as Partial<Resume> | null
if (!parsed || typeof parsed.username !== 'string' || !parsed.username) return null
if (!parsed.settings || typeof parsed.settings !== 'object') return null
return { username: parsed.username, settings: { ...DEFAULT_SETTINGS, ...parsed.settings } }
} catch {
return null
}
}
const POLL_INTERVAL_MS = 2000 const POLL_INTERVAL_MS = 2000
const POLL_TIMEOUT_MS = 120_000 const POLL_TIMEOUT_MS = 120_000
// ResultScreen poll: a bit slower than the workshop poll because each tick
// re-fetches the full SVG, not a small JSON. 3s spacing is responsive
// enough to feel near-instant when the widget lands.
const RESULT_POLL_INTERVAL_MS = 3000
// Give up after 3 minutes — long enough to cover even worst-case
// first-time GitHub fetches; past that the user can hit "Check now".
const RESULT_POLL_TIMEOUT_MS = 180_000
type WidgetStatus = 'ready' | 'building' | 'not_found' | 'rate_limited'
function readWidgetStatus(r: Response): WidgetStatus {
const raw = r.headers.get('X-Widget-Status')
if (raw === 'building' || raw === 'not_found' || raw === 'rate_limited') return raw
return 'ready'
}
export default function App() { export default function App() {
if (typeof window !== 'undefined' && window.location.pathname === '/dev') {
return <DevScreen />
}
const [me, setMe] = useState<Me>({ login: null }) const [me, setMe] = useState<Me>({ login: null })
const [step, setStep] = useState<Step>('search') // Work in progress left behind by a sign-in redirect, if any.
const [username, setUsername] = useState('') const [resumed] = useState(loadResume)
const [settings, setSettings] = useState<WidgetSettings>({ ...DEFAULT_SETTINGS }) const [step, setStep] = useState<Step>(resumed ? 'workshop' : 'search')
const [username, setUsername] = useState(resumed?.username ?? '')
const [settings, setSettings] = useState<WidgetSettings>(resumed?.settings ?? { ...DEFAULT_SETTINGS })
const [widgetData, setWidgetData] = useState<WidgetData | null>(null) const [widgetData, setWidgetData] = useState<WidgetData | null>(null)
const [fetchDone, setFetchDone] = useState(false) const [fetchDone, setFetchDone] = useState(false)
const [fetchError, setFetchError] = useState<string | null>(null) const [fetchError, setFetchError] = useState<string | null>(null)
@@ -62,9 +108,21 @@ export default function App() {
const [generatedSvg, setGeneratedSvg] = useState<string | null>(null) const [generatedSvg, setGeneratedSvg] = useState<string | null>(null)
const [generateError, setGenerateError] = useState<string | null>(null) const [generateError, setGenerateError] = useState<string | null>(null)
const [generating, setGenerating] = useState(false) const [generating, setGenerating] = useState(false)
// The URL we actually fetched for the preview — also the one we show as
// the embed snippet. For owners this is /api/<u> (backed by stored
// settings). For visitors it's /api/<u>?<query>, which round-trips their
// Workshop edits without touching the owner's saved widget.
const [embedUrl, setEmbedUrl] = useState<string>('')
// 'ready' once the backend has actually rendered the user's widget; until
// then the SVG returned by /api/<u> is the "Building @user's widget…"
// placeholder. We poll on this so the page upgrades itself from
// placeholder to real widget without the user having to refresh.
const [widgetStatus, setWidgetStatus] = useState<'ready' | 'building' | 'not_found' | 'rate_limited'>('ready')
const pollTimer = useRef<number | null>(null) const pollTimer = useRef<number | null>(null)
const pollStart = useRef<number>(0) const pollStart = useRef<number>(0)
const aborted = useRef(false) const aborted = useRef(false)
const resultPollTimer = useRef<number | null>(null)
const resultPollStart = useRef<number>(0)
const stopPolling = useCallback(() => { const stopPolling = useCallback(() => {
if (pollTimer.current != null) { if (pollTimer.current != null) {
@@ -73,10 +131,57 @@ export default function App() {
} }
}, []) }, [])
const stopResultPolling = useCallback(() => {
if (resultPollTimer.current != null) {
window.clearTimeout(resultPollTimer.current)
resultPollTimer.current = null
}
}, [])
// Pull and re-render the embed SVG once. Used both by the auto-poll loop
// (when the first /api/<u> returned a building placeholder) and by the
// manual "Check now" button on ResultScreen.
const refetchEmbed = useCallback(async () => {
if (!embedUrl) return
try {
const r = await fetch(`${embedUrl}${embedUrl.includes('?') ? '&' : '?'}t=${Date.now()}`)
if (!r.ok) return
const status = readWidgetStatus(r)
const text = await r.text()
setGeneratedSvg(text)
setWidgetStatus(status)
} catch {
/* transient — let the next poll tick try again */
}
}, [embedUrl])
useEffect(() => stopPolling, [stopPolling]) useEffect(() => stopPolling, [stopPolling])
useEffect(() => stopResultPolling, [stopResultPolling])
useEffect(() => { fetchMe().then(setMe) }, []) useEffect(() => { fetchMe().then(setMe) }, [])
const startFetch = useCallback((user: string) => { // Result-screen auto-refresh. Backend serves a "Building @user's widget…"
// placeholder SVG (with header X-Widget-Status: building) until the
// worker finishes the first build. Without this loop the user would
// stare at the placeholder until they manually reloaded.
useEffect(() => {
if (step !== 'result' || widgetStatus !== 'building' || !embedUrl) return
resultPollStart.current = Date.now()
const tick = async () => {
await refetchEmbed()
if (Date.now() - resultPollStart.current > RESULT_POLL_TIMEOUT_MS) {
stopResultPolling()
return
}
resultPollTimer.current = window.setTimeout(tick, RESULT_POLL_INTERVAL_MS)
}
resultPollTimer.current = window.setTimeout(tick, RESULT_POLL_INTERVAL_MS)
return stopResultPolling
}, [step, widgetStatus, embedUrl, refetchEmbed, stopResultPolling])
// `keepSettings` is set when resuming after a sign-in redirect: the
// settings already on screen are the user's own unsaved edits, so neither
// the reset nor the server hydration below may overwrite them.
const startFetch = useCallback((user: string, keepSettings = false) => {
stopPolling() stopPolling()
aborted.current = false aborted.current = false
pollStart.current = Date.now() pollStart.current = Date.now()
@@ -84,6 +189,49 @@ export default function App() {
setFetchError(null) setFetchError(null)
// Show demo data immediately so Workshop is interactive while the worker builds. // Show demo data immediately so Workshop is interactive while the worker builds.
setWidgetData(DEMO_WIDGET_DATA) setWidgetData(DEMO_WIDGET_DATA)
// Reset to defaults first so the form doesn't briefly show the previous
// user's settings while we fetch this user's saved blob.
if (!keepSettings) setSettings({ ...DEFAULT_SETTINGS })
// Hydrate the Workshop form from the user's persisted settings.
// Backend stores snake_case keys; we map them onto the camelCase
// state shape here. 404 (not enrolled yet) is expected — keep defaults.
if (!keepSettings) void (async () => {
try {
const r = await fetch(`/api/${encodeURIComponent(user)}/settings`, {
credentials: 'include',
})
if (aborted.current) return
if (!r.ok) return
const body = await r.json().catch(() => null) as { settings?: Record<string, unknown> } | null
const s = body?.settings
if (!s || typeof s !== 'object') return
setSettings(prev => {
const next: WidgetSettings = { ...prev }
if (typeof s.theme === 'string') next.theme = s.theme
if (Array.isArray(s.enabled)) next.widgets = s.enabled.filter(x => typeof x === 'string') as string[]
if (Array.isArray(s.widget_order)) next.widgetOrder = s.widget_order.filter(x => typeof x === 'string') as string[]
if (Array.isArray(s.custom_tags)) next.customTags = s.custom_tags.filter(x => typeof x === 'string') as string[]
if (Array.isArray(s.hidden_languages)) next.hiddenLanguages = s.hidden_languages.filter(x => typeof x === 'string') as string[]
if (s.widget_settings && typeof s.widget_settings === 'object') {
next.widgetSettings = s.widget_settings as PerWidgetSettings
}
if (Array.isArray(s.achievements)) {
next.achievements = s.achievements
.filter((a): a is Record<string, unknown> => !!a && typeof a === 'object')
.map(a => ({
title: typeof a.title === 'string' ? a.title : '',
subtitle: typeof a.subtitle === 'string' ? a.subtitle : '',
event_date: typeof a.event_date === 'string' ? a.event_date : '',
icon: typeof a.icon === 'string' ? a.icon : 'trophy',
}))
}
return next
})
} catch (e) {
if (!aborted.current) console.warn('Settings load failed:', e)
}
})()
const poll = async () => { const poll = async () => {
if (aborted.current) return if (aborted.current) return
@@ -100,13 +248,23 @@ export default function App() {
setFetchDone(true) setFetchDone(true)
return return
} }
if (r.status === 404 || status === 'not_found') { if (status === 'not_found') {
// Fetcher confirmed the user doesn't exist on GitHub.
setFetchError('User not found') setFetchError('User not found')
setFetchDone(true) setFetchDone(true)
return return
} }
if (r.status === 404) {
// 404 without status==='not_found' means the user simply isn't
// enrolled yet (no settings row). Keep the demo data on screen
// and stop polling — no error to display.
setFetchDone(true)
return
}
if (r.status === 429 || status === 'rate_limited') { if (r.status === 429 || status === 'rate_limited') {
setFetchError('Enrollment limit reached — try again tomorrow') setFetchError((body as { cap?: string }).cap === 'daily'
? 'Enrollment limit reached — try again tomorrow'
: 'Enrollment limit reached — try again in an hour')
setFetchDone(true) setFetchDone(true)
return return
} }
@@ -128,6 +286,24 @@ export default function App() {
poll() poll()
}, [stopPolling]) }, [stopPolling])
// Keep the in-progress username and settings recoverable across the
// sign-in redirect (and a plain reload). Cleared once the user is back
// on the search screen, so a fresh visit starts fresh.
useEffect(() => {
try {
if (step === 'search' || !username) sessionStorage.removeItem(RESUME_KEY)
else sessionStorage.setItem(RESUME_KEY, JSON.stringify({ username, settings }))
} catch {
/* private mode or quota: resuming is a nicety, not a requirement */
}
}, [step, username, settings])
// Restore: the widget data itself is not persisted, so re-fetch it for
// the username we came back to.
useEffect(() => {
if (resumed) startFetch(resumed.username, true)
}, [resumed, startFetch])
const handleSearch = (user: string) => { const handleSearch = (user: string) => {
setUsername(user) setUsername(user)
startFetch(user) startFetch(user)
@@ -139,52 +315,86 @@ export default function App() {
setGenerating(true) setGenerating(true)
setGeneratedSvg(null) setGeneratedSvg(null)
setGenerateError(null) setGenerateError(null)
setWidgetStatus('ready')
const isOwner = !!me.login && me.login.toLowerCase() === username.toLowerCase()
try { try {
// Push the user's Workshop choices to the backend BEFORE rendering. if (isOwner) {
// The backend's /generate endpoint re-reads settings from SQLite and // Owner path: persist settings, then force a server-side render
// renders with them, so without this PATCH the SVG would reflect // against the stored payload. The resulting /api/<u> is the embed.
// whatever was last persisted (usually the enroll-time defaults) const backendSettings = {
// rather than the user's current selections. theme: settings.theme,
const backendSettings = { enabled: settings.widgets,
theme: settings.theme, widget_order: settings.widgetOrder,
enabled: settings.widgets, custom_tags: settings.customTags,
custom_tags: settings.customTags, hidden_languages: settings.hiddenLanguages,
hidden_languages: settings.hiddenLanguages, widget_settings: settings.widgetSettings,
widget_settings: settings.widgetSettings, achievements: settings.achievements.filter(a => a.title.trim()),
achievements: settings.achievements.filter(a => a.title.trim()), }
} const patchRes = await fetch(`/api/${encodeURIComponent(username)}/settings`, {
const patchRes = await fetch(`/api/${encodeURIComponent(username)}/settings`, { method: 'PATCH',
method: 'PATCH', credentials: 'include',
credentials: 'include', headers: { 'Content-Type': 'application/json' },
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(backendSettings),
body: JSON.stringify(backendSettings), })
}) if (!patchRes.ok && patchRes.status !== 404) {
if (!patchRes.ok && patchRes.status !== 404) { setGenerateError(`Settings sync failed (HTTP ${patchRes.status})`)
setGenerateError(`Settings sync failed (HTTP ${patchRes.status})`) return
return }
}
const r = await fetch(`/api/${encodeURIComponent(username)}/generate`, { const r = await fetch(`/api/${encodeURIComponent(username)}/generate`, {
method: 'POST', method: 'POST',
credentials: 'include', credentials: 'include',
}) })
if (r.status === 404) { if (r.status === 404) {
const body = await r.json().catch(() => ({} as { status?: string })) const body = await r.json().catch(() => ({} as { status?: string }))
setGenerateError(body.status === 'not_found' ? 'User not found' : 'Not enrolled') setGenerateError(body.status === 'not_found' ? 'User not found' : 'Not enrolled')
return return
}
if (r.status === 503) {
const body = await r.json().catch(() => ({} as { error?: string }))
if (body.error === 'github_rate_limited') {
setGenerateError("GitHub's API limit is reached for now. Your card builds automatically once it resets (within the hour), and you can paste the embed now.")
return
}
}
if (!r.ok) {
setGenerateError(`Generate failed (HTTP ${r.status})`)
return
}
const cleanUrl = `${window.location.origin}/api/${encodeURIComponent(username)}`
// Cache-bust so regenerate after settings change shows the new
// version, not a stale browser copy. The cache-busting `t` param
// is not read server-side (not in the allow-list) so the render
// stays cacheable at the edge.
const svgRes = await fetch(`${cleanUrl}?t=${Date.now()}`)
if (!svgRes.ok) {
setGenerateError(`SVG fetch failed (HTTP ${svgRes.status})`)
return
}
setGeneratedSvg(await svgRes.text())
setEmbedUrl(cleanUrl)
setWidgetStatus(readWidgetStatus(svgRes))
} else {
// Visitor path: encode Workshop edits into a query string and hit
// the same URL we'll hand the user for their README. No owner
// settings are written. The backend renders ad-hoc against the
// fetcher's cached payload for this user.
const url = buildEmbedUrl(window.location.origin, username, settings)
// Same cache-bust trick — unknown query params are ignored by the
// sanitizer, so this doesn't alter the rendered output.
const svgRes = await fetch(`${url}${url.includes('?') ? '&' : '?'}t=${Date.now()}`)
if (svgRes.status === 404) {
setGenerateError('User not enrolled — ask them to sign in and generate first')
return
}
if (!svgRes.ok) {
setGenerateError(`SVG fetch failed (HTTP ${svgRes.status})`)
return
}
setGeneratedSvg(await svgRes.text())
setEmbedUrl(url)
setWidgetStatus(readWidgetStatus(svgRes))
} }
if (!r.ok) {
setGenerateError(`Generate failed (HTTP ${r.status})`)
return
}
// Fetch the backend-rendered composite SVG. Cache-bust so regenerate
// after settings change shows the new version, not a stale browser copy.
const svgRes = await fetch(`/api/${encodeURIComponent(username)}?t=${Date.now()}`)
if (!svgRes.ok) {
setGenerateError(`SVG fetch failed (HTTP ${svgRes.status})`)
return
}
setGeneratedSvg(await svgRes.text())
} catch (e) { } catch (e) {
console.warn('generate call failed:', e) console.warn('generate call failed:', e)
setGenerateError('Network error') setGenerateError('Network error')
@@ -220,6 +430,7 @@ export default function App() {
fetchDone={fetchDone} fetchDone={fetchDone}
fetchError={fetchError} fetchError={fetchError}
widgetData={widgetData} widgetData={widgetData}
isDemoData={widgetData === DEMO_WIDGET_DATA}
me={me} me={me}
onAuthChange={setMe} onAuthChange={setMe}
/> />
@@ -230,7 +441,11 @@ export default function App() {
generating={generating} generating={generating}
generatedSvg={generatedSvg} generatedSvg={generatedSvg}
generateError={generateError} generateError={generateError}
embedUrl={embedUrl}
widgetStatus={widgetStatus}
onBack={handleBack} onBack={handleBack}
onRegenerate={handleGenerate}
onRefresh={refetchEmbed}
/> />
)} )}
</div> </div>
@@ -0,0 +1,163 @@
import { useEffect, useState } from 'react'
import { fetchGrowth, type Growth } from '../lib/dev'
type Mode = 'daily' | 'weekly'
export function GrowthChart() {
const [data, setData] = useState<Growth | null>(null)
const [mode, setMode] = useState<Mode>('daily')
useEffect(() => { fetchGrowth().then(setData).catch(() => {}) }, [])
// Trim leading empty buckets so the chart starts at the first day/week
// with traffic instead of e.g. four weeks of zeros from before the
// service went live.
const rawPoints = data ? (mode === 'daily' ? data.daily : data.weekly) : []
const firstActive = rawPoints.findIndex(p => p.requests > 0 || p.users > 0)
const points = firstActive >= 0 ? rawPoints.slice(firstActive) : []
const labels = points.map(p => 'day' in p ? p.day : p.week)
const requests = points.map(p => p.requests)
const users = points.map(p => p.users)
return (
<div className="rounded-lg border border-white/10 bg-white/[0.02] p-4">
<div className="mb-3 flex items-center justify-between">
<div className="text-sm text-white/70">Growth</div>
<div className="flex gap-1 text-xs">
<Tab active={mode === 'daily'} onClick={() => setMode('daily')}>day · 30</Tab>
<Tab active={mode === 'weekly'} onClick={() => setMode('weekly')}>week · 12</Tab>
</div>
</div>
{!data ? (
<div className="text-xs text-white/40">loading…</div>
) : points.length === 0 ? (
<div className="text-xs text-white/40">no traffic yet</div>
) : (
<div className="space-y-4">
<Line label="Requests" values={requests} labels={labels} mode={mode} stroke="#60a5fa" />
<Line label="Unique users" values={users} labels={labels} mode={mode} stroke="#a78bfa" />
</div>
)}
</div>
)
}
function Tab({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {
return (
<button
onClick={onClick}
className={`rounded px-2 py-0.5 font-mono transition ${
active ? 'bg-white/10 text-white' : 'text-white/40 hover:text-white/70'
}`}
>
{children}
</button>
)
}
function Line({ label, values, labels, mode, stroke }: {
label: string; values: number[]; labels: string[]; mode: Mode; stroke: string
}) {
const width = 600
const height = 70
const vbH = height + 10 // viewBox height; bottom 10 holds the x-tick marks
const max = Math.max(1, ...values)
const n = values.length
const stepX = n > 1 ? width / (n - 1) : 0
const total = values.reduce((a, b) => a + b, 0)
const latest = values[n - 1] ?? 0
// Map a value to its y coordinate in viewBox space; reused for both the
// line points and the y-axis label positions so they stay aligned.
const yFor = (v: number) => height - (v / max) * (height - 4) - 2
const xy = values.map((v, i) => ({ x: n > 1 ? i * stepX : width / 2, y: yFor(v) }))
const pts = xy.map(p => `${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(' ')
// Sealed area polygon: only valid when we have a real line (n >= 2).
const area = n > 1 ? `0,${height} ${pts} ${width},${height}` : ''
const ticks = pickTicks(labels, Math.min(6, n))
// y-axis labels: top (max), middle, baseline (0). Percent positions are
// relative to the same viewBox the chart is drawn in.
const yMarks = max > 1
? [max, Math.round(max / 2), 0]
: [max, 0]
return (
<div>
<div className="mb-1 flex items-baseline justify-between text-xs">
<span className="text-white/60">{label}</span>
<span className="font-mono tabular-nums text-white/40">
latest <span className="text-white/80">{latest.toLocaleString()}</span>
<span className="ml-3">total <span className="text-white/80">{total.toLocaleString()}</span></span>
</span>
</div>
<div className="flex gap-1.5">
{/* y-axis */}
<div className="relative w-7 shrink-0" style={{ height: vbH }}>
{yMarks.map(v => (
<span key={v}
className="absolute right-0 -translate-y-1/2 font-mono text-[10px] tabular-nums text-white/35"
style={{ top: `${(yFor(v) / vbH) * 100}%` }}>
{fmtCompact(v)}
</span>
))}
</div>
{/* plot + x-axis */}
<div className="min-w-0 flex-1">
<svg viewBox={`0 0 ${width} ${vbH}`} className="w-full" style={{ height: vbH }} preserveAspectRatio="none">
{area && <polyline points={area} fill={stroke} fillOpacity="0.08" stroke="none" />}
{n > 1 && (
<polyline points={pts} fill="none" stroke={stroke} strokeWidth={1.5}
strokeLinecap="round" strokeLinejoin="round"
vectorEffect="non-scaling-stroke" />
)}
{n === 1 && (
<circle cx={xy[0].x} cy={xy[0].y} r={3} fill={stroke} />
)}
{ticks.map(t => {
const x = n > 1 ? t.idx * stepX : width / 2
return (
<line key={`tick-${t.idx}`} x1={x} x2={x} y1={height} y2={height + 3}
stroke="rgb(255 255 255 / 0.15)" strokeWidth={1}
vectorEffect="non-scaling-stroke" />
)
})}
</svg>
<div className="relative mt-1 h-3">
{ticks.map(t => (
<span key={`label-${t.idx}`}
className="absolute -translate-x-1/2 whitespace-nowrap font-mono text-[10px] text-white/40"
style={{ left: n > 1 ? `${(t.idx / (n - 1)) * 100}%` : '50%' }}>
{formatTick(t.label, mode)}
</span>
))}
</div>
</div>
</div>
</div>
)
}
function fmtCompact(n: number): string {
if (n >= 10000) return `${Math.round(n / 1000)}k`
if (n >= 1000) return `${(n / 1000).toFixed(1)}k`
return String(Math.round(n))
}
function pickTicks(labels: string[], n: number): { idx: number; label: string }[] {
if (labels.length === 0 || n <= 0) return []
if (labels.length <= n) return labels.map((label, idx) => ({ idx, label }))
const out: { idx: number; label: string }[] = []
for (let i = 0; i < n; i++) {
const idx = Math.round((i * (labels.length - 1)) / (n - 1))
out.push({ idx, label: labels[idx] })
}
return out
}
function formatTick(label: string, mode: Mode): string {
if (mode === 'daily') {
// "2026-05-27" -> "05-27"
return label.length >= 10 ? label.slice(5) : label
}
// "2026-W21" -> "W21"
const parts = label.split('-')
return parts[1] || label
}
@@ -0,0 +1,30 @@
import { useEffect, useState } from 'react'
import { fetchHealth, type Health } from '../lib/dev'
export function HealthStrip() {
const [h, setH] = useState<Health | null>(null)
useEffect(() => { fetchHealth().then(setH).catch(() => {}) }, [])
if (!h) return null
const pct = (n: number) => `${(n * 100).toFixed(1)}%`
return (
<div className="rounded-lg border border-white/10 bg-white/[0.02] p-4">
<div className="mb-3 text-sm text-white/70">Health</div>
<div className="grid grid-cols-3 gap-3 text-center">
<Pill label="Edge cache hit" value={pct(h.edge_cache_hit_rate)} />
<Pill label="Fetch error" value={pct(h.fetcher_error_rate)} tone={h.fetcher_error_rate > 0.05 ? 'warn' : 'ok'} />
<Pill label="Events dropped 24h" value={h.events_dropped_24h.toLocaleString()}
tone={h.events_dropped_24h > 0 ? 'warn' : 'ok'} />
</div>
</div>
)
}
function Pill({ label, value, tone = 'ok' }: { label: string; value: string; tone?: 'ok' | 'warn' }) {
const color = tone === 'warn' ? 'text-amber-400' : 'text-emerald-400'
return (
<div className="rounded bg-white/[0.03] px-2 py-2">
<div className="text-xs text-white/40">{label}</div>
<div className={`mt-1 font-mono text-lg ${color}`}>{value}</div>
</div>
)
}
@@ -0,0 +1,34 @@
import { useEffect, useState } from 'react'
import { fetchLatency, type LatencyRow } from '../lib/dev'
export function LatencyChart() {
const [rows, setRows] = useState<LatencyRow[]>([])
useEffect(() => { fetchLatency().then(setRows).catch(() => {}) }, [])
const max = Math.max(1, ...rows.map(r => r.p95))
return (
<div className="rounded-lg border border-white/10 bg-white/[0.02] p-4">
<div className="mb-3 text-sm text-white/70">Latency by endpoint</div>
{rows.length === 0 && <div className="text-xs text-white/40">no traffic yet</div>}
<div className="space-y-1.5">
{rows.map(r => (
<div key={r.endpoint} className="grid grid-cols-[1fr_auto] items-center gap-3 font-mono text-xs">
<div>
<div className="text-white/70">{r.endpoint}</div>
<div className="mt-1 h-1.5 w-full overflow-hidden rounded bg-white/[0.04]">
<div className="h-full bg-sky-400/60" style={{ width: `${(r.p50 / max) * 100}%` }} />
<div className="-mt-1.5 h-1.5 bg-sky-300/30" style={{ width: `${(r.p95 / max) * 100}%` }} />
</div>
</div>
<div className="text-right text-white/80 tabular-nums">
<span>{r.p50}</span><span className="text-white/30"> · </span>
<span>{r.p95}</span><span className="text-white/30"> · </span>
<span>{r.p99}ms</span>
</div>
</div>
))}
</div>
</div>
)
}
@@ -0,0 +1,17 @@
type Props = { values: number[]; width?: number; height?: number; stroke?: string }
export function Sparkline({ values, width = 140, height = 32, stroke = '#60a5fa' }: Props) {
if (values.length === 0) return <svg width={width} height={height} />
const max = Math.max(1, ...values)
const stepX = width / Math.max(1, values.length - 1)
const pts = values.map((v, i) => {
const x = i * stepX
const y = height - (v / max) * (height - 2) - 1
return `${x.toFixed(1)},${y.toFixed(1)}`
}).join(' ')
return (
<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
<polyline points={pts} fill="none" stroke={stroke} strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" />
</svg>
)
}
@@ -0,0 +1,26 @@
import type { ReactNode } from 'react'
import { Sparkline } from './Sparkline'
import type { Summary } from '../lib/dev'
function Card({ label, value, sub }: { label: string; value: string; sub?: ReactNode }) {
return (
<div className="rounded-lg border border-white/10 bg-white/[0.02] px-4 py-3">
<div className="text-xs uppercase tracking-wide text-white/50">{label}</div>
<div className="mt-1 text-2xl font-mono text-white">{value}</div>
{sub && <div className="mt-1 text-xs text-white/40">{sub}</div>}
</div>
)
}
export function StatCards({ s }: { s: Summary }) {
const fmt = (n: number) => n.toLocaleString()
return (
<div className="grid grid-cols-1 gap-3 md:grid-cols-4">
<Card label="Requests 7d" value={fmt(s.requests_7d)}
sub={<Sparkline values={s.daily_requests.map(d => d.count)} />} />
<Card label="Active users 7d" value={fmt(s.active_users_7d)} />
<Card label="p50 / p95 latency" value={`${s.p50_ms}/${s.p95_ms}ms`} />
<Card label="Renders 7d" value={fmt(s.renders_7d)} sub={`avg ${s.avg_render_ms}ms`} />
</div>
)
}
@@ -0,0 +1,81 @@
import { useEffect, useMemo, useState } from 'react'
import { fetchUsers, type UserRow } from '../lib/dev'
function timeAgo(ts: number | null): string {
if (!ts) return '—'
const s = Math.max(0, Math.floor(Date.now() / 1000 - ts))
if (s < 60) return `${s}s ago`
if (s < 3600) return `${Math.floor(s / 60)}m ago`
if (s < 86400) return `${Math.floor(s / 3600)}h ago`
return `${Math.floor(s / 86400)}d ago`
}
export function UsersTable() {
const [q, setQ] = useState('')
const [sort, setSort] = useState<'requests' | 'latency' | 'last_seen'>('requests')
const [rows, setRows] = useState<UserRow[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
let alive = true
const h = window.setTimeout(() => {
setLoading(true)
fetchUsers(q, sort).then(r => { if (alive) { setRows(r); setLoading(false) } })
.catch(() => { if (alive) setLoading(false) })
}, 200)
return () => { alive = false; window.clearTimeout(h) }
}, [q, sort])
const sorted = useMemo(() => rows, [rows])
return (
<div className="rounded-lg border border-white/10 bg-white/[0.02]">
<div className="flex items-center justify-between border-b border-white/10 px-4 py-2">
<div className="text-sm text-white/70">Users</div>
<div className="flex gap-2">
<select value={sort} onChange={e => setSort(e.target.value as 'requests' | 'latency' | 'last_seen')}
className="rounded bg-white/[0.04] px-2 py-1 text-xs text-white/80">
<option value="requests">requests</option>
<option value="latency">latency</option>
<option value="last_seen">last seen</option>
</select>
<input value={q} onChange={e => setQ(e.target.value)} placeholder="search…"
className="rounded bg-white/[0.04] px-2 py-1 text-xs text-white/80 placeholder:text-white/30" />
</div>
</div>
<table className="w-full text-left text-sm">
<thead className="text-xs uppercase text-white/40">
<tr>
<th className="px-4 py-2 font-normal">User</th>
<th className="px-4 py-2 font-normal">Req 7d</th>
<th className="px-4 py-2 font-normal">Last seen</th>
<th className="px-4 py-2 font-normal">Top endpoint</th>
<th className="px-4 py-2 text-right font-normal">Avg ms</th>
</tr>
</thead>
<tbody>
{loading && <tr><td colSpan={5} className="px-4 py-6 text-center text-white/40">loading…</td></tr>}
{!loading && sorted.length === 0 && (
<tr><td colSpan={5} className="px-4 py-6 text-center text-white/40">no users yet</td></tr>
)}
{sorted.map(u => (
<tr key={u.username} className="border-t border-white/5">
<td className="px-4 py-2 text-white/90">
<div className="flex items-center gap-2">
{u.github_avatar_url
? <img src={u.github_avatar_url} alt="" className="h-5 w-5 rounded-full" />
: <span className="inline-block h-5 w-5 rounded-full bg-white/10" />}
<span className="font-mono">{u.username}</span>
</div>
</td>
<td className="px-4 py-2 font-mono text-white/80">{u.requests_7d.toLocaleString()}</td>
<td className="px-4 py-2 text-white/60">{timeAgo(u.last_seen)}</td>
<td className="px-4 py-2 font-mono text-white/60">{u.top_endpoint || '—'}</td>
<td className="px-4 py-2 text-right font-mono text-white/80">{u.avg_latency_ms}</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
+8
View File
@@ -36,4 +36,12 @@ export const DEMO_WIDGET_DATA: WidgetData = {
{ language: 'Go', percentage: 18, loc: 5 }, { language: 'Go', percentage: 18, loc: 5 },
{ language: 'Rust', percentage: 12, loc: 3 }, { language: 'Rust', percentage: 12, loc: 3 },
], ],
streaks: {
current: 12,
max: 47,
current_start: new Date(Date.now() - 11 * 86400000).toISOString().slice(0, 10),
last_active_date: new Date().toISOString().slice(0, 10),
max_start: '2024-09-04',
max_end: '2024-10-20',
},
} }
+57
View File
@@ -0,0 +1,57 @@
// Read helpers for the /dev dashboard. All four endpoints require a
// Basic-auth session that the browser establishes via the WWW-Authenticate
// challenge the first time the SPA hits /api/dev/summary.
export type Summary = {
requests_7d: number
active_users_7d: number
p50_ms: number
p95_ms: number
renders_7d: number
avg_render_ms: number
daily_requests: { day: string; count: number }[]
}
export type UserRow = {
username: string
requests_7d: number
last_seen: number | null
avg_latency_ms: number
top_endpoint: string
github_avatar_url: string | null
}
export type LatencyRow = {
endpoint: string
count: number
p50: number
p95: number
p99: number
}
export type Health = {
edge_cache_hit_rate: number
fetcher_error_rate: number
events_dropped_24h: number
oldest_event_ts: number | null
}
export type Growth = {
daily: { day: string; users: number; requests: number }[]
weekly: { week: string; users: number; requests: number }[]
}
async function getJSON<T>(path: string): Promise<T> {
const r = await fetch(path, { credentials: 'include' })
if (r.status === 401) throw new Error('unauthorized')
if (r.status === 503) throw new Error('dashboard_disabled')
if (!r.ok) throw new Error(`HTTP ${r.status}`)
return (await r.json()) as T
}
export const fetchSummary = () => getJSON<Summary>('/api/dev/summary')
export const fetchUsers = (q = '', sort = 'requests') =>
getJSON<UserRow[]>(`/api/dev/users?q=${encodeURIComponent(q)}&sort=${sort}`)
export const fetchLatency = () => getJSON<LatencyRow[]>('/api/dev/latency')
export const fetchHealth = () => getJSON<Health>('/api/dev/health')
export const fetchGrowth = () => getJSON<Growth>('/api/dev/growth')
+114 -7
View File
@@ -13,6 +13,11 @@ export type CollaboratorData = { username: string; shared_repos: number; shared_
export type FocusCategory = { category: string; percentage: number; commit_count: number } export type FocusCategory = { category: string; percentage: number; commit_count: number }
export type LanguageData = { language: string; percentage: number; loc: number } export type LanguageData = { language: string; percentage: number; loc: number }
export type AchievementInput = { title: string; subtitle: string; event_date: string; icon: string } export type AchievementInput = { title: string; subtitle: string; event_date: string; icon: string }
export type StreakData = {
current: number; max: number
current_start?: string; last_active_date?: string
max_start?: string; max_end?: string
}
export type WidgetData = { export type WidgetData = {
grade?: GradeData grade?: GradeData
@@ -20,11 +25,13 @@ export type WidgetData = {
collaborators?: CollaboratorData[] collaborators?: CollaboratorData[]
focus?: FocusCategory[] focus?: FocusCategory[]
languages?: LanguageData[] languages?: LanguageData[]
streaks?: StreakData
} }
export type PerWidgetSettings = { export type PerWidgetSettings = {
grade?: { max_tags?: number } grade?: { max_tags?: number }
impact?: { line_color?: string } impact?: { line_color?: string }
streaks?: { color?: string }
collaborators?: { max_count?: number; bar_color?: string } collaborators?: { max_count?: number; bar_color?: string }
focus?: { max_categories?: number } focus?: { max_categories?: number }
languages?: { max_languages?: number } languages?: { max_languages?: number }
@@ -104,9 +111,19 @@ function renderGrade(data: GradeData, t: Theme, s?: { max_tags?: number }): stri
const tagPad = tagsH > 24 ? 18 : 14 const tagPad = tagsH > 24 ? 18 : 14
const cardH = tags.length ? tagsY + tagsH + tagPad : statsY + 54 const cardH = tags.length ? tagsY + tagsH + tagPad : statsY + 54
let inner = `<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="${circ.toFixed(1)}" stroke-dashoffset="${offset.toFixed(1)}" stroke-linecap="round" transform="rotate(-90)"/><text x="0" y="-4" text-anchor="middle" dominant-baseline="middle" font-family="${font}" font-size="${gf}" font-weight="800" fill="${color}">${esc(data.grade)}</text><text x="0" y="18" text-anchor="middle" font-family="${font}" font-size="11" fill="${t.text_secondary}">${data.score.toFixed(0)} / 100</text></g> const breakdownLabels: Record<string, string> = {
commits: 'Commits', consistency: 'Consistency', repos: 'Repos',
stars: 'Stars', forks: 'Forks', activity: 'Activity', followers: 'Followers',
}
const topStrengths = Object.entries(data.breakdown || {})
.sort((a, b) => b[1] - a[1])
.slice(0, 2)
.map(([k]) => breakdownLabels[k] ?? k.charAt(0).toUpperCase() + k.slice(1))
const strengthsLine = topStrengths.length ? `Strong in ${topStrengths.join(' · ')}` : ''
let inner = `<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="${circ.toFixed(1)}" stroke-dashoffset="${offset.toFixed(1)}" stroke-linecap="round" transform="rotate(-90)"/><text x="0" y="${(gf * 0.35).toFixed(2)}" text-anchor="middle" font-family="${font}" font-size="${gf}" font-weight="800" fill="${color}">${esc(data.grade)}</text></g>
<line x1="100" y1="16" x2="100" y2="80" stroke="${t.grid}" stroke-width="1"/> <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="${font}" font-size="16" font-weight="700" fill="${t.text}">Developer Profile</text><text x="0" y="28" font-family="${font}" font-size="11" fill="${t.text_secondary}">Grade <tspan fill="${color}" font-weight="700">${esc(data.grade)}</tspan> · ${data.score.toFixed(0)}/100</text></g> <g transform="translate(114, 26)"><text x="0" y="10" font-family="${font}" font-size="16" font-weight="700" fill="${t.text}">Developer Profile</text><text x="0" y="32" font-family="${font}" font-size="11" fill="${t.text_secondary}">${esc(strengthsLine)}</text><text x="0" y="50" font-family="${font}" font-size="10" letter-spacing="0.4" fill="${t.text_secondary}">Score <tspan fill="${t.text}" font-weight="600">${data.score.toFixed(0)}</tspan> / 100</text></g>
<line x1="20" y1="${statsY-4}" x2="360" y2="${statsY-4}" stroke="${t.grid}" stroke-width="0.5"/> <line x1="20" y1="${statsY-4}" x2="360" y2="${statsY-4}" stroke="${t.grid}" stroke-width="0.5"/>
<g transform="translate(20, ${statsY})">${statsSvg}</g>` <g transform="translate(20, ${statsY})">${statsSvg}</g>`
@@ -247,6 +264,79 @@ function renderLanguages(languages: LanguageData[], t: Theme, s?: { max_language
return cardWrapper(inner, 380, rowsH + 36, t, 'Languages') return cardWrapper(inner, 380, rowsH + 36, t, 'Languages')
} }
const STREAK_MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
const STREAK_COLOR_RE = /^#[0-9a-fA-F]{3,8}$/
function streaksSafeColor(value: string | undefined, fallback: string): string {
if (typeof value !== 'string' || value.length > 32) return fallback
return STREAK_COLOR_RE.test(value) ? value : fallback
}
function streakParseDate(iso?: string): { y: number; m: number; d: number } | null {
if (!iso) return null
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso)
if (!m) return null
const y = Number(m[1]), mo = Number(m[2]), d = Number(m[3])
if (!y || mo < 1 || mo > 12 || d < 1 || d > 31) return null
return { y, m: mo, d }
}
function streakFmtDay(dt: { y: number; m: number; d: number }, includeYear: boolean): string {
return includeYear ? `${STREAK_MONTHS[dt.m-1]} ${dt.d}, ${dt.y}` : `${STREAK_MONTHS[dt.m-1]} ${dt.d}`
}
function fmtStreakCurrent(startIso?: string, todayIso?: string): string {
const s = streakParseDate(startIso); if (!s) return ''
const t = streakParseDate(todayIso) ?? { y: new Date().getFullYear(), m: 1, d: 1 }
return `${streakFmtDay(s, s.y !== t.y)} – Today`
}
function fmtStreakLongest(startIso?: string, endIso?: string): string {
const s = streakParseDate(startIso), e = streakParseDate(endIso)
if (s && e) {
if (s.y === e.y) return `${streakFmtDay(s, false)} – ${streakFmtDay(e, true)}`
return `${streakFmtDay(s, true)} – ${streakFmtDay(e, true)}`
}
if (e) return streakFmtDay(e, true)
if (s) return streakFmtDay(s, true)
return ''
}
function renderStreaks(data: StreakData, t: Theme, s?: { color?: string }): string {
const width = 380, height = 170
const currentColor = streaksSafeColor(s?.color, t.accent)
const maxColor = t.text
const leftX = 105, rightX = 275, dividerX = 190
const barX = 50, barW = 280
const fraction = data.max > 0 ? Math.max(0, Math.min(1, data.current / data.max)) : 0
const fillW = +(barW * fraction).toFixed(2)
const currentCaption = data.current > 0
? fmtStreakCurrent(data.current_start, data.last_active_date)
: ''
const longestCaption = fmtStreakLongest(data.max_start, data.max_end)
const endDot = fillW > 0
? `<circle cx="${(barX + fillW).toFixed(2)}" cy="94.5" r="3.5" fill="${currentColor}"/>`
: ''
const inner = `
<text x="${leftX}" y="22" text-anchor="middle" font-family="${font}" font-size="10" font-weight="600" letter-spacing="1.4" fill="${t.text_secondary}">CURRENT</text>
<text x="${leftX}" y="66" text-anchor="middle" font-family="${font}" font-size="40" font-weight="800" fill="${currentColor}">${data.current}</text>
<text x="${rightX}" y="22" text-anchor="middle" font-family="${font}" font-size="10" font-weight="600" letter-spacing="1.4" fill="${t.text_secondary}">LONGEST</text>
<text x="${rightX}" y="66" text-anchor="middle" font-family="${font}" font-size="40" font-weight="800" fill="${maxColor}">${data.max}</text>
<line x1="${dividerX}" y1="10" x2="${dividerX}" y2="76" stroke="${t.card_border}" stroke-width="1"/>
<rect x="${barX}" y="92" width="${barW}" height="5" rx="2.5" fill="${t.grid}"/>
<rect x="${barX}" y="92" width="${fillW}" height="5" rx="2.5" fill="${currentColor}"/>
${endDot}
<text x="${barX}" y="116" font-family="${font}" font-size="10" fill="${t.text_secondary}">${esc(currentCaption)}</text>
<text x="${barX + barW}" y="116" text-anchor="end" font-family="${font}" font-size="10" fill="${t.text_secondary}">${esc(longestCaption)}</text>`
return cardWrapper(inner, width, height, t, 'Streaks')
}
function achievementIconSvg(iconType: string, color: string): string { function achievementIconSvg(iconType: string, color: string): string {
// Mirrors generator/src/widgets/achievements.py::_achievement_icon_svg so // Mirrors generator/src/widgets/achievements.py::_achievement_icon_svg so
// the Workshop client preview matches the backend-rendered composite. // the Workshop client preview matches the backend-rendered composite.
@@ -316,6 +406,8 @@ export function renderAllWidgets(opts: {
widgetSvgs.grade = renderGrade(opts.data.grade, t, opts.widgetSettings.grade) widgetSvgs.grade = renderGrade(opts.data.grade, t, opts.widgetSettings.grade)
if (enabled.has('impact') && opts.data.impact) if (enabled.has('impact') && opts.data.impact)
widgetSvgs.impact = renderImpact(opts.data.impact, t, opts.widgetSettings.impact) widgetSvgs.impact = renderImpact(opts.data.impact, t, opts.widgetSettings.impact)
if (enabled.has('streaks') && opts.data.streaks)
widgetSvgs.streaks = renderStreaks(opts.data.streaks, t, opts.widgetSettings.streaks)
if (enabled.has('collaborators') && opts.data.collaborators) if (enabled.has('collaborators') && opts.data.collaborators)
widgetSvgs.collaborators = renderCollaborators(opts.data.collaborators, t, opts.widgetSettings.collaborators) widgetSvgs.collaborators = renderCollaborators(opts.data.collaborators, t, opts.widgetSettings.collaborators)
if (enabled.has('focus') && opts.data.focus) if (enabled.has('focus') && opts.data.focus)
@@ -334,8 +426,10 @@ export function renderAllWidgets(opts: {
widgetSvgs.achievements = renderAchievements(opts.achievements, t, opts.widgetSettings.achievements) widgetSvgs.achievements = renderAchievements(opts.achievements, t, opts.widgetSettings.achievements)
// Compose // Compose
const totalW = 420, headerH = 60, padding = 20, gap = 16 const showName = enabled.has('name')
const ordered = opts.widgetOrder.filter(k => enabled.has(k) && widgetSvgs[k]) const totalW = 420, headerH = showName ? 60 : 0, padding = 20, gap = 16
// "name" is a pseudo-widget — it controls the header, not a rendered svg.
const ordered = opts.widgetOrder.filter(k => k !== 'name' && enabled.has(k) && widgetSvgs[k])
const parts = ordered.map(key => { const parts = ordered.map(key => {
const { inner, h } = extractInner(widgetSvgs[key], key) const { inner, h } = extractInner(widgetSvgs[key], key)
@@ -345,8 +439,21 @@ export function renderAllWidgets(opts: {
const contentH = parts.reduce((a, p) => a + p.h, 0) + gap * Math.max(parts.length - 1, 0) const contentH = parts.reduce((a, p) => a + p.h, 0) + gap * Math.max(parts.length - 1, 0)
const totalH = headerH + contentH + padding * 2 + 10 const totalH = headerH + contentH + padding * 2 + 10
const avatar = `<circle cx="30" cy="30" r="16" fill="${t.accent}" opacity="0.3"/>` // Header (avatar + username). Only drawn when "name" is enabled. The
const header = `${avatar}<text x="54" y="38" font-family="${font}" font-size="16" font-weight="700" fill="${t.text}">${esc(opts.username || 'Developer')}</text><line x1="${padding}" y1="${headerH}" x2="${totalW-padding}" y2="${headerH}" stroke="${t.card_border}" stroke-width="0.5"/>` // avatar pulls from github.com/<user>.png which redirects to
// avatars.githubusercontent.com; the accent circle underneath is a
// fallback for missing users / slow loads.
let header = ''
if (showName) {
const avatarUrl = opts.username
? `https://github.com/${encodeURIComponent(opts.username)}.png?size=64`
: ''
const avatarImg = avatarUrl
? `<image x="14" y="14" width="32" height="32" href="${esc(avatarUrl)}" clip-path="url(#mainAvatarClip)" preserveAspectRatio="xMidYMid slice"/>`
: ''
const avatar = `<defs><clipPath id="mainAvatarClip"><circle cx="30" cy="30" r="16"/></clipPath></defs><circle cx="30" cy="30" r="16" fill="${t.accent}" opacity="0.3"/>${avatarImg}`
header = `${avatar}<text x="54" y="38" font-family="${font}" font-size="16" font-weight="700" fill="${t.text}">${esc(opts.username || 'Developer')}</text><line x1="${padding}" y1="${headerH}" x2="${totalW-padding}" y2="${headerH}" stroke="${t.card_border}" stroke-width="0.5"/>`
}
let yOffset = headerH + padding let yOffset = headerH + padding
let embedded = '' let embedded = ''
@@ -359,6 +466,6 @@ export function renderAllWidgets(opts: {
<rect width="${totalW}" height="${totalH}" rx="16" fill="${t.bg}"/> <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"/> <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} ${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 gh-stats</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.com</text>
</svg>` </svg>`
} }
@@ -0,0 +1,90 @@
// Settings ⇄ query-string encoder for the public widget embed URL.
//
// The backend's `GET /api/<u>?...` accepts the same fields that
// `PATCH /settings` takes, but encoded flat in the query. The encoding is
// designed to stay human-readable for the common cases (theme, widgets,
// order) and fall back to compact base64 only for achievements, which are
// shape-y enough that spelling them out inflates the URL.
//
// Keep this in sync with `sanitize_settings_query` in `generator/src/api.py`.
import type { WidgetSettings, Achievement } from '../App'
// The theme id the backend treats as the default. Omit from the URL so
// the common case stays terse.
const DEFAULT_THEME = 'midnight'
// Standard widget set / order. If the user hasn't deviated, skip emitting
// the param so the embed URL doesn't balloon with boilerplate.
const DEFAULT_WIDGETS = ['name', 'grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages']
const DEFAULT_ORDER = ['name', 'grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages', 'achievements']
function arrayEquals(a: string[], b: string[]): boolean {
if (a.length !== b.length) return false
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false
return true
}
// RFC-4648 url-safe base64 without padding. Matches what Python's
// `base64.urlsafe_b64decode` re-pads in the backend parser.
function urlsafeB64Encode(s: string): string {
const bytes = new TextEncoder().encode(s)
let bin = ''
for (const b of bytes) bin += String.fromCharCode(b)
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '')
}
function achievementsParam(achievements: Achievement[]): string | null {
const keepers = achievements.filter(a => (a.title || '').trim())
if (!keepers.length) return null
const payload = keepers.map(a => ({
title: a.title,
subtitle: a.subtitle,
event_date: a.event_date,
icon: a.icon,
}))
return urlsafeB64Encode(JSON.stringify(payload))
}
export function settingsToQuery(settings: WidgetSettings): string {
const params = new URLSearchParams()
if (settings.theme && settings.theme !== DEFAULT_THEME) {
params.set('theme', settings.theme)
}
if (!arrayEquals(settings.widgets, DEFAULT_WIDGETS)) {
params.set('widgets', settings.widgets.join(','))
}
if (!arrayEquals(settings.widgetOrder, DEFAULT_ORDER)) {
params.set('order', settings.widgetOrder.join(','))
}
if (settings.hiddenLanguages.length) {
params.set('hide', settings.hiddenLanguages.join(','))
}
if (settings.customTags.length) {
params.set('tags', settings.customTags.join(','))
}
// Per-widget settings flatten to `<widget>.<key>=<value>`. Any undefined
// or null leaf is skipped so the URL stays minimal.
for (const [widget, ws] of Object.entries(settings.widgetSettings)) {
if (!ws) continue
for (const [key, val] of Object.entries(ws as Record<string, unknown>)) {
if (val === undefined || val === null || val === '') continue
params.set(`${widget}.${key}`, String(val))
}
}
const ach = achievementsParam(settings.achievements)
if (ach) params.set('ach', ach)
// URLSearchParams.toString() percent-encodes values (including the `#` in
// hex colors), so callers can splice the result straight into a URL.
return params.toString()
}
export function buildEmbedUrl(origin: string, username: string, settings: WidgetSettings): string {
const qs = settingsToQuery(settings)
const base = `${origin}/api/${encodeURIComponent(username)}`
return qs ? `${base}?${qs}` : base
}
@@ -0,0 +1,79 @@
import { useEffect, useState } from 'react'
import type { ReactNode } from 'react'
import { fetchSummary, type Summary } from '../lib/dev'
import { StatCards } from '../components/StatCards'
import { UsersTable } from '../components/UsersTable'
import { LatencyChart } from '../components/LatencyChart'
import { HealthStrip } from '../components/HealthStrip'
import { GrowthChart } from '../components/GrowthChart'
const REFRESH_MS = 15_000
export function DevScreen() {
const [s, setS] = useState<Summary | null>(null)
const [error, setError] = useState<string | null>(null)
const [lastRefresh, setLastRefresh] = useState<Date>(new Date())
useEffect(() => {
let alive = true
const load = () =>
fetchSummary()
.then(v => { if (!alive) return; setS(v); setError(null); setLastRefresh(new Date()) })
.catch(e => { if (alive) setError(e.message || 'error') })
load()
const h = window.setInterval(load, REFRESH_MS)
return () => { alive = false; window.clearInterval(h) }
}, [])
if (error === 'dashboard_disabled') {
return (
<Shell>
<div className="rounded-lg border border-amber-500/30 bg-amber-500/[0.06] p-6 text-amber-200">
The /dev dashboard is not configured on this deploy
(set DEV_DASHBOARD_USER and DEV_DASHBOARD_PASSWORD).
</div>
</Shell>
)
}
if (error === 'unauthorized') {
return (
<Shell>
<div className="text-white/60">Sign in to view the dashboard. Reload to retry.</div>
</Shell>
)
}
return (
<Shell lastRefresh={lastRefresh}>
{s ? <StatCards s={s} /> : <div className="text-white/40">loading…</div>}
<div className="mt-6">
<GrowthChart />
</div>
<div className="mt-6">
<UsersTable />
</div>
<div className="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2">
<LatencyChart />
<HealthStrip />
</div>
</Shell>
)
}
function Shell({ children, lastRefresh }: { children: ReactNode; lastRefresh?: Date }) {
return (
<div className="min-h-screen bg-[#0b0d10] px-6 py-6 text-white">
<div className="mx-auto max-w-6xl">
<header className="mb-6 flex items-baseline justify-between">
<h1 className="font-mono text-lg text-white/90">/dev · gh-stats analytics</h1>
{lastRefresh && (
<div className="text-xs text-white/40">
last refresh {lastRefresh.toLocaleTimeString()}
</div>
)}
</header>
{children}
</div>
</div>
)
}
+125 -5
View File
@@ -1,5 +1,16 @@
import DOMPurify from 'dompurify' import DOMPurify from 'dompurify'
import { useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
// Stats cards people already have in their profile README. A visitor who has
// one needs "replace that line", not "paste this somewhere".
const OTHER_CARDS: [RegExp, string][] = [
[/github-readme-stats/i, 'github-readme-stats'],
[/streak-stats|readme-streak/i, 'GitHub Readme Streak Stats'],
[/github-stats-extended/i, 'github-stats-extended'],
[/github-profile-summary-cards/i, 'github-profile-summary-cards'],
[/github-profile-trophy/i, 'github-profile-trophy'],
[/github-readme-activity-graph/i, 'github-readme-activity-graph'],
]
function sanitizeSvg(raw: string): string { function sanitizeSvg(raw: string): string {
return DOMPurify.sanitize(raw, { return DOMPurify.sanitize(raw, {
@@ -14,14 +25,62 @@ type Props = {
generating: boolean generating: boolean
generatedSvg: string | null generatedSvg: string | null
generateError: string | null generateError: string | null
// Owner renders embed as /api/<u>; visitors get /api/<u>?<their settings>.
// We display whichever URL was used to produce the SVG above, so the
// snippet they copy matches what they're previewing.
embedUrl: string
// 'building' means the SVG above is still the "Building @user's
// widget…" placeholder; the parent is auto-polling for the real one.
widgetStatus: 'ready' | 'building' | 'not_found' | 'rate_limited'
onBack: () => void onBack: () => void
onRegenerate: () => void
// Manual refetch — same fetch the auto-poll runs, exposed as a button
// so the user has a way to nudge it if they want.
onRefresh: () => void
} }
export function ResultScreen({ username, generating, generatedSvg, generateError, onBack }: Props) { export function ResultScreen({ username, generating, generatedSvg, generateError, embedUrl, widgetStatus, onBack, onRegenerate, onRefresh }: Props) {
const safeSvg = useMemo(() => (generatedSvg ? sanitizeSvg(generatedSvg) : ''), [generatedSvg]) const safeSvg = useMemo(() => (generatedSvg ? sanitizeSvg(generatedSvg) : ''), [generatedSvg])
const [copied, setCopied] = useState(false) const [copied, setCopied] = useState(false)
const embedUrl = `${window.location.origin}/api/${encodeURIComponent(username)}` const fallbackUrl = `${window.location.origin}/api/${encodeURIComponent(username)}`
const embedSnippet = `![${username}](${embedUrl})` const finalUrl = embedUrl || fallbackUrl
const embedSnippet = `[![${username}](${finalUrl})](${window.location.origin})`
// The snippet is useless without somewhere to paste it: GitHub only renders a
// profile README from the repo named exactly after the account. Most people
// arriving here don't have that repo yet, so offer both paths.
const profileRepo = encodeURIComponent(username)
const editReadmeUrl = `https://github.com/${profileRepo}/${profileRepo}/edit/HEAD/README.md`
const createRepoUrl = `https://github.com/new?name=${profileRepo}&description=${encodeURIComponent('My GitHub profile')}&visibility=public`
// raw.githubusercontent.com sends Access-Control-Allow-Origin: *, so the
// browser can read the profile README directly. Any failure leaves the
// generic hint in place.
const [found, setFound] = useState<{ repo: string; card: string } | null>(null)
const otherCard = found?.repo === profileRepo ? found.card : null
// No profile repo at all: GitHub's new-file page takes ?filename=&value=, so
// after creating the (empty) repo one click opens a README with the card in it.
const [noRepo, setNoRepo] = useState<string | null>(null)
const addReadmeUrl = `https://github.com/${profileRepo}/${profileRepo}/new/main?filename=README.md&value=${encodeURIComponent(embedSnippet + '\n')}`
useEffect(() => {
let live = true
fetch(`https://raw.githubusercontent.com/${profileRepo}/${profileRepo}/HEAD/README.md`)
.then(r => {
// A 404 here can also mean readme.md in another case, so only the
// API's 404 for the repo itself counts as "no repo".
if (r.status === 404) {
fetch(`https://api.github.com/repos/${profileRepo}/${profileRepo}`)
.then(a => { if (live && a.status === 404) setNoRepo(profileRepo) })
.catch(() => {})
}
return r.ok ? r.text() : ''
})
.then(text => {
if (!live || /gh-stats\.com/i.test(text)) return
const hit = OTHER_CARDS.find(([re]) => re.test(text))
if (hit) setFound({ repo: profileRepo, card: hit[1] })
})
.catch(() => {})
return () => { live = false }
}, [profileRepo])
const copy = async () => { const copy = async () => {
try { try {
@@ -35,7 +94,7 @@ export function ResultScreen({ username, generating, generatedSvg, generateError
return ( return (
<div className="min-h-screen flex flex-col items-center animate-fade-in-up"> <div className="min-h-screen flex flex-col items-center animate-fade-in-up">
<div className="w-full max-w-3xl px-6 pt-6"> <div className="w-full max-w-3xl px-6 pt-6 flex items-center justify-between">
<button <button
onClick={onBack} onClick={onBack}
className="flex items-center gap-1.5 text-xs text-gray-400 hover:text-gray-600 transition-colors" className="flex items-center gap-1.5 text-xs text-gray-400 hover:text-gray-600 transition-colors"
@@ -45,6 +104,28 @@ export function ResultScreen({ username, generating, generatedSvg, generateError
</svg> </svg>
Back Back
</button> </button>
<button
onClick={onRegenerate}
disabled={generating}
title="Re-render the widget from the most recent cached data. Does not re-fetch from GitHub."
className="flex items-center gap-1.5 text-xs text-gray-500 hover:text-gray-800 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
>
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={generating ? 'animate-spin-slow' : ''}
>
<path d="M21 12a9 9 0 1 1-3-6.7L21 8" />
<path d="M21 3v5h-5" />
</svg>
{generating ? 'Regenerating…' : 'Regenerate'}
</button>
</div> </div>
<div className="flex-1 flex flex-col items-center justify-center px-6 pb-12 w-full max-w-3xl"> <div className="flex-1 flex flex-col items-center justify-center px-6 pb-12 w-full max-w-3xl">
@@ -67,6 +148,18 @@ export function ResultScreen({ username, generating, generatedSvg, generateError
{!generating && !generateError && safeSvg && ( {!generating && !generateError && safeSvg && (
<> <>
{widgetStatus === 'building' && (
<div className="mt-6 flex items-center gap-2 text-xs text-gray-500">
<div className="w-3 h-3 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin-slow" />
<span>Still building on the server — this page will update automatically when ready.</span>
<button
onClick={onRefresh}
className="ml-2 px-2 py-1 rounded-md text-gray-600 hover:text-gray-900 hover:bg-gray-100 transition-colors"
>
Check now
</button>
</div>
)}
<div className="w-full mt-6 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 Force the inline SVG to scale up to the card width. The
@@ -80,6 +173,22 @@ export function ResultScreen({ username, generating, generatedSvg, generateError
</div> </div>
<div className="w-full mt-8"> <div className="w-full mt-8">
{noRepo === profileRepo && (
<div className="mb-6 rounded-xl ring-1 ring-gray-200 bg-white p-4">
<p className="text-sm text-gray-700 mb-3">
{username} has no profile README yet. GitHub shows the README of the repo named <code className="text-gray-600">{username}/{username}</code> on your profile.
</p>
<div className="flex flex-col sm:flex-row gap-2">
<a href={createRepoUrl} target="_blank" rel="noopener noreferrer" className="flex-1 text-center py-2.5 px-3 rounded-lg bg-gray-800 text-white text-sm hover:bg-gray-700 transition-colors">
1. Create {username}/{username}
</a>
<a href={addReadmeUrl} target="_blank" rel="noopener noreferrer" className="flex-1 text-center py-2.5 px-3 rounded-lg bg-gray-800 text-white text-sm hover:bg-gray-700 transition-colors">
2. Add the card to its README
</a>
</div>
<p className="mt-2 text-xs text-gray-500">In step 1, leave "Add a README" unticked. Step 2 opens a README with this card already in it; commit it.</p>
</div>
)}
<p className="text-xs uppercase tracking-wider text-gray-500 mb-2">Embed in your README</p> <p className="text-xs uppercase tracking-wider text-gray-500 mb-2">Embed in your README</p>
<div className="relative"> <div className="relative">
<pre className="bg-gray-900 text-gray-100 text-xs p-4 pr-12 rounded-lg overflow-x-auto"> <pre className="bg-gray-900 text-gray-100 text-xs p-4 pr-12 rounded-lg overflow-x-auto">
@@ -102,6 +211,17 @@ export function ResultScreen({ username, generating, generatedSvg, generateError
)} )}
</button> </button>
</div> </div>
{noRepo !== profileRepo && <p className="mt-3 text-xs text-gray-500">
Paste it into <code className="text-gray-600">{username}/{username}</code>, the repo GitHub shows on your profile.{' '}
<a href={editReadmeUrl} onClick={copy} target="_blank" rel="noopener noreferrer" className="text-gray-700 underline hover:text-gray-900">Copy &amp; open your README</a>
{' \u00b7 '}
<a href={createRepoUrl} target="_blank" rel="noopener noreferrer" className="text-gray-700 underline hover:text-gray-900">Create the repo</a>
</p>}
{otherCard && (
<p className="mt-2 text-xs text-gray-600">
This README already shows a {otherCard} card. Replace that line with the one above to swap it for this card.
</p>
)}
</div> </div>
</> </>
)} )}
+60 -25
View File
@@ -4,8 +4,14 @@ type Props = {
onSearch: (username: string) => void onSearch: (username: string) => void
} }
// A real card served by the live API, so the landing page shows the actual
// product, not a mockup. The frame below has a fixed height so a slow or
// failed load never reflows the page or pushes the input out of view.
const EXAMPLE_URL = 'https://gh-stats.com/api/shaymanor'
export function SearchScreen({ onSearch }: Props) { export function SearchScreen({ onSearch }: Props) {
const [value, setValue] = useState('') const [value, setValue] = useState('')
const [exampleFailed, setExampleFailed] = useState(false)
const handleSubmit = (e: React.FormEvent) => { const handleSubmit = (e: React.FormEvent) => {
e.preventDefault() e.preventDefault()
@@ -14,31 +20,60 @@ export function SearchScreen({ onSearch }: Props) {
} }
return ( return (
<div className="min-h-screen flex items-center justify-center animate-fade-in-up"> <div className="min-h-screen flex items-start md:items-center justify-center px-6 py-12 animate-fade-in-up">
<div className="text-center w-full max-w-md px-6"> <div className="w-full max-w-4xl grid gap-10 md:grid-cols-2 md:items-center">
<h1 className="font-serif text-4xl text-gray-800 tracking-tight mb-2"> <div className="w-full max-w-md mx-auto md:mx-0 text-center md:text-left">
GitHub Stats <h1 className="font-serif text-4xl md:text-5xl text-gray-800 tracking-tight mb-3">
</h1> GitHub Stats
<p className="text-sm text-gray-400 mb-8"> </h1>
Generate your profile widget <p className="text-sm text-gray-500 leading-relaxed mb-8">
</p> One image for your profile README: your score, contribution timeline,
<form onSubmit={handleSubmit} className="flex gap-2"> top collaborators, language breakdown, commit streaks and auto-awarded tags.
<input </p>
type="text" <form onSubmit={handleSubmit} className="flex gap-2">
value={value} <input
onChange={e => setValue(e.target.value)} type="text"
placeholder="Enter GitHub username..." value={value}
autoFocus onChange={e => setValue(e.target.value)}
className="flex-1 px-4 py-3 rounded-xl border border-gray-200 bg-white text-sm text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 transition-colors" placeholder="Enter GitHub username..."
/> autoFocus
<button className="flex-1 min-w-0 px-4 py-3 rounded-xl border border-gray-200 bg-white text-sm text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 transition-colors"
type="submit" />
disabled={!value.trim()} <button
className="px-6 py-3 rounded-xl bg-gray-800 text-white text-sm font-medium hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors" type="submit"
> disabled={!value.trim()}
Go className="px-6 py-3 rounded-xl bg-gray-800 text-white text-sm font-medium hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
</button> >
</form> Go
</button>
</form>
<p className="mt-3 text-xs text-gray-400">
Five themes · one line of markdown · no signup
</p>
</div>
<div className="w-full max-w-[420px] mx-auto md:mx-0">
<div className="relative h-[300px] md:h-[420px] overflow-hidden rounded-2xl border border-gray-200 bg-white">
{exampleFailed ? (
<p className="absolute inset-0 flex items-center justify-center text-xs text-gray-400">
Example card unavailable
</p>
) : (
<img
src={EXAMPLE_URL}
width={420}
height={1196}
alt="Example stats card"
onError={() => setExampleFailed(true)}
className="block w-full"
/>
)}
<div className="pointer-events-none absolute inset-x-0 bottom-0 h-14 md:h-16 bg-gradient-to-t from-gray-50 to-transparent" />
</div>
<p className="mt-3 text-center md:text-left font-mono text-[11px] text-gray-400 truncate">
gh-stats.com/api/shaymanor
</p>
</div>
</div> </div>
</div> </div>
) )
+318 -119
View File
@@ -2,7 +2,6 @@ import { useState, useMemo, type ReactNode } from 'react'
import DOMPurify from 'dompurify' import DOMPurify from 'dompurify'
import type { WidgetSettings, Achievement, PerWidgetSettings } from '../App' import type { WidgetSettings, Achievement, PerWidgetSettings } from '../App'
import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets' import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets'
import { signInUrl } from '../lib/auth'
import type { Me } from '../lib/auth' import type { Me } from '../lib/auth'
// Defense-in-depth: the client-rendered preview assembles SVG from // Defense-in-depth: the client-rendered preview assembles SVG from
@@ -25,17 +24,24 @@ const SVG_SANITIZE_CONFIG = {
], ],
} }
// Mini-preview swatches (bg + card + accent). Flat-color swatches all read
// the same dark/light — showing the accent color is what actually separates
// Midnight (blue) from Onyx (purple) from Nord (cyan), etc.
const THEMES = [ const THEMES = [
{ id: 'midnight', label: 'Midnight', color: '#121820' }, { id: 'midnight', label: 'Midnight', bg: '#121820', card: '#1a2230', border: '#2a3444', accent: '#58a6ff', light: false },
{ id: 'onyx', label: 'Onyx', color: '#09090b' }, { id: 'onyx', label: 'Onyx', bg: '#09090b', card: '#18181b', border: '#27272a', accent: '#a78bfa', light: false },
{ id: 'nord', label: 'Nord', color: '#1e2433' }, { id: 'nord', label: 'Nord', bg: '#1e2433', card: '#2a3142', border: '#3d4659', accent: '#88c0d0', light: false },
{ id: 'clean', label: 'Clean', color: '#ffffff', border: true }, { id: 'clean', label: 'Clean', bg: '#ffffff', card: '#f6f8fa', border: '#d8dee4', accent: '#0969da', light: true },
{ id: 'paper', label: 'Paper', color: '#faf8f5', border: true }, { id: 'paper', label: 'Paper', bg: '#faf8f5', card: '#f5f0eb', border: '#e0d8cf', accent: '#b45309', light: true },
] ]
const ALL_WIDGETS = [ const ALL_WIDGETS = [
// "name" is the avatar + username header. Pinned at the top — can be
// toggled off but never reordered. Keep this entry first.
{ id: 'name', label: 'Name' },
{ id: 'grade', label: 'Grade' }, { id: 'grade', label: 'Grade' },
{ id: 'impact', label: 'Impact Timeline' }, { id: 'impact', label: 'Impact Timeline' },
{ id: 'streaks', label: 'Streaks' },
{ id: 'collaborators', label: 'Top Collaborators' }, { id: 'collaborators', label: 'Top Collaborators' },
{ id: 'focus', label: 'Recent Focus' }, { id: 'focus', label: 'Recent Focus' },
{ id: 'languages', label: 'Languages' }, { id: 'languages', label: 'Languages' },
@@ -74,8 +80,12 @@ const ICONS: { id: string; svg: ReactNode }[] = [
id: 'medal', id: 'medal',
svg: ( svg: (
<svg {...ICON_SVG_PROPS}> <svg {...ICON_SVG_PROPS}>
<circle cx="12" cy="8" r="6" /> <path d="M7.21 15 2.66 7.14a2 2 0 0 1 .13-2.2L4.4 2.8A2 2 0 0 1 6 2h12a2 2 0 0 1 1.6.8l1.6 2.14a2 2 0 0 1 .14 2.2L16.79 15" />
<path d="m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526" /> <path d="M11 12 5.12 2.2" />
<path d="m13 12 5.88-9.8" />
<path d="M8 7h8" />
<circle cx="12" cy="17" r="5" />
<path d="M12 18v-2h-.5" />
</svg> </svg>
), ),
}, },
@@ -198,7 +208,7 @@ function ColorPicker({ value, onChange }: { value: string; onChange: (v: string)
key={c} key={c}
onClick={() => onChange(c)} onClick={() => onChange(c)}
className={`w-5 h-5 rounded-full transition-all ${ className={`w-5 h-5 rounded-full transition-all ${
value === c ? 'ring-2 ring-offset-1 ring-blue-500' : 'hover:ring-1 hover:ring-gray-300' value === c ? 'ring-2 ring-offset-1 ring-gray-900' : 'hover:ring-1 hover:ring-gray-300'
}`} }`}
style={{ backgroundColor: c }} style={{ backgroundColor: c }}
/> />
@@ -216,6 +226,7 @@ type Props = {
fetchDone: boolean fetchDone: boolean
fetchError: string | null fetchError: string | null
widgetData: WidgetData | null widgetData: WidgetData | null
isDemoData: boolean
me: Me me: Me
onAuthChange?: (m: Me) => void onAuthChange?: (m: Me) => void
} }
@@ -229,10 +240,49 @@ export function WorkshopScreen({
fetchDone, fetchDone,
fetchError, fetchError,
widgetData, widgetData,
isDemoData,
me, me,
}: Props) { }: Props) {
const canEdit = !!me.login && me.login.toLowerCase() === username.toLowerCase() const canEdit = !!me.login && me.login.toLowerCase() === username.toLowerCase()
const [expandedWidget, setExpandedWidget] = useState<string | null>(null) const [expandedWidget, setExpandedWidget] = useState<string | null>(null)
// Index being dragged + index currently hovered (for drop-line indicator).
const [dragIndex, setDragIndex] = useState<number | null>(null)
const [dropIndex, setDropIndex] = useState<number | null>(null)
// Same pattern for the achievements list so the two drag interactions
// don't share state and fight each other.
const [achDragIndex, setAchDragIndex] = useState<number | null>(null)
const [achDropIndex, setAchDropIndex] = useState<number | null>(null)
// Build the render-order list from settings.widgetOrder, tolerating
// stale persisted data: drop unknown ids, append any known widgets
// the stored order forgot. Keeps the UI functional if ALL_WIDGETS
// gains or loses an entry between releases.
const knownIds = useMemo(() => new Set(ALL_WIDGETS.map(w => w.id)), [])
// "name" is pinned at index 0 regardless of persisted order. We still keep
// it in orderedIds so the composite-render path can find it, but the drag
// UI below treats it as non-reorderable.
const orderedIds = useMemo(() => {
const seen = new Set<string>()
const out: string[] = ['name']
seen.add('name')
for (const id of settings.widgetOrder) {
if (knownIds.has(id) && !seen.has(id)) { seen.add(id); out.push(id) }
}
for (const w of ALL_WIDGETS) {
if (!seen.has(w.id)) { seen.add(w.id); out.push(w.id) }
}
return out
}, [settings.widgetOrder, knownIds])
const moveWidget = (from: number, to: number) => {
if (from === to || from < 0 || to < 0 || from >= orderedIds.length || to >= orderedIds.length) return
// Never move "name" and never drop another widget above it (index 0).
if (orderedIds[from] === 'name' || to === 0) return
const next = orderedIds.slice()
const [item] = next.splice(from, 1)
next.splice(to, 0, item)
onSettingsChange({ ...settings, widgetOrder: next })
}
const updateSetting = <K extends keyof WidgetSettings>(key: K, val: WidgetSettings[K]) => { const updateSetting = <K extends keyof WidgetSettings>(key: K, val: WidgetSettings[K]) => {
onSettingsChange({ ...settings, [key]: val }) onSettingsChange({ ...settings, [key]: val })
@@ -278,6 +328,15 @@ export function WorkshopScreen({
updateSetting('achievements', settings.achievements.filter((_, i) => i !== idx)) updateSetting('achievements', settings.achievements.filter((_, i) => i !== idx))
} }
const moveAchievement = (from: number, to: number) => {
const list = settings.achievements
if (from === to || from < 0 || to < 0 || from >= list.length || to >= list.length) return
const next = list.slice()
const [item] = next.splice(from, 1)
next.splice(to, 0, item)
updateSetting('achievements', next)
}
// Render SVG client-side whenever settings change (instant, no API call) // Render SVG client-side whenever settings change (instant, no API call)
const svgContent = useMemo(() => { const svgContent = useMemo(() => {
if (!widgetData) return '' if (!widgetData) return ''
@@ -285,14 +344,14 @@ export function WorkshopScreen({
data: widgetData, data: widgetData,
theme: settings.theme, theme: settings.theme,
widgets: settings.widgets, widgets: settings.widgets,
widgetOrder: ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'], widgetOrder: orderedIds,
achievements: settings.achievements, achievements: settings.achievements,
widgetSettings: settings.widgetSettings, widgetSettings: settings.widgetSettings,
hiddenLanguages: settings.hiddenLanguages, hiddenLanguages: settings.hiddenLanguages,
username, username,
}) })
return DOMPurify.sanitize(raw, SVG_SANITIZE_CONFIG) return DOMPurify.sanitize(raw, SVG_SANITIZE_CONFIG)
}, [widgetData, settings, username]) }, [widgetData, settings, username, orderedIds])
return ( return (
<div className="min-h-screen animate-fade-in-up"> <div className="min-h-screen animate-fade-in-up">
@@ -310,7 +369,15 @@ export function WorkshopScreen({
Back Back
</button> </button>
<div className="text-sm font-semibold text-gray-800 mb-6">{username}</div> <div className="text-sm font-semibold text-gray-800 mb-4">{username}</div>
<button
onClick={onGenerate}
className="w-full py-3 rounded-xl bg-gray-800 text-white text-sm font-medium hover:bg-gray-700 transition-colors mb-6"
>
Get embed code →
</button>
{fetchError && ( {fetchError && (
<div className="flex items-center gap-1.5 text-[10px] text-red-500 mb-6"> <div className="flex items-center gap-1.5 text-[10px] text-red-500 mb-6">
<div className="w-1.5 h-1.5 rounded-full bg-red-400" /> <div className="w-1.5 h-1.5 rounded-full bg-red-400" />
@@ -318,18 +385,13 @@ export function WorkshopScreen({
</div> </div>
)} )}
{!canEdit && ( {!canEdit && me.login && (
<div className="banner"> <div className="banner">
{me.login {`Signed in as ${me.login}. Changes here produce a shareable link with query params. Only ${username} can save them permanently.`}
? `Signed in as ${me.login}. You can only edit your own widget.`
: <a href={signInUrl()}>Sign in with GitHub to edit your widget</a>}
</div> </div>
)} )}
{/* Theme, Widgets, Achievements editor, Generate — owner-only */} {/* Theme */}
{canEdit && (
<>
{/* Theme */}
<div className="mb-5"> <div className="mb-5">
<div className="text-[10px] uppercase tracking-wider text-gray-400 font-medium mb-3">Theme</div> <div className="text-[10px] uppercase tracking-wider text-gray-400 font-medium mb-3">Theme</div>
<div className="flex gap-2 flex-wrap"> <div className="flex gap-2 flex-wrap">
@@ -338,15 +400,23 @@ export function WorkshopScreen({
key={t.id} key={t.id}
onClick={() => updateSetting('theme', t.id)} onClick={() => updateSetting('theme', t.id)}
title={t.label} title={t.label}
className={`w-9 h-9 rounded-lg transition-all ${ aria-label={t.label}
className={`w-9 h-9 rounded-lg overflow-hidden transition-all ${
settings.theme === t.id settings.theme === t.id
? 'ring-2 ring-blue-500 ring-offset-2' ? 'ring-2 ring-gray-900 ring-offset-2'
: t.border : t.light
? 'border border-gray-200 hover:border-gray-300' ? 'ring-1 ring-gray-200 hover:ring-gray-300'
: 'hover:ring-1 hover:ring-gray-300 hover:ring-offset-1' : 'hover:ring-1 hover:ring-gray-400 hover:ring-offset-1'
}`} }`}
style={{ backgroundColor: t.color }} >
/> <svg viewBox="0 0 36 36" width="36" height="36">
<rect width="36" height="36" rx="8" fill={t.bg} />
<rect x="6" y="8" width="24" height="20" rx="4" fill={t.card} stroke={t.border} strokeWidth="1" />
<circle cx="11" cy="18" r="3" fill={t.accent} />
<rect x="16" y="16.25" width="10" height="1.75" rx="0.875" fill={t.accent} opacity="0.75" />
<rect x="16" y="19.75" width="7" height="1.5" rx="0.75" fill={t.accent} opacity="0.35" />
</svg>
</button>
))} ))}
</div> </div>
<div className="text-[10px] text-gray-400 mt-1.5"> <div className="text-[10px] text-gray-400 mt-1.5">
@@ -358,14 +428,83 @@ export function WorkshopScreen({
<div className="mb-5"> <div className="mb-5">
<div className="text-[10px] uppercase tracking-wider text-gray-400 font-medium mb-3">Widgets</div> <div className="text-[10px] uppercase tracking-wider text-gray-400 font-medium mb-3">Widgets</div>
<div className="flex flex-col gap-0.5"> <div className="flex flex-col gap-0.5">
{ALL_WIDGETS.map(w => { {orderedIds.map((id, idx) => {
const w = ALL_WIDGETS.find(x => x.id === id)
if (!w) return null
const enabled = settings.widgets.includes(w.id) const enabled = settings.widgets.includes(w.id)
const hasAdvanced = ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'].includes(w.id) const hasAdvanced = ['grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages', 'achievements'].includes(w.id)
const isExpanded = expandedWidget === w.id && enabled const isExpanded = expandedWidget === w.id && enabled
// "name" is pinned — no drag affordance, no drop lines.
// The dropIndex comparisons below still use the real idx
// so downstream rows behave normally when name is skipped.
const isPinned = w.id === 'name'
const isDragging = !isPinned && dragIndex === idx
const showDropLineAbove = !isPinned && idx > 0 && dropIndex === idx && dragIndex !== null && dragIndex !== idx
// Drop-line below the last row when dragging past the end.
const showDropLineBelow = !isPinned && idx === orderedIds.length - 1 && dropIndex === orderedIds.length && dragIndex !== null
return ( return (
<div key={w.id}> <div key={w.id}>
<div className="flex items-center"> {showDropLineAbove && <div className="h-0.5 bg-gray-900 rounded-full mx-2 mb-0.5" />}
<div
className={`flex items-center transition-opacity ${isDragging ? 'opacity-40' : ''}`}
draggable={!isPinned}
onDragStart={isPinned ? undefined : e => {
setDragIndex(idx)
e.dataTransfer.effectAllowed = 'move'
// Firefox needs some payload to start a drag.
e.dataTransfer.setData('text/plain', String(idx))
}}
onDragOver={isPinned ? undefined : e => {
if (dragIndex === null) return
e.preventDefault()
e.dataTransfer.dropEffect = 'move'
// Midpoint decides whether the drop slot is this row
// or the next — gives a predictable feel between rows.
const rect = e.currentTarget.getBoundingClientRect()
const after = e.clientY - rect.top > rect.height / 2
const target = after ? idx + 1 : idx
// Landing on the drag source's own slot is a no-op;
// hide the indicator so it doesn't look interactive.
if (target === dragIndex || target === dragIndex + 1) {
setDropIndex(null)
} else {
setDropIndex(target)
}
}}
onDrop={isPinned ? undefined : e => {
e.preventDefault()
if (dragIndex === null || dropIndex === null) {
setDragIndex(null); setDropIndex(null); return
}
// Removing the source before inserting shifts later
// indices down by one — adjust the target accordingly.
const to = dropIndex > dragIndex ? dropIndex - 1 : dropIndex
moveWidget(dragIndex, to)
setDragIndex(null); setDropIndex(null)
}}
onDragEnd={isPinned ? undefined : () => { setDragIndex(null); setDropIndex(null) }}
>
{isPinned ? (
<span
className="px-1 text-gray-300 select-none"
title="Pinned — can't be reordered"
aria-hidden
>
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<rect x="3" y="11" width="18" height="10" rx="2"/>
<path d="M7 11V7a5 5 0 0 1 10 0v4"/>
</svg>
</span>
) : (
<span
className="px-1 text-gray-300 hover:text-gray-500 cursor-grab active:cursor-grabbing select-none"
title="Drag to reorder"
aria-hidden
>
⋮⋮
</span>
)}
<button <button
onClick={() => toggleWidget(w.id)} onClick={() => toggleWidget(w.id)}
className={`flex-1 flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-xs transition-colors text-left ${ className={`flex-1 flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-xs transition-colors text-left ${
@@ -374,7 +513,7 @@ export function WorkshopScreen({
: 'text-gray-400 hover:text-gray-500 hover:bg-gray-50/50' : 'text-gray-400 hover:text-gray-500 hover:bg-gray-50/50'
}`} }`}
> >
<div className={`w-3.5 h-3.5 rounded flex-shrink-0 transition-colors ${enabled ? 'bg-blue-500' : 'bg-gray-200'}`} /> <div className={`w-3.5 h-3.5 rounded flex-shrink-0 transition-colors ${enabled ? 'bg-gray-900' : 'bg-gray-200'}`} />
{w.label} {w.label}
</button> </button>
{hasAdvanced && enabled && ( {hasAdvanced && enabled && (
@@ -387,6 +526,7 @@ export function WorkshopScreen({
</button> </button>
)} )}
</div> </div>
{showDropLineBelow && <div className="h-0.5 bg-gray-900 rounded-full mx-2 mt-0.5" />}
{isExpanded && ( {isExpanded && (
<div className="ml-6 mt-1 mb-2 p-2.5 rounded-lg bg-gray-50/80 border border-gray-100 flex flex-col gap-2.5"> <div className="ml-6 mt-1 mb-2 p-2.5 rounded-lg bg-gray-50/80 border border-gray-100 flex flex-col gap-2.5">
@@ -400,6 +540,16 @@ export function WorkshopScreen({
/> />
</div> </div>
)} )}
{w.id === 'grade' && (
<a
href="https://github.com/ShayManor/github-readme-stats#how-the-score-works"
target="_blank"
rel="noopener noreferrer"
className="text-[10px] text-gray-500 underline"
>
How the score works
</a>
)}
{w.id === 'impact' && ( {w.id === 'impact' && (
<div> <div>
@@ -411,6 +561,16 @@ export function WorkshopScreen({
</div> </div>
)} )}
{w.id === 'streaks' && (
<div>
<span className="text-[10px] text-gray-500 block mb-1.5">Streak color</span>
<ColorPicker
value={getWidgetSetting('streaks', 'color', '#58a6ff')}
onChange={v => updateWidgetSetting('streaks', 'color', v)}
/>
</div>
)}
{w.id === 'collaborators' && ( {w.id === 'collaborators' && (
<div className="flex flex-col gap-2.5"> <div className="flex flex-col gap-2.5">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
@@ -461,13 +621,127 @@ export function WorkshopScreen({
)} )}
{w.id === 'achievements' && ( {w.id === 'achievements' && (
<div className="flex items-center justify-between"> <div className="flex flex-col gap-2.5">
<span className="text-[10px] text-gray-500">Max shown</span> <div className="flex items-center justify-between">
<NumberStepper <span className="text-[10px] text-gray-500">Max shown</span>
value={getWidgetSetting('achievements', 'max_items', 5)} <NumberStepper
min={1} max={10} value={getWidgetSetting('achievements', 'max_items', 5)}
onChange={v => updateWidgetSetting('achievements', 'max_items', v)} min={1} max={10}
/> onChange={v => updateWidgetSetting('achievements', 'max_items', v)}
/>
</div>
<div className="flex flex-col gap-2">
{settings.achievements.map((ach, aidx) => {
const achIsDragging = achDragIndex === aidx
const achShowLineAbove = aidx > 0 && achDropIndex === aidx && achDragIndex !== null && achDragIndex !== aidx
const achShowLineBelow = aidx === settings.achievements.length - 1 && achDropIndex === settings.achievements.length && achDragIndex !== null
return (
<div key={aidx}>
{achShowLineAbove && <div className="h-0.5 bg-gray-900 rounded-full mx-2 mb-0.5" />}
<div
className={`p-2.5 rounded-lg border border-gray-100 bg-white transition-opacity ${achIsDragging ? 'opacity-40' : ''}`}
draggable
onDragStart={e => {
setAchDragIndex(aidx)
e.dataTransfer.effectAllowed = 'move'
e.dataTransfer.setData('text/plain', String(aidx))
}}
onDragOver={e => {
if (achDragIndex === null) return
e.preventDefault()
e.dataTransfer.dropEffect = 'move'
const rect = e.currentTarget.getBoundingClientRect()
const after = e.clientY - rect.top > rect.height / 2
const target = after ? aidx + 1 : aidx
if (target === achDragIndex || target === achDragIndex + 1) {
setAchDropIndex(null)
} else {
setAchDropIndex(target)
}
}}
onDrop={e => {
e.preventDefault()
if (achDragIndex === null || achDropIndex === null) {
setAchDragIndex(null); setAchDropIndex(null); return
}
const to = achDropIndex > achDragIndex ? achDropIndex - 1 : achDropIndex
moveAchievement(achDragIndex, to)
setAchDragIndex(null); setAchDropIndex(null)
}}
onDragEnd={() => { setAchDragIndex(null); setAchDropIndex(null) }}
>
<div className="flex items-center gap-1.5 mb-2">
<span
className="text-gray-300 hover:text-gray-500 cursor-grab active:cursor-grabbing select-none pr-1"
title="Drag to reorder"
aria-hidden
>
<svg width="10" height="12" viewBox="0 0 10 16" fill="currentColor" aria-hidden="true">
<circle cx="2.5" cy="3" r="1.2"/><circle cx="7.5" cy="3" r="1.2"/>
<circle cx="2.5" cy="8" r="1.2"/><circle cx="7.5" cy="8" r="1.2"/>
<circle cx="2.5" cy="13" r="1.2"/><circle cx="7.5" cy="13" r="1.2"/>
</svg>
</span>
{ICONS.map(ic => {
const selected = ach.icon === ic.id
return (
<button
key={ic.id}
onClick={() => updateAchievement(aidx, 'icon', ic.id)}
className={`w-8 h-8 rounded-md flex items-center justify-center transition-colors ${
selected
? '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'
}`}
title={ic.id}
aria-pressed={selected}
>
{ic.svg}
</button>
)
})}
<div className="flex-1" />
<button
onClick={() => removeAchievement(aidx)}
className="text-gray-300 hover:text-red-400 transition-colors text-xs px-1"
title="Remove"
>
✕
</button>
</div>
<input
type="text"
value={ach.title}
onChange={e => updateAchievement(aidx, 'title', e.target.value)}
placeholder="Title (e.g. Hackathon Winner)"
className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5"
/>
<input
type="text"
value={ach.subtitle}
onChange={e => updateAchievement(aidx, 'subtitle', e.target.value)}
placeholder="Subtitle (e.g. 1st Place · AI Track)"
className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5"
/>
<input
type="text"
value={ach.event_date}
onChange={e => updateAchievement(aidx, 'event_date', e.target.value)}
placeholder="Date (e.g. 2025-01)"
className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300"
/>
</div>
{achShowLineBelow && <div className="h-0.5 bg-gray-900 rounded-full mx-2 mt-0.5" />}
</div>
)
})}
<button
onClick={addAchievement}
className="w-full py-2 rounded-lg border border-dashed border-gray-200 text-xs text-gray-400 hover:text-gray-600 hover:border-gray-300 transition-colors"
>
+ Add achievement
</button>
</div>
</div> </div>
)} )}
</div> </div>
@@ -477,92 +751,17 @@ export function WorkshopScreen({
})} })}
</div> </div>
</div> </div>
{/* Achievements editor */}
{settings.widgets.includes('achievements') && (
<div className="mb-5">
<div className="text-[10px] uppercase tracking-wider text-gray-400 font-medium mb-3">Achievements</div>
<div className="flex flex-col gap-2">
{settings.achievements.map((ach, idx) => (
<div key={idx} className="p-2.5 rounded-lg border border-gray-100 bg-gray-50/50">
<div className="flex items-center gap-1.5 mb-2">
{ICONS.map(ic => {
const selected = ach.icon === ic.id
return (
<button
key={ic.id}
onClick={() => updateAchievement(idx, 'icon', ic.id)}
className={`w-8 h-8 rounded-md flex items-center justify-center transition-colors ${
selected
? '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'
}`}
title={ic.id}
aria-pressed={selected}
>
{ic.svg}
</button>
)
})}
<div className="flex-1" />
<button
onClick={() => removeAchievement(idx)}
className="text-gray-300 hover:text-red-400 transition-colors text-xs px-1"
title="Remove"
>
✕
</button>
</div>
<input
type="text"
value={ach.title}
onChange={e => updateAchievement(idx, 'title', e.target.value)}
placeholder="Title (e.g. Hackathon Winner)"
className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5"
/>
<input
type="text"
value={ach.subtitle}
onChange={e => updateAchievement(idx, 'subtitle', e.target.value)}
placeholder="Subtitle (e.g. 1st Place · AI Track)"
className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5"
/>
<input
type="text"
value={ach.event_date}
onChange={e => updateAchievement(idx, 'event_date', e.target.value)}
placeholder="Date (e.g. 2025-01)"
className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300"
/>
</div>
))}
<button
onClick={addAchievement}
className="w-full py-2 rounded-lg border border-dashed border-gray-200 text-xs text-gray-400 hover:text-gray-600 hover:border-gray-300 transition-colors"
>
+ Add achievement
</button>
</div>
</div>
)}
{/* Spacer */}
<div className="flex-1 min-h-4" />
{/* Generate button */}
<button
onClick={onGenerate}
className="w-full py-3 rounded-xl bg-gray-800 text-white text-sm font-medium hover:bg-gray-700 transition-colors"
>
Generate →
</button>
</>
)}
</div> </div>
{/* Right preview area */} {/* Right preview area */}
<div className="flex-1 flex items-start justify-center p-8 overflow-auto"> <div className="flex-1 flex items-start justify-center p-8 overflow-auto">
<div className="relative"> <div className="relative">
{isDemoData && svgContent && (
<div className="flex items-center gap-1.5 mx-auto mb-3 w-fit rounded-full border border-amber-200 bg-amber-50 px-2.5 py-1 text-[10px] text-amber-700">
<div className="w-1.5 h-1.5 rounded-full bg-amber-400" />
Sample data until your stats finish building
</div>
)}
{svgContent ? ( {svgContent ? (
<div dangerouslySetInnerHTML={{ __html: svgContent }} /> <div dangerouslySetInnerHTML={{ __html: svgContent }} />
) : ( ) : (
+22
View File
@@ -0,0 +1,22 @@
"""Gunicorn settings: one access line per request on stdout, for Pantheos.
Docker's json-file driver captures stdout and Pantheos ingests it, so each line
becomes a request log and feeds the container's rps / 5xx / p95. Monitoring
traffic (/metrics scrapes, /health checks) is left out so it doesn't drown the
real requests.
"""
from gunicorn import glogging
accesslog = "-"
access_log_format = '"%(r)s" %(s)s %(M)sms'
_QUIET_PATHS = ("/metrics", "/health")
class _Logger(glogging.Logger):
def access(self, resp, req, environ, request_time):
if req.path not in _QUIET_PATHS:
super().access(resp, req, environ, request_time)
logger_class = _Logger
+213
View File
@@ -0,0 +1,213 @@
"""Generate static SVG examples for the README.
Renders each widget plus the composite card in every built-in theme using
plausible hand-crafted model instances. Outputs go to
`screenshots/examples/`. Run from the repo root:
cd generator && python -m scripts.gen_readme_examples
No GitHub calls, no fetcher, no database.
"""
from __future__ import annotations
import os
import pathlib
import sys
from datetime import date, timedelta
# Ensure `src` package is importable when running `python -m scripts.*`.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src.models import (
AchievementData,
CollaboratorData,
FocusCategory,
GradeData,
ImpactWeek,
LanguageData,
StreakData,
TagData,
)
from src.widgets import (
render_achievements_widget,
render_collaborators_widget,
render_focus_widget,
render_grade_widget,
render_impact_widget,
render_languages_widget,
render_streaks_widget,
)
from src.widgets.composite import compose_widget
OUT = pathlib.Path(__file__).resolve().parents[2] / "assets" / "examples"
OUT.mkdir(parents=True, exist_ok=True)
def grade_sample() -> GradeData:
return GradeData(
grade="A",
score=88.4,
stats={"commits": 1423, "prs": 87, "stars": 342, "repos": 28, "followers": 156},
tags=[
TagData(tag="Backend", source="earned", confidence=0.95),
TagData(tag="ML", source="earned", confidence=0.82),
TagData(tag="Systems", source="earned", confidence=0.70),
TagData(tag="Cloud", source="earned", confidence=0.60),
TagData(tag="founder", source="earned", label="Founder #42"),
TagData(tag="Open Source", source="chosen"),
],
)
def impact_sample() -> list[ImpactWeek]:
today = date.today()
start = today - timedelta(days=7 * 26)
pattern = [3, 5, 8, 6, 11, 14, 9, 12, 18, 22, 17, 19, 25, 21, 28, 32, 26, 24,
30, 35, 29, 33, 41, 38, 34, 37]
weeks: list[ImpactWeek] = []
for i, count in enumerate(pattern):
weeks.append(ImpactWeek(week_start=(start + timedelta(days=7 * i)).isoformat(),
commits=count))
return weeks
def streaks_sample() -> StreakData:
today = date.today()
return StreakData(
current=23,
max=61,
current_start=(today - timedelta(days=22)).isoformat(),
last_active_date=today.isoformat(),
max_start=(today - timedelta(days=220)).isoformat(),
max_end=(today - timedelta(days=160)).isoformat(),
)
def collaborators_sample() -> list[CollaboratorData]:
return [
CollaboratorData(username="torvalds", shared_repos=4, shared_commits=142),
CollaboratorData(username="gaearon", shared_repos=3, shared_commits=98),
CollaboratorData(username="sindresorhus", shared_repos=2, shared_commits=64),
CollaboratorData(username="tj", shared_repos=2, shared_commits=47),
CollaboratorData(username="yyx990803", shared_repos=1, shared_commits=31),
]
def focus_sample() -> list[FocusCategory]:
return [
FocusCategory(category="Backend", percentage=38.0, commit_count=412),
FocusCategory(category="ML", percentage=24.0, commit_count=260),
FocusCategory(category="Frontend", percentage=18.0, commit_count=195),
FocusCategory(category="DevOps", percentage=12.0, commit_count=130),
FocusCategory(category="Cloud", percentage=8.0, commit_count=87),
]
def languages_sample() -> list[LanguageData]:
return [
LanguageData(language="Python", percentage=41.0, loc=180_432),
LanguageData(language="TypeScript", percentage=23.0, loc=102_310),
LanguageData(language="Go", percentage=15.0, loc=66_540),
LanguageData(language="Rust", percentage=11.0, loc=48_210),
LanguageData(language="Shell", percentage=6.0, loc=27_004),
LanguageData(language="Dockerfile", percentage=4.0, loc=18_120),
]
def achievements_sample() -> list[AchievementData]:
return [
AchievementData(title="Hackathon winner",
subtitle="Y Combinator AI Hackathon",
event_date="2025-11",
icon="hackathon"),
AchievementData(title="Speaker at PyCon",
subtitle="Async at scale",
event_date="2024-05",
icon="star"),
AchievementData(title="Open Source Award",
subtitle="GitHub Stars program",
event_date="2024-01",
icon="trophy"),
AchievementData(title="AWS Certified Solutions Architect",
subtitle="Professional",
event_date="2023-09",
icon="medal"),
]
def render_all(theme: str, widget_settings: dict | None = None) -> dict[str, str]:
ws = widget_settings or {}
widgets = {
"grade": render_grade_widget(grade_sample(), theme, settings=ws.get("grade")),
"impact": render_impact_widget(impact_sample(), theme, settings=ws.get("impact")),
"streaks": render_streaks_widget(streaks_sample(), theme, settings=ws.get("streaks")),
"collaborators": render_collaborators_widget(collaborators_sample(), theme, settings=ws.get("collaborators")),
"focus": render_focus_widget(focus_sample(), theme, settings=ws.get("focus")),
"languages": render_languages_widget(languages_sample(), theme, settings=ws.get("languages")),
"achievements": render_achievements_widget(achievements_sample(), theme, settings=ws.get("achievements")),
}
return widgets
def write(name: str, svg: str) -> None:
(OUT / name).write_text(svg)
print(f" wrote {name} ({len(svg)}B)")
def main() -> None:
print(f"generating into {OUT}")
# Individual widgets in the default theme.
default = render_all("dark")
for key, svg in default.items():
write(f"{key}.svg", svg)
# Composite card in every theme.
for theme in ("dark", "onyx", "nord", "light", "paper"):
widgets = render_all(theme)
svg = compose_widget(
widgets=widgets,
enabled=["grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"],
theme_name=theme,
username="demo",
show_name=False,
)
label = {"dark": "midnight", "light": "clean"}.get(theme, theme)
write(f"composite-{label}.svg", svg)
# Customization demos.
purple_impact = render_impact_widget(impact_sample(), "dark",
settings={"line_color": "#a78bfa"})
write("impact-purple.svg", purple_impact)
green_streaks = render_streaks_widget(streaks_sample(), "dark",
settings={"color": "#3fb950"})
write("streaks-green.svg", green_streaks)
compact_grade = render_grade_widget(grade_sample(), "dark",
settings={"max_tags": 3})
write("grade-compact.svg", compact_grade)
hidden_langs = render_languages_widget(
[l for l in languages_sample() if l.language not in {"Shell", "Dockerfile"}],
"dark",
)
write("languages-hide.svg", hidden_langs)
# Composite picking only a few widgets, onyx theme.
onyx_widgets = render_all("onyx")
svg = compose_widget(
widgets={k: onyx_widgets[k] for k in ("grade", "streaks", "languages")},
enabled=["grade", "streaks", "languages"],
theme_name="onyx",
username="demo",
show_name=False,
)
write("composite-custom.svg", svg)
print("done")
if __name__ == "__main__":
main()
+481
View File
@@ -0,0 +1,481 @@
"""Analytics: bounded in-memory queue, daemon flush thread, query helpers.
Three call sites write events:
* record_request — generator's own HTTP path (rarely used; edge handles most)
* record_render — worker / on-demand /generate
* ingest_batch — POST /internal/analytics/events from edge & fetcher
All writes go through a shared bounded deque so the hot path never blocks on
SQLite I/O. A daemon thread flushes the queue every _FLUSH_SECONDS into
analytics.db in a single transaction.
"""
import json
import logging
import math
import threading
import time
from collections import deque
from typing import Any
from . import config, db
log = logging.getLogger("generator.analytics")
_FLUSH_SECONDS = config.ANALYTICS_FLUSH_SECONDS
_QUEUE_MAX = config.ANALYTICS_QUEUE_MAX
_RETENTION_DAYS = config.ANALYTICS_RETENTION_DAYS
_QUEUE: deque = deque(maxlen=_QUEUE_MAX)
_QUEUE_LOCK = threading.Lock()
_FLUSH_THREAD: threading.Thread | None = None
_THREAD_LOCK = threading.Lock()
_events_dropped: int = 0
_drop_lock = threading.Lock()
_ALLOWED_KINDS = {"request", "render", "fetch"}
_ALLOWED_SERVICES = {"edge", "generator", "fetcher"}
def _reset_for_tests() -> None:
"""Clear the queue + dropped counter; rebuild deque so a monkeypatched
_QUEUE_MAX takes effect for the next test."""
global _FLUSH_THREAD, _events_dropped, _QUEUE
with _QUEUE_LOCK:
_QUEUE = deque(maxlen=_QUEUE_MAX)
with _drop_lock:
_events_dropped = 0
_FLUSH_THREAD = None
def _enqueue(event: dict) -> None:
global _events_dropped
with _QUEUE_LOCK:
if len(_QUEUE) >= _QUEUE.maxlen:
with _drop_lock:
_events_dropped += 1
return
_QUEUE.append(event)
def record_request(endpoint: str, username: str | None, widget: str | None,
status: int, latency_ms: int, cache_hit: int | None = None) -> None:
_enqueue({
"ts": int(time.time()),
"service": "generator",
"kind": "request",
"username": username,
"endpoint": endpoint,
"widget": widget,
"status": int(status),
"latency_ms": int(latency_ms),
"cache_hit": cache_hit,
})
def record_render(username: str, widget: str, latency_ms: int) -> None:
_enqueue({
"ts": int(time.time()),
"service": "generator",
"kind": "render",
"username": username,
"endpoint": None,
"widget": widget,
"status": None,
"latency_ms": int(latency_ms),
"cache_hit": None,
})
def _coerce_int_or_none(v: Any) -> int | None:
if isinstance(v, bool) or v is None:
return None
if isinstance(v, int):
return v
return None
def _validate(ev: Any) -> dict | None:
if not isinstance(ev, dict):
return None
try:
ts = int(ev.get("ts", 0))
if ts <= 0:
ts = int(time.time())
service = ev.get("service")
kind = ev.get("kind")
latency_ms = int(ev.get("latency_ms"))
except (TypeError, ValueError):
return None
if service not in _ALLOWED_SERVICES or kind not in _ALLOWED_KINDS:
return None
return {
"ts": ts,
"service": service,
"kind": kind,
"username": ev.get("username") if isinstance(ev.get("username"), str) else None,
"endpoint": ev.get("endpoint") if isinstance(ev.get("endpoint"), str) else None,
"widget": ev.get("widget") if isinstance(ev.get("widget"), str) else None,
"status": _coerce_int_or_none(ev.get("status")),
"latency_ms": max(0, latency_ms),
"cache_hit": _coerce_int_or_none(ev.get("cache_hit")),
}
def ingest_batch(events: list) -> int:
"""Validate + persist a batch in one transaction. Returns rows inserted."""
if not isinstance(events, list):
return 0
cleaned = []
for ev in events[:500]:
n = _validate(ev)
if n is not None:
cleaned.append(n)
if not cleaned:
return 0
with db.analytics_conn() as c:
c.executemany(
"""INSERT INTO events(ts, service, kind, username, endpoint, widget,
status, latency_ms, cache_hit)
VALUES (:ts, :service, :kind, :username, :endpoint, :widget,
:status, :latency_ms, :cache_hit)""",
cleaned,
)
c.commit()
return len(cleaned)
def _drain_queue() -> list[dict]:
with _QUEUE_LOCK:
out = list(_QUEUE)
_QUEUE.clear()
return out
def _flush_loop() -> None:
while True:
time.sleep(_FLUSH_SECONDS)
try:
batch = _drain_queue()
if batch:
ingest_batch(batch)
except Exception:
log.exception("analytics flush failed")
def start_flush_thread() -> None:
global _FLUSH_THREAD
with _THREAD_LOCK:
if _FLUSH_THREAD is not None and _FLUSH_THREAD.is_alive():
return
t = threading.Thread(target=_flush_loop, name="analytics-flush", daemon=True)
t.start()
_FLUSH_THREAD = t
def _percentile(sorted_vals: list[int], pct: float) -> int:
if not sorted_vals:
return 0
n = len(sorted_vals)
k = max(0, min(n - 1, math.ceil(pct / 100.0 * n) - 1))
return int(sorted_vals[k])
def query_summary() -> dict:
now = int(time.time())
week_ago = now - 7 * 86400
with db.analytics_conn() as c:
req_rows = c.execute(
"""SELECT username, latency_ms, ts FROM events
WHERE kind='request' AND ts >= ?""", (week_ago,)
).fetchall()
render_rows = c.execute(
"""SELECT username, latency_ms FROM events
WHERE kind='render' AND ts >= ?""", (week_ago,)
).fetchall()
requests_7d = len(req_rows)
renders_7d = len(render_rows)
latencies = sorted(r["latency_ms"] for r in req_rows)
active = {r["username"] for r in req_rows if r["username"]}
active.update(r["username"] for r in render_rows if r["username"])
avg_render_ms = (sum(r["latency_ms"] for r in render_rows) // renders_7d) if renders_7d else 0
by_day: dict[str, int] = {}
for r in req_rows:
day = time.strftime("%Y-%m-%d", time.gmtime(r["ts"]))
by_day[day] = by_day.get(day, 0) + 1
daily = []
for i in range(6, -1, -1):
day = time.strftime("%Y-%m-%d", time.gmtime(now - i * 86400))
daily.append({"day": day, "count": by_day.get(day, 0)})
return {
"requests_7d": requests_7d,
"active_users_7d": len(active),
"p50_ms": _percentile(latencies, 50),
"p95_ms": _percentile(latencies, 95),
"renders_7d": renders_7d,
"avg_render_ms": avg_render_ms,
"daily_requests": daily,
}
def query_users(q: str = "", sort: str = "requests", limit: int = 200) -> list[dict]:
now = int(time.time())
week_ago = now - 7 * 86400
with db.analytics_conn() as c:
c.execute("ATTACH DATABASE ? AS settings", (db.SETTINGS_DB_PATH,))
try:
# Count any event kind (request OR render) as activity so the
# table matches `active_users_7d` in query_summary — without
# this, render-only users (e.g. cron-driven worker refreshes
# before any edge traffic) appear in the count but not the
# table, which looks like a bug.
rows = c.execute(
"""SELECT e.username AS username,
SUM(CASE WHEN e.kind='request' THEN 1 ELSE 0 END) AS requests_7d,
MAX(e.ts) AS last_seen,
COALESCE(AVG(CASE WHEN e.kind='request'
THEN e.latency_ms END), 0) AS avg_latency_ms,
(SELECT u.github_avatar_url FROM settings.users u
WHERE u.username = e.username) AS github_avatar_url
FROM events e
WHERE e.kind IN ('request', 'render')
AND e.ts >= ? AND e.username IS NOT NULL
GROUP BY e.username""",
(week_ago,),
).fetchall()
top_eps_rows = c.execute(
"""SELECT username, endpoint, COUNT(*) AS n
FROM events
WHERE kind='request' AND ts >= ? AND username IS NOT NULL
GROUP BY username, endpoint""",
(week_ago,),
).fetchall()
finally:
c.execute("DETACH DATABASE settings")
top_by_user: dict[str, tuple[str, int]] = {}
for r in top_eps_rows:
cur = top_by_user.get(r["username"])
if cur is None or r["n"] > cur[1]:
top_by_user[r["username"]] = (r["endpoint"], r["n"])
out = []
needle = q.lower().strip()
for r in rows:
if needle and needle not in (r["username"] or "").lower():
continue
out.append({
"username": r["username"],
"requests_7d": r["requests_7d"],
"last_seen": r["last_seen"],
"avg_latency_ms": int(r["avg_latency_ms"] or 0),
"top_endpoint": top_by_user.get(r["username"], ("", 0))[0],
"github_avatar_url": r["github_avatar_url"],
})
key = {
"requests": lambda u: -u["requests_7d"],
"latency": lambda u: -u["avg_latency_ms"],
"last_seen": lambda u: -(u["last_seen"] or 0),
}.get(sort, lambda u: -u["requests_7d"])
out.sort(key=key)
return out[: max(1, min(int(limit), 500))]
def rollup_daily_stats() -> int:
"""Snapshot the events table into daily_stats so per-day numbers
survive the 14d event prune.
Aggregates every day that still has events in the events table,
UPSERTing one row per day with (request count, JSON list of unique
usernames). Days whose events have already been pruned are left
untouched — their previously-written daily_stats row is preserved.
Idempotent: re-running rebuilds the affected days from current
events. Pairs with prune_old, which aligns its cutoff to UTC
midnight so a day is either entirely retained or entirely pruned
(no half-pruned days that would corrupt the snapshot on next call).
Returns number of day rows written.
"""
with db.analytics_conn() as c:
rows = c.execute(
"""SELECT ts, kind, username FROM events
WHERE kind IN ('request', 'render')"""
).fetchall()
if not rows:
return 0
buckets: dict[str, dict] = {}
for r in rows:
day = time.strftime("%Y-%m-%d", time.gmtime(r["ts"]))
b = buckets.setdefault(day, {"requests": 0, "users": set()})
if r["kind"] == "request":
b["requests"] += 1
if r["username"]:
b["users"].add(r["username"])
now_iso = db._now()
payload = [
{"day": day,
"requests": b["requests"],
"users_json": json.dumps(sorted(b["users"]), separators=(",", ":")),
"updated_at": now_iso}
for day, b in buckets.items()
]
with db.analytics_conn() as c:
c.executemany(
"""INSERT INTO daily_stats(day, requests, users_json, updated_at)
VALUES (:day, :requests, :users_json, :updated_at)
ON CONFLICT(day) DO UPDATE SET
requests = excluded.requests,
users_json = excluded.users_json,
updated_at = excluded.updated_at""",
payload,
)
c.commit()
return len(payload)
def query_growth(daily_n: int = 30, weekly_n: int = 12) -> dict:
"""Per-day and per-week unique users + request counts.
Reads from daily_stats (the long-lived snapshot table) so historical
numbers survive past the 14d event retention. Calls rollup_daily_stats
first so today's partial-day numbers are fresh even between cron ticks.
"Users" mirrors the active_users definition in query_summary — any
kind in (request, render) counts as active. Weekly uniques are the
set-union across the week's days (not a sum), so a user active on
multiple days in the same week counts once.
Returns:
{"daily": [{"day": "YYYY-MM-DD", "users": int, "requests": int}, ...], # oldest -> newest
"weekly": [{"week": "GGGG-Www", "users": int, "requests": int}, ...]}
"""
rollup_daily_stats()
now = int(time.time())
with db.analytics_conn() as c:
stat_rows = c.execute(
"SELECT day, requests, users_json FROM daily_stats"
).fetchall()
by_day: dict[str, dict] = {}
for r in stat_rows:
try:
users = set(json.loads(r["users_json"]))
except (ValueError, TypeError):
users = set()
by_day[r["day"]] = {"requests": int(r["requests"] or 0), "users": users}
daily = []
for i in range(daily_n - 1, -1, -1):
d = time.strftime("%Y-%m-%d", time.gmtime(now - i * 86400))
b = by_day.get(d)
daily.append({
"day": d,
"requests": b["requests"] if b else 0,
"users": len(b["users"]) if b else 0,
})
# Weekly: union across each ISO week's days. Stepping by 7 days from
# `now` lands on a different calendar day each loop but always inside
# the target ISO week, so %G-W%V correctly picks out one week per step.
week_buckets: dict[str, dict] = {}
for day, b in by_day.items():
try:
gm = time.strptime(day, "%Y-%m-%d")
except ValueError:
continue
wk = time.strftime("%G-W%V", gm)
wb = week_buckets.setdefault(wk, {"requests": 0, "users": set()})
wb["requests"] += b["requests"]
wb["users"].update(b["users"])
weekly = []
for i in range(weekly_n - 1, -1, -1):
wk = time.strftime("%G-W%V", time.gmtime(now - i * 7 * 86400))
wb = week_buckets.get(wk)
weekly.append({
"week": wk,
"requests": wb["requests"] if wb else 0,
"users": len(wb["users"]) if wb else 0,
})
return {"daily": daily, "weekly": weekly}
def query_latency() -> list[dict]:
now = int(time.time())
week_ago = now - 7 * 86400
with db.analytics_conn() as c:
top = c.execute(
"""SELECT endpoint, COUNT(*) AS n FROM events
WHERE kind='request' AND ts >= ? AND endpoint IS NOT NULL
GROUP BY endpoint ORDER BY n DESC LIMIT 12""",
(week_ago,),
).fetchall()
out = []
for r in top:
vals = [
row["latency_ms"]
for row in c.execute(
"""SELECT latency_ms FROM events
WHERE kind='request' AND ts >= ? AND endpoint = ?""",
(week_ago, r["endpoint"]),
).fetchall()
]
vals.sort()
out.append({
"endpoint": r["endpoint"],
"count": r["n"],
"p50": _percentile(vals, 50),
"p95": _percentile(vals, 95),
"p99": _percentile(vals, 99),
})
return out
def query_health() -> dict:
now = int(time.time())
week_ago = now - 7 * 86400
with db.analytics_conn() as c:
edge = c.execute(
"""SELECT SUM(CASE WHEN cache_hit=1 THEN 1 ELSE 0 END) AS hits,
COUNT(*) AS total
FROM events WHERE service='edge' AND kind='request' AND ts >= ?""",
(week_ago,),
).fetchone()
fetcher = c.execute(
"""SELECT SUM(CASE WHEN status >= 400 THEN 1 ELSE 0 END) AS errs,
COUNT(*) AS total
FROM events WHERE service='fetcher' AND kind='fetch' AND ts >= ?""",
(week_ago,),
).fetchone()
oldest = c.execute(
"SELECT MIN(ts) AS oldest FROM events"
).fetchone()
edge_total = (edge["total"] or 0)
fetch_total = (fetcher["total"] or 0)
return {
"edge_cache_hit_rate": (edge["hits"] / edge_total) if edge_total else 0.0,
"fetcher_error_rate": (fetcher["errs"] / fetch_total) if fetch_total else 0.0,
"events_dropped_24h": _events_dropped,
"oldest_event_ts": oldest["oldest"] if oldest and oldest["oldest"] else None,
}
def prune_old(retention_days: int = _RETENTION_DAYS) -> int:
# Align cutoff to UTC midnight: a day's events are either fully kept
# or fully pruned. Without this, the rollup running after a prune
# could observe a half-emptied day and overwrite daily_stats with
# partial counts.
import calendar
target_day = time.gmtime(int(time.time()) - retention_days * 86400)
cutoff = calendar.timegm((target_day.tm_year, target_day.tm_mon, target_day.tm_mday,
0, 0, 0, 0, 0, 0))
deleted = 0
with db.analytics_conn() as c:
while True:
cur = c.execute(
"DELETE FROM events WHERE id IN ("
" SELECT id FROM events WHERE ts < ? LIMIT 5000)",
(cutoff,),
)
c.commit()
n = cur.rowcount or 0
deleted += n
if n < 5000:
break
return deleted
+630 -12
View File
@@ -14,6 +14,7 @@ Two-phase pipeline:
* POST /api/<u>/generate synchronously renders and persists the composite * POST /api/<u>/generate synchronously renders and persists the composite
SVG. This is what the user's "Generate" button calls. SVG. This is what the user's "Generate" button calls.
""" """
import hmac
import logging import logging
import os import os
import time import time
@@ -24,9 +25,10 @@ from functools import wraps
from threading import BoundedSemaphore, Lock from threading import BoundedSemaphore, Lock
from flask import Flask, jsonify, request, Response, send_from_directory, session from flask import Flask, jsonify, request, Response, send_from_directory, session
from . import auth, config, db, fetcher_client, placeholder from . import analytics, auth, config, db, fetcher_client, placeholder, processor
from .themes import THEMES from .themes import THEMES
from .utils import is_valid_username, settings_size_ok from .utils import is_valid_username, settings_size_ok
from .widgets import render_grade_widget
import json as _json import json as _json
log = logging.getLogger("generator.api") log = logging.getLogger("generator.api")
@@ -71,6 +73,21 @@ def _kickoff_prefetch_async(username: str):
log.warning("prefetch pool shut down; skipping kickoff for %s", username) log.warning("prefetch pool shut down; skipping kickoff for %s", username)
def _request_fetch_async(username: str) -> None:
"""Ask the fetcher to start a background GitHub fetch for `username`.
Returns as soon as the fetcher acks (HTTP 202). The fetcher will POST
back to /internal/data-ready when the data lands in fetcher.db, which
is what enqueues the build job. Failures here are logged and dropped:
the generator's cron loop will see the user on its next tick and try
again, so a transient network blip can't permanently strand a signup.
"""
try:
fetcher_client.start_fetch_async(username)
except Exception:
log.warning("fetch-async kickoff failed for %s", username, exc_info=True)
# ---- Per-IP rate limiter ----------------------------------------------------- # ---- Per-IP rate limiter -----------------------------------------------------
# In-process sliding-window limiter. Good enough for v1; behind a reverse proxy # In-process sliding-window limiter. Good enough for v1; behind a reverse proxy
# we read X-Forwarded-For (trusting only the last hop set by the proxy). For a # we read X-Forwarded-For (trusting only the last hop set by the proxy). For a
@@ -150,12 +167,55 @@ def rate_limited(bucket: str):
return deco return deco
def track_request(widget):
"""Record one analytics 'request' event per call. `widget` may be a
literal string or a callable taking the route kwargs.
The endpoint template comes from Flask's matched url_rule; the
username is the route arg or `?username=` query param. Stack ABOVE
@rate_limited so 429s are counted too — rate-limit hits are signal.
"""
def deco(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
t0 = time.monotonic()
resp = fn(*args, **kwargs)
try:
uname = kwargs.get("username") or request.args.get("username") or ""
uname = uname.lower() if isinstance(uname, str) and uname else None
if isinstance(resp, tuple):
status_code = resp[1] if len(resp) > 1 else 200
else:
status_code = getattr(resp, "status_code", 200)
rule = request.url_rule.rule if request.url_rule else ""
endpoint = rule.replace("<username>", "<u>")
w = widget(kwargs) if callable(widget) else widget
analytics.record_request(
endpoint=endpoint, username=uname, widget=w,
status=int(status_code),
latency_ms=int((time.monotonic() - t0) * 1000),
)
except Exception:
log.exception("analytics record_request failed")
return resp
return wrapper
return deco
_STATIC_DIR = os.path.join(os.path.dirname(__file__), "static") _STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
app = Flask(__name__, static_folder=None) app = Flask(__name__, static_folder=None)
# Tolerate stray trailing slashes on every route. README embeds are copied by
# hand from all over — upstream github-readme-stats even prints its canonical
# URL as `/api/top-langs/?username=X` (note the '/' before '?'). Flask's
# default strict_slashes turns any such URL into a hard 404 with no redirect,
# so a single misplaced slash silently breaks a user's widget. Set on the map
# before the route decorators run so every rule inherits the lenient default.
app.url_map.strict_slashes = False
if config.SECRET_KEY: if config.SECRET_KEY:
app.secret_key = config.SECRET_KEY app.secret_key = config.SECRET_KEY
else: else:
@@ -184,7 +244,18 @@ app.config["MAX_CONTENT_LENGTH"] = 128 * 1024
# ["max_count"])` raise, or by ballooning the DB with unbounded fields. # ["max_count"])` raise, or by ballooning the DB with unbounded fields.
# We normalize to an explicit allow-list of fields and coerce/trim types. # We normalize to an explicit allow-list of fields and coerce/trim types.
_ALLOWED_WIDGETS = {"grade", "impact", "collaborators", "focus", "languages", "achievements"} _ALLOWED_WIDGETS = {"name", "grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"}
# Singular / other-service aliases accepted by the widget-first compat route
# (`/api/<widget>/<u>`). Lets people paste e.g. `/api/streak/<u>` straight from
# a streak-stats badge URL and still hit this fork's `streaks` widget.
_WIDGET_ALIASES = {
"streak": "streaks",
"lang": "languages",
"langs": "languages",
"top-langs": "languages",
"achievement": "achievements",
"collaborator": "collaborators",
}
_ALLOWED_ICONS = {"trophy", "medal", "star", "hackathon"} _ALLOWED_ICONS = {"trophy", "medal", "star", "hackathon"}
_MAX_ACHIEVEMENTS = 10 _MAX_ACHIEVEMENTS = 10
_TITLE_MAX = 80 _TITLE_MAX = 80
@@ -240,6 +311,7 @@ def _coerce_widget_settings(v) -> dict:
allowed = { allowed = {
"grade": {"max_tags": "int"}, "grade": {"max_tags": "int"},
"impact": {"line_color": "color"}, "impact": {"line_color": "color"},
"streaks": {"color": "color"},
"collaborators": {"max_count": "int", "bar_color": "color"}, "collaborators": {"max_count": "int", "bar_color": "color"},
"focus": {"max_categories": "int"}, "focus": {"max_categories": "int"},
"languages": {"max_languages": "int"}, "languages": {"max_languages": "int"},
@@ -259,6 +331,8 @@ def _coerce_widget_settings(v) -> dict:
clean[key] = int(val) clean[key] = int(val)
except (TypeError, ValueError): except (TypeError, ValueError):
continue continue
elif kind == "bool":
clean[key] = bool(val)
elif kind == "color": elif kind == "color":
# Deep color validation happens in the widget renderer # Deep color validation happens in the widget renderer
# (safe_color). Here we only reject obviously wrong types # (safe_color). Here we only reject obviously wrong types
@@ -270,6 +344,86 @@ def _coerce_widget_settings(v) -> dict:
return out return out
def sanitize_settings_query(args) -> dict:
"""Parse settings overrides from URL query params for the public
`GET /api/<u>` endpoint. This is the unauthenticated edit path — the
caller doesn't need to own the widget, they just craft a URL whose
query string encodes their chosen settings.
Accepted params (all optional, case-sensitive):
theme=<name> - one of THEMES keys
widgets=<csv> - enabled widget ids
order=<csv> - widget render order
hide=<csv> - languages to exclude
tags=<csv> - extra custom tags
<widget>.<key>=<value> - per-widget settings (e.g. grade.max_tags=6,
impact.line_color=%23a78bfa)
ach=<url-safe-base64-json> - list of {title, subtitle, event_date, icon}
Unknown keys and malformed values are silently dropped; the same
allow-listing rules as `sanitize_settings` apply. The result is a
partial settings dict that can be merged onto the user's stored
settings without any further validation.
"""
out: dict = {}
if args is None:
return out
theme = args.get("theme")
if isinstance(theme, str) and theme in THEMES:
out["theme"] = theme
def _csv(key: str) -> list[str]:
v = args.get(key) or ""
return [s for s in (p.strip() for p in v.split(",")) if s]
if "widgets" in args:
out["enabled"] = [w for w in _csv("widgets") if w in _ALLOWED_WIDGETS][:20]
if "order" in args:
out["widget_order"] = [w for w in _csv("order") if w in _ALLOWED_WIDGETS][:20]
if "hide" in args:
out["hidden_languages"] = [s[:_LANG_MAX] for s in _csv("hide")[:_MAX_HIDDEN_LANGS]]
if "tags" in args:
out["custom_tags"] = [s[:_TAG_MAX] for s in _csv("tags")[:_MAX_CUSTOM_TAGS]]
# Per-widget settings via dot-notation keys. Collect first, then hand off
# to _coerce_widget_settings so type rules stay in exactly one place.
ws_raw: dict[str, dict] = {}
for key in args.keys():
if "." not in key:
continue
widget, sub = key.split(".", 1)
if widget not in _ALLOWED_WIDGETS:
continue
ws_raw.setdefault(widget, {})[sub] = args.get(key)
if ws_raw:
ws = _coerce_widget_settings(ws_raw)
if ws:
out["widget_settings"] = ws
# Achievements as url-safe base64(json). Compact enough for reasonable
# counts; longer embeds can still fall back to the authenticated path.
ach_raw = args.get("ach")
if isinstance(ach_raw, str) and ach_raw:
try:
import base64
padded = ach_raw + "=" * (-len(ach_raw) % 4)
decoded = base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8")
parsed = _json.loads(decoded)
except Exception:
parsed = None
if isinstance(parsed, list):
cleaned = []
for a in parsed[:_MAX_ACHIEVEMENTS]:
ca = _coerce_achievement(a)
if ca:
cleaned.append(ca)
out["achievements"] = cleaned
return out
def sanitize_settings(body: dict) -> dict: def sanitize_settings(body: dict) -> dict:
"""Project an untrusted JSON object down to the fields we accept. """Project an untrusted JSON object down to the fields we accept.
@@ -314,9 +468,41 @@ def sanitize_settings(body: dict) -> dict:
return out return out
@app.route("/dev")
@auth.require_basic_auth
def dev_index():
"""Gate the dashboard page itself so the browser pops the native
Basic-Auth prompt before any HTML loads. Without this, the SPA bundle
serves unauthenticated and the dashboard shell renders before the XHR
401 lands — defeating the auth wall."""
index = os.path.join(_STATIC_DIR, "index.html")
if os.path.isfile(index):
return send_from_directory(_STATIC_DIR, "index.html")
return jsonify({"error": "frontend not built"}), 503
@app.route("/", defaults={"path": ""}) @app.route("/", defaults={"path": ""})
@app.route("/<path:path>") @app.route("/<path:path>")
def spa(path: str): def spa(path: str):
# Drop-in shortcut: `/?username=X` (or `/api/?username=X`) force-renders
# just the developer profile (grade) widget for that user and returns the
# SVG directly. No SPA, no composite — the single widget that README
# embeds care about. `/api/<u>` and friends keep working below.
if path in ("", "api", "api/") and request.args.get("username"):
t0 = time.monotonic()
u = request.args.get("username", "")
resp = _serve_profile_widget(u)
try:
status_code = resp[1] if isinstance(resp, tuple) else getattr(resp, "status_code", 200)
analytics.record_request(
endpoint="/?username=<u>",
username=(u or "").lower() if isinstance(u, str) else None,
widget="grade", status=int(status_code),
latency_ms=int((time.monotonic() - t0) * 1000),
)
except Exception:
log.exception("analytics record_request failed")
return resp
if path.startswith("api/"): if path.startswith("api/"):
return jsonify({"error": "not found"}), 404 return jsonify({"error": "not found"}), 404
if path: if path:
@@ -349,12 +535,23 @@ def auth_logout():
return ("", 204) return ("", 204)
def _enrollment_capped() -> bool:
"""True when a new enrollment would exceed the daily budget or the hourly
burst guard. Both protect the shared GitHub PAT."""
return (db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP
or db.enrollments_last_hour() >= config.ENROLLMENT_HOURLY_CAP)
@app.route("/api/auth/github/login", methods=["GET"]) @app.route("/api/auth/github/login", methods=["GET"])
def auth_github_login(): def auth_github_login():
import secrets as _secrets import secrets as _secrets
nxt = request.args.get("next", "/") nxt = request.args.get("next", "/")
# Only accept local relative paths to prevent open-redirect. # Only accept local relative paths to prevent open-redirect.
if not isinstance(nxt, str) or not nxt.startswith("/"): # Reject protocol-relative ("//evil") and backslash ("/\evil") forms,
# which browsers resolve against the current scheme.
if (not isinstance(nxt, str)
or not nxt.startswith("/")
or nxt.startswith(("//", "/\\"))):
nxt = "/" nxt = "/"
state = _secrets.token_urlsafe(32) state = _secrets.token_urlsafe(32)
session["oauth_state"] = state session["oauth_state"] = state
@@ -364,9 +561,16 @@ def auth_github_login():
def _derived_redirect_uri() -> str: def _derived_redirect_uri() -> str:
# Works behind cloudflared: the X-Forwarded-Proto/Host headers are set. # The tunnel does not reliably forward the original scheme, so
# X-Forwarded-Proto can be absent and request.scheme is then http. GitHub
# compares redirect_uri against the callback registered on the OAuth app
# character for character, so an http:// value is rejected with "The
# redirect_uri is not associated with this application" and sign-in becomes
# impossible. Anything that is not a local dev host is served over https.
proto = request.headers.get("X-Forwarded-Proto") or request.scheme proto = request.headers.get("X-Forwarded-Proto") or request.scheme
host = request.headers.get("X-Forwarded-Host") or request.host host = request.headers.get("X-Forwarded-Host") or request.host
if host.split(":")[0] not in ("localhost", "127.0.0.1"):
proto = "https"
return f"{proto}://{host}/api/auth/github/callback" return f"{proto}://{host}/api/auth/github/callback"
@@ -418,13 +622,29 @@ def auth_github_callback():
session["gh_id"] = gh_id session["gh_id"] = gh_id
session["gh_avatar_url"] = avatar_url session["gh_avatar_url"] = avatar_url
# Implicit enrollment. Idempotent; refreshes github_avatar_url on return logins. # Implicit enrollment. Three converging paths kick off the build, all
# idempotent — the goal is that no single failure (fetcher unreachable,
# worker process not running, callback mis-delivered) can strand the
# signup waiting on cron's 15-min tick.
# 1) db.enroll() enqueues a 'build' job. Worker container or the
# in-process kickoff pool will pop it; if the fetcher has no
# data yet, /data auto-fetches synchronously (fast now that the
# pipeline is parallelized end-to-end).
# 2) _request_fetch_async asks the fetcher to start a background
# fetch immediately. When it finishes, it calls back to
# /internal/data-ready, which is a no-op if a pending build for
# this user already exists — it just shortens latency in the
# common case.
# 3) _kickoff_prefetch_async runs process_one() in this process's
# thread pool. This is the safety net for deployments that don't
# run a separate worker process (gunicorn-only setups).
defaults = { defaults = {
"theme": "dark", "theme": "dark",
"enabled": config.ENABLED_WIDGETS, "enabled": config.ENABLED_WIDGETS,
"widget_order": config.WIDGET_ORDER, "widget_order": config.WIDGET_ORDER,
} }
db.enroll(login, defaults, github_id=gh_id, github_avatar_url=avatar_url) db.enroll(login, defaults, github_id=gh_id, github_avatar_url=avatar_url)
_request_fetch_async(login)
_kickoff_prefetch_async(login) _kickoff_prefetch_async(login)
return redirect(nxt) return redirect(nxt)
@@ -435,15 +655,81 @@ def health():
return jsonify({"status": "ok", "service": "generator"}) return jsonify({"status": "ok", "service": "generator"})
@app.route("/internal/data-ready", methods=["POST"])
def internal_data_ready():
"""Called by the fetcher when a /fetch-async background job finishes.
Token-protected by the same shared secret used for generator -> fetcher
calls. The body is `{username, payload_hash, ok}`. If the user is
enrolled, enqueue a build job; the worker picks it up on its next 0.5s
tick and the fetcher's data is already cached, so the build runs in
seconds. If the user is not enrolled here we silently ignore — the
fetcher might have been kicked off by some other path (cron, manual
refresh) and we don't want to leak a job for a stranger.
"""
token = request.headers.get("X-Internal-Token", "")
if not config.FETCHER_INTERNAL_TOKEN or not hmac.compare_digest(
token, config.FETCHER_INTERNAL_TOKEN
):
return jsonify({"error": "unauthorized"}), 401
body = request.get_json(silent=True) or {}
username = body.get("username")
if not isinstance(username, str) or not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
username = username.lower()
if db.get_settings(username) is None:
return jsonify({"ignored": True, "reason": "not_enrolled"}), 200
if not body.get("ok", True):
# The fetch failed (network / GitHub 5xx). No point queueing a
# build that would just fail too. The cron loop will retry the
# fetch on its next tick.
return jsonify({"ignored": True, "reason": "fetch_failed"}), 200
# Idempotent: the OAuth callback already enqueues a build directly so
# the worker can make progress even if this callback never arrives.
# If a build is already pending/running, don't queue a second one.
if db.has_open_build(username):
return jsonify({"ignored": True, "reason": "already_queued"}), 200
job_id = db.enqueue_build(username)
log.info("enqueued build %d for %s after fetch completion", job_id, username)
return jsonify({"queued": True, "job_id": job_id}), 200
@app.route("/internal/analytics/events", methods=["POST"])
def internal_analytics_events():
token = request.headers.get("X-Internal-Token", "")
if not config.FETCHER_INTERNAL_TOKEN or not hmac.compare_digest(
token, config.FETCHER_INTERNAL_TOKEN
):
return jsonify({"error": "unauthorized"}), 401
body = request.get_json(silent=True) or {}
events = body.get("events", [])
if not isinstance(events, list):
return jsonify({"error": "bad_request"}), 400
n = analytics.ingest_batch(events)
return jsonify({"ingested": n})
# Literal placeholders from the README snippets. Lowercased because the
# username normaliser lowercases before this is reached.
_DOC_PLACEHOLDERS = {"your_username", "yourusername", "your-username", "username"}
@app.route("/api/<username>", methods=["GET"]) @app.route("/api/<username>", methods=["GET"])
@track_request("composite")
@rate_limited("read") @rate_limited("read")
def get_widget(username: str): def get_widget(username: str):
if username.lower() in _DOC_PLACEHOLDERS:
# People paste the README snippet without swapping YOUR_USERNAME for
# their own name, so GitHub renders a broken image on their profile.
# A card that says what to do is more use to them than a JSON 400.
return _placeholder_response("unsubstituted", username)
if not is_valid_username(username): if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400 return jsonify({"error": "invalid_username"}), 400
return _serve(username, widget_name="composite") return _serve(username, widget_name="composite")
@app.route("/api/<username>/<widget>.svg", methods=["GET"]) @app.route("/api/<username>/<widget>.svg", methods=["GET"])
@track_request(lambda kw: kw.get("widget"))
@rate_limited("read") @rate_limited("read")
def get_widget_named(username: str, widget: str): def get_widget_named(username: str, widget: str):
if not is_valid_username(username): if not is_valid_username(username):
@@ -453,24 +739,119 @@ def get_widget_named(username: str, widget: str):
return _serve(username, widget_name=widget) return _serve(username, widget_name=widget)
@app.route("/api/<widget>/<username>", methods=["GET"])
@track_request(lambda kw: _WIDGET_ALIASES.get(kw.get("widget"), kw.get("widget")))
@rate_limited("read")
def get_widget_first(widget: str, username: str):
"""Widget-first compat format: `/api/<widget>/<username>`.
The native shape is `/api/<u>/<widget>.svg`, but people copy the
reversed `/api/streak/<u>` form out of other badge services' READMEs.
Map the (aliased) widget name onto the same auto-enrolling `_serve`
path so a first hit for a never-seen user queues a build instead of
falling through to the catch-all 404.
Routing precedence: Flask matches the static-suffixed
`/api/<u>/<widget>.svg` rule and the literal `/api/<u>/data` (and
/settings, /generate, /refresh) rules ahead of this fully-dynamic one,
so it only claims the two-segment space that previously 404'd.
"""
if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
name = _WIDGET_ALIASES.get(widget, widget)
if name not in _ALLOWED_WIDGETS and name != "composite":
return jsonify({"error": "unknown_widget"}), 400
return _serve(username, widget_name=name)
@app.route("/api/top-langs", methods=["GET"])
@track_request("languages")
@rate_limited("read")
def compat_top_langs():
"""Compatibility shim for upstream anuraghazra/github-readme-stats URLs.
People copy `/api/top-langs?username=X&...` straight out of READMEs
that target the upstream Vercel-hosted service and just swap in
gh-stats.com. Without this route the request would fall through to
/api/<u> with username='top-langs', which is meaningless here.
Routing precedence: Flask matches the literal '/api/top-langs' before
the '/api/<username>' rule, so this can't shadow real users.
Upstream-only query params (layout, title_color, text_color,
bg_color, hide_border, langs_count, hide, etc.) are deliberately
ignored — themeing in this fork is per-user, configured in the
workshop, not per-URL. The intent is that the embedded image
*renders something coherent* instead of 'user not found'.
"""
username = request.args.get("username", "")
if not isinstance(username, str) or not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
username = username.lower()
# Same auto-enroll path as GET /api/<u>/data so a first-time visitor
# doesn't sit on a placeholder forever. Daily cap is the abuse
# backstop; without it a botnet hitting random ?username= values
# could exhaust the GitHub PAT budget.
if db.get_settings(username) is None:
if _enrollment_capped():
return _placeholder_response("rate_limited", username)
defaults = {
"theme": "dark",
"enabled": config.ENABLED_WIDGETS,
"widget_order": config.WIDGET_ORDER,
}
db.enroll(username, defaults)
_request_fetch_async(username)
_kickoff_prefetch_async(username)
return _serve(username, widget_name="languages")
@app.route("/api/<username>/data", methods=["GET"]) @app.route("/api/<username>/data", methods=["GET"])
@track_request("data")
@rate_limited("read") @rate_limited("read")
def get_user_data(username: str): def get_user_data(username: str):
"""Precomputed widget data for client-side SVG rendering. """Precomputed widget data for client-side SVG rendering.
Pure DB lookup — never touches the fetcher or runs compute on the hot Auto-enrolls visitors for users that haven't signed in themselves yet
path. Enrollment is now OAuth-driven only. (subject to ENROLLMENT_DAILY_CAP, same as the /?username=X shortcut).
Without this, typing someone else's username into the workshop's
search bar produced 'not_enrolled' forever — the user only got
enrolled if they personally went through OAuth, which makes the
public-preview UX dead-on-arrival.
""" """
if not is_valid_username(username): if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400 return jsonify({"error": "invalid_username"}), 400
username = username.lower()
settings_row = db.get_settings(username) settings_row = db.get_settings(username)
if settings_row is None: if settings_row is None:
return jsonify({"status": "not_found"}), 404 # Daily cap is the abuse backstop: a botnet typing random names
# can't burn through the GitHub PAT budget past this number.
if _enrollment_capped():
cap = "daily" if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP else "hourly"
return jsonify({"status": "rate_limited", "cap": cap}), 429
defaults = {
"theme": "dark",
"enabled": config.ENABLED_WIDGETS,
"widget_order": config.WIDGET_ORDER,
}
# Same triple-converging kickoff as the OAuth callback: enqueue
# the build directly + ask the fetcher to start in the background
# + run process_one in the API's thread pool. Robust to any one
# of the three paths failing.
db.enroll(username, defaults)
_request_fetch_async(username)
_kickoff_prefetch_async(username)
return jsonify({"status": "building"}), 202
db.touch_last_requested(username) db.touch_last_requested(username)
row = db.get_current_widget_data(username) row = db.get_current_widget_data(username)
if row is None: if row is None:
# Same self-heal as _serve: covers the case where a build
# permanently failed and nothing else will re-enqueue it.
if not db.has_open_build(username):
db.enqueue_build(username)
_kickoff_prefetch_async(username)
return jsonify({"status": "building"}), 202 return jsonify({"status": "building"}), 202
if row["settings_hash"] == "not_found": if row["settings_hash"] == "not_found":
@@ -482,12 +863,34 @@ def get_user_data(username: str):
def _serve(username: str, widget_name: str) -> Response: def _serve(username: str, widget_name: str) -> Response:
"""Serves a cached SVG for README embeds. """Serves a cached SVG for README embeds.
SVGs are only produced by POST /api/<u>/generate. Before that the Two code paths:
endpoint returns a "building" placeholder; enrollment is now OAuth-driven * No query overrides: return the pre-rendered composite stored in
so this path never auto-enrolls on its own. widgets.db (cheap, cacheable).
* Query overrides present: render on-demand with the override dict
merged onto the owner's stored settings. Nothing is persisted; the
owner's widget is unaffected. This is how unauthenticated users
"edit" a widget — they just craft a URL.
""" """
# GitHub usernames are case-insensitive; records are keyed by the
# canonical lowercase. Normalize here so `/api/Alice` resolves to the
# same row as `/api/alice` instead of missing it and re-enrolling.
username = username.lower()
settings_row = db.get_settings(username) settings_row = db.get_settings(username)
if settings_row is None: if settings_row is None:
# Auto-enroll on first hit so embed URLs for never-seen users
# actually trigger a build, instead of returning a "building"
# placeholder that nothing ever resolves. Same daily-cap +
# triple-kickoff pattern as /api/<u>/data and /api/top-langs.
if _enrollment_capped():
return _placeholder_response("rate_limited", username)
defaults = {
"theme": "dark",
"enabled": config.ENABLED_WIDGETS,
"widget_order": config.WIDGET_ORDER,
}
db.enroll(username, defaults)
_request_fetch_async(username)
_kickoff_prefetch_async(username)
return _placeholder_response("building", username) return _placeholder_response("building", username)
db.touch_last_requested(username) db.touch_last_requested(username)
@@ -500,6 +903,45 @@ def _serve(username: str, widget_name: str) -> Response:
"X-Content-Type-Options": "nosniff", "X-Content-Type-Options": "nosniff",
} }
# Ad-hoc render path. The composite accepts the full override set; named
# widgets accept `theme` only, because the compat shims that reach them
# (/api/top-langs?..., /api/streak/<u>) carry upstream params whose
# meaning differs from ours. A themed README URL migrated off upstream
# must render in the theme it asks for, not the owner's stored one.
overrides = sanitize_settings_query(request.args)
if widget_name != "composite":
overrides = {k: v for k, v in overrides.items() if k == "theme"}
# No current widget means no build has landed yet, so the fetcher likely
# has no data either; an ad hoc render would trigger a GitHub fetch per
# request. Fall through to the building placeholder instead.
if overrides and current_hash is not None and current_hash != "not_found":
# Honor the possibly-overridden theme for error placeholders.
override_theme = overrides.get("theme") if isinstance(overrides.get("theme"), str) else None
effective_theme = override_theme or theme
acquired = _GENERATE_SEMAPHORE.acquire(timeout=config.GENERATE_SEMAPHORE_WAIT_S)
if not acquired:
resp = jsonify({"error": "busy"})
resp.status_code = 503
resp.headers["Retry-After"] = "5"
return resp
try:
from . import worker
svg = worker.render_composite_adhoc(username, overrides, widget_name)
except Exception:
log.exception("adhoc render failed for %s", username)
svg = None
finally:
_GENERATE_SEMAPHORE.release()
if svg is None:
return _placeholder_response("building", username, theme=effective_theme)
# Query-string renders are deterministic from (user, query) but
# depend on fetcher data that does rotate. Use a short shared cache
# window so bursty viewers of the same embed don't all hit compute.
headers = {"X-Widget-Status": "ready",
"Cache-Control": "public, max-age=300",
**headers_common}
return Response(svg, mimetype="image/svg+xml", headers=headers)
if current_hash == "not_found": if current_hash == "not_found":
svg = db.get_current_widget(username, widget_name) or placeholder.render("not_found", username, theme=theme) svg = db.get_current_widget(username, widget_name) or placeholder.render("not_found", username, theme=theme)
headers = {"X-Widget-Status": "not_found", "Cache-Control": "no-store", **headers_common} headers = {"X-Widget-Status": "not_found", "Cache-Control": "no-store", **headers_common}
@@ -507,6 +949,25 @@ def _serve(username: str, widget_name: str) -> Response:
svg = db.get_current_widget(username, widget_name) svg = db.get_current_widget(username, widget_name)
if svg is None: if svg is None:
# Enrolled but no widget for this hash. Almost always the brief
# window before the worker drains the build job enrolled queued.
# The edge case worth handling: the build permanently failed
# (MAX_ATTEMPTS=3 → status='failed'), and the cron loop only
# re-enqueues on payload-hash changes, so the user would otherwise
# sit on "building" until GitHub data changed. Self-heal by
# enqueuing a fresh build if nothing's in flight.
#
# But only when the build genuinely hasn't landed. A completed build
# persists widget_data for the hash current_widget points at, so if
# that row exists this widget simply renders nothing for this user
# (`name` is drawn inside the composite and never stands alone;
# `achievements` is skipped when the user has authored none). Without
# this check every request re-enqueues a build that can never produce
# the SVG, pinning the worker and growing the prefetch queue.
built = db.get_current_widget_data(username) is not None
if not built and not db.has_open_build(username):
db.enqueue_build(username)
_kickoff_prefetch_async(username)
return _placeholder_response("building", username, theme=theme) return _placeholder_response("building", username, theme=theme)
headers = {"X-Widget-Status": "ready", headers = {"X-Widget-Status": "ready",
@@ -523,9 +984,93 @@ def _placeholder_response(variant: str, username: str, theme: str = "dark") -> R
"X-Content-Type-Options": "nosniff"}) "X-Content-Type-Options": "nosniff"})
def _serve_profile_widget(username: str) -> Response:
"""Force-generate and return the developer profile (grade) widget SVG.
Powers the `/?username=X` and `/api/?username=X` shortcuts. Unlike the
cached `/api/<u>` composite path, this one will auto-enroll a new user
(subject to the daily cap) so a first-time visitor who pastes a
username in the URL gets a usable SVG back on the first request.
Only the grade widget is rendered; no composite, no other widgets.
"""
if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
username = username.lower()
if not _rate_limit("read"):
return jsonify({"error": "rate_limited"}), 429
settings_row = db.get_settings(username)
just_enrolled = False
if settings_row is None:
if _enrollment_capped():
return _placeholder_response("rate_limited", username)
defaults = {
"theme": "dark",
"enabled": config.ENABLED_WIDGETS,
"widget_order": config.WIDGET_ORDER,
}
db.enroll(username, defaults)
just_enrolled = True
settings_row = db.get_settings(username)
if settings_row is None:
return _placeholder_response("building", username)
theme_raw = settings_row["settings"].get("theme", "dark")
theme = theme_raw if isinstance(theme_raw, str) and theme_raw in THEMES else "dark"
# `?theme=` override, same allow-list as the composite path. This route
# already renders per request, so honoring it costs nothing extra.
theme = sanitize_settings_query(request.args).get("theme", theme)
acquired = _GENERATE_SEMAPHORE.acquire(timeout=config.GENERATE_SEMAPHORE_WAIT_S)
if not acquired:
resp = jsonify({"error": "busy"})
resp.status_code = 503
resp.headers["Retry-After"] = "5"
return resp
try:
result = fetcher_client.get_data(username)
payload = result.get("data") or {}
if payload.get("error") == "not_found":
return _placeholder_response("not_found", username, theme=theme)
t0 = time.monotonic()
grade = processor.compute_grade(
payload,
custom_tags=settings_row["settings"].get("custom_tags"),
)
ws = (settings_row["settings"].get("widget_settings") or {}).get("grade")
svg = render_grade_widget(grade, theme, settings=ws)
analytics.record_render(username, "grade",
int((time.monotonic() - t0) * 1000))
except Exception:
log.exception("profile widget render failed for %s", username)
return _placeholder_response("building", username, theme=theme)
finally:
_GENERATE_SEMAPHORE.release()
db.touch_last_requested(username)
# Drain the build job enqueued by db.enroll in-process. Placed after the
# sync fetcher call so process_one reuses the cached fetcher payload
# instead of racing it for a second GitHub fetch. Safety net for the
# case where the worker container is unhealthy — without this, all
# widgets except grade would sit on "building" until cron flips.
if just_enrolled:
_kickoff_prefetch_async(username)
return Response(
svg,
mimetype="image/svg+xml",
headers={
"X-Widget-Status": "ready",
"Cache-Control": "public, max-age=300",
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:",
"X-Content-Type-Options": "nosniff",
},
)
@app.route("/api/<username>/settings", methods=["GET"]) @app.route("/api/<username>/settings", methods=["GET"])
@rate_limited("read") @rate_limited("read")
def get_settings(username: str): def get_settings(username: str):
username = username.lower()
s = db.get_settings(username) s = db.get_settings(username)
if s is None: if s is None:
return jsonify({"error": "not_enrolled"}), 404 return jsonify({"error": "not_enrolled"}), 404
@@ -543,6 +1088,7 @@ def get_settings(username: str):
@auth.require_same_origin @auth.require_same_origin
@auth.require_github_owner @auth.require_github_owner
def patch_settings(username: str): def patch_settings(username: str):
username = username.lower()
current = db.get_settings(username) current = db.get_settings(username)
if current is None: if current is None:
return jsonify({"error": "not_enrolled"}), 404 return jsonify({"error": "not_enrolled"}), 404
@@ -578,6 +1124,7 @@ def generate(username: str):
from . import worker from . import worker
if not is_valid_username(username): if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400 return jsonify({"error": "invalid_username"}), 400
username = username.lower()
if db.get_settings(username) is None: if db.get_settings(username) is None:
return jsonify({"error": "not_enrolled"}), 404 return jsonify({"error": "not_enrolled"}), 404
@@ -591,7 +1138,14 @@ def generate(username: str):
widgets = worker.render_widgets_now(username) widgets = worker.render_widgets_now(username)
except LookupError: except LookupError:
return jsonify({"error": "not_enrolled"}), 404 return jsonify({"error": "not_enrolled"}), 404
except Exception: except Exception as e:
# The fetcher answers 503 when GitHub's quota is spent; the card
# still builds on its own once it resets, so say that, not 502.
if getattr(getattr(e, "response", None), "status_code", None) == 503:
resp = jsonify({"error": "github_rate_limited"})
resp.status_code = 503
resp.headers["Retry-After"] = "600"
return resp
log.exception("generate failed for %s", username) log.exception("generate failed for %s", username)
return jsonify({"error": "render_failed"}), 502 return jsonify({"error": "render_failed"}), 502
finally: finally:
@@ -612,6 +1166,7 @@ def generate(username: str):
@auth.require_same_origin @auth.require_same_origin
@auth.require_github_owner @auth.require_github_owner
def refresh(username: str): def refresh(username: str):
username = username.lower()
s = db.get_settings(username) s = db.get_settings(username)
if s is None: if s is None:
return jsonify({"error": "not_enrolled"}), 404 return jsonify({"error": "not_enrolled"}), 404
@@ -627,15 +1182,78 @@ def refresh(username: str):
return jsonify({"refreshed": True, "job_id": job_id}) return jsonify({"refreshed": True, "job_id": job_id})
@app.route("/api/dev/summary", methods=["GET"])
@auth.require_basic_auth
def dev_summary():
return jsonify(analytics.query_summary())
@app.route("/api/dev/users", methods=["GET"])
@auth.require_basic_auth
def dev_users():
q = request.args.get("q", "")
sort = request.args.get("sort", "requests")
return jsonify(analytics.query_users(q=q, sort=sort))
@app.route("/api/dev/latency", methods=["GET"])
@auth.require_basic_auth
def dev_latency():
return jsonify(analytics.query_latency())
@app.route("/api/dev/health", methods=["GET"])
@auth.require_basic_auth
def dev_health():
return jsonify(analytics.query_health())
@app.route("/api/dev/growth", methods=["GET"])
@auth.require_basic_auth
def dev_growth():
return jsonify(analytics.query_growth())
@app.errorhandler(413) @app.errorhandler(413)
def _too_large(_e): def _too_large(_e):
return jsonify({"error": "payload_too_large"}), 413 return jsonify({"error": "payload_too_large"}), 413
def _invalidate_widgets_on_new_build() -> None:
"""On boot, if BUILD_VERSION differs from the last stamp, queue a
rebuild for every enrolled user so widgets re-render against the new
code. Races safely with the worker/cron containers: the first caller
to flip the meta row enqueues; the rest observe a no-op.
"""
if not config.BUILD_VERSION:
return
try:
if db.claim_build_version(config.BUILD_VERSION):
n = db.enqueue_build_all()
log.info("build %s: queued %d rebuild(s)", config.BUILD_VERSION, n)
except Exception:
# Never let a failed invalidation prevent the API from booting —
# the next boot (or a manual refresh) will pick up the change.
log.exception("build-version invalidation failed")
def main(): def main():
db.init_dbs() db.init_dbs()
_invalidate_widgets_on_new_build()
analytics.start_flush_thread()
app.run(host="0.0.0.0", port=config.PORT) app.run(host="0.0.0.0", port=config.PORT)
def _boot_analytics_for_gunicorn():
"""Gunicorn imports the module without calling main(); fire the daemon
flush thread here so render timings actually get flushed in production.
Idempotent — start_flush_thread checks for a running thread."""
try:
analytics.start_flush_thread()
except Exception:
log.exception("analytics boot failed")
_boot_analytics_for_gunicorn()
if __name__ == "__main__": if __name__ == "__main__":
main() main()
+40
View File
@@ -78,3 +78,43 @@ def require_same_origin(fn):
return jsonify({"error": "bad_origin"}), 403 return jsonify({"error": "bad_origin"}), 403
return fn(*args, **kwargs) return fn(*args, **kwargs)
return wrapper return wrapper
import base64
import hmac as _hmac
from functools import wraps as _wraps
from flask import jsonify as _jsonify, request as _request
from . import config as _config
def require_basic_auth(fn):
"""HTTP Basic Auth gate for the /dev dashboard. Returns 503 if either
credential env var is unset so a missing-secret deploy fails closed.
Constant-time comparison on the decoded user+pass concatenation keeps
the timing channel narrow without leaking length."""
@_wraps(fn)
def wrapper(*args, **kwargs):
u = _config.DEV_DASHBOARD_USER
p = _config.DEV_DASHBOARD_PASSWORD
if not u or not p:
return _jsonify({"error": "dashboard_disabled"}), 503
hdr = _request.headers.get("Authorization", "")
if not hdr.startswith("Basic "):
return _unauth()
try:
decoded = base64.b64decode(hdr[6:].encode("ascii"), validate=True).decode("utf-8")
except Exception:
return _unauth()
expected = f"{u}:{p}"
if not _hmac.compare_digest(decoded, expected):
return _unauth()
return fn(*args, **kwargs)
return wrapper
def _unauth():
resp = _jsonify({"error": "unauthorized"})
resp.status_code = 401
resp.headers["WWW-Authenticate"] = 'Basic realm="dev"'
return resp
+23 -4
View File
@@ -42,15 +42,24 @@ COMMIT_PER_REPO = int(os.getenv("COMMIT_PER_REPO", "30"))
API_TIMEOUT = int(os.getenv("API_TIMEOUT", "5")) API_TIMEOUT = int(os.getenv("API_TIMEOUT", "5"))
"""Timeout in seconds for API requests.""" """Timeout in seconds for API requests."""
# Deploy / invalidation.
# When set (populated from IMAGE_TAG in deploy/compose.yml), every generator
# container compares this to the persisted 'widgets_built_version' on boot;
# if it changed, all enrolled users get a fresh build job queued so widgets
# re-render against the new code. Empty string disables the check — useful
# in local dev where a restart shouldn't invalidate the cache.
BUILD_VERSION = os.getenv("BUILD_VERSION", "").strip()
# Data source # Data source
DATA_SOURCE_TYPE = os.getenv("DATA_SOURCE", "direct") DATA_SOURCE_TYPE = os.getenv("DATA_SOURCE", "direct")
"""Data source type: 'direct' for immediate API calls, 'queued' for batch processing.""" """Data source type: 'direct' for immediate API calls, 'queued' for batch processing."""
# Widget settings # Widget settings
WIDGET_ORDER = ["grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"] WIDGET_ORDER = ["name", "grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"]
"""Default order of widgets. Customize by reordering this list.""" """Default order of widgets. "name" is the avatar+username header and is
always pinned first in the UI — it can be toggled off but not reordered."""
ENABLED_WIDGETS = ["grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"] ENABLED_WIDGETS = ["name", "grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"]
"""Which widgets to display. Remove any you don't want to show.""" """Which widgets to display. Remove any you don't want to show."""
# Language filtering # Language filtering
@@ -109,10 +118,20 @@ TAG_TOPIC_MAP = {
PORT = int(os.getenv("GENERATOR_PORT", "5002")) PORT = int(os.getenv("GENERATOR_PORT", "5002"))
SETTINGS_DB_PATH = os.getenv("GENERATOR_SETTINGS_DB_PATH", "./data/settings.db") SETTINGS_DB_PATH = os.getenv("GENERATOR_SETTINGS_DB_PATH", "./data/settings.db")
WIDGETS_DB_PATH = os.getenv("GENERATOR_WIDGETS_DB_PATH", "./data/widgets.db") WIDGETS_DB_PATH = os.getenv("GENERATOR_WIDGETS_DB_PATH", "./data/widgets.db")
ANALYTICS_DB_PATH = os.getenv("GENERATOR_ANALYTICS_DB_PATH", "./data/analytics.db")
ANALYTICS_RETENTION_DAYS = int(os.getenv("ANALYTICS_RETENTION_DAYS", "14"))
ANALYTICS_FLUSH_SECONDS = int(os.getenv("ANALYTICS_FLUSH_SECONDS", "5"))
ANALYTICS_QUEUE_MAX = int(os.getenv("ANALYTICS_QUEUE_MAX", "2000"))
DEV_DASHBOARD_USER = os.getenv("DEV_DASHBOARD_USER", "")
DEV_DASHBOARD_PASSWORD = os.getenv("DEV_DASHBOARD_PASSWORD", "")
FETCHER_URL = os.getenv("FETCHER_URL", "http://localhost:5001") FETCHER_URL = os.getenv("FETCHER_URL", "http://localhost:5001")
FETCHER_INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "") FETCHER_INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
REDIS_URL = os.getenv("REDIS_URL", "") REDIS_URL = os.getenv("REDIS_URL", "")
ENROLLMENT_DAILY_CAP = int(os.getenv("ENROLLMENT_DAILY_CAP", "50")) ENROLLMENT_DAILY_CAP = int(os.getenv("ENROLLMENT_DAILY_CAP", "500"))
# Burst guard. A new user costs ~37 GitHub REST calls (p90 ~104) against a
# 5000/hr budget, and a launch spike arrives in one hour rather than spread
# over a day, so the hourly ceiling is what actually protects the PAT.
ENROLLMENT_HOURLY_CAP = int(os.getenv("ENROLLMENT_HOURLY_CAP", "60"))
WIDGET_LRU_PER_USER = int(os.getenv("WIDGET_LRU_PER_USER", "10")) WIDGET_LRU_PER_USER = int(os.getenv("WIDGET_LRU_PER_USER", "10"))
POLL_INTERVAL_MINUTES = int(os.getenv("GENERATOR_POLL_INTERVAL_MINUTES", "15")) POLL_INTERVAL_MINUTES = int(os.getenv("GENERATOR_POLL_INTERVAL_MINUTES", "15"))
+12 -1
View File
@@ -6,7 +6,7 @@ import logging
import os import os
import time import time
from . import config, db, fetcher_client from . import analytics, config, db, fetcher_client
log = logging.getLogger("generator.cron") log = logging.getLogger("generator.cron")
@@ -47,6 +47,17 @@ def tick() -> dict:
failed += 1 failed += 1
if _TICK_INTER_USER_SLEEP_S > 0: if _TICK_INTER_USER_SLEEP_S > 0:
time.sleep(_TICK_INTER_USER_SLEEP_S) time.sleep(_TICK_INTER_USER_SLEEP_S)
try:
# Snapshot first, prune second: rollup persists the per-day
# aggregates that the growth chart reads, then prune drops the
# raw events whose stats we just captured.
analytics.rollup_daily_stats()
except Exception:
log.exception("analytics rollup failed")
try:
analytics.prune_old()
except Exception:
log.exception("analytics prune failed")
return {"enqueued": enqueued, "failed": failed, "skipped_queue_full": skipped_queue_full} return {"enqueued": enqueued, "failed": failed, "skipped_queue_full": skipped_queue_full}
+169 -17
View File
@@ -15,6 +15,7 @@ from . import config
SETTINGS_DB_PATH = config.SETTINGS_DB_PATH SETTINGS_DB_PATH = config.SETTINGS_DB_PATH
WIDGETS_DB_PATH = config.WIDGETS_DB_PATH WIDGETS_DB_PATH = config.WIDGETS_DB_PATH
ANALYTICS_DB_PATH = config.ANALYTICS_DB_PATH
_SETTINGS_SCHEMA = """ _SETTINGS_SCHEMA = """
CREATE TABLE IF NOT EXISTS users ( CREATE TABLE IF NOT EXISTS users (
@@ -44,6 +45,10 @@ CREATE TABLE IF NOT EXISTS jobs (
updated_at TEXT NOT NULL updated_at TEXT NOT NULL
); );
CREATE INDEX IF NOT EXISTS idx_jobs_pending ON jobs(status, created_at); CREATE INDEX IF NOT EXISTS idx_jobs_pending ON jobs(status, created_at);
CREATE TABLE IF NOT EXISTS meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS user_streaks ( CREATE TABLE IF NOT EXISTS user_streaks (
username TEXT PRIMARY KEY, username TEXT PRIMARY KEY,
current_streak INTEGER NOT NULL DEFAULT 0, current_streak INTEGER NOT NULL DEFAULT 0,
@@ -81,6 +86,36 @@ CREATE INDEX IF NOT EXISTS idx_widgets_username ON widgets(username);
CREATE INDEX IF NOT EXISTS idx_widget_data_username ON widget_data(username); CREATE INDEX IF NOT EXISTS idx_widget_data_username ON widget_data(username);
""" """
_ANALYTICS_SCHEMA = """
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts INTEGER NOT NULL,
service TEXT NOT NULL,
kind TEXT NOT NULL,
username TEXT,
endpoint TEXT,
widget TEXT,
status INTEGER,
latency_ms INTEGER NOT NULL,
cache_hit INTEGER
);
CREATE INDEX IF NOT EXISTS idx_events_ts ON events(ts);
CREATE INDEX IF NOT EXISTS idx_events_user_ts ON events(username, ts);
CREATE INDEX IF NOT EXISTS idx_events_endpoint_ts ON events(endpoint, ts);
-- Per-day aggregates that outlive the events table. Events are pruned at
-- ANALYTICS_RETENTION_DAYS (14d default), but the dev dashboard's growth
-- chart needs per-day/per-week numbers going back further. analytics.py's
-- rollup writes one row per day with the request count and the set of
-- unique usernames (as JSON, so weekly uniques can be computed by union).
CREATE TABLE IF NOT EXISTS daily_stats (
day TEXT PRIMARY KEY,
requests INTEGER NOT NULL,
users_json TEXT NOT NULL,
updated_at TEXT NOT NULL
);
"""
def _now() -> str: def _now() -> str:
return datetime.utcnow().isoformat(timespec="seconds") + "Z" return datetime.utcnow().isoformat(timespec="seconds") + "Z"
@@ -119,6 +154,21 @@ def _widgets_conn():
conn.close() conn.close()
@contextmanager
def analytics_conn():
conn = _open(ANALYTICS_DB_PATH)
try:
yield conn
finally:
conn.close()
def init_analytics_db() -> None:
with analytics_conn() as c:
c.executescript(_ANALYTICS_SCHEMA)
c.commit()
def init_dbs() -> None: def init_dbs() -> None:
with _settings_conn() as c: with _settings_conn() as c:
c.executescript(_SETTINGS_SCHEMA) c.executescript(_SETTINGS_SCHEMA)
@@ -134,6 +184,7 @@ def init_dbs() -> None:
with _widgets_conn() as c: with _widgets_conn() as c:
c.executescript(_WIDGETS_SCHEMA) c.executescript(_WIDGETS_SCHEMA)
c.commit() c.commit()
init_analytics_db()
def settings_hash(settings: dict) -> str: def settings_hash(settings: dict) -> str:
@@ -145,13 +196,19 @@ def settings_hash(settings: dict) -> str:
def enroll(username: str, defaults: dict, def enroll(username: str, defaults: dict,
github_id: int | None = None, github_id: int | None = None,
github_avatar_url: str | None = None) -> dict: github_avatar_url: str | None = None,
"""Insert a settings row if missing, bump the daily counter, enqueue a build. enqueue_build: bool = True) -> dict:
"""Insert a settings row if missing, bump the daily counter, optionally
enqueue a build.
Idempotent: calling again for an existing user refreshes github_avatar_url `enqueue_build=False` is used by the OAuth callback so the build job is
(so login keeps the avatar fresh) and enqueues a rebuild. Always returns only added to the queue *after* the fetcher has actually fetched the
{"job_id": int}. No token is returned — auth is handled by the signed user (via the /internal/data-ready callback). Without this, the worker
session cookie. would pop a build job for a user the fetcher hasn't seen yet and either
block on a synchronous GitHub fetch or retry-fail until cron.
Idempotent: calling again for an existing user refreshes
github_avatar_url. Returns {"job_id": int|None}.
""" """
sh = settings_hash(defaults) sh = settings_hash(defaults)
now = _now() now = _now()
@@ -176,13 +233,16 @@ def enroll(username: str, defaults: dict,
ON CONFLICT(day) DO UPDATE SET count = count + 1""", ON CONFLICT(day) DO UPDATE SET count = count + 1""",
(_today(),), (_today(),),
) )
cur = c.execute( job_id: int | None = None
"""INSERT INTO jobs(kind, username, status, created_at, updated_at) if enqueue_build:
VALUES ('build', ?, 'pending', ?, ?)""", cur = c.execute(
(username, now, now), """INSERT INTO jobs(kind, username, status, created_at, updated_at)
) VALUES ('build', ?, 'pending', ?, ?)""",
(username, now, now),
)
job_id = cur.lastrowid
c.commit() c.commit()
return {"job_id": cur.lastrowid} return {"job_id": job_id}
def enrollments_today() -> int: def enrollments_today() -> int:
@@ -191,11 +251,31 @@ def enrollments_today() -> int:
return row["count"] if row else 0 return row["count"] if row else 0
def enrollments_last_hour() -> int:
"""Enrollments in the trailing 60 minutes. Reads `users.enrolled_at`
directly (ISO-8601 Zulu, so lexicographic order is chronological) rather
than keeping a second counter table."""
cutoff = (datetime.utcnow() - timedelta(hours=1)).isoformat(timespec="seconds") + "Z"
with _settings_conn() as c:
row = c.execute(
"SELECT COUNT(*) AS n FROM users WHERE enrolled_at >= ?", (cutoff,)
).fetchone()
return row["n"] if row else 0
def enrollment_rank(username: str) -> Optional[int]: def enrollment_rank(username: str) -> Optional[int]:
"""1-based position in overall enrollment order by enrolled_at. Used by """1-based position in overall enrollment order by enrolled_at. Used by
tag rules that reward early users (e.g. the 'founder' tag).""" tag rules that reward early users (e.g. the 'founder' tag).
Usernames are persisted lowercased by `enroll()`, but callers may pass the
GitHub-returned login (which preserves the original casing). Normalize
here so a mixed-case lookup doesn't silently miss the row.
"""
if not username:
return None
key = username.lower()
with _settings_conn() as c: with _settings_conn() as c:
row = c.execute("SELECT enrolled_at FROM users WHERE username=?", (username,)).fetchone() row = c.execute("SELECT enrolled_at FROM users WHERE username=?", (key,)).fetchone()
if row is None: if row is None:
return None return None
return c.execute( return c.execute(
@@ -336,6 +416,72 @@ def enqueue_build(username: str) -> int:
return cur.lastrowid return cur.lastrowid
def has_open_build(username: str) -> bool:
"""True if the user has a pending or running build job. Used by callers
that want enqueue idempotency without taking on the SQL themselves."""
with _settings_conn() as c:
row = c.execute(
"""SELECT 1 FROM jobs
WHERE username=? AND kind='build' AND status IN ('pending', 'running')
LIMIT 1""",
(username,),
).fetchone()
return row is not None
def enqueue_build_all() -> int:
"""Enqueue a 'build' job for every enrolled user that doesn't already
have one pending. Returns the number inserted. Idempotent — safe to
call from whichever generator container boots first after a deploy.
"""
now = _now()
with _settings_conn() as c:
c.execute("BEGIN IMMEDIATE")
cur = c.execute(
"""INSERT INTO jobs(kind, username, status, created_at, updated_at)
SELECT 'build', u.username, 'pending', ?, ?
FROM users u
WHERE NOT EXISTS (
SELECT 1 FROM jobs j
WHERE j.username = u.username
AND j.kind = 'build'
AND j.status IN ('pending', 'running')
)""",
(now, now),
)
inserted = cur.rowcount or 0
c.commit()
return inserted
def claim_build_version(version: str) -> bool:
"""Atomically stamp the 'widgets_built_version' meta row. Returns True
iff this call changed it (the caller should then enqueue rebuilds);
False if it already matched — i.e. another container on this host
already claimed this deploy.
Uses BEGIN IMMEDIATE so racing generator/worker/cron containers
serialize and only one observes the change.
"""
if not version:
return False
with _settings_conn() as c:
c.execute("BEGIN IMMEDIATE")
row = c.execute(
"SELECT value FROM meta WHERE key='widgets_built_version'"
).fetchone()
if row and row["value"] == version:
c.commit()
return False
c.execute(
"""INSERT INTO meta(key, value) VALUES('widgets_built_version', ?)
ON CONFLICT(key) DO UPDATE SET value=excluded.value""",
(version,),
)
c.commit()
return True
def pending_job_count() -> int: def pending_job_count() -> int:
"""Depth of the build queue. Used as backpressure so bursts of """Depth of the build queue. Used as backpressure so bursts of
enroll/PATCH don't blow up SQLite when the worker is behind.""" enroll/PATCH don't blow up SQLite when the worker is behind."""
@@ -347,8 +493,11 @@ def pending_job_count() -> int:
def claim_next_job() -> Optional[dict]: def claim_next_job() -> Optional[dict]:
now = _now() now = _now()
with _settings_conn() as c: with _settings_conn() as c:
# A pending job whose updated_at is in the future is backing off
# (see fail_job's delay_s) and is not claimable yet.
row = c.execute( row = c.execute(
"SELECT * FROM jobs WHERE status='pending' ORDER BY created_at LIMIT 1" "SELECT * FROM jobs WHERE status='pending' AND updated_at <= ? ORDER BY created_at LIMIT 1",
(now,),
).fetchone() ).fetchone()
if row is None: if row is None:
return None return None
@@ -365,11 +514,14 @@ def complete_job(job_id: int) -> None:
c.commit() c.commit()
def fail_job(job_id: int, err: str, retry: bool) -> None: def fail_job(job_id: int, err: str, retry: bool, delay_s: float = 0) -> None:
status = "pending" if retry else "failed" status = "pending" if retry else "failed"
when = _now()
if retry and delay_s > 0:
when = (datetime.utcnow() + timedelta(seconds=delay_s)).isoformat(timespec="seconds") + "Z"
with _settings_conn() as c: with _settings_conn() as c:
c.execute("UPDATE jobs SET status=?, last_error=?, updated_at=? WHERE id=?", c.execute("UPDATE jobs SET status=?, last_error=?, updated_at=? WHERE id=?",
(status, err, _now(), job_id)) (status, err, when, job_id))
c.commit() c.commit()
+23 -2
View File
@@ -8,14 +8,35 @@ def _headers() -> dict:
return {"X-Internal-Token": config.FETCHER_INTERNAL_TOKEN} return {"X-Internal-Token": config.FETCHER_INTERNAL_TOKEN}
# Most calls hit the cache and return in <100ms; the only slow path is when
# the fetcher's /data endpoint falls back to a synchronous GitHub fetch
# (used by the /?username=X shortcut). 60s leaves headroom for the
# parallelized worst case (~15-25s) without poisoning the worker's job
# retry chain on a transient blip.
_TIMEOUT_S = 60
def get_data(username: str) -> dict: def get_data(username: str) -> dict:
r = requests.get(f"{config.FETCHER_URL}/data/{username}", headers=_headers(), timeout=30) r = requests.get(f"{config.FETCHER_URL}/data/{username}", headers=_headers(),
timeout=_TIMEOUT_S)
r.raise_for_status() r.raise_for_status()
return r.json() return r.json()
def force_fetch(username: str) -> dict: def force_fetch(username: str) -> dict:
r = requests.post(f"{config.FETCHER_URL}/fetch", headers=_headers(), r = requests.post(f"{config.FETCHER_URL}/fetch", headers=_headers(),
json={"username": username}, timeout=30) json={"username": username}, timeout=_TIMEOUT_S)
r.raise_for_status()
return r.json()
def start_fetch_async(username: str) -> dict:
"""Tell the fetcher to fetch this user in the background. Returns 202
after the fetcher has accepted the job — does NOT wait for the GitHub
fetch to complete. The fetcher will POST back to /internal/data-ready
on this service when the data is persisted, which is what enqueues the
build job. See fetcher.api.fetch_async for the other half."""
r = requests.post(f"{config.FETCHER_URL}/fetch-async", headers=_headers(),
json={"username": username}, timeout=10)
r.raise_for_status() r.raise_for_status()
return r.json() return r.json()
+6 -1
View File
@@ -4,11 +4,13 @@ Uses the same card wrapper + theme system as real widgets so they look consisten
""" """
from .themes.themes import THEMES from .themes.themes import THEMES
from .utils.svg_helpers import card_wrapper, escape from .utils.svg_helpers import card_wrapper, escape
from .widgets.attribution import attribution_text
_MESSAGES = { _MESSAGES = {
"building": ("Building @{u}'s widget\u2026", "This usually takes under a minute."), "building": ("Building @{u}'s widget\u2026", "This usually takes under a minute."),
"rate_limited": ("Too many new users today", "Try again tomorrow."), "rate_limited": ("Too many new users right now", "Try again later."),
"not_found": ("GitHub user @{u} doesn't exist", "Check the spelling of the username."), "not_found": ("GitHub user @{u} doesn't exist", "Check the spelling of the username."),
"unsubstituted": ("Replace YOUR_USERNAME in the URL", "Put your own GitHub username there, e.g. /api/octocat."),
} }
@@ -24,5 +26,8 @@ def render(variant: str, username: str, theme: str = "dark") -> str:
f'font-size="18" font-weight="600" fill="{palette["text"]}">{escape(title)}</text>' f'font-size="18" font-weight="600" fill="{palette["text"]}">{escape(title)}</text>'
f'<text x="24" y="82" font-family="-apple-system,Segoe UI,sans-serif" ' f'<text x="24" y="82" font-family="-apple-system,Segoe UI,sans-serif" '
f'font-size="13" fill="{palette["text_secondary"]}">{escape(subtitle)}</text>' f'font-size="13" fill="{palette["text_secondary"]}">{escape(subtitle)}</text>'
# The card is 120 tall and the subtitle ends around y=85, so the
# footer fits inside the existing bottom padding.
+ attribution_text(palette, 200, 112, 0)
) )
return card_wrapper(inner, width=400, height=120, theme=palette) return card_wrapper(inner, width=400, height=120, theme=palette)
+91 -34
View File
@@ -1,6 +1,6 @@
"""GitHub data processing and widget generation.""" """GitHub data processing and widget generation."""
from datetime import datetime, timedelta from datetime import datetime, timedelta, date
from collections import defaultdict from collections import defaultdict
from .models import ( from .models import (
@@ -65,15 +65,40 @@ def compute_grade(github_data: dict, custom_tags: list[str] = None) -> GradeData
if prs == 0: if prs == 0:
prs = sum(1 for ev in events if ev.get("type") == "PullRequestEvent") prs = sum(1 for ev in events if ev.get("type") == "PullRequestEvent")
scores = { # Last-year consistency: count distinct ISO weeks with at least one
"repos": min(repo_count / 30 * 100, 100), # commit on the GitHub contribution calendar (which always covers the
"stars": min(stars / 200 * 100, 100), # trailing year). 40 active weeks out of ~52 tops this factor out, so
"forks": min(forks / 50 * 100, 100), # someone who works in bursts isn't penalised, but sporadic once-a-
"followers": min(followers / 100 * 100, 100), # quarter activity scores low.
"activity": min(len(events) / 80 * 100, 100), daily = github_data.get("commits", [])
} active_weeks: set = set()
if isinstance(daily, list):
for day in daily:
if not isinstance(day, dict):
continue
if day.get("count", 0) <= 0:
continue
date_str = day.get("date")
if not isinstance(date_str, str):
continue
try:
iso = date.fromisoformat(date_str).isocalendar()
active_weeks.add((iso[0], iso[1]))
except ValueError:
continue
total = sum(scores.values()) / len(scores) # Weights sum to 1.0
per_factor = {
"commits": (min(commits / 3000 * 100, 100), 0.33),
"consistency": (min(len(active_weeks) / 40 * 100, 100), 0.22),
"repos": (min(repo_count / 40 * 100, 100), 0.15),
"stars": (min(stars / 200 * 100, 100), 0.11),
"forks": (min(forks / 20 * 100, 100), 0.08),
"activity": (min(len(events) / 80 * 100, 100), 0.08),
"followers": (min(followers / 100 * 100, 100), 0.03),
}
scores = {k: v for k, (v, _w) in per_factor.items()}
total = sum(v * w for v, w in per_factor.values())
# Grade scale # Grade scale
if total >= 97: if total >= 97:
@@ -100,18 +125,11 @@ def compute_grade(github_data: dict, custom_tags: list[str] = None) -> GradeData
grade = "B-" grade = "B-"
elif total >= 42: elif total >= 42:
grade = "C+" 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: else:
grade = "F" # C is the floor. Anything that would previously have slid into C-,
# D+, D, D-, or F is clamped up to C — the widget is meant to be an
# encouraging profile snapshot, not a failure grade.
grade = "C"
stats = { stats = {
"commits": commits, "commits": commits,
@@ -427,8 +445,13 @@ def compute_focus(github_data: dict, hidden_languages: list[str] = None) -> list
focus_counts = defaultdict(float) focus_counts = defaultdict(float)
# Use top 30 most recently pushed repos # Use top 30 most recently pushed repos. `r.get("pushed_at", "")` is
sorted_repos = sorted(repos, key=lambda r: r.get("pushed_at", ""), reverse=True) # NOT enough — when GitHub returns the field as JSON null (archived /
# never-pushed repos, common in torvalds-sized accounts), .get returns
# None and the sort blows up with "'<' not supported between instances
# of 'str' and 'NoneType'". `or ""` coerces null-valued keys to the
# same empty-string fallback as missing keys.
sorted_repos = sorted(repos, key=lambda r: r.get("pushed_at") or "", reverse=True)
active_repos = sorted_repos[:30] active_repos = sorted_repos[:30]
# Count languages in active repos (excluding hidden languages) # Count languages in active repos (excluding hidden languages)
@@ -495,18 +518,45 @@ def compute_languages(github_data: dict, hidden_languages: list[str] = None) ->
hidden_set = {h for h in hidden_languages} hidden_set = {h for h in hidden_languages}
repos = github_data["repos"] repos = github_data["repos"]
byte_totals: dict[str, int] = defaultdict(int) login = (github_data.get("user") or {}).get("login") or ""
have_bytes = False login_lc = login.lower()
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: def _is_authored(r: dict) -> bool:
# Repos the user mostly didn't write shouldn't dominate their
# language mix. "Authored" = not a fork AND owned by the user
# (or by an org where we can't easily tell, so stay conservative
# and require personal ownership). This drops the big-fork /
# random-org-contribution case that was skewing the widget.
if r.get("fork"):
return False
owner_login = ((r.get("owner") or {}).get("login") or "").lower()
return bool(owner_login) and owner_login == login_lc
def _byte_tally(predicate) -> dict[str, int]:
totals: dict[str, int] = defaultdict(int)
for r in repos:
if not predicate(r):
continue
lb = r.get("language_bytes") or {}
if not isinstance(lb, dict):
continue
for lang, n in lb.items():
if lang and lang not in hidden_set:
totals[lang] += int(n or 0)
return totals
# Preferred: bytes across authored repos only.
byte_totals = _byte_tally(_is_authored)
# Fallback ladder so the widget is never empty: if the user has no
# authored repos with byte data (rare — new accounts, or everything
# is a fork), expand to all non-fork repos, and finally to everything.
if not byte_totals:
byte_totals = _byte_tally(lambda r: not r.get("fork"))
if not byte_totals:
byte_totals = _byte_tally(lambda r: True)
if byte_totals:
total = sum(byte_totals.values()) or 1 total = sum(byte_totals.values()) or 1
return [ return [
LanguageData( LanguageData(
@@ -517,12 +567,19 @@ def compute_languages(github_data: dict, hidden_languages: list[str] = None) ->
for lang, size in sorted(byte_totals.items(), key=lambda x: -x[1]) for lang, size in sorted(byte_totals.items(), key=lambda x: -x[1])
] ]
# Legacy fallback: repo-count by primary language. # Legacy fallback: repo-count by primary language, same ownership filter.
lang_counts: dict[str, int] = defaultdict(int) lang_counts: dict[str, int] = defaultdict(int)
for r in repos: for r in repos:
if not _is_authored(r):
continue
lang = r.get("language") lang = r.get("language")
if lang and lang not in hidden_set: if lang and lang not in hidden_set:
lang_counts[lang] += 1 lang_counts[lang] += 1
if not lang_counts:
for r in repos:
lang = r.get("language")
if lang and lang not in hidden_set:
lang_counts[lang] += 1
total = sum(lang_counts.values()) or 1 total = sum(lang_counts.values()) or 1
return [ return [
+5 -1
View File
@@ -3,6 +3,7 @@
from ..models import AchievementData from ..models import AchievementData
from ..themes import THEMES from ..themes import THEMES
from ..utils import escape, card_wrapper from ..utils import escape, card_wrapper
from .attribution import FOOTER_H, attribution_text
def _achievement_icon_svg(icon_type: str, color: str) -> str: def _achievement_icon_svg(icon_type: str, color: str) -> str:
@@ -69,5 +70,8 @@ def render_achievements_widget(
font-size="10" fill="{t["text_secondary"]}">{escape(ach.subtitle)}{(" · " + escape(ach.event_date)) if ach.event_date else ""}</text> font-size="10" fill="{t["text_secondary"]}">{escape(ach.subtitle)}{(" · " + escape(ach.event_date)) if ach.event_date else ""}</text>
</g>''' </g>'''
total_h = len(shown) * 56 + 50 # The last achievement row leaves only 14px below it, so reserve
# FOOTER_H for the attribution footer.
total_h = len(shown) * 56 + 50 + FOOTER_H
items += attribution_text(t, 190, total_h - 36 - 8)
return card_wrapper(items, 380, total_h, t, "Achievements") return card_wrapper(items, 380, total_h, t, "Achievements")
+24
View File
@@ -0,0 +1,24 @@
"""Shared "Generated with gh-stats.com" footer for standalone widget SVGs.
Every widget served at /api/<u>/<widget>.svg carries this footer; keeping it
in one place means all eight cards render it at the same size, opacity and
offset from the card's bottom edge.
"""
# Vertical space the footer needs at the bottom of a card. Widgets without
# that much bottom padding already grow by it; composite.py reads the same
# number back off data-gh-h to reclaim it when the widget is inlined.
FOOTER_H = 16
def attribution_text(theme: dict, x: float, y: float, reserved_h: int = FOOTER_H) -> str:
"""Footer <text>, centered on x with its baseline at y.
data-gh-attribution marks it for composite.py to strip; data-gh-h says how
much card height the composite reclaims along with it (0 when the footer
sits inside padding the card already had).
"""
return f'''<text data-gh-attribution="1" data-gh-h="{reserved_h}"
x="{x}" y="{y}" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="{theme["text_secondary"]}" opacity="0.75">Generated with gh-stats.com</text>'''
+4
View File
@@ -3,6 +3,7 @@
from ..models import CollaboratorData from ..models import CollaboratorData
from ..themes import THEMES from ..themes import THEMES
from ..utils import escape, card_wrapper, safe_color from ..utils import escape, card_wrapper, safe_color
from .attribution import attribution_text
def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str = "dark", settings: dict | None = None) -> str: def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str = "dark", settings: dict | None = None) -> str:
@@ -49,4 +50,7 @@ def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str
</g>''' </g>'''
total_h = len(collabs[:max_count]) * 50 + 48 total_h = len(collabs[:max_count]) * 50 + 48
# The rows already leave 26px of bottom padding, so the footer fits
# inside it and the card height is unchanged (reserved height 0).
items += attribution_text(t, 190, total_h - 36 - 8, 0)
return card_wrapper(items, 380, total_h, t, "Top Collaborators") return card_wrapper(items, 380, total_h, t, "Top Collaborators")
+44 -11
View File
@@ -5,9 +5,23 @@ from ..themes import THEMES
from ..utils import escape from ..utils import escape
_ATTRIBUTION_RE = re.compile(
r'<text\b[^>]*\bdata-gh-attribution="1"[^>]*>[^<]*</text>',
re.DOTALL,
)
_ATTRIBUTION_H_RE = re.compile(r'\bdata-gh-h="(\d+)"')
def _extract_inner(svg: str, widget_key: str) -> tuple[str, int]: 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. """Extract the inner content from a widget SVG and rewrite IDs to be unique.
Also strips any per-widget "Generated with gh-stats.com" attribution text
(marked with data-gh-attribution="1") and shrinks the reported height
by data-gh-h so the composite doesn't reserve empty space for the
removed footer. The composite has its own attribution at the bottom
of the whole card; per-widget attributions are for the standalone
/api/<u>/<widget>.svg embed paths.
Returns (inner_svg_content, height). Returns (inner_svg_content, height).
""" """
# Parse height # Parse height
@@ -31,6 +45,14 @@ def _extract_inner(svg: str, widget_key: str) -> tuple[str, int]:
inner = re.sub(r'<svg[^>]*>', '', inner, count=1) inner = re.sub(r'<svg[^>]*>', '', inner, count=1)
inner = re.sub(r'</svg>\s*$', '', inner) inner = re.sub(r'</svg>\s*$', '', inner)
# Strip any embedded attribution and reclaim its reserved height.
attr_match = _ATTRIBUTION_RE.search(inner)
if attr_match:
inner = inner.replace(attr_match.group(0), '', 1)
h_match = _ATTRIBUTION_H_RE.search(attr_match.group(0))
if h_match:
h -= int(h_match.group(1))
return inner, h return inner, h
@@ -40,20 +62,29 @@ def compose_widget(
theme_name: str = "dark", theme_name: str = "dark",
username: str = "", username: str = "",
avatar_b64: str = "", avatar_b64: str = "",
show_name: bool = True,
) -> str: ) -> str:
""" """
Takes rendered SVG strings for each widget type and composes them Takes rendered SVG strings for each widget type and composes them
into a single unified profile widget by inlining widget SVGs directly. into a single unified profile widget by inlining widget SVGs directly.
`show_name` controls whether the avatar + username header block is
drawn. It's the "name" pseudo-widget — pinned first in the UI, can be
toggled off but not reordered. When false, widgets start at the top
edge (minus the standard padding) so there's no orphan gap.
""" """
t = THEMES[theme_name] t = THEMES[theme_name]
total_w = 420 total_w = 420
header_h = 60 header_h = 60 if show_name else 0
padding = 20 padding = 20
gap = 16 gap = 16
# Extract inner content from each widget SVG # Extract inner content from each widget SVG. "name" has no rendered
# widget — it maps to the header block and is consumed by show_name.
parts = [] parts = []
for key in enabled: for key in enabled:
if key == "name":
continue
if key in widgets and widgets[key]: if key in widgets and widgets[key]:
inner, h = _extract_inner(widgets[key], key) inner, h = _extract_inner(widgets[key], key)
parts.append((key, inner, h)) parts.append((key, inner, h))
@@ -61,16 +92,16 @@ def compose_widget(
content_h = sum(h for _, _, h in parts) + gap * max(len(parts) - 1, 0) content_h = sum(h for _, _, h in parts) + gap * max(len(parts) - 1, 0)
total_h = header_h + content_h + padding * 2 + 10 total_h = header_h + content_h + padding * 2 + 10
# Header # Header (avatar + username). Only drawn when "name" is enabled.
avatar_svg = "" header = ""
if avatar_b64: if show_name:
avatar_svg = f''' if avatar_b64:
avatar_svg = f'''
<defs><clipPath id="mainAvatarClip"><circle cx="30" cy="30" r="16"/></clipPath></defs> <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)"/>''' <image x="14" y="14" width="32" height="32" href="data:image/png;base64,{avatar_b64}" clip-path="url(#mainAvatarClip)"/>'''
else: else:
avatar_svg = f'<circle cx="30" cy="30" r="16" fill="{t["accent"]}" opacity="0.3"/>' avatar_svg = f'<circle cx="30" cy="30" r="16" fill="{t["accent"]}" opacity="0.3"/>'
header = f'''
header = f'''
{avatar_svg} {avatar_svg}
<text x="54" y="38" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" <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> font-size="16" font-weight="700" fill="{t["text"]}">{escape(username or "Developer")}</text>
@@ -94,7 +125,9 @@ def compose_widget(
fill="none" stroke="{t["card_border"]}" stroke-width="1"/> fill="none" stroke="{t["card_border"]}" stroke-width="1"/>
{header} {header}
{embedded} {embedded}
<a href="https://gh-stats.com/?ref=card" xlink:href="https://gh-stats.com/?ref=card" target="_top">
<text x="{total_w // 2}" y="{total_h - 8}" text-anchor="middle" <text x="{total_w // 2}" y="{total_h - 8}" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="{t["text_secondary"]}" opacity="0.5">Generated with gh-stats</text> font-size="10" fill="{t["text_secondary"]}" opacity="0.75">Generated with gh-stats.com</text>
</a>
</svg>''' </svg>'''
+5 -1
View File
@@ -3,6 +3,7 @@
from ..models import FocusCategory from ..models import FocusCategory
from ..themes import THEMES, FOCUS_COLORS from ..themes import THEMES, FOCUS_COLORS
from ..utils import escape, card_wrapper from ..utils import escape, card_wrapper
from .attribution import FOOTER_H, attribution_text
def render_focus_widget(categories: list[FocusCategory], theme_name: str = "dark", period: str = "1y", settings: dict | None = None) -> str: def render_focus_widget(categories: list[FocusCategory], theme_name: str = "dark", period: str = "1y", settings: dict | None = None) -> str:
@@ -59,5 +60,8 @@ def render_focus_widget(categories: list[FocusCategory], theme_name: str = "dark
<text x="16" y="{subtitle_y}" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" <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>''' font-size="9" fill="{t["text_secondary"]}" opacity="0.7">Recent activity · {period_display}</text>'''
card_h = len(cats) * 36 + 54 # The period subtitle leaves only 8px below it, so reserve FOOTER_H for
# the attribution footer.
card_h = len(cats) * 36 + 54 + FOOTER_H
items += attribution_text(t, 190, card_h - 36 - 8)
return card_wrapper(items, 380, card_h, t, "Recent Focus") return card_wrapper(items, 380, card_h, t, "Recent Focus")
+47 -6
View File
@@ -4,11 +4,32 @@ import math
from ..models import GradeData from ..models import GradeData
from ..themes import THEMES, TAG_COLORS, GRADE_COLORS from ..themes import THEMES, TAG_COLORS, GRADE_COLORS
from ..utils import escape, card_wrapper, icon_svg from ..utils import escape, card_wrapper, icon_svg
from .attribution import FOOTER_H, attribution_text
# Tokens that should render uppercase instead of title-cased (e.g. "ml-engineer" # Tokens that should render uppercase instead of title-cased (e.g. "ml-engineer"
# → "ML Engineer", not "Ml Engineer"). # → "ML Engineer", not "Ml Engineer").
_TAG_ACRONYMS = {"ml", "ai", "ui", "ux", "api", "cli", "sql", "css", "html", "js", "ios"} _TAG_ACRONYMS = {"ml", "ai", "ui", "ux", "api", "cli", "sql", "css", "html", "js", "ios"}
# Human-readable names for the breakdown factors `compute_grade` emits. Used in
# the subtitle's "Strong in ..." callout to surface the two highest-scoring
# pillars of the grade — real info instead of repeating the letter + score.
_BREAKDOWN_LABELS = {
"commits": "Commits",
"consistency": "Consistency",
"repos": "Repos",
"stars": "Stars",
"forks": "Forks",
"activity": "Activity",
"followers": "Followers",
}
def _top_strengths(breakdown: dict | None, n: int = 2) -> list[str]:
if not breakdown:
return []
ranked = sorted(breakdown.items(), key=lambda kv: kv[1], reverse=True)
return [_BREAKDOWN_LABELS.get(k, k.capitalize()) for k, _ in ranked[:n]]
def _format_tag_label(tag: str) -> str: def _format_tag_label(tag: str) -> str:
# Custom tags may define an explicit label in src/tag_rules.py::TAG_DEFS. # Custom tags may define an explicit label in src/tag_rules.py::TAG_DEFS.
@@ -47,7 +68,10 @@ def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dic
radius = 36 radius = 36
circumference = 2 * math.pi * radius circumference = 2 * math.pi * radius
offset = circumference * (1 - score / 100) # S-tier grades get a fully closed ring regardless of exact score — the
# letter "S" itself carries the "top of the scale" meaning, so the visual
# should match. S+, S++ share the full circle.
offset = 0 if base == "S" else circumference * (1 - score / 100)
grade_font = 30 if len(data.grade) <= 2 else 22 grade_font = 30 if len(data.grade) <= 2 else 22
# Stats row with icons # Stats row with icons
@@ -105,7 +129,16 @@ def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dic
stats_y = 100 stats_y = 100
tags_y = stats_y + 54 tags_y = stats_y + 54
tag_padding = 18 if tags_h > 24 else 14 tag_padding = 18 if tags_h > 24 else 14
# Reserve space at the bottom for the "Generated with gh-stats.com"
# attribution. Matches the composite widget's footer convention so
# the standalone grade widget feels visually consistent when it's
# embedded on its own (the /api/<u>/grade.svg path).
footer_h = FOOTER_H
card_h = (tags_y + tags_h + tag_padding) if data.tags else (stats_y + 54) card_h = (tags_y + tags_h + tag_padding) if data.tags else (stats_y + 54)
card_h += footer_h
strengths = _top_strengths(data.breakdown)
strengths_line = f"Strong in {' · '.join(strengths)}" if strengths else ""
inner = f''' inner = f'''
<g transform="translate(52, 48)"> <g transform="translate(52, 48)">
@@ -115,18 +148,18 @@ def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dic
stroke-linecap="round" transform="rotate(-90)"> stroke-linecap="round" transform="rotate(-90)">
<animate attributeName="stroke-dashoffset" from="{circumference}" to="{offset}" dur="1s" fill="freeze"/> <animate attributeName="stroke-dashoffset" from="{circumference}" to="{offset}" dur="1s" fill="freeze"/>
</circle> </circle>
<text x="0" y="-4" text-anchor="middle" dominant-baseline="middle" <text x="0" y="{grade_font * 0.35:.2f}" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="{grade_font}" font-weight="800" fill="{color}">{escape(data.grade)}</text> 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> </g>
<line x1="100" y1="16" x2="100" y2="80" stroke="{t["grid"]}" stroke-width="1"/> <line x1="100" y1="16" x2="100" y2="80" stroke="{t["grid"]}" stroke-width="1"/>
<g transform="translate(114, 26)"> <g transform="translate(114, 26)">
<text x="0" y="10" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" <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> 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" <text x="0" y="32" 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> font-size="11" fill="{t["text_secondary"]}">{strengths_line}</text>
<text x="0" y="50" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="{t["text_secondary"]}" letter-spacing="0.4">Score <tspan fill="{t["text"]}" font-weight="600">{score:.0f}</tspan> / 100</text>
</g> </g>
<line x1="20" y1="{stats_y - 4}" x2="360" y2="{stats_y - 4}" stroke="{t["grid"]}" stroke-width="0.5"/> <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})"> <g transform="translate(20, {stats_y})">
@@ -140,4 +173,12 @@ def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dic
{tags_svg} {tags_svg}
</g>''' </g>'''
# Footer attribution. Marked with data-gh-attribution so composite.py
# can strip it (and reclaim the 16px) when this widget gets inlined
# — the composite has its own footer at the bottom of the whole
# card, so showing both would double-tag the same image.
# Positioned in the inner-svg coordinate space (card_wrapper passes
# title="" here, so inner is not vertically offset).
inner += attribution_text(t, 190, card_h - 8, footer_h)
return card_wrapper(inner, 380, card_h, t, "") return card_wrapper(inner, 380, card_h, t, "")
+7 -1
View File
@@ -3,6 +3,7 @@
from ..models import ImpactWeek from ..models import ImpactWeek
from ..themes import THEMES from ..themes import THEMES
from ..utils import card_wrapper, safe_color from ..utils import card_wrapper, safe_color
from .attribution import FOOTER_H, attribution_text
def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", period: str = "6mo", settings: dict | None = None) -> str: def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", period: str = "6mo", settings: dict | None = None) -> str:
@@ -14,7 +15,9 @@ def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", peri
t = THEMES[theme_name] t = THEMES[theme_name]
s = settings or {} s = settings or {}
line_color = safe_color(s.get("line_color"), t["accent"]) line_color = safe_color(s.get("line_color"), t["accent"])
w, h = 380, 200 # The summary block already ends ~12px above the card edge, which the
# footer would sit on top of, so reserve FOOTER_H for it.
w, h = 380, 200 + FOOTER_H
chart_x, chart_y = 40, 8 chart_x, chart_y = 40, 8
chart_w, chart_h = 316, 82 chart_w, chart_h = 316, 82
@@ -31,6 +34,7 @@ def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", peri
<text x="0" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" <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> font-size="9" fill="{t["text_secondary"]}">commits over {period}</text>
</g>''' </g>'''
inner += attribution_text(t, 190, h - 36 - 8)
return card_wrapper(inner, w, h, t, "Impact Timeline") return card_wrapper(inner, w, h, t, "Impact Timeline")
max_commits = max((wk.commits for wk in weeks), default=1) or 1 max_commits = max((wk.commits for wk in weeks), default=1) or 1
@@ -92,4 +96,6 @@ def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", peri
font-size="9" fill="{t["text_secondary"]}">commits over {period}</text> font-size="9" fill="{t["text_secondary"]}">commits over {period}</text>
</g>''' </g>'''
inner += attribution_text(t, 190, h - 36 - 8)
return card_wrapper(inner, w, h, t, "Impact Timeline") return card_wrapper(inner, w, h, t, "Impact Timeline")
+22 -6
View File
@@ -4,6 +4,7 @@ import math
from ..models import LanguageData from ..models import LanguageData
from ..themes import THEMES, LANG_COLORS, FOCUS_COLORS from ..themes import THEMES, LANG_COLORS, FOCUS_COLORS
from ..utils import escape, card_wrapper from ..utils import escape, card_wrapper
from .attribution import FOOTER_H, attribution_text
def render_languages_widget(languages: list[LanguageData], theme_name: str = "dark", settings: dict | None = None) -> str: def render_languages_widget(languages: list[LanguageData], theme_name: str = "dark", settings: dict | None = None) -> str:
@@ -40,12 +41,18 @@ def render_languages_widget(languages: list[LanguageData], theme_name: str = "da
for lang in langs: for lang in langs:
lang.percentage = round(lang.percentage * factor, 1) 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 cx, r = 60, 44
inner_r = 28 inner_r = 28
# The donut is 2 * (r + stroke-width/2) = 104px tall, but the legend block
# is only 22px per language. Centering the donut on the legend alone put
# its top above the card body whenever the legend was shorter than the
# donut (<= 3 languages), overlapping the card title. Center the donut and
# the legend on the body's midline instead; at >= 4 languages this is
# identical to the old geometry.
legend_height = len(langs) * 22
rows_h = max(legend_height + 40, 120)
cy = rows_h / 2
legend_start = (rows_h - legend_height) / 2
circumference = 2 * math.pi * r circumference = 2 * math.pi * r
arcs = "" arcs = ""
@@ -95,5 +102,14 @@ def render_languages_widget(languages: list[LanguageData], theme_name: str = "da
{legend} {legend}
</g>''' </g>'''
rows_h = max(len(langs) * 22 + 40, 120) # Footer attribution. Marked with data-gh-attribution so composite.py
return card_wrapper(inner, 380, rows_h + 36, t, "Languages") # can strip it (and reclaim the 16px) when inlining the widget into
# the larger composite — the composite has its own footer, showing
# both would be visually redundant. card_wrapper here passes
# title="Languages", which adds a 36px translate to inner. The 36 is
# already baked into the card height (rows_h + 36); the attribution
# adds another 16 on top, positioned 8px from the bottom of the card.
footer_h = FOOTER_H
card_h = rows_h + 36 + footer_h
inner += attribution_text(t, 190, card_h - 36 - 8, footer_h)
return card_wrapper(inner, 380, card_h, t, "Languages")
+83 -55
View File
@@ -3,40 +3,45 @@
from datetime import date from datetime import date
from ..models import StreakData from ..models import StreakData
from ..themes import THEMES from ..themes import THEMES
from ..utils import escape, card_wrapper from ..utils import escape, card_wrapper, safe_color
from .attribution import FOOTER_H, attribution_text
_FLAME_SVG = ( def _fmt_day(d: date, include_year: bool) -> str:
'<path d="M12 2c1 4 5 5 5 10a5 5 0 1 1-10 0c0-2 1-3 2-4 0 1 1 2 2 2 ' # %-d strips leading zero (POSIX-only; the service runs in a Linux container).
'-1-2 0-5 1-8z" fill="{color}" opacity="0.95"/>' return d.strftime("%b %-d, %Y") if include_year else d.strftime("%b %-d")
)
_TROPHY_SVG = (
'<path d="M6 3h12v3a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V3z" fill="none" '
'stroke="{color}" stroke-width="1.6"/>'
'<path d="M4 4h2v2a2 2 0 0 1-2 2H3V5a1 1 0 0 1 1-1zM20 4h-2v2a2 2 0 0 0 2 '
'2h1V5a1 1 0 0 0-1-1z" fill="none" stroke="{color}" stroke-width="1.4"/>'
'<rect x="9" y="11" width="6" height="3" fill="{color}"/>'
'<rect x="7" y="14" width="10" height="2" rx="0.5" fill="{color}"/>'
)
def _fmt_date(iso: str) -> str: def _fmt_current(start_iso: str, today_iso: str) -> str:
if not iso: """Caption for the current-streak date, e.g. 'Apr 8 – Today' or
'Apr 8, 2025 – Today' when the streak spans years."""
if not start_iso:
return "" return ""
try: try:
d = date.fromisoformat(iso) s = date.fromisoformat(start_iso)
t = date.fromisoformat(today_iso) if today_iso else date.today()
except ValueError: except ValueError:
return "" return ""
return d.strftime("%b %d, %Y") return f"{_fmt_day(s, s.year != t.year)} – Today"
def _fmt_range(start: str, end: str) -> str: def _fmt_longest(start_iso: str, end_iso: str) -> str:
s = _fmt_date(start) """Caption for the longest-streak date range. Keeps the year on the end date;
e = _fmt_date(end) adds a year to the start date only when start/end straddle years."""
try:
s = date.fromisoformat(start_iso) if start_iso else None
e = date.fromisoformat(end_iso) if end_iso else None
except ValueError:
return ""
if s and e: if s and e:
return f"{s} – {e}" if s.year == e.year:
return s or e return f"{_fmt_day(s, False)} – {_fmt_day(e, True)}"
return f"{_fmt_day(s, True)} – {_fmt_day(e, True)}"
if e:
return _fmt_day(e, True)
if s:
return _fmt_day(s, True)
return ""
def render_streaks_widget( def render_streaks_widget(
@@ -47,50 +52,73 @@ def render_streaks_widget(
"""Render the streaks widget. """Render the streaks widget.
Settings: Settings:
show_dates (bool): Show date captions below each number. Default True. color (str): Hex color for the current-streak number and progress bar
fill (default theme accent).
""" """
t = THEMES[theme_name] t = THEMES[theme_name]
s = settings or {} s = settings or {}
show_dates = bool(s.get("show_dates", True)) current_color = safe_color(s.get("color"), t["accent"])
max_color = t["text"]
width = 380 # The body already ends ~15px above the card edge, which the footer would
height = 170 # sit on top of, so reserve FOOTER_H for it.
col_w = width / 2 width, height = 380, 170 + FOOTER_H
current_color = t["accent"] # Inner content is translated 36px down by card_wrapper's title strip, so
max_color = t.get("text", "#e6e6e6") # every y below is measured from that inner origin.
left_x = 105
right_x = 275
divider_x = 190
bar_x = 50
bar_w = 280
current_sub = _fmt_date(data.current_start) if data.current_start else "—" fraction = (data.current / data.max) if data.max > 0 else 0.0
max_sub = _fmt_range(data.max_start, data.max_end) if (data.max_start or data.max_end) else "" fraction = max(0.0, min(1.0, fraction))
fill_w = round(bar_w * fraction, 2)
date_lines = "" current_caption = _fmt_current(data.current_start, data.last_active_date) if data.current > 0 else ""
if show_dates: longest_caption = _fmt_longest(data.max_start, data.max_end)
date_lines = f'''
<text x="{col_w / 2}" y="130" text-anchor="middle" # End-cap dot on the progress fill — hidden at 0% so it doesn't float
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" # detached at the bar start when the user has no current streak.
font-size="9" fill="{t["text_secondary"]}">{escape("since " + current_sub) if data.current > 0 else ""}</text> end_dot = ""
<text x="{col_w + col_w / 2}" y="130" text-anchor="middle" if fill_w > 0:
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" end_dot = (
font-size="9" fill="{t["text_secondary"]}">{escape(max_sub)}</text>''' f'<circle cx="{bar_x + fill_w:.2f}" cy="94.5" r="3.5" '
f'fill="{current_color}"/>'
)
inner = f''' inner = f'''
<g transform="translate({col_w / 2 - 12}, 14)">{_FLAME_SVG.format(color=current_color)}</g> <text x="{left_x}" y="22" text-anchor="middle"
<text x="{col_w / 2}" y="78" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" font-weight="600" letter-spacing="1.4"
fill="{t["text_secondary"]}">CURRENT</text>
<text x="{left_x}" y="66" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="{current_color}">{data.current}</text> font-size="40" font-weight="800" fill="{current_color}">{data.current}</text>
<text x="{col_w / 2}" y="108" text-anchor="middle"
<text x="{right_x}" y="22" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="{t["text_secondary"]}" letter-spacing="0.5">Current Streak</text> font-size="10" font-weight="600" letter-spacing="1.4"
fill="{t["text_secondary"]}">LONGEST</text>
<line x1="{col_w}" y1="24" x2="{col_w}" y2="{height - 24 - 36}" stroke="{t["grid"]}" stroke-width="1"/> <text x="{right_x}" y="66" text-anchor="middle"
<g transform="translate({col_w + col_w / 2 - 12}, 14)">{_TROPHY_SVG.format(color=max_color)}</g>
<text x="{col_w + col_w / 2}" y="78" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="{max_color}">{data.max}</text> font-size="40" font-weight="800" fill="{max_color}">{data.max}</text>
<text x="{col_w + col_w / 2}" y="108" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="{t["text_secondary"]}" letter-spacing="0.5">Longest Streak</text>
{date_lines}'''
return card_wrapper(inner, width, height, t, "") <line x1="{divider_x}" y1="10" x2="{divider_x}" y2="76"
stroke="{t["card_border"]}" stroke-width="1"/>
<rect x="{bar_x}" y="92" width="{bar_w}" height="5" rx="2.5" fill="{t["grid"]}"/>
<rect x="{bar_x}" y="92" width="{fill_w}" height="5" rx="2.5" fill="{current_color}"/>
{end_dot}
<text x="{bar_x}" y="116"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="{t["text_secondary"]}">{escape(current_caption)}</text>
<text x="{bar_x + bar_w}" y="116" text-anchor="end"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="{t["text_secondary"]}">{escape(longest_caption)}</text>'''
inner += attribution_text(t, 190, height - 36 - 8)
return card_wrapper(inner, width, height, t, "Streaks")
+111 -18
View File
@@ -1,27 +1,40 @@
"""Prefetch worker. Pulls pending jobs and populates widget data. """Prefetch worker. Pulls pending jobs, populates widget data, renders SVGs.
Two-phase pipeline: Each job (from enroll/settings-change/cron-detected payload change) goes
* Phase 1 (this module): on enroll/settings-change, fetch the raw GitHub through two steps in one pass: compute the widget_data dict for the client-
payload from the fetcher and compute widget data for the client-side side Workshop preview, then render and persist the composite + per-widget
Workshop preview. No SVG rendering. SVGs so embedded README widgets stay fresh as the underlying GitHub data
* Phase 2 (render_widgets_now, called from the API's Generate endpoint): rotates. The /generate endpoint reuses the same render path for on-demand
synchronously render composite SVG from the cached raw + current re-renders triggered by the Generate button.
settings and persist to widgets.db.
This split keeps the fetcher hot while the user edits settings and defers
expensive SVG composition until the user clicks Generate.
Run as its own container: CMD python -m src.worker Run as its own container: CMD python -m src.worker
""" """
import logging import logging
import random
import time import time
from dataclasses import asdict from dataclasses import asdict
from . import cache, config, db, fetcher_client, placeholder, processor from . import analytics, cache, config, db, fetcher_client, placeholder, processor
from .widgets import compose_widget from .widgets import compose_widget
log = logging.getLogger("generator.worker") log = logging.getLogger("generator.worker")
MAX_ATTEMPTS = 3 MAX_ATTEMPTS = 3
# A fetcher 503 means GitHub's quota is spent. Retrying in seconds burns all
# attempts before the hourly reset, so back off exponentially (1, 2, 4, ...
# minutes, jittered, capped at an hour) and allow enough attempts to span
# a full quota window.
RATE_LIMIT_MAX_ATTEMPTS = 8
RATE_LIMIT_BACKOFF_CAP_S = 3600
def _rate_limit_delay(e: Exception, attempts: int) -> float:
resp = getattr(e, "response", None)
try:
retry_after = float(resp.headers.get("Retry-After"))
except (AttributeError, TypeError, ValueError):
retry_after = 0
delay = max(retry_after, 60 * 2 ** (attempts - 1))
return min(delay * random.uniform(0.8, 1.2), RATE_LIMIT_BACKOFF_CAP_S)
def _compute_widget_data(payload: dict, settings: dict, username: str) -> dict: def _compute_widget_data(payload: dict, settings: dict, username: str) -> dict:
@@ -52,6 +65,22 @@ def _compute_widget_data(payload: dict, settings: dict, username: str) -> dict:
} }
def _render_and_persist(username: str, payload: dict, settings: dict, settings_hash: str) -> None:
"""Render SVGs from the payload and persist to widgets.db. Used by the
cron-driven worker so embedded widgets keep ticking forward (streak
counter, etc.) as the fetcher refreshes the underlying data — without
waiting for the user to manually click Generate."""
t0 = time.monotonic()
widgets = _render_widgets(username, payload, settings)
db.put_widgets(username, settings_hash, widgets)
cache.Cache().delete(
f"widget:composite:{username}",
*[f"widget:{n}:{username}" for n in widgets],
)
analytics.record_render(username, "composite",
int((time.monotonic() - t0) * 1000))
def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, str]: def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, str]:
enabled = settings.get("enabled") or config.ENABLED_WIDGETS enabled = settings.get("enabled") or config.ENABLED_WIDGETS
order = settings.get("widget_order") or config.WIDGET_ORDER order = settings.get("widget_order") or config.WIDGET_ORDER
@@ -67,10 +96,18 @@ def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, s
achievements=settings.get("achievements") or [], achievements=settings.get("achievements") or [],
stored_streak=stored_streak, stored_streak=stored_streak,
) )
ordered = [w for w in order if w in enabled and w in widgets and widgets[w]] enabled_set = set(enabled)
show_name = "name" in enabled_set
# Preserve "name" in the ordered list so the composite honors its
# user-ordered position (always 0 today, but future-proof).
ordered = [
w for w in order
if w in enabled_set and (w == "name" or (w in widgets and widgets[w]))
]
composite = compose_widget( composite = compose_widget(
widgets=widgets, enabled=ordered, theme_name=theme, widgets=widgets, enabled=ordered, theme_name=theme,
username=username, avatar_b64=payload.get("avatar_b64", ""), username=username, avatar_b64=payload.get("avatar_b64", ""),
show_name=show_name,
) )
out = {name: svg for name, svg in widgets.items() if svg} out = {name: svg for name, svg in widgets.items() if svg}
out["composite"] = composite out["composite"] = composite
@@ -78,7 +115,10 @@ def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, s
def process_one() -> bool: def process_one() -> bool:
"""Phase 1: claim a pending job and populate widget data (no SVG).""" """Claim a pending job: populate widget_data AND render SVGs. The render
step is what keeps embedded README widgets fresh as the fetcher rotates
payloads — without it, SVGs would only ever update when the user clicks
Generate, which is why the streak counter previously appeared frozen."""
job = db.claim_next_job() job = db.claim_next_job()
if job is None: if job is None:
return False return False
@@ -98,21 +138,61 @@ def process_one() -> bool:
db.fail_job(job["id"], "settings missing", retry=False) db.fail_job(job["id"], "settings missing", retry=False)
return True return True
widget_data = _compute_widget_data(payload, settings_row["settings"], username) settings = settings_row["settings"]
db.put_widget_data(username, settings_row["settings_hash"], widget_data) settings_hash = settings_row["settings_hash"]
db.point_current_widget(username, settings_row["settings_hash"]) widget_data = _compute_widget_data(payload, settings, username)
db.put_widget_data(username, settings_hash, widget_data)
_render_and_persist(username, payload, settings, settings_hash)
db.point_current_widget(username, settings_hash)
db.set_last_fetcher_hash(username, result.get("payload_hash", "")) db.set_last_fetcher_hash(username, result.get("payload_hash", ""))
db.lru_trim(username, config.WIDGET_LRU_PER_USER) db.lru_trim(username, config.WIDGET_LRU_PER_USER)
db.complete_job(job["id"]) db.complete_job(job["id"])
log.info("prefetched data for %s", username) log.info("prefetched + rendered widgets for %s", username)
return True return True
except Exception as e: except Exception as e:
if getattr(getattr(e, "response", None), "status_code", None) == 503:
retry = job["attempts"] < RATE_LIMIT_MAX_ATTEMPTS
db.fail_job(job["id"], str(e)[:500], retry=retry,
delay_s=_rate_limit_delay(e, job["attempts"]))
log.warning("prefetch rate-limited for %s (retry=%s): %s", username, retry, e)
return True
retry = job["attempts"] < MAX_ATTEMPTS retry = job["attempts"] < MAX_ATTEMPTS
db.fail_job(job["id"], str(e)[:500], retry=retry) db.fail_job(job["id"], str(e)[:500], retry=retry)
log.warning("prefetch failed for %s (retry=%s): %s", username, retry, e) log.warning("prefetch failed for %s (retry=%s): %s", username, retry, e)
return True return True
def render_composite_adhoc(username: str, override_settings: dict,
widget_name: str = "composite") -> str | None:
"""Render `widget_name` for `username` using stored settings merged
with the per-request `override_settings`. Does NOT persist anything.
Used by the public `GET /api/<u>?...` endpoint so unauthenticated visitors
can preview/embed a widget configured purely via query string, without
touching the owner's stored settings.
Returns the SVG string, or None if the user isn't enrolled / the fetcher
has no data for them (caller should fall through to the cached path).
"""
settings_row = db.get_settings(username)
if settings_row is None:
return None
result = fetcher_client.get_data(username)
payload = result.get("data") or {}
if not payload or payload.get("error") == "not_found":
return None
effective = {**settings_row["settings"], **(override_settings or {})}
if widget_name != "composite":
# Only the requested widget is returned, so don't pay to render the
# rest: generate_widgets_from_github skips anything not enabled.
effective["enabled"] = [widget_name]
t0 = time.monotonic()
widgets = _render_widgets(username, payload, effective)
analytics.record_render(username, "composite",
int((time.monotonic() - t0) * 1000))
return widgets.get(widget_name)
def render_widgets_now(username: str) -> dict[str, str]: def render_widgets_now(username: str) -> dict[str, str]:
"""Phase 2: synchronously render composite SVG and persist it. """Phase 2: synchronously render composite SVG and persist it.
@@ -132,11 +212,14 @@ def render_widgets_now(username: str) -> dict[str, str]:
cache.Cache().delete(f"widget:composite:{username}") cache.Cache().delete(f"widget:composite:{username}")
return {"composite": svg} return {"composite": svg}
t0 = time.monotonic()
widgets = _render_widgets(username, payload, settings_row["settings"]) widgets = _render_widgets(username, payload, settings_row["settings"])
db.put_widgets(username, settings_row["settings_hash"], widgets) db.put_widgets(username, settings_row["settings_hash"], widgets)
db.point_current_widget(username, settings_row["settings_hash"]) db.point_current_widget(username, settings_row["settings_hash"])
c = cache.Cache() c = cache.Cache()
c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets]) c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets])
analytics.record_render(username, "composite",
int((time.monotonic() - t0) * 1000))
log.info("rendered widgets on-demand for %s", username) log.info("rendered widgets on-demand for %s", username)
return widgets return widgets
@@ -144,6 +227,16 @@ def render_widgets_now(username: str) -> dict[str, str]:
def main(): def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
db.init_dbs() db.init_dbs()
# If this boot is the first container to see a new BUILD_VERSION,
# enqueue a rebuild for every enrolled user. claim_build_version is
# atomic so racing with the api/cron containers is safe.
if config.BUILD_VERSION:
try:
if db.claim_build_version(config.BUILD_VERSION):
n = db.enqueue_build_all()
log.info("build %s: queued %d rebuild(s)", config.BUILD_VERSION, n)
except Exception:
log.exception("build-version invalidation failed")
while True: while True:
db.reclaim_stuck_jobs(older_than_minutes=10) db.reclaim_stuck_jobs(older_than_minutes=10)
if not process_one(): if not process_one():
+276
View File
@@ -0,0 +1,276 @@
import os, tempfile, time
import pytest
from src import db as dbmod
from src import analytics as a
@pytest.fixture
def fresh(monkeypatch):
with tempfile.TemporaryDirectory() as d:
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(d, "a.db"))
dbmod.init_dbs()
a._reset_for_tests()
yield
def test_ingest_batch_writes_rows(fresh):
n = a.ingest_batch([
{"ts": 1000, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 12, "cache_hit": 1},
{"ts": 1001, "service": "edge", "kind": "request",
"username": "bob", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 8, "cache_hit": 0},
])
assert n == 2
with dbmod.analytics_conn() as c:
rows = c.execute("SELECT username, latency_ms FROM events ORDER BY ts").fetchall()
assert [(r["username"], r["latency_ms"]) for r in rows] == [("alice", 12), ("bob", 8)]
def test_ingest_drops_bad_rows(fresh):
n = a.ingest_batch([
{"ts": 1, "service": "edge", "kind": "request", "latency_ms": 1},
{"missing": "everything"},
{"ts": 2, "service": "edge", "kind": "request", "latency_ms": "not-int"},
])
assert n == 1
def test_record_render_flushes_to_db(fresh, monkeypatch):
monkeypatch.setattr(a, "_FLUSH_SECONDS", 0.05)
a.start_flush_thread()
a.record_render("alice", "composite", 142)
deadline = time.time() + 3
row = None
while time.time() < deadline:
with dbmod.analytics_conn() as c:
row = c.execute("SELECT * FROM events WHERE kind='render'").fetchone()
if row:
break
time.sleep(0.05)
assert row is not None
assert row["username"] == "alice"
assert row["widget"] == "composite"
assert row["latency_ms"] == 142
def test_summary_aggregates_last_7d(fresh):
now = int(time.time())
rows = [
{"ts": now - 60, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 10, "cache_hit": 1},
{"ts": now - 120, "service": "edge", "kind": "request",
"username": "bob", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 50, "cache_hit": 0},
{"ts": now - 10 * 86400, "service": "edge", "kind": "request",
"username": "old", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 999, "cache_hit": 0},
{"ts": now - 30, "service": "generator", "kind": "render",
"username": "alice", "widget": "composite", "latency_ms": 200},
]
a.ingest_batch(rows)
s = a.query_summary()
assert s["requests_7d"] == 2 # 'old' falls outside the 7d window
assert s["active_users_7d"] == 2 # alice (edge+render dedup) + bob
assert s["renders_7d"] == 1
assert s["avg_render_ms"] == 200
assert s["p50_ms"] in (10, 50)
assert s["p95_ms"] == 50
assert len(s["daily_requests"]) == 7
def test_query_users_returns_per_user_rows(fresh):
now = int(time.time())
a.ingest_batch([
{"ts": now - 60, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 10, "cache_hit": 1},
{"ts": now - 30, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>/grade.svg", "widget": "grade",
"status": 200, "latency_ms": 20, "cache_hit": 1},
{"ts": now - 10, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 30, "cache_hit": 1},
])
users = a.query_users()
assert len(users) == 1
u = users[0]
assert u["username"] == "alice"
assert u["requests_7d"] == 3
assert u["top_endpoint"] == "/<u>"
assert u["avg_latency_ms"] == 20
def test_query_latency_returns_percentiles(fresh):
now = int(time.time())
a.ingest_batch([
{"ts": now - 1, "service": "edge", "kind": "request",
"username": "u", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": v, "cache_hit": 1}
for v in range(1, 101)
])
rows = a.query_latency()
by_ep = {r["endpoint"]: r for r in rows}
assert by_ep["/<u>"]["count"] == 100
assert by_ep["/<u>"]["p50"] == 50
assert by_ep["/<u>"]["p95"] == 95
assert by_ep["/<u>"]["p99"] == 99
def test_query_growth_buckets_by_day_and_week(fresh):
now = int(time.time())
a.ingest_batch([
# Today: alice (2 requests), bob (1 request), carol (render only)
{"ts": now - 60, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 10, "cache_hit": 1},
{"ts": now - 120, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 10, "cache_hit": 1},
{"ts": now - 180, "service": "edge", "kind": "request",
"username": "bob", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 10, "cache_hit": 1},
{"ts": now - 240, "service": "generator", "kind": "render",
"username": "carol", "widget": "composite", "latency_ms": 100},
# 10 days ago: dave (1 request) — outside the 30d window's start
# would still land in the daily bucket if within range
{"ts": now - 10 * 86400, "service": "edge", "kind": "request",
"username": "dave", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 10, "cache_hit": 1},
])
g = a.query_growth(daily_n=30, weekly_n=12)
assert len(g["daily"]) == 30
assert len(g["weekly"]) == 12
# Today = last entry. Requests count only kind='request', users include
# render-only callers — matching active_users_7d's definition.
today = g["daily"][-1]
assert today["requests"] == 3
assert today["users"] == 3 # alice, bob, carol
# 10-day-ago bucket has dave's single request
ten_days_ago = g["daily"][-11]
assert ten_days_ago["requests"] == 1
assert ten_days_ago["users"] == 1
# Current week (last weekly entry) includes today's traffic
assert g["weekly"][-1]["requests"] >= 3
assert g["weekly"][-1]["users"] >= 3
def test_growth_numbers_survive_event_prune(fresh):
"""The whole point of daily_stats: per-day counts must persist even
after their underlying events get pruned past the retention window."""
now = int(time.time())
twenty_days_ago = now - 20 * 86400
a.ingest_batch([
{"ts": twenty_days_ago, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 10, "cache_hit": 1},
{"ts": twenty_days_ago + 60, "service": "edge", "kind": "request",
"username": "bob", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 10, "cache_hit": 1},
{"ts": twenty_days_ago + 120, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 10, "cache_hit": 1},
])
a.rollup_daily_stats()
pruned = a.prune_old(retention_days=14)
assert pruned == 3 # all three events were older than 14 days
g = a.query_growth(daily_n=30, weekly_n=12)
target_day = time.strftime("%Y-%m-%d", time.gmtime(twenty_days_ago))
bucket = next(d for d in g["daily"] if d["day"] == target_day)
assert bucket["requests"] == 3
assert bucket["users"] == 2 # alice (deduped) + bob
def test_weekly_uniques_dedupe_across_days(fresh):
"""A user active on multiple days within the same ISO week counts
once for that week — set union, not sum-of-daily-uniques."""
now = int(time.time())
# Pin to a known weekday so all three timestamps land in the same ISO week.
# Monday-ish: subtract `weekday` days from now to land near Mon, then offset.
monday = now - time.gmtime(now).tm_wday * 86400 + 12 * 3600 # noon UTC Monday
a.ingest_batch([
{"ts": monday, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 10, "cache_hit": 1},
{"ts": monday + 86400, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 10, "cache_hit": 1},
{"ts": monday + 2 * 86400, "service": "edge", "kind": "request",
"username": "bob", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 10, "cache_hit": 1},
])
g = a.query_growth(daily_n=30, weekly_n=12)
target_week = time.strftime("%G-W%V", time.gmtime(monday))
week_row = next(w for w in g["weekly"] if w["week"] == target_week)
assert week_row["requests"] == 3
assert week_row["users"] == 2 # alice (Mon+Tue) deduped + bob (Wed)
def test_query_health(fresh):
now = int(time.time())
a.ingest_batch([
{"ts": now - 1, "service": "edge", "kind": "request",
"username": "u", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 1, "cache_hit": 1},
{"ts": now - 2, "service": "edge", "kind": "request",
"username": "u", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 1, "cache_hit": 0},
{"ts": now - 3, "service": "fetcher", "kind": "fetch",
"username": "u", "endpoint": "github/users/<u>",
"status": 500, "latency_ms": 100},
{"ts": now - 4, "service": "fetcher", "kind": "fetch",
"username": "u", "endpoint": "github/users/<u>",
"status": 200, "latency_ms": 100},
])
h = a.query_health()
assert abs(h["edge_cache_hit_rate"] - 0.5) < 1e-6
assert abs(h["fetcher_error_rate"] - 0.5) < 1e-6
assert h["events_dropped_24h"] == 0
def test_prune_drops_old_events(fresh):
now = int(time.time())
a.ingest_batch([
{"ts": now - 20 * 86400, "service": "edge", "kind": "request",
"username": "u", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 1, "cache_hit": 1},
{"ts": now, "service": "edge", "kind": "request",
"username": "u", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 1, "cache_hit": 1},
])
deleted = a.prune_old(retention_days=14)
assert deleted == 1
with dbmod.analytics_conn() as c:
n = c.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"]
assert n == 1
def test_queue_drops_when_full_and_counts(fresh, monkeypatch):
monkeypatch.setattr(a, "_QUEUE_MAX", 3)
a._reset_for_tests()
for i in range(10):
a.record_render("u", "composite", i)
assert a._events_dropped == 7
def test_query_users_includes_render_only_users(fresh):
"""Render-only users (worker fired but no edge traffic yet) must still
appear in the table — without this, `active_users_7d` says N while the
table looks empty, which reads as a bug."""
now = int(time.time())
a.ingest_batch([
{"ts": now - 60, "service": "generator", "kind": "render",
"username": "alice", "widget": "composite", "latency_ms": 200},
])
users = a.query_users()
assert len(users) == 1
u = users[0]
assert u["username"] == "alice"
assert u["requests_7d"] == 0 # no request events yet
assert u["last_seen"] == now - 60
assert u["avg_latency_ms"] == 0 # latency only averages request events
+808 -6
View File
@@ -10,9 +10,12 @@ def client(monkeypatch):
# No-op the kickoff so tests don't spawn background threads that # No-op the kickoff so tests don't spawn background threads that
# would try to reach the (unmocked) fetcher and race tempdir teardown. # would try to reach the (unmocked) fetcher and race tempdir teardown.
monkeypatch.setattr(apimod, "_kickoff_prefetch_async", lambda *_a, **_kw: None) monkeypatch.setattr(apimod, "_kickoff_prefetch_async", lambda *_a, **_kw: None)
# Same reason for the new async-fetch hook used by the OAuth callback.
monkeypatch.setattr(apimod, "_request_fetch_async", lambda *_a, **_kw: None)
with tempfile.TemporaryDirectory() as d: with tempfile.TemporaryDirectory() as d:
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db")) monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db")) monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(d, "a.db"))
dbmod.init_dbs() dbmod.init_dbs()
# Configure OAuth fixture with allowed origins and insecure cookies for testing. # Configure OAuth fixture with allowed origins and insecure cookies for testing.
monkeypatch.setattr(cfg, "ALLOWED_ORIGINS", ("https://gh-stats.com",)) monkeypatch.setattr(cfg, "ALLOWED_ORIGINS", ("https://gh-stats.com",))
@@ -32,14 +35,67 @@ def test_health(client):
assert r.get_json()["service"] == "generator" assert r.get_json()["service"] == "generator"
def test_get_unknown_user_returns_building_placeholder_without_enrolling(client): def test_root_with_username_param_force_renders_grade_widget(client, monkeypatch):
"""The SVG endpoint is for README embeds — enrollment is frontend-driven """`GET /?username=<u>` auto-enrolls and returns just the grade widget SVG,
through /data or /api/enroll, so GET /api/<u> does not auto-enroll.""" force-generated from fresh fetcher data. No composite, no other widgets."""
from src.models import GradeData
monkeypatch.setattr(
"src.api.fetcher_client.get_data",
lambda u: {"data": {"user": {}, "repos": [], "events": []}, "payload_hash": "h"},
)
monkeypatch.setattr(
"src.api.processor.compute_grade",
lambda *a, **kw: GradeData(grade="A", score=88.0, stats={}, tags=[]),
)
monkeypatch.setattr("src.api.render_grade_widget", lambda *a, **kw: "<svg id='grade'/>")
r = client.get("/?username=alice")
assert r.status_code == 200
assert r.mimetype == "image/svg+xml"
assert r.headers["X-Widget-Status"] == "ready"
assert dbmod.get_settings("alice") is not None
body = r.data.decode()
assert "<svg" in body
assert "composite" not in body
def test_api_with_username_param_also_works(client, monkeypatch):
"""Same shortcut is available at `/api/?username=<u>` so the /api prefix
stays consistent for callers that expect it."""
from src.models import GradeData
monkeypatch.setattr(
"src.api.fetcher_client.get_data",
lambda u: {"data": {"user": {}, "repos": [], "events": []}, "payload_hash": "h"},
)
monkeypatch.setattr(
"src.api.processor.compute_grade",
lambda *a, **kw: GradeData(grade="A", score=88.0, stats={}, tags=[]),
)
monkeypatch.setattr("src.api.render_grade_widget", lambda *a, **kw: "<svg id='grade'/>")
r = client.get("/api/?username=bob")
assert r.status_code == 200
assert r.mimetype == "image/svg+xml"
assert r.headers["X-Widget-Status"] == "ready"
def test_root_without_username_serves_spa(client):
"""Plain `/` still returns the SPA (or the 'frontend not built' fallback
in test, where static assets aren't bundled)."""
r = client.get("/")
# Either 200 (static built) or 503 (not built) — the important thing is we
# don't accidentally route to the grade-widget handler.
assert r.status_code in (200, 503)
assert r.mimetype != "image/svg+xml"
def test_get_unknown_user_auto_enrolls_and_returns_building(client):
"""The SVG embed endpoint must kick off enrollment + prefetch on first
hit — otherwise a README embed for a never-seen username would return
'building' forever with nothing ever advancing the build."""
r = client.get("/api/alice") r = client.get("/api/alice")
assert r.status_code == 200 assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "building" assert r.headers["X-Widget-Status"] == "building"
assert "Building" in r.data.decode() assert "Building" in r.data.decode()
assert dbmod.get_settings("alice") is None assert dbmod.get_settings("alice") is not None
def test_enrolled_but_not_generated_returns_building(client): def test_enrolled_but_not_generated_returns_building(client):
@@ -60,6 +116,98 @@ def test_enrolled_user_with_built_widget_returns_ready(client):
assert b"ready" in r.data assert b"ready" in r.data
def test_get_widget_is_case_insensitive(client):
"""GitHub usernames are case-insensitive, so records are stored under the
canonical lowercase. A request for `/api/Alice` must resolve to the
existing `alice` record instead of missing it and returning 'building'
(or re-enrolling a duplicate)."""
dbmod.enroll("alice", {"theme": "dark"})
dbmod.put_widgets("alice", "h1", {"composite": "<svg>ready</svg>"})
dbmod.point_current_widget("alice", "h1")
r = client.get("/api/Alice")
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "ready"
assert b"ready" in r.data
def test_get_widget_named_is_case_insensitive(client):
dbmod.enroll("alice", {"theme": "dark"})
dbmod.put_widgets("alice", "h1", {"grade": "<svg>gradesvg</svg>"})
dbmod.point_current_widget("alice", "h1")
r = client.get("/api/Alice/grade.svg")
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "ready"
assert b"gradesvg" in r.data
def test_settings_get_is_case_insensitive(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.get("/api/Alice/settings")
assert r.status_code == 200
assert r.get_json()["settings"]["theme"] == "dark"
# ---- widget-first compat format: /api/<widget>/<username> ----------------
# Reversed shape (`/api/streak/<u>`) that people copy from other badge
# services. Must resolve to the named widget and auto-enroll/build on miss.
def test_widget_first_streak_alias_serves_streaks_widget(client):
dbmod.enroll("alice", {"theme": "dark"})
dbmod.put_widgets("alice", "h1", {"streaks": "<svg>streaksvg</svg>"})
dbmod.point_current_widget("alice", "h1")
r = client.get("/api/streak/alice")
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "ready"
assert b"streaksvg" in r.data
def test_widget_first_canonical_name_serves_widget(client):
dbmod.enroll("alice", {"theme": "dark"})
dbmod.put_widgets("alice", "h1", {"grade": "<svg>gradesvg</svg>"})
dbmod.point_current_widget("alice", "h1")
r = client.get("/api/grade/alice")
assert r.status_code == 200
assert b"gradesvg" in r.data
def test_widget_first_unknown_user_auto_enrolls_and_builds(client):
"""The whole point: a never-seen user in widget-first form must queue a
build instead of returning 404."""
r = client.get("/api/streak/newcomer")
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "building"
assert dbmod.get_settings("newcomer") is not None
def test_widget_first_is_case_insensitive(client):
r = client.get("/api/streak/Newcomer")
assert r.status_code == 200
assert dbmod.get_settings("newcomer") is not None
def test_widget_first_unknown_widget_rejected(client):
r = client.get("/api/boguswidget/alice")
assert r.status_code == 400
assert r.get_json()["error"] == "unknown_widget"
def test_widget_first_does_not_shadow_named_svg_route(client):
"""The native `/api/<u>/<widget>.svg` route must still win for .svg URLs."""
dbmod.enroll("alice", {"theme": "dark"})
dbmod.put_widgets("alice", "h1", {"grade": "<svg>namedsvg</svg>"})
dbmod.point_current_widget("alice", "h1")
r = client.get("/api/alice/grade.svg")
assert r.status_code == 200
assert b"namedsvg" in r.data
def test_widget_first_does_not_shadow_data_route(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.get("/api/alice/data")
assert r.is_json # data route returns JSON status, not an SVG
def test_settings_patch_enqueues_rebuild(client): def test_settings_patch_enqueues_rebuild(client):
dbmod.enroll("alice", {"theme": "dark"}) dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s: with client.session_transaction() as s:
@@ -168,6 +316,21 @@ def test_generate_endpoint_renders_and_stores_svg(client):
assert b"<svg>r</svg>" in r2.data assert b"<svg>r</svg>" in r2.data
def test_generate_rate_limited_returns_503(client):
"""A spent GitHub quota surfaces as 503 github_rate_limited, not 502."""
import requests
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
resp = requests.Response()
resp.status_code = 503
err = requests.HTTPError("503 Server Error", response=resp)
with patch("src.worker.render_widgets_now", side_effect=err):
r = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 503
assert r.get_json() == {"error": "github_rate_limited"}
def test_generate_endpoint_rejects_unenrolled(client): def test_generate_endpoint_rejects_unenrolled(client):
"""With OAuth, unenrolled means having a session but no profile.""" """With OAuth, unenrolled means having a session but no profile."""
with client.session_transaction() as s: with client.session_transaction() as s:
@@ -238,9 +401,202 @@ def test_refresh_without_session_is_401(client):
assert r.status_code == 401 assert r.status_code == 401
def test_data_unknown_user_returns_404(client): def test_data_unknown_user_auto_enrolls_and_returns_building(client):
"""Visitor auto-enroll: typing someone else's username into the workshop
search bar (which polls /data) must kick off the build pipeline, not
sit forever on a 404. Daily-cap protected by ENROLLMENT_DAILY_CAP."""
r = client.get("/api/testuser/data") r = client.get("/api/testuser/data")
assert r.status_code == 404 assert r.status_code == 202
assert r.get_json()["status"] == "building"
# The user is now in `users` with a build queued, just like an OAuth
# signup or the /?username=X shortcut would have done.
assert dbmod.get_settings("testuser") is not None
def test_data_unknown_user_when_cap_reached_returns_429(client, monkeypatch):
monkeypatch.setattr(cfg, "ENROLLMENT_DAILY_CAP", 0)
r = client.get("/api/testuser/data")
assert r.status_code == 429
assert r.get_json()["status"] == "rate_limited"
# No enrollment should have happened — cap is the abuse backstop.
assert dbmod.get_settings("testuser") is None
def test_widget_with_no_output_does_not_reenqueue_forever(client):
"""`name` is drawn inside the composite and never persisted standalone, so
its SVG is permanently absent. Once a build has landed, requesting it must
NOT enqueue another build: every request doing so pins the worker and grows
the prefetch queue without bound under load."""
dbmod.enroll("alice", {"theme": "dark"})
dbmod.put_widget_data("alice", "h1", {"some": "data"})
dbmod.put_widgets("alice", "h1", {"composite": "<svg>ready</svg>"})
dbmod.point_current_widget("alice", "h1")
before = dbmod.pending_job_count()
for _ in range(5):
r = client.get("/api/alice/name.svg")
assert r.headers["X-Widget-Status"] == "building"
assert dbmod.pending_job_count() == before
def test_missing_widget_still_self_heals_when_no_build_landed(client):
"""The self-heal must survive: no widget_data means the build never
completed, so one rebuild should still be queued."""
dbmod.enroll("bob", {"theme": "dark"})
# Drain the enrollment build without it ever persisting widget_data,
# i.e. the permanently-failed build the self-heal exists for.
job = dbmod.claim_next_job()
dbmod.fail_job(job["id"], "boom", retry=False)
assert dbmod.pending_job_count() == 0
r = client.get("/api/bob/grade.svg")
assert r.headers["X-Widget-Status"] == "building"
assert dbmod.pending_job_count() == 1
def test_data_unknown_user_when_hourly_cap_reached_returns_429(client, monkeypatch):
"""The hourly burst guard is what protects the PAT during a launch spike:
a day's budget arriving inside one hour would exhaust it."""
monkeypatch.setattr(cfg, "ENROLLMENT_DAILY_CAP", 10_000)
monkeypatch.setattr(cfg, "ENROLLMENT_HOURLY_CAP", 0)
r = client.get("/api/testuser/data")
assert r.status_code == 429
assert r.get_json()["status"] == "rate_limited"
assert dbmod.get_settings("testuser") is None
def test_data_unknown_user_enrolls_when_under_both_caps(client, monkeypatch):
monkeypatch.setattr(cfg, "ENROLLMENT_DAILY_CAP", 10_000)
monkeypatch.setattr(cfg, "ENROLLMENT_HOURLY_CAP", 10_000)
r = client.get("/api/testuser/data")
assert r.status_code == 202
assert dbmod.get_settings("testuser") is not None
# ---- README snippet pasted without substituting the username ----
@pytest.mark.parametrize("name", ["YOUR_USERNAME", "your_username", "yourusername", "username"])
def test_unsubstituted_placeholder_returns_card_not_400(client, name):
"""The README snippet uses YOUR_USERNAME. People paste it as-is, which
renders a broken image on their profile. Serve instructions instead."""
r = client.get(f"/api/{name}")
assert r.status_code == 200
assert r.mimetype == "image/svg+xml"
assert r.headers["X-Widget-Status"] == "unsubstituted"
assert b"Replace YOUR_USERNAME" in r.data
# ---- /api/top-langs compat shim for upstream github-readme-stats URLs ----
def test_top_langs_requires_username_query_param(client):
r = client.get("/api/top-langs")
assert r.status_code == 400
assert r.get_json()["error"] == "invalid_username"
def test_top_langs_rejects_invalid_username(client):
r = client.get("/api/top-langs?username=../etc/passwd")
assert r.status_code == 400
def test_top_langs_route_does_not_shadow_real_user_named_top(client):
"""Sanity: Flask matches the literal '/api/top-langs' route before
falling through to '/api/<username>', but a user literally named
'top' should still resolve via the variable route."""
dbmod.enroll("top", {"theme": "dark"})
dbmod.put_widgets("top", "h1", {"composite": "<svg>top</svg>"})
dbmod.point_current_widget("top", "h1")
r = client.get("/api/top")
assert r.status_code == 200
assert b"top" in r.data
def test_top_langs_serves_languages_widget_for_existing_user(client):
"""The shim's job is to map upstream's URL shape to this fork's
languages widget. Cached SVG should come back unchanged."""
dbmod.enroll("alice", {"theme": "dark"})
dbmod.put_widgets("alice", "h1", {
"composite": "<svg>composite</svg>",
"languages": "<svg>langs</svg>",
})
dbmod.point_current_widget("alice", "h1")
r = client.get("/api/top-langs?username=alice")
assert r.status_code == 200
assert r.headers.get("Content-Type", "").startswith("image/svg")
assert b"langs" in r.data
def test_top_langs_auto_enrolls_unknown_user(client):
"""Visitor copy-pasting an upstream-style URL for a user we've never
seen should kick off the build pipeline, same as /data does."""
r = client.get("/api/top-langs?username=newcomer")
assert r.status_code == 200 # placeholder SVG
assert dbmod.get_settings("newcomer") is not None
def test_top_langs_when_cap_reached_returns_placeholder(client, monkeypatch):
monkeypatch.setattr(cfg, "ENROLLMENT_DAILY_CAP", 0)
r = client.get("/api/top-langs?username=newcomer")
assert r.status_code == 200
# Rate-limited placeholder, not enrolled.
assert dbmod.get_settings("newcomer") is None
def test_top_langs_ignores_upstream_specific_query_params(client):
"""Upstream's layout/title_color/hide/langs_count/etc. params have
no equivalent in this fork. The shim should not crash on them — it
should just serve the cached widget and ignore the noise."""
dbmod.enroll("alice", {"theme": "dark"})
dbmod.put_widgets("alice", "h1", {"languages": "<svg>langs</svg>"})
dbmod.point_current_widget("alice", "h1")
r = client.get(
"/api/top-langs?username=alice&layout=compact&hide_border=true"
"&title_color=58C4DD&text_color=58C4DD&bg_color=00000000"
"&langs_count=6&hide=html,css"
)
assert r.status_code == 200
assert b"langs" in r.data
# ---- Trailing-slash tolerance -----------------------------------------------
# Flask's default strict_slashes turns `/api/top-langs/?username=X` — the exact
# shape upstream github-readme-stats prints (note the '/' before '?') — into a
# hard 404 with no redirect. Every /api route had the same latent bug: any
# copied URL carrying a stray trailing slash 404'd. These pin the lenient
# behavior so both forms resolve.
def test_top_langs_trailing_slash_before_query(client):
"""Upstream's canonical URL is `/api/top-langs/?username=X`. The trailing
slash must not 404 — it's the single most common broken embed."""
dbmod.enroll("alice", {"theme": "dark"})
dbmod.put_widgets("alice", "h1", {"languages": "<svg>langs</svg>"})
dbmod.point_current_widget("alice", "h1")
r = client.get("/api/top-langs/?username=alice")
assert r.status_code == 200
assert b"langs" in r.data
def test_widget_first_trailing_slash(client):
"""`/api/streak/alice/` must resolve to the same widget as `/api/streak/alice`."""
dbmod.enroll("alice", {"theme": "dark"})
dbmod.put_widgets("alice", "h1", {"streaks": "<svg>streaksvg</svg>"})
dbmod.point_current_widget("alice", "h1")
r = client.get("/api/streak/alice/")
assert r.status_code == 200
assert b"streaksvg" in r.data
def test_composite_trailing_slash(client):
"""`/api/alice/` must resolve like `/api/alice`."""
dbmod.enroll("alice", {"theme": "dark"})
dbmod.put_widgets("alice", "h1", {"composite": "<svg>compositesvg</svg>"})
dbmod.point_current_widget("alice", "h1")
r = client.get("/api/alice/")
assert r.status_code == 200
assert b"compositesvg" in r.data
def test_enroll_endpoint_is_gone(client): def test_enroll_endpoint_is_gone(client):
@@ -249,6 +605,254 @@ def test_enroll_endpoint_is_gone(client):
assert r.status_code == 405 assert r.status_code == 405
# ---- POST /internal/data-ready: callback from fetcher when an async fetch lands ----
def test_data_ready_requires_internal_token(client, monkeypatch):
monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret")
r = client.post("/internal/data-ready", json={"username": "alice"})
assert r.status_code == 401
def test_data_ready_enqueues_build_for_enrolled_user(client, monkeypatch):
"""The whole point of the async path: the build job appears in the queue
after the fetcher has stored data, not before. Enrolling a user no
longer adds a job, so /data-ready is the only thing that does."""
monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret")
dbmod.enroll("alice", {"theme": "dark"}, enqueue_build=False)
assert dbmod.pending_job_count() == 0
r = client.post("/internal/data-ready",
headers={"X-Internal-Token": "secret"},
json={"username": "alice", "payload_hash": "h1", "ok": True})
assert r.status_code == 200
assert r.get_json()["queued"] is True
assert dbmod.pending_job_count() == 1
def test_data_ready_ignores_unknown_user(client, monkeypatch):
"""If we get a callback for someone who hasn't enrolled here we must not
create a job — the fetcher might be shared or the enrollment might
have been deleted in between."""
monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret")
r = client.post("/internal/data-ready",
headers={"X-Internal-Token": "secret"},
json={"username": "stranger", "payload_hash": "h1", "ok": True})
assert r.status_code == 200
assert r.get_json()["ignored"] is True
assert dbmod.pending_job_count() == 0
def test_data_ready_does_not_enqueue_on_failed_fetch(client, monkeypatch):
monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret")
dbmod.enroll("alice", {"theme": "dark"}, enqueue_build=False)
r = client.post("/internal/data-ready",
headers={"X-Internal-Token": "secret"},
json={"username": "alice", "payload_hash": "", "ok": False})
assert r.status_code == 200
assert r.get_json()["ignored"] is True
assert dbmod.pending_job_count() == 0
def test_data_ready_is_idempotent_when_build_already_pending(client, monkeypatch):
"""The OAuth callback now enqueues a build directly so the worker can
make progress even if /internal/data-ready never arrives. When the
callback DOES arrive after that, it must not queue a second build."""
monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret")
dbmod.enroll("alice", {"theme": "dark"}) # default enqueue_build=True
assert dbmod.pending_job_count() == 1
r = client.post("/internal/data-ready",
headers={"X-Internal-Token": "secret"},
json={"username": "alice", "payload_hash": "h1", "ok": True})
assert r.status_code == 200
assert r.get_json()["ignored"] is True
assert r.get_json()["reason"] == "already_queued"
# Critically, no second build job — the worker would just process the
# same widgets twice with no benefit.
assert dbmod.pending_job_count() == 1
def test_query_override_triggers_adhoc_render_without_persisting(client):
"""GET /api/<u>?theme=... renders on-demand via worker.render_composite_adhoc
and does not mutate the stored settings blob — this is the path visitors
use to embed a customized widget of someone else's profile."""
dbmod.enroll("alice", {"theme": "midnight"})
dbmod.put_widgets("alice", "h1", {"composite": "<svg>cached</svg>"})
dbmod.point_current_widget("alice", "h1")
captured = {}
def fake_adhoc(username, overrides, widget_name="composite"):
captured["username"] = username
captured["overrides"] = overrides
captured["widget_name"] = widget_name
return "<svg>adhoc</svg>"
with patch("src.worker.render_composite_adhoc", side_effect=fake_adhoc):
r = client.get("/api/alice?theme=onyx&widgets=name,grade")
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "ready"
assert r.headers["Cache-Control"] == "public, max-age=300"
assert b"<svg>adhoc</svg>" in r.data
assert captured["username"] == "alice"
assert captured["overrides"]["theme"] == "onyx"
assert captured["overrides"]["enabled"] == ["name", "grade"]
# Stored settings must remain untouched.
assert dbmod.get_settings("alice")["settings"]["theme"] == "midnight"
def test_query_override_without_params_uses_cached_composite(client):
"""No query params → fast path serves the pre-rendered composite from
widgets.db. Ad-hoc render must not be invoked."""
dbmod.enroll("alice", {"theme": "midnight"})
dbmod.put_widgets("alice", "h1", {"composite": "<svg>cached</svg>"})
dbmod.point_current_widget("alice", "h1")
with patch("src.worker.render_composite_adhoc") as adhoc:
r = client.get("/api/alice")
assert adhoc.call_count == 0
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "ready"
assert b"<svg>cached</svg>" in r.data
def test_query_override_skips_adhoc_render_before_first_build(client):
"""With no build landed yet the fetcher likely has no data, so an ad hoc
render would start a GitHub fetch per request. Serve the building
placeholder instead."""
dbmod.enroll("alice", {"theme": "midnight"})
with patch("src.worker.render_composite_adhoc") as adhoc:
r = client.get("/api/alice?theme=onyx&widgets=name,grade")
assert adhoc.call_count == 0
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "building"
def test_query_override_ignores_unknown_params(client):
"""Keys not in the allow-list are dropped by sanitize_settings_query so
bogus query strings don't trigger the expensive ad-hoc path."""
dbmod.enroll("alice", {"theme": "midnight"})
dbmod.put_widgets("alice", "h1", {"composite": "<svg>cached</svg>"})
dbmod.point_current_widget("alice", "h1")
with patch("src.worker.render_composite_adhoc") as adhoc:
r = client.get("/api/alice?nonsense=1&t=12345")
assert adhoc.call_count == 0
assert b"<svg>cached</svg>" in r.data
# ---- ?theme= on the single-widget routes and the compat shims --------------
# READMEs migrating off upstream github-readme-stats carry `&theme=` in the
# URL. Dropping it silently renders the profile in the wrong colors, which
# reads as the product being broken.
_THEME_PAYLOAD = {"user": {"login": "alice"}, "repos": [], "events": [],
"commits": [], "total_commits": 0, "recent_commits": 0,
"total_prs": 0, "collaborators_data": [], "avatar_b64": ""}
def test_named_widget_honors_theme_query_param(client):
"""`/api/<u>/grade.svg?theme=X` must render in X, not in the owner's
stored theme, and must not persist anything."""
dbmod.enroll("alice", {"theme": "midnight", "enabled": ["grade"]})
dbmod.put_widget_data("alice", "h1", {"some": "data"})
dbmod.put_widgets("alice", "h1", {"grade": "<svg>cached</svg>"})
dbmod.point_current_widget("alice", "h1")
with patch("src.worker.fetcher_client.get_data",
return_value={"data": _THEME_PAYLOAD, "payload_hash": "h"}):
paper = client.get("/api/alice/grade.svg?theme=paper")
onyx = client.get("/api/alice/grade.svg?theme=onyx")
assert paper.status_code == 200 and onyx.status_code == 200
assert paper.data != onyx.data
assert b"#f5f0eb" in paper.data # paper card_bg
assert b"#18181b" in onyx.data # onyx card_bg
assert paper.headers["X-Widget-Status"] == "ready"
assert paper.headers["Cache-Control"] == "public, max-age=300"
assert dbmod.get_settings("alice")["settings"]["theme"] == "midnight"
assert dbmod.get_current_widget("alice", "grade") == "<svg>cached</svg>"
def test_named_widget_without_theme_serves_cached_svg(client):
"""No overrides → unchanged fast path: cached SVG, hour-long cache."""
dbmod.enroll("alice", {"theme": "midnight"})
dbmod.put_widgets("alice", "h1", {"grade": "<svg>cached</svg>"})
dbmod.point_current_widget("alice", "h1")
with patch("src.worker.render_composite_adhoc") as adhoc:
r = client.get("/api/alice/grade.svg")
assert adhoc.call_count == 0
assert b"<svg>cached</svg>" in r.data
assert r.headers["Cache-Control"] == "public, max-age=3600"
def test_compat_shims_honor_theme_query_param(client):
"""Both upstream-shaped shims route through the same override path."""
dbmod.enroll("alice", {"theme": "midnight"})
dbmod.put_widgets("alice", "h1", {"languages": "<svg>langs</svg>",
"streaks": "<svg>streak</svg>"})
dbmod.point_current_widget("alice", "h1")
calls = []
def fake_adhoc(username, overrides, widget_name="composite"):
calls.append((username, overrides, widget_name))
return f"<svg>{widget_name}-{overrides['theme']}</svg>"
with patch("src.worker.render_composite_adhoc", side_effect=fake_adhoc):
langs = client.get("/api/top-langs?username=alice&theme=paper")
streak = client.get("/api/streak/alice?theme=onyx")
assert b"languages-paper" in langs.data
assert b"streaks-onyx" in streak.data
assert [c[2] for c in calls] == ["languages", "streaks"]
def test_username_shim_honors_theme_query_param(client, monkeypatch):
"""`/api?username=X&theme=Y` renders the grade widget per request, so the
override applies directly to the theme it renders with."""
monkeypatch.setattr(
"src.api.fetcher_client.get_data",
lambda u: {"data": _THEME_PAYLOAD, "payload_hash": "h"},
)
monkeypatch.setattr("src.api.render_grade_widget",
lambda grade, theme, **kw: f"<svg>{theme}</svg>")
dbmod.enroll("alice", {"theme": "midnight"})
assert b"<svg>paper</svg>" in client.get("/api?username=alice&theme=paper").data
assert b"<svg>onyx</svg>" in client.get("/?username=alice&theme=onyx").data
# Unknown theme falls back to the stored one rather than erroring.
assert b"<svg>midnight</svg>" in client.get("/api?username=alice&theme=bogus").data
def test_invalid_theme_falls_back_to_cached_widget(client):
"""An unknown or malformed theme is dropped by sanitize_settings_query:
no ad-hoc render, no injection, still a 200 with the default rendering."""
dbmod.enroll("alice", {"theme": "midnight"})
dbmod.put_widgets("alice", "h1", {"grade": "<svg>cached</svg>",
"languages": "<svg>langs</svg>"})
dbmod.point_current_widget("alice", "h1")
with patch("src.worker.render_composite_adhoc") as adhoc:
r = client.get("/api/alice/grade.svg?theme=<script>evil</script>")
shim = client.get("/api/top-langs?username=alice&theme=../../etc/passwd")
assert adhoc.call_count == 0
assert r.status_code == 200
assert b"<svg>cached</svg>" in r.data
assert b"evil" not in r.data
assert shim.status_code == 200
assert b"<svg>langs</svg>" in shim.data
def test_per_login_mutate_rate_limit(client, monkeypatch): def test_per_login_mutate_rate_limit(client, monkeypatch):
"""Per-login rate limit on mutate routes allows up to MAX requests, """Per-login rate limit on mutate routes allows up to MAX requests,
then rejects with 429.""" then rejects with 429."""
@@ -266,3 +870,201 @@ def test_per_login_mutate_rate_limit(client, monkeypatch):
# Third request should be rate-limited. # Third request should be rate-limited.
r3 = client.patch("/api/alice/settings", json={}, headers=h) r3 = client.patch("/api/alice/settings", json={}, headers=h)
assert r3.status_code == 429 assert r3.status_code == 429
def test_internal_analytics_events_requires_token(client, monkeypatch):
monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret")
r = client.post("/internal/analytics/events", json={"events": []})
assert r.status_code == 401
def test_internal_analytics_events_ingests(client, monkeypatch):
from src import analytics
monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret")
analytics._reset_for_tests()
body = {
"events": [
{"ts": 1700000000, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 12, "cache_hit": 1}
]
}
r = client.post("/internal/analytics/events",
headers={"X-Internal-Token": "secret"},
json=body)
assert r.status_code == 200
assert r.get_json()["ingested"] == 1
def _basic(user="admin", pw="pw"):
import base64
return {"Authorization": "Basic " + base64.b64encode(f"{user}:{pw}".encode()).decode()}
def test_dev_summary_requires_auth(client, monkeypatch):
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
r = client.get("/api/dev/summary")
assert r.status_code == 401
def test_dev_summary_returns_shape(client, monkeypatch):
from src import analytics
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
analytics._reset_for_tests()
import time as _time
analytics.ingest_batch([
{"ts": int(_time.time()) - 60, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 11, "cache_hit": 1},
])
r = client.get("/api/dev/summary", headers=_basic())
assert r.status_code == 200
body = r.get_json()
for key in ("requests_7d", "active_users_7d", "p50_ms", "p95_ms",
"renders_7d", "avg_render_ms", "daily_requests"):
assert key in body
assert len(body["daily_requests"]) == 7
def test_dev_users_endpoint(client, monkeypatch):
from src import analytics
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
analytics._reset_for_tests()
import time as _time
analytics.ingest_batch([
{"ts": int(_time.time()) - 60, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 11, "cache_hit": 1},
])
r = client.get("/api/dev/users", headers=_basic())
assert r.status_code == 200
rows = r.get_json()
assert any(u["username"] == "alice" for u in rows)
def test_dev_latency_and_health(client, monkeypatch):
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
r = client.get("/api/dev/latency", headers=_basic())
assert r.status_code == 200
assert isinstance(r.get_json(), list)
r2 = client.get("/api/dev/health", headers=_basic())
assert r2.status_code == 200
body = r2.get_json()
for key in ("edge_cache_hit_rate", "fetcher_error_rate",
"events_dropped_24h"):
assert key in body
def test_dev_page_requires_basic_auth(client, monkeypatch):
"""The /dev page itself must 401 without credentials so the browser pops
the native Basic-Auth prompt before any HTML loads. Without this gate
the SPA bundle serves unauthenticated and the dashboard shell renders
before the XHR 401 lands."""
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
r = client.get("/dev")
assert r.status_code == 401
assert r.headers.get("WWW-Authenticate", "").startswith("Basic")
def test_dev_page_503_when_dashboard_disabled(client, monkeypatch):
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "")
r = client.get("/dev")
assert r.status_code == 503
def test_dev_page_serves_html_with_good_creds(client, monkeypatch, tmp_path):
"""With valid Basic credentials, /dev should return whatever index.html
contains (or 503 if the frontend isn't built — both branches mean we
passed the auth gate)."""
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
r = client.get("/dev", headers=_basic())
# 200 if the bundle is on disk, 503 otherwise — both prove auth passed.
assert r.status_code in (200, 503)
def test_get_widget_records_request_event(client, monkeypatch):
"""Hitting /api/<u> must emit one analytics 'request' event so the
dashboard's req_7d/top_endpoint/avg_latency columns actually populate
in deployments without an edge in front."""
from src import analytics
analytics._reset_for_tests()
monkeypatch.setattr(dbmod, "enroll", lambda *a, **kw: {"job_id": None})
# Enroll the user so /api/<u> serves a placeholder rather than 4xx;
# status doesn't matter — we only care that an event is recorded.
dbmod.enroll("alice", {"theme": "dark", "enabled": ["grade"], "widget_order": ["grade"]})
client.get("/api/alice")
# Drain the in-memory queue (the daemon flush thread isn't running in tests)
analytics.ingest_batch(analytics._drain_queue())
with dbmod.analytics_conn() as c:
rows = c.execute(
"SELECT username, widget, endpoint, kind FROM events WHERE kind='request'"
).fetchall()
assert any(
r["username"] == "alice" and r["widget"] == "composite"
and r["endpoint"] == "/api/<u>"
for r in rows
)
def test_get_widget_named_records_endpoint_template(client, monkeypatch):
from src import analytics
analytics._reset_for_tests()
dbmod.enroll("bob", {"theme": "dark", "enabled": ["grade"], "widget_order": ["grade"]})
client.get("/api/bob/grade.svg")
analytics.ingest_batch(analytics._drain_queue())
with dbmod.analytics_conn() as c:
rows = c.execute(
"SELECT username, widget, endpoint FROM events WHERE kind='request'"
).fetchall()
assert any(
r["username"] == "bob" and r["widget"] == "grade"
and r["endpoint"] == "/api/<u>/<widget>.svg"
for r in rows
)
def test_get_user_data_records_request_event(client, monkeypatch):
from src import analytics
analytics._reset_for_tests()
dbmod.enroll("carol", {"theme": "dark", "enabled": ["grade"], "widget_order": ["grade"]})
client.get("/api/carol/data")
analytics.ingest_batch(analytics._drain_queue())
with dbmod.analytics_conn() as c:
rows = c.execute(
"SELECT username, widget, endpoint FROM events WHERE kind='request'"
).fetchall()
assert any(
r["username"] == "carol" and r["widget"] == "data"
and r["endpoint"] == "/api/<u>/data"
for r in rows
)
def test_oauth_redirect_uri_is_https_in_production(client, monkeypatch):
"""GitHub matches redirect_uri against the registered callback character for
character. The tunnel can leave X-Forwarded-Proto unset, which made the app
send http:// and GitHub reject every sign-in with "The redirect_uri is not
associated with this application". Only a local dev host may be plaintext."""
monkeypatch.setattr(cfg, "GITHUB_OAUTH_REDIRECT_URI", "")
r = client.get("/api/auth/github/login?next=/",
headers={"Host": "gh-stats.com"})
assert r.status_code == 302
loc = r.headers["Location"]
assert "redirect_uri=https%3A%2F%2Fgh-stats.com%2Fapi%2Fauth%2Fgithub%2Fcallback" in loc, loc
assert "http%3A%2F%2Fgh-stats.com" not in loc
def test_oauth_redirect_uri_stays_http_on_localhost(client, monkeypatch):
"""Local development must keep working over plain http."""
monkeypatch.setattr(cfg, "GITHUB_OAUTH_REDIRECT_URI", "")
r = client.get("/api/auth/github/login?next=/",
headers={"Host": "localhost:5002"})
assert r.status_code == 302
assert "redirect_uri=http%3A%2F%2Flocalhost%3A5002" in r.headers["Location"]
+190
View File
@@ -0,0 +1,190 @@
"""Per-widget attribution behaves correctly in both contexts.
Standalone widget SVGs (served at /api/<u>/<widget>.svg) must show the
"Generated with gh-stats.com" footer; the composite (served at /api/<u>)
must strip the per-widget footer and only show its own bottom one.
"""
import xml.etree.ElementTree as ET
import pytest
from src import placeholder
from src.models import (
AchievementData,
CollaboratorData,
FocusCategory,
GradeData,
ImpactWeek,
LanguageData,
StreakData,
TagData,
)
from src.widgets import (
render_achievements_widget,
render_collaborators_widget,
render_focus_widget,
render_grade_widget,
render_impact_widget,
render_languages_widget,
render_streaks_widget,
compose_widget,
)
def _grade_fixture() -> GradeData:
return GradeData(
grade="A", score=80,
stats={"commits": 100, "prs": 10, "stars": 5, "repos": 3, "followers": 1},
tags=[TagData(tag="builder", source="earned")],
breakdown={"commits": 0.8, "consistency": 0.6, "stars": 0.4},
)
def _languages_fixture() -> list[LanguageData]:
return [
LanguageData(language="Python", percentage=60.0, loc=0),
LanguageData(language="TypeScript", percentage=40.0, loc=0),
]
# Every widget reachable at /api/<u>/<widget>.svg, rendered from a minimal
# fixture. Parametrised so a new standalone widget can't ship without a footer.
_STANDALONE = {
"grade": lambda: render_grade_widget(_grade_fixture(), theme_name="dark"),
"languages": lambda: render_languages_widget(_languages_fixture(), theme_name="dark"),
"streaks": lambda: render_streaks_widget(
StreakData(current=5, max=12, current_start="2026-08-18",
last_active_date="2026-08-22", max_start="2026-01-01",
max_end="2026-01-12"),
theme_name="dark",
),
"impact": lambda: render_impact_widget(
[ImpactWeek(week_start="2026-01-05", commits=7),
ImpactWeek(week_start="2026-01-12", commits=3)],
theme_name="dark",
),
"impact_empty": lambda: render_impact_widget([], theme_name="dark"),
"focus": lambda: render_focus_widget(
[FocusCategory(category="Backend", percentage=70.0, commit_count=70),
FocusCategory(category="Docs", percentage=30.0, commit_count=30)],
theme_name="dark",
),
"collaborators": lambda: render_collaborators_widget(
[CollaboratorData(username="bob", shared_repos=2, shared_commits=30)],
theme_name="dark",
),
"achievements": lambda: render_achievements_widget(
[AchievementData(title="Hackathon win", subtitle="MIT", event_date="2026-03")],
theme_name="dark",
),
}
@pytest.mark.parametrize("name", sorted(_STANDALONE))
def test_standalone_widget_has_attribution(name):
svg = _STANDALONE[name]()
assert "Generated with gh-stats.com" in svg
assert 'data-gh-attribution="1"' in svg
@pytest.mark.parametrize("name", sorted(_STANDALONE))
def test_standalone_widget_is_well_formed_svg(name):
ET.fromstring(_STANDALONE[name]())
@pytest.mark.parametrize("name", sorted(_STANDALONE))
def test_attribution_is_legible_and_consistent(name):
"""The footer is a credit line, not a disclaimer: big enough to read,
faint enough to stay subordinate, and identical across every widget."""
root = ET.fromstring(_STANDALONE[name]())
nodes = [e for e in root.iter() if e.get("data-gh-attribution") == "1"]
assert len(nodes) == 1
node = nodes[0]
assert node.get("font-size") == "10"
assert node.get("opacity") == "0.75"
assert node.get("text-anchor") == "middle"
@pytest.mark.parametrize("variant", ["building", "rate_limited", "not_found", "unsubstituted"])
def test_placeholder_cards_have_attribution(variant):
svg = placeholder.render(variant, "alice", theme="dark")
assert "Generated with gh-stats.com" in svg
ET.fromstring(svg)
def test_attribution_uses_theme_colors_not_hardcoded_hex():
"""The footer must pick up each theme's secondary text token."""
from src.themes.themes import THEMES
for theme_name in ("dark", "light"):
root = ET.fromstring(render_grade_widget(_grade_fixture(), theme_name=theme_name))
node = next(e for e in root.iter() if e.get("data-gh-attribution") == "1")
assert node.get("fill") == THEMES[theme_name]["text_secondary"]
def test_composite_strips_per_widget_attribution_from_grade():
"""Embedded inside the composite, the grade widget's per-widget
attribution must be removed — the composite has its own footer at
the bottom, showing both would be visually redundant."""
grade_svg = render_grade_widget(_grade_fixture(), theme_name="dark")
composite = compose_widget(
widgets={"grade": grade_svg},
enabled=["grade"],
theme_name="dark",
username="alice",
avatar_b64="",
show_name=False,
)
# The composite has exactly ONE attribution (its own). The widget's
# footer attribution should be gone.
assert composite.count("Generated with gh-stats.com") == 1
# No leftover attribution markers leaked through.
assert "data-gh-attribution" not in composite
def test_composite_strips_per_widget_attribution_from_languages():
langs_svg = render_languages_widget(_languages_fixture(), theme_name="dark")
composite = compose_widget(
widgets={"languages": langs_svg},
enabled=["languages"],
theme_name="dark",
username="alice",
avatar_b64="",
show_name=False,
)
assert composite.count("Generated with gh-stats.com") == 1
assert "data-gh-attribution" not in composite
def test_composite_strips_attribution_from_multiple_widgets():
"""When several attribution-bearing widgets are inlined together,
the composite still shows only its own single footer line."""
grade_svg = render_grade_widget(_grade_fixture(), theme_name="dark")
langs_svg = render_languages_widget(_languages_fixture(), theme_name="dark")
composite = compose_widget(
widgets={"grade": grade_svg, "languages": langs_svg},
enabled=["grade", "languages"],
theme_name="dark",
username="alice",
avatar_b64="",
show_name=False,
)
# Each widget contributed an attribution; the composite contributes
# one of its own — total visible attributions must be exactly 1.
assert composite.count("Generated with gh-stats.com") == 1
def test_composite_reclaims_attribution_height():
"""Stripping the attribution from a per-widget SVG must also reduce
the slot height the composite reserves — otherwise we'd leave 16px
of empty space at the bottom of every embedded widget."""
from src.widgets import composite as composite_mod
grade_svg = render_grade_widget(_grade_fixture(), theme_name="dark")
inner_with_attr, h_with_attr = composite_mod._extract_inner(grade_svg, "grade")
# The standalone grade SVG declares its full height including the
# 16px footer; the embed height should be 16 less.
import re
full_h = int(re.search(r'height="(\d+)"', grade_svg).group(1))
assert h_with_attr == full_h - 16
assert "data-gh-attribution" not in inner_with_attr
+74
View File
@@ -137,6 +137,16 @@ def test_login_rejects_external_next(api_client):
assert s.get("oauth_next") == "/" assert s.get("oauth_next") == "/"
@pytest.mark.parametrize("bad_next", ["//evil.example", "//evil.example/x", "/\\evil.example"])
def test_login_rejects_protocol_relative_next(api_client, bad_next):
# Browsers resolve //host and /\host against the current scheme, so these
# are open-redirect vectors even though they start with "/".
r = api_client.get(f"/api/auth/github/login?next={bad_next}")
assert r.status_code in (302, 303)
with api_client.session_transaction() as s:
assert s.get("oauth_next") == "/"
def test_callback_state_mismatch_400(api_client): def test_callback_state_mismatch_400(api_client):
with api_client.session_transaction() as s: with api_client.session_transaction() as s:
s["oauth_state"] = "correct" s["oauth_state"] = "correct"
@@ -171,3 +181,67 @@ def test_callback_happy_path_sets_session(api_client, monkeypatch):
assert s["gh_avatar_url"] == "https://x/a.png" assert s["gh_avatar_url"] == "https://x/a.png"
# Row should now exist with github profile populated. # Row should now exist with github profile populated.
assert dbmod.get_settings("alice") is not None assert dbmod.get_settings("alice") is not None
def test_require_basic_auth_503_when_unset(monkeypatch):
from flask import Flask, jsonify
from src import auth as authmod
from src import config as cfg
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "")
app = Flask(__name__)
@app.route("/x")
@authmod.require_basic_auth
def x():
return jsonify({"ok": True})
with app.test_client() as c:
r = c.get("/x")
assert r.status_code == 503
def test_require_basic_auth_401_on_bad(monkeypatch):
import base64
from flask import Flask, jsonify
from src import auth as authmod
from src import config as cfg
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
app = Flask(__name__)
@app.route("/x")
@authmod.require_basic_auth
def x():
return jsonify({"ok": True})
with app.test_client() as c:
r = c.get("/x")
assert r.status_code == 401
assert r.headers.get("WWW-Authenticate", "").startswith("Basic")
bad = base64.b64encode(b"admin:wrong").decode()
r2 = c.get("/x", headers={"Authorization": f"Basic {bad}"})
assert r2.status_code == 401
def test_require_basic_auth_200_on_good(monkeypatch):
import base64
from flask import Flask, jsonify
from src import auth as authmod
from src import config as cfg
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
app = Flask(__name__)
@app.route("/x")
@authmod.require_basic_auth
def x():
return jsonify({"ok": True})
with app.test_client() as c:
good = base64.b64encode(b"admin:pw").decode()
r = c.get("/x", headers={"Authorization": f"Basic {good}"})
assert r.status_code == 200
+21
View File
@@ -35,3 +35,24 @@ def test_tick_skips_when_hash_unchanged(tmp_dbs):
return_value={"data": {}, "payload_hash": "same"}): return_value={"data": {}, "payload_hash": "same"}):
stats = cronmod.tick() stats = cronmod.tick()
assert stats["enqueued"] == 0 assert stats["enqueued"] == 0
def test_cron_tick_prunes_old_analytics(tmp_path, monkeypatch):
import os, time
from src import db as dbmod, analytics, cron
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(tmp_path, "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(tmp_path, "w.db"))
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(tmp_path, "a.db"))
dbmod.init_dbs()
analytics.ingest_batch([
{"ts": int(time.time()) - 30 * 86400, "service": "edge", "kind": "request",
"username": "u", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 1, "cache_hit": 1},
])
# tick() iterates enrolled users but there are none, so it returns
# immediately — we only care that the prune call ran.
cron.tick()
with dbmod.analytics_conn() as c:
n = c.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"]
assert n == 0
+47
View File
@@ -9,6 +9,7 @@ def tmp_dbs(monkeypatch):
with tempfile.TemporaryDirectory() as d: with tempfile.TemporaryDirectory() as d:
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db")) monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db")) monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(d, "a.db"))
dbmod.init_dbs() dbmod.init_dbs()
yield d yield d
@@ -31,6 +32,17 @@ def test_enroll_twice_noops(tmp_dbs):
assert r1["job_id"] > 0 and r2["job_id"] > 0 assert r1["job_id"] > 0 and r2["job_id"] > 0
def test_enroll_without_build_skips_job(tmp_dbs):
"""OAuth callback uses this so the build job is only added once the
fetcher has actually fetched (via /internal/data-ready). Otherwise the
worker pops a job for a user with no fetcher data yet."""
r = dbmod.enroll("alice", {"theme": "dark"}, enqueue_build=False)
assert r["job_id"] is None
assert dbmod.pending_job_count() == 0
# The user row itself was still created so callbacks can find them.
assert dbmod.get_settings("alice") is not None
def test_enroll_with_github_profile(tmp_dbs): def test_enroll_with_github_profile(tmp_dbs):
dbmod.enroll("alice", {"theme": "dark"}, github_id=1, github_avatar_url="https://x/a.png") dbmod.enroll("alice", {"theme": "dark"}, github_id=1, github_avatar_url="https://x/a.png")
with dbmod._settings_conn() as c: with dbmod._settings_conn() as c:
@@ -45,6 +57,29 @@ def test_enrollments_daily_counter(tmp_dbs):
assert dbmod.enrollments_today() == 2 assert dbmod.enrollments_today() == 2
def test_enrollments_last_hour_counts_only_recent(tmp_dbs):
dbmod.enroll("alice", {"theme": "dark"})
dbmod.enroll("bob", {"theme": "dark"})
assert dbmod.enrollments_last_hour() == 2
# Age one of them past the window; it must drop out of the burst count
# while still counting toward the daily total.
with dbmod._settings_conn() as c:
c.execute("UPDATE users SET enrolled_at='2020-01-01T00:00:00Z' WHERE username='alice'")
c.commit()
assert dbmod.enrollments_last_hour() == 1
def test_enrollment_rank_is_case_insensitive(tmp_dbs):
"""GitHub returns logins with original casing ("ShayManor") but the users
table stores them lowercased. Without normalization the founder-tag rule
silently misses everyone whose login has capitals."""
dbmod.enroll("shaymanor", {"theme": "dark"})
# Mixed / upper case must find the same row as the lowercased insert.
assert dbmod.enrollment_rank("ShayManor") is not None
assert dbmod.enrollment_rank("SHAYMANOR") == dbmod.enrollment_rank("shaymanor")
assert dbmod.enrollment_rank("missing") is None
def test_update_settings_changes_hash(tmp_dbs): def test_update_settings_changes_hash(tmp_dbs):
dbmod.enroll("alice", {"theme": "dark"}) dbmod.enroll("alice", {"theme": "dark"})
h_before = dbmod.get_settings("alice")["settings_hash"] h_before = dbmod.get_settings("alice")["settings_hash"]
@@ -150,3 +185,15 @@ def test_put_user_streak_upserts(tmp_dbs):
assert row["current_streak"] == 2 assert row["current_streak"] == 2
assert row["max_streak"] == 5 assert row["max_streak"] == 5
assert row["max_start"] == "2024-01-01" assert row["max_start"] == "2024-01-01"
def test_init_dbs_creates_analytics_schema(tmp_path, monkeypatch):
from src import db as dbmod
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", str(tmp_path / "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", str(tmp_path / "w.db"))
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", str(tmp_path / "a.db"))
dbmod.init_dbs()
with dbmod.analytics_conn() as c:
cols = {r["name"] for r in c.execute("PRAGMA table_info(events)").fetchall()}
assert cols == {"id", "ts", "service", "kind", "username",
"endpoint", "widget", "status", "latency_ms", "cache_hit"}

Some files were not shown because too many files have changed in this diff Show More