File size: 9,749 Bytes
6d30676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""Chart + table helpers for the Hub agent-usage leaderboard.

Used by build_local.py (the scheduled HF Job) to render the PNGs embedded in
the dataset card. This module only ever touches the *derived* public data
(relative shares); fetching + deriving from the private source lives in
build_local.py.
"""

from __future__ import annotations

from pathlib import Path

import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import rcParams
from matplotlib.figure import Figure

# --------------------------------------------------------------------------- #
# Constants
# --------------------------------------------------------------------------- #

# Published derived dataset (used when no local data dir is given).
DERIVED_REPO = "huggingface/agent-usage"

ROLLOUT_DATE = "2026-04-03"  # agent/ UA token rollout — before this is noise

# HF brand palette — https://huggingface.co/brand
YELLOW = "#FFD21E"   # primary accent — leader bar
ORANGE = "#FF9D00"   # secondary accent
SLATE = "#1F2937"    # near-black bars / first line
INK = "#111827"      # body text
MUTED = "#6B7280"    # HF gray — axes, footers
GRID = "#E5E7EB"     # light gridline
BG = "#FFFFFF"

# Stable categorical line colours (assigned by agent order).
LINE_COLORS = [
    SLATE, ORANGE, "#2563EB", "#059669", "#DC2626",
    "#7C3AED", "#0891B2", "#CA8A04",
]


def set_brand_style() -> None:
    """Apply HF-flavoured matplotlib defaults (clean sans-serif, white bg)."""
    rcParams.update(
        {
            "font.family": "sans-serif",
            "font.sans-serif": [
                "Source Sans Pro", "Source Sans 3",
                "Helvetica Neue", "Helvetica", "Arial", "DejaVu Sans",
            ],
            "font.size": 11,
            "text.color": INK,
            "savefig.facecolor": BG,
            "axes.facecolor": BG,
            "figure.facecolor": BG,
        }
    )


# --------------------------------------------------------------------------- #
# Selectors
# --------------------------------------------------------------------------- #

def available_months(monthly: pd.DataFrame) -> list[str]:
    return sorted(monthly["month"].dropna().unique().tolist())


def latest_month(monthly: pd.DataFrame) -> str:
    return max(available_months(monthly))


def leaderboard_table(
    monthly: pd.DataFrame,
    month: str | None = None,
    top_n: int = 10,
    exclude_unknown: bool = True,
) -> pd.DataFrame:
    """Ranked top-N agents for a month, ready to display."""
    month = month or latest_month(monthly)
    df = monthly.query("month == @month")
    if exclude_unknown:
        df = df[df["agent"].str.lower() != "unknown"]
    df = df.sort_values("pct_requests", ascending=False).head(top_n).reset_index(drop=True)
    out = df[["agent", "pct_requests", "pct_users"]].copy()
    out.insert(0, "rank", range(1, len(out) + 1))
    out["pct_requests"] = out["pct_requests"].round(2)
    out["pct_users"] = out["pct_users"].astype("Float64").round(2)
    return out


def top_agents(
    monthly: pd.DataFrame,
    month: str | None = None,
    n: int = 5,
    exclude_unknown: bool = True,
) -> list[str]:
    """Top-N agent names by share in the given month (default: latest)."""
    return leaderboard_table(monthly, month, n, exclude_unknown)["agent"].tolist()


# --------------------------------------------------------------------------- #
# Figures
# --------------------------------------------------------------------------- #

def leaderboard_figure(
    monthly: pd.DataFrame,
    month: str | None = None,
    top_n: int = 10,
    show_unknown: bool = True,
) -> Figure:
    """Horizontal-bar snapshot leaderboard, HF-brand register.

    Named harnesses are ranked as usual; `unknown` (unregistered tools) sits as
    a muted gray bar at the bottom — an honest part of the picture and the
    reason to register a harness, without reading as part of the race.
    """
    set_brand_style()
    month = month or latest_month(monthly)
    table = leaderboard_table(monthly, month, top_n, exclude_unknown=True)

    fig = Figure(figsize=(9.2, 9.2), facecolor=BG)
    fig.text(0.06, 0.935, "Agents calling the Hugging Face Hub",
             fontsize=22, color=INK, fontweight="bold")
    fig.text(0.06, 0.895, f"Share of agent-attributed huggingface_hub requests, {month}",
             fontsize=13, color=MUTED)

    ax = fig.add_axes((0.06, 0.10, 0.88, 0.74))
    # rows bottom-to-top: (label, pct, kind) with unknown pinned at the bottom
    rows = [(r["agent"], float(r["pct_requests"]), "named")
            for _, r in table.iloc[::-1].iterrows()]
    if show_unknown:
        unk = monthly.query("month == @month and agent == 'unknown'")
        if len(unk):
            rows.insert(0, ("unknown (unregistered)", float(unk["pct_requests"].iloc[0]), "unknown"))
    if not rows:
        ax.text(0.5, 0.5, "no data", ha="center", va="center", color=MUTED)
        return fig
    xmax = max(pct for _, pct, _ in rows)
    ax.axvline(0, color=MUTED, linewidth=0.6, zorder=1)

    top_idx = len(rows) - 1  # top *named* harness leads
    for i, (label, pct, kind) in enumerate(rows):
        is_unknown = kind == "unknown"
        is_top = i == top_idx
        bar_colour = GRID if is_unknown else (YELLOW if is_top else SLATE)
        ax.barh(i, pct, color=bar_colour, height=0.62, zorder=2)
        ax.text(-xmax * 0.022, i, label, va="center", ha="right",
                fontsize=12 if is_unknown else 14,
                fontstyle="italic" if is_unknown else "normal",
                fontweight="bold" if is_top else "normal",
                color=MUTED if is_unknown else INK)
        ax.text(pct + xmax * 0.012, i, f"{pct:.1f}%", va="center", ha="left",
                fontsize=14, fontweight="bold",
                color=MUTED if is_unknown else (ORANGE if is_top else INK))

    ax.set_yticks([]); ax.set_xticks([])
    for s in ("top", "right", "left", "bottom"):
        ax.spines[s].set_visible(False)
    ax.set_xlim(-xmax * 0.50, xmax * 1.15)
    ax.set_ylim(-0.7, len(rows) - 0.3)

    fig.text(0.06, 0.040,
             f"Source: hf.co/datasets/{DERIVED_REPO}  ·  self-declared agent/ User-Agent tokens.",
             fontsize=10, color=MUTED)
    return fig


def trend_figure(
    daily: pd.DataFrame,
    agents: list[str],
    smooth: bool = True,
    since: str = ROLLOUT_DATE,
) -> Figure:
    """Daily share-over-time lines for the given agents, HF-brand register.

    ``smooth`` applies a 7-day centred rolling mean (min_periods=3) to absorb
    weekend dips and small-denominator noise in the early days.
    """
    set_brand_style()
    df = daily[daily["day"] >= since].copy()
    df = df[df["agent"].isin(agents)]
    df["day"] = pd.to_datetime(df["day"])

    fig = Figure(figsize=(11, 6.2), facecolor=BG)
    fig.text(0.06, 0.93, "Agent share of Hub requests over time",
             fontsize=20, color=INK, fontweight="bold")
    sub = "7-day rolling mean" if smooth else "raw daily share"
    fig.text(0.06, 0.885, f"huggingface_hub  ·  {sub}  ·  since {since}",
             fontsize=12.5, color=MUTED)

    ax = fig.add_axes((0.06, 0.13, 0.80, 0.70))
    if df.empty:
        ax.text(0.5, 0.5, "no data", ha="center", va="center", color=MUTED)
        return fig

    ymax = 0.0
    labels = []  # (y_at_end, agent, colour) for de-collided right-hand labels
    last_x = None
    for idx, agent in enumerate(agents):
        s = (
            df[df["agent"] == agent]
            .sort_values("day")
            .set_index("day")["pct_requests"]
            .astype(float)
        )
        if s.empty:
            continue
        if smooth:
            s = s.rolling(7, center=True, min_periods=3).mean()
        colour = LINE_COLORS[idx % len(LINE_COLORS)]
        ax.plot(s.index, s.values, color=colour, linewidth=2.2, zorder=3)
        valid = s.dropna()
        if not valid.empty:
            labels.append([float(valid.iloc[-1]), agent, colour])
            last_x = valid.index[-1]
            ymax = max(ymax, float(valid.max()))

    ax.set_ylim(0, ymax * 1.12 if ymax else 1)

    # De-collide right-hand direct labels: nudge apart by a min vertical gap
    if labels and last_x is not None:
        gap = (ymax * 1.12) * 0.045  # ~4.5% of axis height
        labels.sort(key=lambda r: r[0])
        for prev, cur in zip(labels, labels[1:]):
            if cur[0] - prev[0] < gap:
                cur[0] = prev[0] + gap
        for y, agent, colour in labels:
            ax.annotate(
                f" {agent}",
                xy=(last_x, y), xytext=(6, 0), textcoords="offset points",
                va="center", ha="left", fontsize=11.5, color=colour,
                fontweight="bold", annotation_clip=False,
            )
    ax.yaxis.set_major_formatter(lambda v, _: f"{v:.0f}%")
    ax.grid(axis="y", color=GRID, linewidth=0.8)
    ax.set_axisbelow(True)
    for s in ("top", "right"):
        ax.spines[s].set_visible(False)
    for s in ("left", "bottom"):
        ax.spines[s].set_color(MUTED)
    ax.tick_params(colors=MUTED, labelsize=10)
    ax.xaxis.set_major_locator(mdates.AutoDateLocator())
    ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))
    # room for the right-hand direct labels
    ax.margins(x=0.02)

    fig.text(0.06, 0.035,
             f"Source: hf.co/datasets/{DERIVED_REPO}  ·  share of agent-attributed huggingface_hub requests.",
             fontsize=10, color=MUTED)
    return fig


def save_png(fig: Figure, path: str | Path) -> Path:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    fig.savefig(path, dpi=200, bbox_inches="tight", pad_inches=0.4, facecolor=BG)
    plt.close(fig)
    return path