feat(processor): add consistency scoring based on active commit weeks.

This commit is contained in:
shay
2026-04-20 13:43:08 -04:00
parent bd59910e54
commit 39d07fb7e0
3 changed files with 118 additions and 65 deletions
+1 -1
View File
@@ -240,7 +240,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": {"show_dates": "bool"}, "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"},
+39 -9
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,45 @@ 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
consistency_score = min(len(active_weeks) / 40 * 100, 100)
total = sum(scores.values()) / len(scores) # Weights sum to 1.0. Commits dominates (the user's actual output),
# consistency is the second-biggest (rewards sustained work over the
# last year, not just lifetime totals). Stars is softened two ways:
# its weight drops from 0.20 to 0.12, and the cap rises from 200 to
# 300 so each individual star contributes less to maxing the factor.
per_factor = {
"commits": (min(commits / 2000 * 100, 100), 0.33),
"consistency": (consistency_score, 0.22),
"repos": (min(repo_count / 30 * 100, 100), 0.15),
"stars": (min(stars / 300 * 100, 100), 0.12),
"forks": (min(forks / 50 * 100, 100), 0.08),
"activity": (min(len(events) / 80 * 100, 100), 0.07),
"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:
+78 -55
View File
@@ -3,40 +3,44 @@
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
_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 +51,69 @@ 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 width, height = 380, 170
height = 170
col_w = width / 2
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>'''
return card_wrapper(inner, width, height, t, "Streaks")